From dubreus at csit.fsu.edu Tue Jun 11 11:32:24 2002 From: dubreus at csit.fsu.edu (mitsch) Date: 11 Jun 2002 08:32:24 -0700 Subject: compiling error: undefined symbol: __gxx_personality_v0 Message-ID: <93523ebb.0206110732.791e745@posting.google.com> Hi, I try to wrap C functions in Python. when I compile, here's the result: Traceback (most recent call last): File "./boost.py", line 2, in ? import getting_started1 ImportError: ./getting_started1.so: undefined symbol: __gxx_personality_v0 can somebody tell why this error? here's my files: getting_stated!.cpp : #include namespace python = boost::python; #include namespace { // Avoid cluttering the global namespace. // A couple of simple C++ functions that we want to expose to Python. std::string greet() { return "hello, world"; } int square(int number) { return number * number; } } BOOST_PYTHON_MODULE_INIT(getting_started1) { // Create an object representing this extension module. python::module_builder this_module("getting_started1"); // Add regular functions to the module. this_module.def(greet, "greet"); this_module.def(square, "square"); } my compile command: g++3 -fpic -g -I/usr/include/python2.1 -I/usr/local/lib/python/boost_1_28_0/ -c ./getting_started1.cpp gcc -shared -lc getting_started1.o -o getting_started1.so From rdacker at pacbell.net Thu Jun 13 21:39:56 2002 From: rdacker at pacbell.net (rdack) Date: 13 Jun 2002 18:39:56 -0700 Subject: urllib question References: <644f6688.0206101835.5dc793b1@posting.google.com> Message-ID: <644f6688.0206131739.6178e286@posting.google.com> rdacker at pacbell.net (rdack) wrote in message news:<644f6688.0206101835.5dc793b1 at posting.google.com>... > this retrieves data from my router: > params = urllib.urlencode({'RC': '@D', 'ACCT' : "root", 'PSWD' : > "71:29:26", 'URL': 'admin' }) > ipurl = "http://" + iphost + "/cgi-bin/logi" > urlfp = urllib.urlopen(ipurl, params) > is there some way i can what exactly this is posting? a way to get the post object out of urlib? it should be something like: POST http://192.168.0.1/cgi-bin/logi Content-Length: 47 Content-Type: application/x-www-form-urlencoded RC=%40D&PSWD=71%3A29%3A26&URL=admin&ACCT=root From jpapa at websense.com Fri Jun 14 16:06:53 2002 From: jpapa at websense.com (J. Papa) Date: 14 Jun 2002 13:06:53 -0700 Subject: Graceful socket shutdown Message-ID: <9e180f21.0206141206.1f4d8c78@posting.google.com> I am posting this because I just spend too many hours debugging and I wanted to save someone else the angst. According to MSDN the proper way to close a winsock connection is to: 1. shutdown( SD_SEND ); 2. call recv in a loop until it returns 0 or SOCKET_ERROR 3. close() So in Python: # This is not robust. # s.close() # This is, hideous, but correct for Win32 s.shutdown( 1 ) while 1: try: byte = s.recv( 1 ) if "" == byte: break except: break s.close() The only time you will see this bug is if your recv buffer still has data in it when you try and close() the socket. This happened to me because my client was a wininet app. Wininet, for some mysterious reason, appends an extra "\r\n" to POSTed data. (I swear I sniffed it, its true.) This extra "\r\n" is not included in the Content-Length of the POST. Hence, there were two extra bytes in the recv buffer when I went to close() my socket. Instead of sending a FIN a RST is sent instead that gets ugly. Regards, J. Papa From quinn at retch.ugcs.caltech.edu Thu Jun 27 16:50:59 2002 From: quinn at retch.ugcs.caltech.edu (Quinn Dunkan) Date: 27 Jun 2002 20:50:59 GMT Subject: RE strings (was: Variable Interpolation - status of PEP 215) References: <4PfQ8.44245$n4.10307683@newsc.telia.net> <29e28c51.0206201156.7e61a7f5@posting.google.com> <3D127B89.EE1C17F4@engcorp.com> <29e28c51.0206210944.400eaedc@posting.google.com> Message-ID: On 21 Jun 2002 10:44:50 -0700, Cimarron Taylor wrote: > import re > def parseline3(line): > m = re.match(r'^EMP:([^,]*),([^,]*),([^,]*),([^,]*)$', line) > if m: > ... > > >Unless I'm mistaken about how the re module works, parseline3 will >recompile the regex each time it is called. parseline2 avoids this You are. Mistaken, that is :) Take a look at sre.py Of course, if you did 20 regexes in the meanwhile, it would be recompiled. I generally take the parseline2 approach anyway, though. From mgerrans at mindspring.com Sun Jun 23 04:13:15 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Sun, 23 Jun 2002 01:13:15 -0700 Subject: Python hits the spot References: <3D1482AE.8FA299D8@kfunigraz.ac.at> <3D14B7B1.7040602@ix.netcom.com> Message-ID: > ...That's the hard lesson that has been learned about > safety systems, is that building in six layers of safety to protect > workers from the consequences of their actions will in fact train > workers to get all six wrong at once. Ah, but that is also what gives us the most entertaining Darwin Awards! :-) From peter at engcorp.com Sun Jun 2 02:12:00 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 02 Jun 2002 02:12:00 -0400 Subject: What does sys.exit(1) means? References: Message-ID: <3CF9B730.4D160FDB@engcorp.com> Ken wrote: > > What does sys.exit(1) means? You can find this if you Read the Fine Manual at http://www.python.org/doc/current/lib/module-sys.html . There is similar documentation for all functions in all standard modules, in case you have similar questions in the future... sys.exit([arg]) Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level. The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered ``successful termination'' and any nonzero value is considered ``abnormal termination'' by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors. If another type of object is passed, None is equivalent to passing zero, and any other object is printed to sys.stderr and results in an exit code of 1. In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs. -Peter From h.baumgartl at chello.NOSPAM.nl Fri Jun 21 09:56:10 2002 From: h.baumgartl at chello.NOSPAM.nl (Henry Baumgartl) Date: Fri, 21 Jun 2002 13:56:10 GMT Subject: application development - separating content from function References: Message-ID: <_fGQ8.280952$i6.18906908@amsnews02.chello.com> Thanks very much for the input! I do believe it has helped me to take off my blinders, look around and realise what it is all about. Going for the ultimate design and functionality prize may well have (indefinitely) delayed actually getting the project under way. How was it again, about the importance of the journey rather than the destination? ;-? Best regards, Henry From brian at sweetapp.com Mon Jun 24 22:03:43 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 24 Jun 2002 19:03:43 -0700 Subject: Suggestions for good programming practices? In-Reply-To: <3D17CC8E.ABB72D14@engcorp.com> Message-ID: <013901c21bec$8a950910$bd5d4540@Dell2> Peter Hansen wrote: > Brian Quinlan wrote: > > > > Peter Hansen wrote: > > > You _are_ returning them "in a struct". It's spelled "tuple" > > > but other than that what's the difference? > > > > struct members are access by name while tuple elements are accessed > > positionally. > > Okay. So why is that a problem? I'm not saying it is. I'm saying that tuples and structs are different. Cheers, Brian From tchur at optushome.com.au Sat Jun 8 17:51:23 2002 From: tchur at optushome.com.au (Tim Churches) Date: Sun, 09 Jun 2002 07:51:23 +1000 Subject: Confidence intervals, stats modules? References: Message-ID: <3D027C5A.E5D8B61E@optushome.com.au> Duncan Smith wrote: > > "Stephen Boulet" wrote in message > news:ug2r3aac4etnef at corp.supernews.com... > > Are there any stats modules to calculate things like confidence intervals, > > mean, standard deviation? Thanks. > > > > -- Stephen > > http://www.nmr.mgh.harvard.edu/Neural_Systems_Group/gary/python.html > Gary's stats module is excellent and is probably sufficient for the uses you describe. There are also some elementary statistical functions in Konrad Hinsen's equally excellent Scientific Python package - see http://starship.python.net/crew/hinsen/scientific.html In fact, you could just use NumPy (Numerical Python) - have a look at the MLab module in NumPy (which is at http://www.pfdubois.com/numpy/ ). However, if you are interested in more advanced statistical analysis and/or in drawing statistical graphs, then have a look at RPy, by Walter Moreira, at http://rpy.sourceforge.net RPy embeds the R stats environment within Python. R is good for most things statistical, from the elementary to the advanced and experimental, and it does truly beautiful graphics. It is a mature project backed by a number of eminent statisticians in five continents. Note that R is multi-platform (see http://www.r-project.org ) but RPy only works under Linux and Unix (and Mac Os X, perhaps) at this stage. I believe a Windows version is in the works. Tim C From senux at senux.com Sun Jun 2 01:09:09 2002 From: senux at senux.com (Brian Lee) Date: Sun, 2 Jun 2002 14:09:09 +0900 Subject: writing to a file (atomic operation) Message-ID: <20020602050909.GA7192@mercury.senux.com> Is this a atomic operation? open('/tmp/test.log', 'a').write('test\n') from py newbie. -- ____ |o | i / Brian Lee #######|< Web - http://www.senux.com/en/ (x-x-x-x) \ GnuPG public key - 0x46C763A3 From peter at engcorp.com Tue Jun 18 21:09:09 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 18 Jun 2002 21:09:09 -0400 Subject: xml fo->pdf processor wanted References: Message-ID: <3D0FD9B5.5A91B1F4@engcorp.com> Johannes Zellner wrote: > > Hi, > > is there a fo (formatting object) to pdf converter in python? I'm pretty sure there is not (yet). You could probably just call out to Java and run FOP though. http://xml.apache.org/fop It would be nice to see something put together from PyXML and ReportLab. I'm a little surprised no enterprising (and totally psychotic :-) soul has announced such a thing yet... -Peter From logiplexsoftware at earthlink.net Mon Jun 24 13:29:46 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Mon, 24 Jun 2002 10:29:46 -0700 Subject: How to represent the infinite ? In-Reply-To: <3d160e45@news.swissonline.ch> References: <3d11ee9b$1@news.swissonline.ch> <20020620.124436.1266235189.32516@software1.logiplex.internal> <3d160e45@news.swissonline.ch> Message-ID: <20020624102946.5dbf92f5.logiplexsoftware@earthlink.net> On Sun, 23 Jun 2002 20:06:37 +0200 erreur wrote: > Thanks.... excelent !! Thanks for replying. Sometimes when no one responds to the bits of code I post I worry that perhaps people don't say anything because my code was just too lame to comment on, but then I remember that it's really because I'm a total and I feel better ;) > "Cliff Wells" wrote in message > news:20020620.124436.1266235189.32516 at software1.logiplex.internal... > > In article , "Cliff Wells" > > wrote: > > > > > > > > > On Thu, 20 Jun 2002 17:02:33 +0200 > > > erreur wrote: > > > > > >> Will somebody have an idea, to represent the infinite one? I have > > >> variables to initialize with is +inf (or - inf). To be sure that > > >> later, all will be smaller (or larger) than my variables. I tried to > > >> redefine the operators on an object. It goes for Inf>10 but I do not > > >> arrive for 10>Inf (because that takes > of Int). -------------------- > > >> def __gt__(self, val): [snip] -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From dreed at capital.edu Sun Jun 23 12:06:05 2002 From: dreed at capital.edu (Dave Reed) Date: Sun, 23 Jun 2002 12:06:05 -0400 Subject: (Newbie) Counting Instances ("Hits") with Regular Expressions In-Reply-To: (emile@fenx.com) References: <3d15e215.43448155@news.texas.net> Message-ID: <200206231606.g5NG65117471@localhost.localdomain> > From: "Emile van Sebille" > > "Ben Fairbank" wrote in message > news:3d15e215.43448155 at news.texas.net... > > I am new both to Python and to regular expressions, which may account > > for my difficulty. I must count the frequenies of certain words in > > files of moderate length (about150 k bytes). I have been reading > > files and then using count(s,sub), which is fast and easy. I now have > > to allow for punctuation and eliminate words within words, etc, and so > > am trying to use regular expressions instead of simple words as > > targets. I do not, however, find a similarly easy to use count > > function in the re module. Yet this is such common operation it must > > be there, or easy to implement. What is the usual way of simply > > counting "hits" in the re module? (And what have I missed in the > > documentation; where is this to be found? I have looked through Lutz > > and Ascher) > > > > >>> s = 'spam and eggs and ham and eggs and spam and eggs' > >>> s.count('am') > 3 > >>> I don't think he wants to count those, only ' am ' There is a much easier solution than what I originally posted: import re s = 'the word is the word but not a keyword' re.findall('\sword\s') outputs: [' word ', ' word '] so len(re.findall('\sword\s') will do what he wants Dave From bokr at oz.net Sat Jun 22 14:43:50 2002 From: bokr at oz.net (Bengt Richter) Date: 22 Jun 2002 18:43:50 GMT Subject: Web templating/db tool with best designer/coder separation? Message-ID: E.g., if you were hoping for an improvement over current practice, which do you consider to be the tool(s) to beat, and what would the killer improvement(s) be? TIA. Regards, Bengt Richter From gerhard at bigfoot.de Fri Jun 7 10:09:16 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Fri, 7 Jun 2002 16:09:16 +0200 Subject: Native code compiler for python? In-Reply-To: References: Message-ID: <20020607140916.GA11037@lilith.my-fqdn.de> * nobody [2002-06-07 06:50 -0700]: > Is there any existing native code compiler for python? Have you checked groups.google.com? > Or Python to C translator? Or someone is doing this? Yes, several, Pyrex among others. But they only compile a subset of Python. Is this question just motivated by interest or do you have any problem with just using the Python interpreter? Do you only want to have a standalone app without requiring an installed interpreter? freeze, McMillan's Installer and py2exe are solutions for _this_ problem. The solution for slow Python code is using a better algorithm, and if this is not possible, writing the innermost loops in C/C++/Fortran/Ada (even Ocaml is possible, IIRC). Using Pyrex might become a possible solution, too. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From edream at tds.net Tue Jun 25 11:04:56 2002 From: edream at tds.net (Edward K. Ream) Date: Tue, 25 Jun 2002 15:04:56 GMT Subject: ConfigParser & converting strings to lists References: <3D152A28.2177B054@tds.net> <3D159F06.2154D3F3@tds.net> Message-ID: <3D188696.1694EE9F@tds.net> > P.S. Do you have an Erdos number? I've never talked to anyone who actually > has one (that I know of). One of my teachers, Chuck MacCluer, http://www.mth.msu.edu/~maccluer/, has an Erdos number of 1, I think. He once distributed a small proof of mine, but it almost certainly never got published. Thanks for asking. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From whisper at oz.net Mon Jun 17 19:15:40 2002 From: whisper at oz.net (David LeBlanc) Date: Mon, 17 Jun 2002 16:15:40 -0700 Subject: Medusa Questions Message-ID: I'm using the latest Sourceforge distro of Medusa and have some questions. Is there any documentation on writing extensions? Is there any documentation on using the demos, in particular the "script_server"? Is the asynccore C extension still usable? BTW, I would have asked on the Yahoo group for Medusa, but didn't want to subscribe to a group that's literally 95%+ spam. You ought to set your group to subscribers-only posting. TIA, David LeBlanc Seattle, WA USA From aahz at pythoncraft.com Fri Jun 28 19:11:55 2002 From: aahz at pythoncraft.com (Aahz) Date: 28 Jun 2002 19:11:55 -0400 Subject: squared functions--most Pythonic way? References: Message-ID: In article , Luigi Ballabio wrote: > > suppose we want to define a function which, given f(x), returns >its square. There are a number of ways which come to mind, such as: > >object-oriented programming: > > def fsquare: > def __init__(self,f): > self.f = f > def __call__(self,x): > return self.f(x)**2 > >functional programming: > > # with an internal named function > def fsquare(f): > def f2(x): > return f(x)**2 > return f2 I'm sensing an ill-defined spec here. To me, your English sentence implies that what's wanted is def fsquare(f, x): return f(x)**2 but both of your examples define closures of some sort. Assuming that your code does what you really want, I don't think either of these two is "more Pythonic"; it depends on your circumstances and who your likely code readers are going to be. I don't have much functional experience, so the OO mechanism works better for me (particularly given that it works back to 1.5.2). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From gerhard.haering at gmx.de Fri Jun 21 03:59:38 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Fri, 21 Jun 2002 09:59:38 +0200 Subject: compile python witout tkinter In-Reply-To: References: <20020621074746.GA765@lilith.my-fqdn.de> Message-ID: <20020621075938.GA896@lilith.my-fqdn.de> * kosh at aesaeion.com [2002-06-21 01:40 -0600]: > On Fri, 21 Jun 2002, Gerhard [iso-8859-15] H?ring wrote: > > > * kosh at aesaeion.com [2002-06-21 01:26 -0600]: > > > On a machine I need to build python on I need to build it without tkinter. > > > > Why? Even if Tkinter gets compiled, it doesn't change anything for the > > rest. You could even delete the tkinter modules afterwards, if you're > > short on disk (quota). > > Because the libraries it depends on are not installed on that machine and > there is no point installing them since they are not needed. No problem, then. It won't get built if the dependencies are not met. As seen in Modules/Setup. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 23.7 ?C Wind: 4.0 m/s From mjackson at wrc.xerox.com Thu Jun 27 09:35:21 2002 From: mjackson at wrc.xerox.com (Mark Jackson) Date: 27 Jun 2002 13:35:21 GMT Subject: question od default args References: Message-ID: "Fredrik Lundh" writes: > Gon?alo Rodrigues wrote: > > > When I want default args I usually do > > > > def (arg = None): > > ... > > > > But what if I want to make None a reasonable argument too? That is, I > > want to know if the user has in fact passed an argument, and if not to > > do something special, with None (or whatever object) being a reasonable > > arg to be passed. > > hmm. wasn't this just discussed in some thread on a > newsgroup near you? > > three alternatives: > > __UNDEF__ = [] # guaranteed to have a unique id > > def myfunc(arg=__UNDEF__): > if arg is __UNDEF__: > print "no argument" > else: > ... More quickly: def myfunc(arg=[]): if arg is myfunc.func_defaults[0]: print "no argument" else: ... -- Mark Jackson - http://www.alumni.caltech.edu/~mjackson Until we test our beliefs, we can't say for sure if we have leeches or we have aspirin. - David Faigman From sholden at holdenweb.com Thu Jun 6 09:55:54 2002 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 6 Jun 2002 09:55:54 -0400 Subject: Pipe return mesage from spawnv to string? References: <3ebec3ea.0206060443.d2cc5bb@posting.google.com> Message-ID: "Stefhan Stj?rn?s" wrote in message news:3ebec3ea.0206060443.d2cc5bb at posting.google.com... > Hi! > > Anyone who knows how to pipe from spawnv? > I start isql.exe with os.spawnv and must see the result. > > run ("isql.exe"," -s ....") > > def run (program, *args): > """Executes program with arguments, using os.spawnv""" > try: > return os.spawnv(os.P_WAIT,program, (program,) +args) > except (os.error), why: > raise SErr, str(why) > Well in that case you want popen*(), not spawn*(). Whether you use popen(), popen2(), popen3() or popen4() will depend on your needs. if-you-need-a-pipe-then-open-one-ly y'rs - steve ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From ark at research.att.com Fri Jun 7 13:47:37 2002 From: ark at research.att.com (Andrew Koenig) Date: Fri, 7 Jun 2002 13:47:37 -0400 (EDT) Subject: Python 2.2.1 vs. gcc 3.1? In-Reply-To: <15616.57963.519636.730290@12-248-41-177.client.attbi.com> (message from Skip Montanaro on Fri, 7 Jun 2002 11:42:19 -0500) References: <15616.57963.519636.730290@12-248-41-177.client.attbi.com> Message-ID: <200206071747.g57HlbH01057@europa.research.att.com> PPS: I tried building one of the .so files by hand, essentially by snarfing the output from the Makefile log and executing it manually: $ gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -I. -I/tmp/build-python/Python-2.2.1/./Include -I/usr/local/include -IInclude/ -c /tmp/build-python/Python-2.2.1/Modules/structmodule.c -o build/temp.solaris-2.8-sun4u-2.2/structmodule.o $ gcc -shared build/temp.solaris-2.8-sun4u-2.2/structmodule.o -L/usr/local/lib -o build/lib.solaris-2.8-sun4u-2.2/struct.so $ ldd build/lib.solaris-2.8-sun4u-2.2/struct.so libgcc_s.so.1 => /usr/gnu/lib/libgcc_s.so.1 libc.so.1 => /usr/lib/libc.so.1 libdl.so.1 => /usr/lib/libdl.so.1 /usr/platform/SUNW,Ultra-5_10/lib/libc_psr.so.1 So apparently it is building a .so file with references correctly resolved. How do I go about finding out the cause of the failure? From tdelaney at avaya.com Sun Jun 23 21:50:06 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Mon, 24 Jun 2002 11:50:06 +1000 Subject: Python hits the spot Message-ID: > From: Peter Hansen [mailto:peter at engcorp.com] > > Aahz wrote: > > > > In article <3d149f19$0$53133$edfadb0f at dspool01.news.tele.dk>, > > Frihtiof Andreas Jensen wrote: > > > > > >My bet is that once you cool off and sits down with some > debugging tools > > >like GDB, Boundschecker or Electric Fence you will indeed find the > > >programming error and fix it. > > > > > >My bet is also that you will not tell anyone either. > > > > Ya know, you could have saved yourself a lot of typing by > simply saying > > PBCAK. ;-) > > To save us from those who can't Google: Problem Between > Chair And Keyboard. That's always been PEBCAK to me ... ^ Problem Exists Between Chair and Keyboard Tim Delaney From donn at u.washington.edu Thu Jun 20 13:52:38 2002 From: donn at u.washington.edu (Donn Cave) Date: 20 Jun 2002 17:52:38 GMT Subject: How to represent the infinite ? References: <3d11ee9b$1@news.swissonline.ch> <20020620193230.53d58f8f.christophe.delord@free.fr> Message-ID: Quoth Christophe Delord : | | There is another simple solution. Just use a float that is bigger than any 64-bit float. For example 10^1000. This float has a special encoding meaning +oo ! | So no need to redefine anything else ;-) | | >>> x=1e1000 | >>> x | inf ... | >>> x-x | nan $ python Python 2.0 (#1, Dec 18 2000, 10:19:52) [C] on osf1V4 Type "copyright", "credits" or "license" for more information. >>> x = 1e1000 >>> x 1.7976931348623157e+308 >>> x > 10 1 >>> x - x 0.0 >>> I missed the original post, hope this helps. Donn Cave, donn at u.washington.edu | > Not need to say to me that I can use 99999999999999 or -99999999999999 or I | > do not know what. | > Nor from a MAX_INT of the machine... bus Python can go higher. | > | | | | | -- | | (o_ Christophe Delord _o) | //\ http://christophe.delord.free.fr/ /\\ | V_/_ mailto:christophe.delord at free.fr _\_V From benjl at cse.unsw.edu.au Sat Jun 1 20:39:07 2002 From: benjl at cse.unsw.edu.au (Benno) Date: 1 Jun 2002 17:39:07 -0700 Subject: wxPython performance References: Message-ID: <332c7c11.0206011639.a396f84@posting.google.com> Andrei Kulakov wrote in message news:... > Hello, > > "hello world" type program from wxPython tutorial takes 6 > seconds to start on my cel 366 128mb system (running Debian). Is > this typical? Why is it so slow? I'm looking for a graphic > toolkit that'd be fairly quick. I don't want to use Tk because of > the looks. I was using wxPython for a while. The main advantage being that it was going to be cross platform, however I found its speed too slow. (Not startup speed, which is fairly irrelevant to me, but just general responsiveness.) I'm not sure if this was just wxWindows itself or the python bindings. I have started using pygtk (easily apt-getable). The only problem I've had with this is the lack of docs. http://www.moeraki.com/pygtktutorial/gtk-tut.html, seems to be the best available, followed by reading the source. Cheers, Benno From quinn at retch.ugcs.caltech.edu Thu Jun 27 13:51:47 2002 From: quinn at retch.ugcs.caltech.edu (Quinn Dunkan) Date: 27 Jun 2002 17:51:47 GMT Subject: Questiion on list References: Message-ID: On Thu, 27 Jun 2002 15:32:28 +0000, SiverFish wrote: >On Thu, 27 Jun 2002 05:11:06 +0000, Quinn Dunkan wrote: > >> On Thu, 27 Jun 2002 14:36:03 +0000, SiverFish >> wrote: >>>I got the list of words now i want to calculate how many word in that >>>list which is the same word (insensitive case),can anyone show me how to >>>do it for example ls = ['abc','cd','abc','adf',abc','dwc','cd'] it will >>>show abc = 3 ,cd = 2, adf = 1, dwc=1 >> >> import string >> d = {} >> for e in map(string.lower, ls): >> d[e] = d.get(e, 0) + 1 >> freqs = [ (count, w) for w, count in d.items() ] freqs.sort() >> freqs.reverse() >> print ', '.join([ '%s = %d' %(count, w) for count, w in freqs ]) > >Could you do it in python 1.5.2 and explain clearly to me please The English version is "use a dictionary". Go through all the words and put each one in the dictionary with the value 1. If the word is already in the dictionary, increment the value. When you are done, you have a dict mapping words to frequency of occurrance. >How about we have to do the same problem here when read in the multiple >files,Thank a lot The words can come from anywhere. Just write a function that takes a list of words and returns a histogram dict as above. Then all you need to do is convert your list of files into a list of words. If you have large files and are concerned about memory usage, you could upgrade to 2.2 and investigate iterators, and pass an appropriate iterator to the function, or stay with 1.5.2 and rewrite the function to modify a dict, and then pass in smaller lists consecutively. Or just lose the function and inline the whole thing. Up to you. d = {} for fp in map(open, files): for line in fp.readlines(): for w in line.split(): d[w] = d.get(w, 0) + 1 fp.close() Of course, if you have to worry about punctuation and hyphenation, things get more complicated... From Backflip at gmx.de Tue Jun 4 04:12:35 2002 From: Backflip at gmx.de (Backflip) Date: 4 Jun 2002 01:12:35 -0700 Subject: Printing a text centered, it would be a newbie prob Message-ID: Hello World (= I?ve got a little problem, i want to put out an import string centert. For example: for word in raw_input("bitte hier ihren text eingeben:").split(): print word text=dies ist ein test now the output looks like this dies ist ein test but i want that it looks like this one dies ist ein test that both rows are simular to each other, could smb help me? Thanks Backflip From tim.one at comcast.net Fri Jun 21 18:19:25 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 21 Jun 2002 18:19:25 -0400 Subject: How to represent the infinite ? In-Reply-To: <20020621183459.63fe2e4d.christophe.delord@free.fr> Message-ID: [Christophe Delord] > ... > But addition, multiplication and exponentiation seem to be implemented > differently (1e300+1e300 is inf and 1e300**2 is an overflow). Python float + and * are done via C + and * on C doubles. Python float ** is done via C libm pow(), and x**y strives to act the same as import math math.pow(x, y) > Is there a reason for these different behaviours? Of course. The question is whether they're rational reasons <0.9 wink>. From syver-en+usenet at online.no Mon Jun 3 19:19:03 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Mon, 03 Jun 2002 23:19:03 GMT Subject: python and windows and pydoc and favorite editor == True References: Message-ID: "J?rgen Hermann" writes: > "Syver Enstad" schrieb im Newsbeitrag > news:un0ugnxa3.fsf at online.no... > > Post if there is any interest. > > OK, post. :) > > http://home.online.no/~syver-en/software.html/files/PyDocEditorStarter.py -- Vennlig hilsen Syver Enstad From donn at u.washington.edu Tue Jun 4 17:35:34 2002 From: donn at u.washington.edu (Donn Cave) Date: 4 Jun 2002 21:35:34 GMT Subject: Behavior of += (was Re: [Python-Dev] Customization docs) References: <3CFCF3E7.AE891EBE@noaa.gov> Message-ID: Quoth "Steve Holden" : | "Donn Cave" wrote ... ... |> Not really - the current semantics are actually better than the fixed |> version, inasmuch as they are at least consistent. As I interpret the |> proposal, the fixed += would sometimes work without rebinding (if the |> object supports it) and sometimes would be an assignment (falling back |> to +.) To me, to allow an object to dictate its relationship to its |> computational environment like that is anathema. | | >>> a = b = (1, 2, 3) | >>> a += ('boo!',) | >>> a, b | ((1, 2, 3, 'boo!'), (1, 2, 3)) | >>> a = b = [1, 2, 3] | >>> a += ['boo!'] | >>> a, b | ([1, 2, 3, 'boo!'], [1, 2, 3, 'boo!']) | | Doesn't look that consistent to me. Add in the fact that implementors of | mutable objects are free to choose either semantic and what you have is ... | exactly what Guido intended. I regard it as a wart, but not one that worried | me. Well, it is consistent. Maybe not in a way that you can see and still remain sane. "Mutable" or not, it must always work like "a = iadd(a, b)", where iadd attempts to perform some computation like __iadd__() or eventually "+". The fact that __iadd__ may return any imaginable value is no queerer than the same fact about __add__. I'm not saying it's good, on the contrary, it's terrible. I just don't think it sounds very good to fix it by changing the rules so it sometimes means the above, and sometimes omits the assignment. As long as it has to work on values that don't support it as a mutating __iadd__ or equivalent, it should probably stay the way it is. Donn Cave, donn at u.washington.edu From johnroth at ameritech.net Mon Jun 24 07:36:42 2002 From: johnroth at ameritech.net (John Roth) Date: Mon, 24 Jun 2002 07:36:42 -0400 Subject: Generic Python References: <3D16E465.F0D2509E@ifib.uni-karlsruhe.de> Message-ID: "Uwe Mayer" wrote in message news:3D16E465.F0D2509E at ifib.uni-karlsruhe.de... > Hi, > > is it possible to to write a class which, f.e. takes an argument in > __init__() and that doesn't return an instance object but a new class > object? Sure, but you have to do it closer to the source level. One quibble here: you can't do it with the __init__() method, that's defined to always return an instance. You have to do it with some kind of generator or factory function. The way you do it is to create the source in a string, and then use exec. However, as another poster mentions, there may be better ways of solving your specific problem. Dynamically generating pieces of program is useful in some highly specialized circumstances, but this might not be one of them. John Roth From mwh at python.net Fri Jun 14 06:09:31 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 14 Jun 2002 10:09:31 GMT Subject: __subclasses__ References: Message-ID: jimrowe at optilink.com (James Rowe) writes: > A search for __subclasses__ on the www.python.org > documentation search pages turns up empty. I can > find not mention of it in my Python books or even > in the "What's new in Python 2.2" document. But: > > class Foo(object): > def __init__(self): > object.__init__(self) > > class Bar(Foo): > pass > > dir(Foo) # returns: > > ['__class__', '__delattr__', '__dict__', '__doc__', > '__getattribute__', '__hash__', '__init__', '__module__', > '__new__', '__reduce__', '__repr__', '__setattr__', > '__str__', '__weakref__'] Whether things show up in dir() is a bit of a lottery (think about __getattr__ methods!). Notice __bases__ isn't in there either, for example. > But there is a __subclasses__ method: > > Foo.__subclasses__() # returns: > > [] > > > So I suppose the question is: Why is __subclasses__ not documented > or listed? Dunno. Lack of time would be my guess. Lots of this stuff isn't documented. > Can we safely use __subclasses__ and not worry about it "going away" > in the future? Well the implementation needs to have access to the functionality it provides (I think this is for situtations like: class a(object): pass class b(a): pass a.__getitem__ = some_meth b()[1] should now invoke some_meth but I'm not sure). This doesn't mean that the current exposure of the functionality to Python code is not going to disappear or change in spelling, but I'd say it was pretty unlikely. Cheers, M. -- It's actually a corruption of "starling". They used to be carried. Since they weighed a full pound (hence the name), they had to be carried by two starlings in tandem, with a line between them. -- Alan J Rosenthal explains "Pounds Sterling" on asr From rkr1410 at poczta.onet.pl Sun Jun 23 12:32:58 2002 From: rkr1410 at poczta.onet.pl (hellboy) Date: Sun, 23 Jun 2002 18:32:58 +0200 Subject: Newbie question (anyone programming with curses?) References: Message-ID: Emile van Sebille wrote: > No one has made a Windows port of the curses module. On a Windows > platform, try the Console module 8<--cut--8< So there is no way to get fast console input/output + colors in text mode and code portability? btw. there actually is a windows implemetation of curses (http://pdcurses.sourceforge.net), but it is written in c (of course) and I am too inexperienced to say if there is some way of incorporating it into python, and how to do it.... From pyth at devel.trillke.net Fri Jun 7 19:46:58 2002 From: pyth at devel.trillke.net (holger krekel) Date: Sat, 8 Jun 2002 01:46:58 +0200 Subject: Efficient python programming... In-Reply-To: <3D013F11.F25FFA72@engcorp.com>; from peter@engcorp.com on Fri, Jun 07, 2002 at 07:17:37PM -0400 References: <3D00A456.4315EDA3@engcorp.com> <3D013F11.F25FFA72@engcorp.com> Message-ID: <20020608014658.G6609@prim.han.de> Peter Hansen wrote: > holger krekel wrote: > > Peter Hansen wrote: > > > You forgot the even more important first thing for a beginner: > > > get it correct! The only good way to do this is to write unit > > > tests that prove it. If you don't have tests, you don't have > > > working code (or how can you prove it?). > > > > yeah. writing tests is *the way* to go if you want other people use > > your code. Although successfull unittests theoretically don't prove > > anything they tend to do in reality. > > Could you explain why you think unittests don't prove anything > when they are successful? I meant to play with the academic notion ('theoretically') of proving algorithms to be correct. From a stricter perspective unittests are just examples and examples do not prove anything. But 'in reality' they do prove that intended usage of an API basically works and nothing broke while fixing bugs or adding new features. > Are you pointing out that if you write a test after the code > and the test passes, you have learned almost nothing? I agree > with that. > > With Test-Driven Development, however, you write the test first, > run it immediately, and ensure that it fails. Only after you > have code that makes it pass are you done. > > In this case, making sure the test fails when the code is wrong, > wouldn't you say that the test mostly proves that the code works? *Mostly*, yes. Unfortunately mathematicians impose a boolean view regarding proofs on us poor coders: proven or not proven. > (Not quibbling about the fact you are still not 100% sure...) which was the whole point of my posting :-) holger From jepler at unpythonic.net Tue Jun 25 10:10:36 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 25 Jun 2002 09:10:36 -0500 Subject: Thread Memory Leak In-Reply-To: References: Message-ID: <20020625141035.GC4435@unpythonic.net> On Tue, Jun 25, 2002 at 09:37:12AM -0300, Marco Catunda wrote: > Hello, > > I've developed a python program with some threads. > This program is a daemon server. I have seen the > memory of that program growing very fast in a short > period of time. So I decided to make a little program > to see what's happen. I see memory grow slowly over time on a RedHat 7.3 system with Python 2.3a0 CVS. The memory numbers are erratic, but at the start they are in a range 3000-13000 VSZ. At the end of the run I did, the numbers seemed to have grown to 6000-18000 VSZ. I did not see this growth on a RedHat 6.2 system with Python 2.1. Since both the OS and Python versions varied between these two systems, I can't say which is at fault. Jeff From d2002xx at myrealbox.com Wed Jun 19 02:54:21 2002 From: d2002xx at myrealbox.com (d2002xx) Date: 18 Jun 2002 23:54:21 -0700 Subject: Create a JIT compiler for python Message-ID: <8d3f4438.0206182254.203fce42@posting.google.com> Hello! I want to create a jit compiler for python. Although I don't yet register the CVS and website, if you want to join or give me any opinions, please e-mail to me: mailto:d2002xx at myrealbox.com *NOT* send to the USENET, because my ISP doesn't provide me NNTP server, using Google is too slow. From theller at python.net Wed Jun 19 10:28:11 2002 From: theller at python.net (Thomas Heller) Date: Wed, 19 Jun 2002 16:28:11 +0200 Subject: imp.loadmodule creates compiled file References: Message-ID: "Neil Hodgson" wrote in message news:zv%P8.332187$o66.856939 at news-server.bigpond.net.au... > I've been using imp.loadmodule with Python 2.2 (on both Windows and > Linux) to load changed versions of source code into a long running process > where they will run alongside objects already created from earlier versions > of the source code. An unexpected result of the call is to create a compiled > module on disk with a name based on the filename argument with "c" appended. > There has been a thread named "Importing a module without creating a .pyc/.pyo file?" recently. I'm not sure this link will work, otherwise search google yourself. http://groups.google.com/groups?hl=de&lr=&ie=UTF8&oe=UTF8&safe=off&th=5a6c36264f7b6d07&rnum=65 IIRC, there have been several useful suggestions. Thomas From david.abrahams at rcn.com Fri Jun 14 21:53:01 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Fri, 14 Jun 2002 21:53:01 -0400 Subject: SWIG and Callbacks References: <3d0a8b6e@nntp.server.uni-frankfurt.de> Message-ID: "Michael 'Mickey' Lauer" wrote in message news:3d0a8b6e at nntp.server.uni-frankfurt.de... > I had a quick look at the other wrappers (SILOON, GRAD, CXX, etc.) > but most look either outdated or not appropriate for this task. > Do you know an (automatic) wrapper generator which has this feature? > > I know sip can do this for c++ libraries - can sip also be used > to wrap plain c-libs without "handwriting" code? On most platforms, Boost.Python would work for you. The determining issue is whether or not the C++ compiler treats "C" and "C++" linkage function pointers the same way. If the appended program will compile with your C++ compiler, you're probably OK: -Dave extern "C" void f() {} void g(void (*)()); int main() { g(f); return 0; } From opus at value.net Sun Jun 30 03:40:22 2002 From: opus at value.net (Opus) Date: Sun, 30 Jun 2002 00:40:22 -0700 Subject: Python needs better error reporting In-Reply-To: <3D1EAF12.84CE5914@cascade-sys.com> Message-ID: <3D1E5376.32716.DF5C94@localhost> I would normally support a more verbose parser for a language. I fully believe that if the thing can tell you there is an error, it should be able to show some proof, and help you out. This being said, the fact that this is not a compiled language (it still needs to read the source file to make sure it is up to date), a verbose parser would slow it down. At the most, I might suggest that there be an option to run just the parser, with more verbose output. Maybe even a different parser would be in order. Idea for anyone???? True, the language definition of Python is nice and clean, it would be nice to see a pre-parser written for it, in it. If it passes, it could even call Python to write out a .pyc file. Maybe even an option for the parser to spot bad-practice code. I.E. Is is faster to call 'var += 1' or 'var = var + 1'. Maybe even one that gives you O analysis of your code. That would be really nice. Could not only play with some code to opomize speed before you use it. On 30 Jun 2002 at 0:11, James J. Besemer wrote: > > I rather think Dave has a good point. > > A better parser could give a more informative diagnostic in this case and I > suspect others. > > Tim Peters wrote: > > > Well, "xor" isn't legit there, but other tokens that are OK after > > > > if s == ' ' > > > > include > > > > [a ong list] > > The question is NOT be what all may follow the string literal. Rather it should > be what tokens are legal between the string literal and end of line? Very > different questions. > > If I'm not mistaken, only ":" or "\" are legal in that narrow context. While > additional tokens may be legal in terms of following the string literal, they > still result in an error, so there's no point in listing them. Line > continuation is a special case all its own. Either it's illegal for some > reason, in which that situation constitutes a diagnostic all its own. Otherwise > it can be completely ignored, as any errors/diagnostics would involve the next > following token, not the line continuation itself. > > So it would be perfectly reasonable for the parser to say "semicolon missing" or > "semicolon expected" in this case. > > Whether or not it's worth the effort to implement is, as always, debatable and > furthermore, I suppose, moot unless somebody is offering to do the work. > > Regards > > --jb > > -- > James J. Besemer 503-280-0838 voice > http://cascade-sys.com 503-280-0375 fax > mailto:jb at cascade-sys.com > > > > > -- > http://mail.python.org/mailman/listinfo/python-list --Opus-- You can't tell me what sucks! - Beavis, a true Objectivist. -------------------------------------------------------- Get added to my Humor list: mailto:opus at value.net?subject=ADD_HUMOR Get added to my Neat list: mailto:opus at value.net?subject=ADD_NEAT Get my PGP public key: mailto:opus at value.net?subject=PSEND&body=send%20PublicKEY.asc Visit My Home Page: http://value.net/~opus/ From johnroth at ameritech.net Sun Jun 30 20:05:23 2002 From: johnroth at ameritech.net (John Roth) Date: Sun, 30 Jun 2002 20:05:23 -0400 Subject: Python needs to explain parsing? was Re: Python needs better error reporting References: <3D1F8843.8080602@ix.netcom.com> Message-ID: "Antaeus Feldspar" wrote in message news:3D1F8843.8080602 at ix.netcom.com... > After reading the thread spun out of all of this, this brings up an idea > that I've had for quite some time: can the Python interpreter be made > to report more information about *how* it is parsing the syntax it finds? > > For instance, given the valid line "if s == ' ':" it might return > something like the following (or at least this might be what is > displayed to the user based on information the parser displays): > > if : ---- [next 8 lines of code] > | > == > / \ > / \ > s ' ' > > thus confirming that what was meant to be a condition is being parsed as > a condition. Clearly if the user sees that the parser is putting the > block of code to be conditionally executed in where the condition should > be, that's a very visual sign of trouble... > > It's not quite the solution David seems to be looking for, but I think > it would address the same problem; is it possible? Frankly, "expecting found " for reasonably intuitive values of and can tell a moderately experienced programmer a great deal. It does very little for novices, however. Except that with a little experience, most people discover that they make the same mistake, over and over again. Then the same error message is helpful, even if it means little to anyone else. John Roth From mcherm at destiny.com Mon Jun 24 09:40:31 2002 From: mcherm at destiny.com (Michael Chermside) Date: Mon, 24 Jun 2002 09:40:31 -0400 Subject: I'd give up Perl tomorrow if only... Message-ID: <3D17214F.5000902@destiny.com> Michael Chermside wrote: > Where can I find the pyperl module? Gerhard H?ring responded: > Google - Enter "pyperl" - then hit "I feel lucky" :-) > > This will bring you to > http://www.cpan.org/modules/by-module/LWP/GAAS/pyperl-1.0.readme which looks to > a non-Perl guy like me that its available as a CPAN module. Well, I had tried that, but (not being a perl kind of guy) I'm not really sure what a CPAN module is or how to obtain or download it. I DID find some version of pyperl at ActiveState (yeah, ActiveState!), but couldn't (in the brief amount of time I spent on it) figure out how to set it up. What I WAS able to figure out has been written up at http://www.faqts.com/knowledge_base/view.phtml/aid/17202/fid/1102 If anyone else can help more, let me know. -- Michael Chermside From sholden at holdenweb.com Mon Jun 3 07:51:56 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 3 Jun 2002 07:51:56 -0400 Subject: socket module and broadcasts ? References: <3CF780D6.DFEDCFB7@ipm.fhg.de> <3CFB14B9.CF8FAA4B@ipm.fhg.de> Message-ID: OK, in that case a read of http://www.mcmillan-inc.com/sock1.html will be helpful for general background if you aren't used to socket programming. But that's more useful for TCP. What you need is for your server to listen on a UDP port, and have the clients do a local broadcast to that UDP port at IP address 255.255.255.255 (which most routers will ignore, since that address is intended for LAN only communications). The sequence of actions required at the server is 1. Create the socket 2. Bind it to appropriate address(es) 3. Use a recvfrom() call to wait for client broadcasts. The sequence of actions required at the client is 1. Create the socket. 2. Bind it to appropriate address. 3. Use sendto() to broadcast for the server. Once the server sees the client broadcast it know the client's IP address, and can use sendto() to return a resposne which will, in turn, give the client the server's address when it executes a recvfrom(). Hope this helps. regards -- ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- "Markus von Ehr" wrote in message news:3CFB14B9.CF8FAA4B at ipm.fhg.de... > Hi Steve, > > > Steve Holden wrote: > > > Do you really want your server to have top > > listen for broadcasts from potential clients? > > that is exactly what I want to do. > > > What if the server and the > > client are of different IP networks? > > I assume that they are both in the same network, but the server is > on an embedded system and initially it can be that its IP address is > unknown, so I want to query for the server and assign an IP address. > > Markus > From sholden at holdenweb.com Wed Jun 19 11:02:42 2002 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 19 Jun 2002 11:02:42 -0400 Subject: simple socket redirector app question References: <5DrP8.25$OT1.34057@newsfeed.slurp.net> Message-ID: "Michael Gilfix" top-posted the code ... > I think SocketServer is a good choice for this. SocketServer is > aimed at providing a easy to drop-in infrastructure for apps that > don't require any complicated server setup. SocketServer would make > this quick and compact. Essentially you just want to read from one > socket and write to the other. Via inhertiance you could construct > a bridge class that contains two socket servers and talks between > them... > > -- Mike > > On Mon, Jun 17 @ 13:27, Bruce Edge wrote: > > I have an app which talks via sockets to local host clients only. > > I'd like to get at it remotely. > > > > Basically it would accept remote connections from a remote client, > > relay them the the local app, and forward the replies back to the > > remote client. > > > > What's the simplest way to write this type of a socket redirector? > > > > Use SocketServer, or is that overkill? > > There's also a suitable proxy in the Medusa distribution, available from Sam Rushing's nightmare.com site. Here's a slightly-modified copy I used in "Python Web Programming". It's perhaps a bit more general than you really need, but I founf it an excellent demonstration of asyncore's operation. regards Steve ----------------------------- Code Follows ---------------------------- import asynchat import asyncore import socket import string class proxy_server(asyncore.dispatcher): def __init__(self, host, port): asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() self.there =(host, port) here =('', port + 8000) self.bind(here) self.listen(5) def handle_accept(self): proxy_receiver(self, self.accept()) class proxy_sender(asynchat.async_chat): def __init__(self, receiver, address): asynchat.async_chat.__init__(self) self.receiver = receiver self.set_terminator(None) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.buffer = '' self.set_terminator('\n') self.connect(address) def handle_connect(self): print 'Connected' def collect_incoming_data(self, data): self.buffer = self.buffer + data def found_terminator(self): data = self.buffer self.buffer = '' print '==>(%d) %s' %(self.id, repr(data)) self.receiver.push(data + '\n') def handle_close(self): self.receiver.close() self.close() class proxy_receiver(asynchat.async_chat): channel_counter = 0 def __init__(self, server,(conn, addr)): asynchat.async_chat.__init__(self, conn) self.set_terminator('\n') self.server = server self.id = proxy_receiver.channel_counter proxy_receiver.channel_counter = proxy_receiver.channel_counter + 1 self.sender = proxy_sender(self, server.there) self.sender.id = self.id self.buffer = '' def collect_incoming_data(self, data): self.buffer = self.buffer + data def found_terminator(self): data = self.buffer self.buffer = '' print '<==(%d) %s' %(self.id, repr(data)) self.sender.push(data + '\n') def handle_close(self): print 'Closing' self.sender.close() self.close() if __name__ == '__main__': import sys import string if len(sys.argv) < 3: print 'Usage: %s ' % sys.argv[0] else: ps = proxy_server(sys.argv[1], string.atoi(sys.argv[2])) asyncore.loop() ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From bokr at oz.net Wed Jun 26 22:01:35 2002 From: bokr at oz.net (Bengt Richter) Date: 27 Jun 2002 02:01:35 GMT Subject: Most efficient way to write data out to a text file? References: <3d1a6993.248534625@netnews.attbi.com> Message-ID: On Thu, 27 Jun 2002 01:28:22 GMT, candiazoo at attbi.com wrote: >I assume some sort of block i/o or preallocating a large block of file space >would be the best way to do it? I am outputting about 700,000 records to a text >file and my program only spits out about 20 records per second. This is using >standard file open and write... > >This is on a W2K machine... perhaps I should use the win32file interface? Any >thoughts/opinions? > I doubt that that is the solution. Where are your "records" coming from and/or how are they being generated/mdified, and how big are they? If you are building string records by s='' followed by s+='chunk' or the like many times, this is a typical newbie performance killer. Try accumulating your chunks in a list, like sl=[] followed by sl.append('chunk') instead, and then do f.write(''.join(sl)) instead of the f.write(s) you would have done. Just guessing... Try timing generation of output data vs writing it, and see what's happening. import time and use clock() to get an accurate floating point seconds time reading. E.g., from time import clock tstart = clock() # ... generate an output record here tendgen=clock() # ... write the output something like f.write(record) here tendwrite=clock() print """\ generating took %f sec outputting took %f sec""" % (tendgen-tstart, tendwrite-tendgen) Regards, Bengt Richter From phlip_cpp at yahoo.com Fri Jun 14 00:47:14 2002 From: phlip_cpp at yahoo.com (Phlip) Date: 14 Jun 2002 04:47:14 GMT Subject: More Tkinter Help please... References: Message-ID: David LeBlanc wrote: > Code comes up for me, but has other bugs I'm not able to diagnose. My theory may be right, and the OP's User-Agent, Microsoft-Entourage/10.0.0.1309, might be converting spaces to (4) tabs at paste time. -- Phlip http://www.greencheese.org/EvolutionaryPsychology -- It's a small Web, after all... -- From johnroth at ameritech.net Wed Jun 5 17:15:59 2002 From: johnroth at ameritech.net (John Roth) Date: Wed, 5 Jun 2002 17:15:59 -0400 Subject: Behavior of += (was Re: [Python-Dev] Customization docs) References: <3CFE6B13.79CA4A8C@noaa.gov> Message-ID: "Chris Barker" wrote in message news:3CFE6B13.79CA4A8C at noaa.gov... > John Roth wrote: > > I don't see a compatability issue here, because > > the current behavior raises an exception. > > Unless someone did the perverse thing I proposed in a earlier post, and > took advantage of the fact that the operation did, in fact, work, even > though it raised an exception! That's perverse enough that whoever does it deserves for their program to fail on an upgrade. > While I completely agree with Huaiyu's argument (though I'm not sure the > "increment with re-binding" is really all that useful for mutables), and > I think the current semantics is a minor wart, I am convinced that the > original behavior that started this thread is a MAJOR WART (I'd call it > a bug). I think I have a pretty good understanding now of why it > happens, and why it isn't trivial to change, but I think it is a very > bad idea for an operation to raise an exception, but also be successful! > > Chris > I thoroughly agree. Operations like += should be atomic - they should either succeed or fail. The remaining question is simply whether it goes to the bug list or to a PEP. John Roth From warlock at eskimo.com Fri Jun 7 20:35:51 2002 From: warlock at eskimo.com (Jim Richardson) Date: Fri, 7 Jun 2002 17:35:51 -0700 Subject: Detecting OS and Window Manager References: Message-ID: <7hjrda.ilm.ln@127.0.0.1> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Fri, 07 Jun 2002 00:34:30 +0100, Darren Winsper wrote: > In , Sean 'Shaleh' Perry > wrote: > >> the only fool proof way to detect KDE, GNOME, etc is to check for X atoms. The >> bigger question is why do you care? As long as they can display a GUI you >> should not be bothered about which one it is. Especially under the X Window >> System it was designed so that random applications DIDN'T know what they were >> running under. > > As the person writing the KDE front-end to the mentioned application, let > me answer your question. The idea is that if the user is running KDE, > then they get a KDE front-end by default. I also hope that should > somebody write a GTK/GNOME front-end, if the user was running GNOME they > would get a GTK-based front-end by default. It's good UI design. > >> Also remember KDE is not a window manager, it is a desktop environment. It is >> perfectly reasonable to run KDE and use fvwm (or even twm) as the window >> manager. Same applies to GNOME. > > OK, Andrew meant DE instead of window manager, but it's still a valid > question. > >> Also, what about someone who only runs say >> Window Maker and never uses GNOME or KDE? > > Well, in that case we just choose a default. The thing is, we want to > detect if PyKDE is installed. If it is, then we can do "import kdecore" > without risk of it throwing an exception. If it isn't, I'd rather not > have to try something along the lines of attempting "import kdecore" and > then having to catch an exception if it's not found. > But the only way to see if PyKDE is installed, is to check it, KDE doesn't require PyKDE, you can't assume that PyKDE will be present simply because someone is running KDE. About the only way I can see you toing this, is with a whole lot of try/fail checks, and even then, if someone is running something other than KDE/Gnome, you will be back to the default. Why not start the default front end first time, then ask the user what front end they would prefer, then save that to a dotfile? -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.7 (GNU/Linux) iD8DBQE9AVFmd90bcYOAWPYRAnkSAKC/z+7HbHqAUEQj53vSdOTUc2QNqACeOArx jTNFcrwH8pAs57SSjsYHiA4= =Ooz6 -----END PGP SIGNATURE----- -- Jim Richardson Anarchist, pagan and proud of it http://www.eskimo.com/~warlock Linux, from watches to supercomputers, for grandmas and geeks. From djc at object-craft.com.au Sun Jun 23 05:31:42 2002 From: djc at object-craft.com.au (Dave Cole) Date: 23 Jun 2002 19:31:42 +1000 Subject: Web templating/db tool with best designer/coder separation? References: Message-ID: >>>>> "Tim" == Tim Churches writes: Tim> Bengt Richter wrote: >> E.g., if you were hoping for an improvement over current practice, >> which do you consider to be the tool(s) to beat, and what would the >> killer improvement(s) be? TIA. If there was a clear definition of what was required in this area I suspect that there would be less attempts at building toolkits. Albatross is a design that evolved from my experience in building a collection of small but data rich intranet applications. I discovered that I was doing the same things over and over. It does not show from the release history of Albatross, but the toolkit was several years in the making. Tim> Albatross by Object Craft (see http://www.object-craft.com.au ) Tim> does an excellent job of separating the presentation layer from Tim> the underlying logic - my understanding is that such separation Tim> was one of its main design goals. However, it does not take a Tim> pedantic position on this - it still allows Python code to be Tim> embedded in HTML templates - such practice is discouraged, but Tim> Albatross provides mechanisms to allow you to do it if you Tim> insist. But more usefully, Albatross provides tags which allow Tim> conditional processing (if-elif-else) and most usefully, Tim> iteration, to be placed in the HTML template. So your Python Tim> business logic code can assemble a Python sequence of, say, Tim> database query results, but it is the HTML template which Tim> iterates through that list to create the final HTML which is sent Tim> to the user's browser. Such a feature is essential, because Tim> otherwise the business logic Python code ends up needing to Tim> creating HTML output itself, which is then merely substituted Tim> into the HTMl template. Thus, the Albatross model is really more Tim> like: "all HTML-related stuff, including conditional processing Tim> and iteration, is looked after in the HTML templates, and all Tim> business logic stuff, divorced from the manner in which it will Tim> be presented, is handled by Python modules." Of course, this is Tim> just the well-known model-view-controller approach, but Albatross Tim> implements this very nicely, IMO. See Tim> http://www.object-craft.com.au/projects/albatross/albatross/fig-presimpexec.html Tim> for more information about this (and to get an idea of the depth Tim> of the Albatross documentation). I think the biggest area which requires improvement in Albatross is still the documentation. Tim> I suspect that the Object Craft guys would welcome help with Tim> further development of Albatross. What the world really needs are Tim> more Pythonic Web applications, rather than more Pythonic Web Tim> application frameworks. People who have tried Albatross could really help us by writing beginner level instructions and by pointing out where the existing documentation is misleading. We are all too close to the code to see clearly. - Dave -- http://www.object-craft.com.au From tdelaney at avaya.com Sun Jun 2 23:33:18 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Mon, 3 Jun 2002 13:33:18 +1000 Subject: prototyping good OOdesign in Python? Message-ID: > From: Roman Suzi [mailto:rnd at onego.ru] > > >Since most of the code never /actually/ gets rewritten in C++, > >the need for special C++ "discipline" in the python code goes > >away. Weeks are slashed from the schedule, and the program is > >more maintainable. > > > >Another nice advantage is that the python programmer gets to ask > >for a raise, and has excellent job security! > > ...because only he knows the magic powers of Python? Raise (hopefully) for completing projects massively under time and budget. Security ... because they will want to hold onto someone so good. Unfortunately, this will only work for 1 or 2 projects ... after that they will *expect* you to bring everything in under time and budget ... but by then the time and budget is massively reduced because of the great results you've brought in ... :) Tim Delaney From jdhunter at nitace.bsd.uchicago.edu Sun Jun 30 10:17:33 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Sun, 30 Jun 2002 09:17:33 -0500 Subject: can't import generators References: Message-ID: >>>>> "Aahz" == Aahz writes: Aahz> Try re-downloading 2.2.1 and building in a completely new Aahz> directory. It's looking to me like you have cross-version Aahz> contamination, and that's probably the best way to test it. Thanks for your help -- I eventually figured out the problem (while working in the kitchen on something else, naturally). My PYTHONPATH still pointed to the python 2.1 libraries. Thanks again, John Hunter From dguo at ux1.cso.uiuc.edu Wed Jun 5 19:13:01 2002 From: dguo at ux1.cso.uiuc.edu (Carolyn Guo) Date: Wed, 5 Jun 2002 18:13:01 -0500 Subject: alignment excel written in Python In-Reply-To: <3CFE9861.5090200@skippinet.com.au> References: <6bd9f01b.0206050736.f469082@posting.google.com> <3CFE9861.5090200@skippinet.com.au> Message-ID: Dear all, I am new one to write something in Python. Currently I am working on writing something to Excel from Python. I have a questions now: How can I deal with the alignment of Excel from Python? for example, put the value in a cell with alignment right, or center. Thanks a lot. Carolyn From mis6 at pitt.edu Wed Jun 19 15:27:16 2002 From: mis6 at pitt.edu (Michele Simionato) Date: 19 Jun 2002 12:27:16 -0700 Subject: Tkinter and the Menu Widget References: <2259b0e2.0206190415.1f232447@posting.google.com> Message-ID: <2259b0e2.0206191127.455ba17d@posting.google.com> "Emile van Sebille" wrote in message news:... > > You've got a scope issue. Try: > > smn[key].add_command(label=submenu,command=lambda key=key, > submenu=submenu: > dosomething(key+'='+submenu)) Thanks ! This is really magic and it works !! Actually I had found another method to fix the problem by using of exec() and eval() but your suggestion is much more elegant. Thanks again, Michele From op73418 at mail.telepac.pt Sun Jun 23 10:12:29 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Sun, 23 Jun 2002 15:12:29 +0100 Subject: a Tree data-structure class? References: Message-ID: On 21 Jun 2002 06:10:30 -0700, steve at ferg.org (Stephen Ferg) wrote: >I do a lot of processing of tree-structured data, so I'm thinking it >would be useful to develop a generic Tree class that I could adapt to >various applications. Or perhaps a Tree class and a generic Node >class. > >But before I start trying to re-invent the wheel, I thought I'd ask if >anybody knows of something like this that has already been developed. > >Note that I'm not talking about a Tree GUI widget, but about a tree >data structure, like a list, a queue, etc. > >-- Steve Ferg (steve at ferg.org) I already have a module with implementations of binary and generalized trees. It is not finished yet, but I can send you what I have right now. I will try to finish it in a few days if time allows and then post the whole thing in the ActiveState cookbook. All the best, Gon?alo Rodrigues From BPettersen at NAREX.com Tue Jun 25 12:53:44 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Tue, 25 Jun 2002 10:53:44 -0600 Subject: Suggestions for good programming practices? Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192158EFB@admin56.narex.com> > From: Aahz [mailto:aahz at pythoncraft.com] > > In article , > Emile van Sebille wrote: > >Aahz > >> In Python 2.1.2 or higher, fire up the interactive interpreter and > >> type "import this". > > > >Except ActiveState's > > > >F:\Python22as>python > >Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] > on win32 > >Type "help", "copyright", "credits" or "license" for more > information. > >>>> import this > >Traceback (most recent call last): > > File "", line 1, in ? > >ImportError: No module named this > > Interesting. That's an ActiveState bug, pure and simple; > this.py is a normal module in Lib/. It's been fixed in the latest version. -- bjorn From emile at fcfw.fenx.com Sun Jun 23 12:17:28 2002 From: emile at fcfw.fenx.com (Emile van Sebille) Date: Sun, 23 Jun 2002 09:17:28 -0700 Subject: (Newbie) Counting Instances ("Hits") with Regular Expressions References: <3d15e215.43448155@news.texas.net> <200206231606.g5NG65117471@localhost.localdomain> Message-ID: <2f9701c21ad1$78616110$0a06a8c0@FENX.COM> Dave Reed > > I don't think he wants to count those, only ' am ' > > There is a much easier solution than what I originally posted: > > import re > s = 'the word is the word but not a keyword' > re.findall('\sword\s') > > outputs: [' word ', ' word '] > so len(re.findall('\sword\s') will do what he wants > >>> s = 'the word is the word, but not a keyword' >>> re.findall(r'\b(word)\b', s.lower()) ['word', 'word'] >>> -- Emile van Sebille emile at fenx.com --------- From mgilfix at eecs.tufts.edu Sun Jun 9 09:45:25 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Sun, 9 Jun 2002 09:45:25 -0400 Subject: Simple pychecker question In-Reply-To: <3D02FDE9.19198F33@engcorp.com>; from peter@engcorp.com on Sun, Jun 09, 2002 at 03:04:09AM -0400 References: <3D02FDE9.19198F33@engcorp.com> Message-ID: <20020609094525.H9486@eecs.tufts.edu> On Sun, Jun 09 @ 03:04, Peter Hansen wrote: > For a routine named and structured like this: > > def transmit(data, timeout=1.0): > > which of the following would you say was the better call > in some code that might be remote from that definition > above? > > 1. transmit('this is a string', 5) > > 2. transmit('this is a string', timeout=5) > > My point: named arguments can increase readability and > maintainability. That's not superfluous, to me. I tend to opt for the hidden defaults. Sometimes, I want to provide the users of my classes the option of intializing the class with data, or setting the data later (as in the case of a graph). So something like: def __init__ (self, data=None) def set_data (self, data) is pretty useful for me. My version of pychecker complained, which got me wondering. But if Neil says it's fixed, then I'm sure it is :) -- Mike -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From catunda at pobox.com Tue Jun 25 14:30:53 2002 From: catunda at pobox.com (Marco Catunda) Date: Tue, 25 Jun 2002 15:30:53 -0300 Subject: Thread Memory Leak References: Message-ID: Sorry, I forgot it. Plataform: Linux RedHat 7.3 Glibc: glibc-2.2.5-34 (libpthread) Python: 2.2.1 Thank you -- Marco Catunda On Tue, 25 Jun 2002 12:14:22 -0300, Tim Peters wrote: > [Marco Catunda] >> I've developed a python program with some threads. This program is a >> daemon server. I have seen the memory of that program growing very fast >> in a short period of time. So I decided to make a little program to see >> what's happen. >> ... > > Which version of Python, which OS, and which thread package? There's no > leak evident when running your program on Win2K using any of Python > 2.1.3, 2.2.1, or current CVS, so whatever you're seeing is specific to > something you haven't told us. From gleki at gol.ge Fri Jun 7 05:01:26 2002 From: gleki at gol.ge (Giorgi Lekishvili) Date: Fri, 07 Jun 2002 11:01:26 +0200 Subject: map Message-ID: <3D007666.2B6D3582@gol.ge> Hi all! Is there a way to map a function with several arguments to a list? E.g., >>>import math >>>import MLab >>>a=MLab.rand(3,5) >>>b=map(math.pow,a) of course, this doesn't work. What to do? My task is to optimize the power (i.e., y in pow(x,y)) to achieve maximal performance. thanx, Giorgi PS: Perhaps I have missed the needed functionality, that's presented in NumPy? From merkosh at hadiko.de Fri Jun 21 09:07:35 2002 From: merkosh at hadiko.de (Uwe Mayer) Date: Fri, 21 Jun 2002 15:07:35 +0200 Subject: why extending copy.* Message-ID: hi, i need shallow and deep copies of objects and I found the copy module in the reference library which does quite a good job. however, they write that one could implement the copy protocol by extending/ overwriting the __copy__() and __deepcopy__() method. since __copy__() and __deepcopy__() already duplicate the instance dictionary, __deepcopy__() even recursively. For what reasons would I want to extend /overwrite the capabilities of __copy__() or __deepcopy__ ()? From huaiyu at gauss.almadan.ibm.com Thu Jun 13 21:38:17 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Fri, 14 Jun 2002 01:38:17 +0000 (UTC) Subject: filter2 References: Message-ID: Michael Hudson wrote: >Jeff Epler writes: >> >> def filter2(test, list): >> l1 = [] >> l2 = [] >> funcs = [l2.append, l1.append] >> map(lambda x: funcs[bool(test(x))](x), list) >> return l1, l2 >> >> >>> print filter2(lambda x: x%3==0, range(16)) >> ([0, 3, 6, 9, 12, 15], [1, 2, 4, 5, 7, 8, 10, 11, 13, 14]) > >Hey, that's pretty neat! Still three function calls per element, >though. Well, four including bool, but that could be gotten rid of by >gross hacks (e.g. not not test(x)). It's not that gross, but it only gives 14% speedup, though. def filter2a(test, list): l1 = [] l2 = [] funcs = [l1.append, l2.append] map(lambda x: funcs[not test(x)](x), list) return l1, l2 BTW, what's the reason that using a list for funcs is faster than using a tuple (as observed under Python 2.2.1 on Linux)? Huaiyu From gerhard.haering at gmx.de Wed Jun 19 21:25:40 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 20 Jun 2002 01:25:40 GMT Subject: procmail replacement in Python References: <20020618235901.GA2197@lilith.my-fqdn.de> <20020619022110.GA6996@lilith.my-fqdn.de> Message-ID: Skip Montanaro wrote in comp.lang.python: > I strongly recommend SA. ACK. I've also never needed to hack the code (I wouldn't know Perl, anyway), as it can be configured very nicely via its config file. > > > [Gerhard H?ring] > >> I'm also investingating Pyzor, as I found the Razor author to be too > >> clueless (also the razor servers aren't open-source). That needs some explanation: http://sf.net/tracker/index.php?func=detail&aid=532357&group_id=3978&atid=103978 He doesn't get mbox parsing, and continues to use his own b0rken implementation. Having described the bug in a very detailed way, and even uploaded a test case, and still having it marked as "invalid" made be /a little/ bitter. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From djc at object-craft.com.au Thu Jun 20 08:41:49 2002 From: djc at object-craft.com.au (Dave Cole) Date: 20 Jun 2002 22:41:49 +1000 Subject: Python to MS SQL Server References: Message-ID: >>>>> "Steve" == Steve Holden writes: Steve> "Bjorn Pettersen" wrote ... >> > From: Mark McEahern [mailto:marklists at mceahern.com] >> > >> > > I am interested in using Python in a MS SQL Server > > >> environment, but do > > not see any database modules out there, >> especially for > > native versus > > using ODBC. Is there such a >> module? >> > >> > This is a total guess, because I haven't done this myself: >> > >> > Have you tried using win32com to use ADO? >> AFAIK, there is no Python database module that goes directly to MS >> SQL Server db lib. ADO does work however, so that's certainly an >> option. Personally, I would probably investigate e.g. mxODBC first >> (the interface is much easier to use from Python). Steve> I agree that ADO is a total pain (although hesitantly, since Steve> Alex Martelli is known to favour it) in Python. I just never Steve> got used to it in VBScript, I guess. Steve> Don't I remember that Dave Col's Sybase module is supposed to Steve> be usable with SQL Server too? I also have a module which uses the MS db library. http://www.object-craft.com.au/projects/mssql/ It needs more work, but might be sufficient for your needs. - Dave -- http://www.object-craft.com.au From fgeiger at datec.at Thu Jun 6 02:14:16 2002 From: fgeiger at datec.at (F. GEIGER) Date: Thu, 6 Jun 2002 08:14:16 +0200 Subject: constructive critisism on pythonwin IDE References: <6bd9f01b.0206050736.f469082@posting.google.com> Message-ID: This a Python issue, not a PythonWin IDE issue. Cheers Franz "sameer" schrieb im Newsbeitrag news:6bd9f01b.0206050736.f469082 at posting.google.com... > First of all, let me start of by saying that Pythonwin is a great IDE. > Now for the constructive critisism. The thing I hate about PythonWin > is, that despite the fact that it's a development environment, there > is a lot of caching done of modules, and the cached copy is not > checked against a potentialy modified copy. Whenever I change the > contents of a file and try to run a module that depends on that file, > I always end up with the old copy. I have to then import and then > reload the changed module in the interactive window for it to refresh. > It would greatly increase my productivity, if I can specify which > modules can be cached. I understand that there is a speed and > development time issue, but I would like a little more fine grained > control on how caching works on PythonWin, as the way it's currently > implemented now is not acceptable. From chandan_mathur at hotmail.com Sat Jun 1 02:14:49 2002 From: chandan_mathur at hotmail.com (Chandan Mathur) Date: Sat, 1 Jun 2002 02:14:49 -0400 Subject: How to install Python without root priviledges ? References: Message-ID: <3cf866fa@news.poly.edu> you have done the right thing.., only without SU priviliges, I think you can run python only on the directory Python-2.2.1 as follows, ./python I have the same problem... and it really sucks :-( "Shagshag13" wrote in message news:acvmin$svjfb$1 at ID-146704.news.dfncis.de... > > I'm a real newbie in unix's world and i would like to install python on a > machine where *i can't have* any root priviledges, how should i do that ? > > (it's on a HP Unix, but don't even know how to check the exact os name or > version...) > > i do this : > > mkdir /home/shagshag/local > download Python-2.2.1.tgz > gunzip > tar -xvf Python-2.2.1.tgz > cd Python-2.2.1 > ./configure --prefix=/home/shagshag/local > make > > And i get nothing !!!! > > Is it the good way to install ??? > > Thanks in advance, > > S13. > > please, don't forget i'm not a skilled unix guy... > > From cliechti at gmx.net Sun Jun 2 13:58:00 2002 From: cliechti at gmx.net (Chris Liechti) Date: 2 Jun 2002 19:58:00 +0200 Subject: win32com under Cygwin References: <3CF9846B.579606ED@wiencko.com> Message-ID: Tom Wiencko wrote in news:3CF9846B.579606ED at wiencko.com: > There may be an easy answer for this, but I have not yet found it... > > I noticed that the Python distribution with Cygwin does not include the > win32 extensions. The only distribution I can find for them is a > Windows executible, which does not seem to know about Cygwin. thats the official page of win32all: http://starship.python.net/crew/mhammond/ the binary version is compiled for the official python.org interpreter. > Can these libraries be loaded under Cygwin? Do they even work under > Cygwin? Can somebody point me toward how to load them if it is > possible? the sources are available from the page above. maybe you can manage to compile it with cygwin for cygwin python. don't know if that is easy... chris -- Chris From james.kew at btinternet.com Thu Jun 27 04:04:23 2002 From: james.kew at btinternet.com (James Kew) Date: Thu, 27 Jun 2002 09:04:23 +0100 Subject: background-processes with win-python? References: Message-ID: "Klaus Reinhardt" wrote in message news:mailman.1025157935.3443.python-list at python.org... > Is there a possibility to execute system-processes > under windows-python in the background? So > I can do this > system("plink .. tu-berlin.de") > without waiting for the real connection. system("start plink ... tu-berlin.de") ? James From DLNXPEGFQVEB at spammotel.com Thu Jun 20 10:38:43 2002 From: DLNXPEGFQVEB at spammotel.com (Christos TZOTZIOY Georgiou) Date: Thu, 20 Jun 2002 17:38:43 +0300 Subject: CR+LF problem References: <3d11bc33.1129927479@news.mad.ttd.net> Message-ID: <12q3hukse2cepcm9tpern92jc71a5vrhvi@4ax.com> On Thu, 20 Jun 2002 11:33:55 GMT, rumours say that mruiz at safa.es (Manuel Ruiz) might have written: >char * txt = "print 123\r\n"; >result = PyRun_Simple( txt, Py_file_input, PyDict_New(), NULL ); did you try char *txt= "print 123\n"; by any chance? I am not very sure if I do help, but in C, newlines are just "\n". "\r\n" is by convention the text line terminator of VMS IIRC, MS-DOS & window derivatives etc. >this code fails to exec txt, I got a SyntaxError exception, >however I if save to file the statement "print 123\r\n" and try to run >it ussing python interprete (version 2.2.1) It run fine. > >Can anyone tell me anything about this rare behaviour -- TZOTZIOY, I speak England very best, Real email address: 'dHpvdEBzaWwtdGVjLmdy\n'.decode('base64') From achim.domma at syynx.de Fri Jun 7 05:11:23 2002 From: achim.domma at syynx.de (Achim Domma) Date: Fri, 7 Jun 2002 11:11:23 +0200 Subject: Distributing Packages / os independent installation folder Message-ID: Hi, I'm building a python interface to ImageMagick. I already succeded in building an installer with distutils, but have some questions regarding portability: - where should my package and shared librarie go to? On windows I put the dll into python22/DLLs and the rest into a folder python22/Lib/site-packages/ImageMagick. What to do on other plattforms? I don't expect a DLLs folder on Linux. ;-) - In my __init__.py I have to change one environment variable. Currently I do it like this: import os os.environ['MAGICK_HOME'] = r'C:\Python22\Lib\site-packages\ImageMagick' from _ImageMagick import * Is there an plattform independent way to get the installation folder of my package? On windows I can get the python folder from registry, but this will also break on linux. greetings Achim From cliechti at gmx.net Mon Jun 10 19:50:31 2002 From: cliechti at gmx.net (Chris Liechti) Date: 11 Jun 2002 01:50:31 +0200 Subject: getting files from a windows network References: <6bd9f01b.0206101523.7af66fc8@posting.google.com> Message-ID: sameer_ at email.com (sameer) wrote in news:6bd9f01b.0206101523.7af66fc8 at posting.google.com: > is there a way to read files in python that are found on a windows > network, i.e. files that users choose to share on their computers on a > windows network. do you mean by e.g. >>> open(r'\\computername\share\test.txt').read() yes :-) ( r'' is a raw string that doesn't touches backslashes unlike normal strings) if you want a list of computers you can use: >>> map(str.strip, os.popen("net view").readlines()[3:-2]) chris -- Chris From jblazi at hotmail.com Mon Jun 24 16:16:05 2002 From: jblazi at hotmail.com (JB) Date: Mon, 24 Jun 2002 22:16:05 +0200 Subject: converting an array of chars to a string References: <3d12dda2_6@news.newsgroups.com> <3d17038e_6@news.newsgroups.com> <3d1757c7_1@news.newsgroups.com> Message-ID: <3d177c4b_9@news.newsgroups.com> Bengt Richter wrote: If I had told you, what I was after, you would have pointed out, that there is a library function that does exactly this. Then I should have explained, why I thought, that the library function was not sufficient (why it was actualy unusable). All this was not necessary and you helped me a lot. I simply did not understand, why those arrays are implemented with overflow checking, which involves additional overhead and is absolutely unnecessary. So thank you very much. -- Janos Blazi -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From mickey at tm.informatik.uni-frankfurt.de Tue Jun 18 17:00:32 2002 From: mickey at tm.informatik.uni-frankfurt.de (Michael 'Mickey' Lauer) Date: 18 Jun 2002 23:00:32 +0200 Subject: SWIG and Callbacks References: <3d0a8b6e@nntp.server.uni-frankfurt.de> <3d0b4fd6@nntp.server.uni-frankfurt.de> <3d0c6d67@nntp.server.uni-frankfurt.de> <3D0CE698.1050806@SPAMnwinternet.com> <3D0D3223.5070500@SPAMnwinternet.com> Message-ID: <3d0f9f70@nntp.server.uni-frankfurt.de> David Abrahams wrote: > Heh, yeah. Unfortunately, documentation is often harder than coding. Even > the current official release of Boost.Python is not very well-documented. > We're working hard to correct that for v2, which is in pre-release. Is it completed enough to try it out for wrapping a small library? If not, could you estimate when it will be ? Yours, :M: -- |----------------------------------------------------------------------------| | Dipl.-Inf. Michael 'Mickey' Lauer mickey at tm.informatik.uni-frankfurt.de | | Raum 10b - ++49 69 798 28358 Fachbereich Informatik und Biologie | |----------------------------------------------------------------------------| From Sascha.Ferley at infineon.net Sun Jun 23 19:37:27 2002 From: Sascha.Ferley at infineon.net (Sascha Ferley) Date: Sun, 23 Jun 2002 17:37:27 -0600 Subject: PIL, Python and CGI References: <3D1626FD.DA934B09@infineon.net> <1HrR8.44835$n4.10519234@newsc.telia.net> Message-ID: <3D165BB7.B901F064@infineon.net> Fredrik Lundh wrote: > Sascha Ferley wrote: > > > raise ImportError, "The _imaging C module is not installed" > > ImportError: The _imaging C module is not installed > > > > Anyone have any ideas? > > when running your CGI script, the Python interpreter > cannot find the _imaging extension. > > chances are that sys.path isn't what you think it is. > > Well I wrote a quick cgi script to get the path .. here is the output: ['/export/server/web/CPSC461/cgi-bin', '/usr/local/lib/python2.2', '/usr/local/lib/python2.2/plat-sunos5', '/usr/local/lib/python2.2/lib-tk', '/usr/local/lib/python2.2/lib-dynload', '/usr/local/lib/python2.2/site-packages', '/usr/local/lib/python2.2/site-packages/PIL'] Program used: #!/usr/local/bin/python import sys import cgi print "Content-Type: text/plain \n\n" print sys.path As one can see the PIL library is in the path .. but still for some strange reason it can't find the _imaging extention.. It is sort of strange that it wouldn't pick it up then.. any more ideas? Sascha From donn at u.washington.edu Tue Jun 18 16:23:29 2002 From: donn at u.washington.edu (Donn Cave) Date: 18 Jun 2002 20:23:29 GMT Subject: socket.inet_aton - bug? References: Message-ID: Quoth "Steve Holden" : | "Uwe Mayer" wrote ... |> socket.inet_ntoa() accepts the string '\xff\xff\xff\xff' which is |> excactly the same i'd expect socket.inet_aton('255.255.255.255') to |> produce if it accepted the string '255.255.255.255' as an IP adress. |> socket.inet_aton() dies with socket.error "illegal IP adress". |> |> i know this is no valid ip adress, but it is a valid netmask. the |> purpose of converting the netmask to a binary format was that i wanted |> to isolate the subnet of an ip adress. |> i wanted to use test_ip & netmask == ip_range to allow subnets to access |> a tcp server. |> is there another way of controlling this or why does socket.inet_aton() |> behave like that? | | I can't really tell you why socket does that, but it seems to be a feature | of the underlying C socket library, which is where inet_aton() is defined. Yes (you mean "C socket module", I suppose - at first I thought you were pointing to the C library inet_aton.) The good news is that it's only this one value, which happens to be identical to INADDR_NONE, and that this value is reliably -1. So at worst, there's a work-around. | The address 255.255.255.255 is, in fact, a valid destination for a | restricted broadcast (one which should be sent out only to hosts on the | local LAN). Donn Cave, donn at u.washington.edu From jonathan at onegoodidea.com Wed Jun 26 09:00:48 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Wed, 26 Jun 2002 14:00:48 +0100 Subject: Python 2.2 __slots__ Bug? References: Message-ID: On 26/6/2002 12:03, in article mailman.1025089474.17780.python-list at python.org, "Glyph Lefkowitz" wrote: > I get "I'm fine" and then a segmentation fault. This only happens when > __slots__ is defined on a new-style class. Seriously, i'm not making those > numbers up -- reliably, 43551 objects will crash the interpreter; fewer will > not. Interestingly I get the construction working fine, but the 'del' crashes the interpreter with (on Mac OS X): ----- Date/Time: 2002-06-26 13:53:19 +0100 OS Version: 10.1.5 (Build 5S66) Command: python PID: 18472 Exception: EXC_BAD_ACCESS (0x0001) Codes: KERN_INVALID_ADDRESS (0x0001) at 0xbff7ffe0 Thread 0 Crashed: #0 0x00037bbc in lookdict_string #1 0x0003804c in PyDict_GetItem #2 0x00018994 in _PyType_Lookup #3 0x00017348 in lookup_maybe #4 0x00016f38 in call_finalizer #5 0x00017054 in subtype_dealloc #6 0x00017118 in subtype_dealloc #7 0x00017118 in subtype_dealloc [etc...] ----- This seems to fail for me at 5430 objects. I couldn't get the allocation to crash at all (or at least up to a million objects, after which I got bored). Jonathan From cliechti at gmx.net Mon Jun 24 18:32:48 2002 From: cliechti at gmx.net (Chris Liechti) Date: 25 Jun 2002 00:32:48 +0200 Subject: AF_UNIX + SOCK_DGRAM References: Message-ID: [posted and mailed] "James T. Dennis" wrote in news:af84af$1dkt$1 at news.idiom.com: >> Actually think you have run into a bug in Python's socket module. >> If it's convenient for you to build your own socket module, change >> it like this and see what happens (I'm looking at version 2.1 here.) > >> *** socketmodule.c.dist Sun Apr 15 17:21:33 2001 >> --- socketmodule.c Thu Jun 20 10:10:12 2002 >> *************** >> *** 597,602 **** >> --- 597,603 ---- >> case AF_UNIX: >> { >> struct sockaddr_un *a = (struct sockaddr_un *) addr; >> + a->sun_path[addrlen - (sizeof(*a) - >> sizeof(a->sun_path))] = 0; >> return PyString_FromString(a->sun_path); >> } >> #endif why not simply use PyString_FromStringAndSize(const char *v, int len)? couln't you just file a patch on SF? should i do it? >> The address returned from recvfrom is (addr, len), but we've been >> ignoring len on the theory that the string would be NUL-terminated. >> It isn't, so there can be some garbage on the end. -- Chris From skip at pobox.com Tue Jun 11 09:50:18 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 11 Jun 2002 08:50:18 -0500 Subject: if number is 1-2, 4 or 6-8 or 12-28, 30, 32... In-Reply-To: References: Message-ID: <15622.26.84312.207270@12-248-41-177.client.attbi.com> Gustaf> Cliff's solution was really fast, but it took a while to Gustaf> understand. :) One thing I frequently forget about is the else: clause for try/except statements. This lets you isolate as small a piece of code as possible in the try: clause, making it a bit easier to understand what triggers the exception: def isin(n, ranges): for r in ranges: try: s, e = r except TypeError: if n == r: return 1 else: if s <= n <= e: return 1 return 0 You could also fold the int case into the tuple case (making it a bit more uniform), but at a slight cost in performance if you have lots of ints. In this case, all the try/except statement is responsible for is setting s and e: def isin(n, ranges): for r in ranges: try: s, e = r except TypeError: s, e = n, n if s <= n <= e: return 1 return 0 -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) Boycott Netflix - they spam - http://www.musi-cal.com/~skip/netflix.html From kseehof at neuralintegrator.com Tue Jun 11 21:55:31 2002 From: kseehof at neuralintegrator.com (Ken Seehof) Date: Tue, 11 Jun 2002 18:55:31 -0700 Subject: (no subject) Message-ID: Where are the windows binaries for python22_d.lib? Do I need to build the sources to get it? Thanks, - Ken From dryose at juno.com Tue Jun 4 14:57:34 2002 From: dryose at juno.com (yose) Date: 4 Jun 2002 11:57:34 -0700 Subject: mySQL on Solaris .8 References: <79d1869.0206030646.512af52c@posting.google.com> <79d1869.0206031202.228c4387@posting.google.com> Message-ID: <79d1869.0206041057.2c73a2c7@posting.google.com> Skip Montanaro wrote in message news:... > >> I am trying to install a mySQL database in solaris 2.8. I have a copy > >> of the distro for mySQL-python-0.9.1. When I try to run setup.py, I > >> am told that I am missing distutils.core > > >> Where do I get this? What package is it part of? > > Joe, > > It's part of the core Python distribution (since 2.0 or 2.1 I think). > Sounds like either you're running an older version of Python or the one you > have is misinstalled in some way. Assuming you have MySQL's client libs and > a recent enough version of Python correctly installed, Installing > mysql-python should take less than 30 seconds from the time you execute > > python setup.py install Interesting. It seems like my distro (2.0; the latest that cleanly supports sockets, etc.) DOES have distutils. However, python itself doesnt seem to notice. What system variable do I need to set to point to the Lib/ directory? Joe From BPettersen at NAREX.com Sun Jun 30 18:07:18 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Sun, 30 Jun 2002 16:07:18 -0600 Subject: How to get rid the new line Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192158F15@admin56.narex.com> > From: Frank Tobin [mailto:ftobin at neverending.org] > > Bjorn Pettersen, on 2002-06-30, wrote: > > > I submitted a patch for this (that handled mac, win, and unix line > > endings) but it was declined by the BDFL. I suspect one of > > the reasons were that I named it chomp... > > sed s/chomp/bite/ < patch | mail python-bugs-list at python.org I believe in CVS Python you can say line = line.rstrip('\n') to get a sufficiently similar effect to chomp. 2.3-will-be-out-any-day-now-'ly y'rs -- bjorn From jiba at tuxfamily.org Thu Jun 20 15:18:24 2002 From: jiba at tuxfamily.org (Lamy Jean-Baptiste) Date: Thu, 20 Jun 2002 21:18:24 +0200 Subject: [ANN] EventObj Message-ID: EventObj 0.2 http://oomadness.tuxfamily.org/p-eventobj.php EventObj is a (hackish) pure Python module that allows to add modification callback (=event) to any Python object (including lists and dicts). EventObj requires at least Python 2.2 (tested with 2.2.1). EventObj can be usefull for debugging, for IDE (to spy object modification ?), for OO databases, or just for maitaining anything up-to-date with an object. Python hack-lovers may be interesting at looking the pure Python source code (I use __setattr__ on ). EventObj is Free Software and is available under the GNU GPL. Enjoy the hack ! Jiba -- Jean-Baptiste LAMY -- jiba at tuxfamily.org http://oomadness.tuxfamily.org From rnd at onego.ru Sat Jun 1 14:54:49 2002 From: rnd at onego.ru (Roman Suzi) Date: Sat, 1 Jun 2002 22:54:49 +0400 (MSD) Subject: prototyping good OOdesign in Python? Message-ID: Maybe this was already discussed, but I'd liked to raise this topic again. Python has superb OOProgramming support. Lets not dispute this for a moment. Now let's consider that we need to make well-designed OOP solution first prototyped in Python. What troubles are there? Python is too dynamic and all that. And all those nifty features need to be translated properly into, say, C++. Recently I encountered the following piece of code (from Arts++ project): //=========================================================================== // Copyright Notice // // By accessing this software, arts++, you are duly informed // of and agree to be bound by the conditions described below in this // notice: // // This software product, arts++, is developed by Daniel W. McRobb, and // copyrighted(C) 1998 by the University of California, San Diego // (UCSD), with all rights reserved. UCSD administers the CAIDA grant, // NCR-9711092, under which part of this code was developed. // // There is no charge for arts++ software. You can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License, Version 2.1, February 1999, which is incorporated by // reference herein. // // arts++ is distributed WITHOUT ANY WARRANTY, IMPLIED OR EXPRESS, OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE or that the use // of it will not infringe on any third party's intellectual // property rights. // // You should have received a copy of the GNU Lesser General Public // License along with arts++. Copies can also be obtained from: // // http://www.gnu.org/copyleft/lesser.html // // or by writing to: // // Free Software Foundation, Inc. // 59 Temple Place, Suite 330 // Boston, MA 02111-1307 // USA // // Or contact: // // info at caida.org //=========================================================================== // constructor ............skip Arts::Arts() { this->_data._ipPath = (ArtsIpPathData *)0; this->_data._asMatrix = (ArtsAsMatrixData *)0; this->_data._netMatrix = (ArtsNetMatrixData *)0; this->_data._portTable = (ArtsPortTableData *)0; this->_data._portMatrix = (ArtsPortMatrixData *)0; this->_data._protocolTable = (ArtsProtocolTableData *)0; this->_data._selectedPortTable = (ArtsSelectedPortTableData *)0; this->_data._interfaceMatrix = (ArtsInterfaceMatrixData *)0; this->_data._nextHopTable = (ArtsNextHopTableData *)0; this->_data._bgp4RouteTable = (ArtsBgp4RouteTableData *)0; this->_data._rttTimeSeriesTable = (ArtsRttTimeSeriesTableData *)0; this->_data._tosTable = (ArtsTosTableData *)0; #ifndef NDEBUG ++_numObjects; #endif } Arts::Arts(const Arts & arts) { this->_header = arts.Header(); this->_attributes = arts.Attributes(); switch (this->_header.Identifier()) { case artsC_OBJECT_IP_PATH: this->_data._ipPath = new ArtsIpPathData; assert(this->_data._ipPath != (ArtsIpPathData *)0); *(this->_data._ipPath) = *(arts.IpPathData()); break; case artsC_OBJECT_AS_MATRIX: this->_data._asMatrix = new ArtsAsMatrixData; assert(this->_data._asMatrix != (ArtsAsMatrixData *)0); *(this->_data._asMatrix) = *(arts.AsMatrixData()); break; case artsC_OBJECT_NET: this->_data._netMatrix = new ArtsNetMatrixData; assert(this->_data._netMatrix != (ArtsNetMatrixData *)0); *(this->_data._netMatrix) = *(arts.NetMatrixData()); break; case artsC_OBJECT_PORT: this->_data._portTable = new ArtsPortTableData; assert(this->_data._portTable != (ArtsPortTableData *)0); *(this->_data._portTable) = *(arts.PortTableData()); break; case artsC_OBJECT_SELECTED_PORT: this->_data._selectedPortTable = new ArtsSelectedPortTableData; assert(this->_data._selectedPortTable != (ArtsSelectedPortTableData *)0); *(this->_data._selectedPortTable) = *(arts.SelectedPortTableData()); break; case artsC_OBJECT_PORT_MATRIX: this->_data._portMatrix = new ArtsPortMatrixData; assert(this->_data._portMatrix != (ArtsPortMatrixData *)0); *(this->_data._portMatrix) = *(arts.PortMatrixData()); break; case artsC_OBJECT_PROTO: this->_data._protocolTable = new ArtsProtocolTableData; assert(this->_data._protocolTable != (ArtsProtocolTableData *)0); *(this->_data._protocolTable) = *(arts.ProtocolTableData()); break; case artsC_OBJECT_TOS: this->_data._tosTable = new ArtsTosTableData; assert(this->_data._tosTable != (ArtsTosTableData *)0); *(this->_data._tosTable) = *(arts.TosTableData()); break; case artsC_OBJECT_INTERFACE_MATRIX: this->_data._interfaceMatrix = new ArtsInterfaceMatrixData; assert(this->_data._interfaceMatrix != (ArtsInterfaceMatrixData *)0); *(this->_data._interfaceMatrix) = *(arts.InterfaceMatrixData()); break; case artsC_OBJECT_NEXT_HOP: this->_data._nextHopTable = new ArtsNextHopTableData; assert(this->_data._nextHopTable != (ArtsNextHopTableData *)0); *(this->_data._nextHopTable) = *(arts.NextHopTableData()); break; case artsC_OBJECT_BGP4: this->_data._bgp4RouteTable = new ArtsBgp4RouteTableData; assert(this->_data._bgp4RouteTable != (ArtsBgp4RouteTableData *)0); *(this->_data._bgp4RouteTable) = *(arts.Bgp4RouteTableData()); break; case artsC_OBJECT_RTT_TIME_SERIES: this->_data._rttTimeSeriesTable = new ArtsRttTimeSeriesTableData; assert(this->_data._rttTimeSeriesTable != (ArtsRttTimeSeriesTableData *)0); *(this->_data._rttTimeSeriesTable) = *(arts.RttTimeSeriesTableData()); break; default: break; } #ifndef NDEBUG ++_numObjects; #endif } ..........skip the rest of file - there are 2-3 more similar .......... switch-constructs. ------------------------------------------------------------ This code looks like... automatically generated. Rather than manually written. I do not know why it was written in C++ at all. Of course, I imagine 2-3 variants of how to refactor it if I were writing the code in Python. I am pretty sure there were no select statement (switches) in Python code, because that is what polymorphism is about. But then again, translating back to C++ could be difficult. The mentioned example is all about reading a specially formatted binary file to produce certain slices of information. And for each class it uses separate .cc/.hh file! While all the difference between different classes - structure of corresponding data entries. My approach in this case could be one resource file, with format specification (like DTD). Plus one univarsal class to handle big binary file according to "DTD"). Plus maybe separate resource file with data query specifications. And it could be at most 80 Kb Python project, not that monster Arts++ is in both source and binary forms... Well, if you still follow this thread, the question is - how well Python could serve as an ARCHITECTURAL prototype if it has too rich OOP facilities? That is, is Python of help when trying to prototype certain design? Developing in C++ looks so unnecessary hard after things were done in Python... Or, it may be put this way: what discipline a Python programmer must obey to allow it's prototype to be conveniently rewriten in C++? The above thoughts aren't probably well-formed. But I hope my concern is understood. Sincerely yours, Roman Suzi -- \_ Russia \_ Karelia \_ Petrozavodsk \_ rnd at onego.ru \_ \_ Saturday, June 01, 2002 \_ Powered by Linux RedHat 7.2 \_ \_ "Tried to play my shoehorn... all I got was footnotes!" \_ From hwcowan at hotmail.com Fri Jun 7 00:16:22 2002 From: hwcowan at hotmail.com (Hugh Cowan) Date: 6 Jun 2002 21:16:22 -0700 Subject: Creating Dynamic Web Pages (ZOPE) Message-ID: <46ca81a0.0206062016.789d3af6@posting.google.com> Hello, I am not exactly sure where to post this question -- the only reference that I could find for ZOPE in the Newsgroups is here. I appologize if this is not the correct place. I have the situation where I need to create a simple Intranet for my company to display dynamic / data driven web-pages. We are running a Windows NT network with MS-SQL Server and IIS. I had originally thought of using ASP (Server Side Scripting) to generate the dynamic web-pages. While I know how to create the Intranet using ASP, I have yet to find any RAD type Web-Tools that will allow me to quickly and easily generate the ASP pages required, and I don't fancy using the Notepad approach either. My scenario is typical where I need to put together a company Intranet with a few front end Web-Pages where users can select information, various links, and enter search criteria. The information is then retrieved from the MS-SQL Server and the results are sent back to the user. It's nothing fancy, no shopping carts, or remembering sessions states, etc.. just really a simple front-end interface for non-technical people to easily retrieve information. I don't know if ZOPE would fit my situation or not. I know that it is / can be used to create complex E-commerce sites, but I am wondering if it is overkill for what I need done. Would I be better off trying to find some sort of RAD Web Tool instead (anyone have any good suggestions) ? Thanks so much, Hugh From djc at object-craft.com.au Tue Jun 18 17:40:52 2002 From: djc at object-craft.com.au (Dave Cole) Date: 19 Jun 2002 07:40:52 +1000 Subject: Python to MS SQL Server References: Message-ID: >>>>> "Bjorn" == Bjorn Pettersen writes: >> From: Mark McEahern [mailto:marklists at mceahern.com] >> >> > I am interested in using Python in a MS SQL Server > environment, >> but do > not see any database modules out there, especially for > >> native versus > using ODBC. Is there such a module? >> >> This is a total guess, because I haven't done this myself: >> >> Have you tried using win32com to use ADO? Bjorn> AFAIK, there is no Python database module that goes directly to Bjorn> MS SQL Server db lib. ADO does work however, so that's Bjorn> certainly an option. Personally, I would probably investigate Bjorn> e.g. mxODBC first (the interface is much easier to use from Bjorn> Python). http://www.object-craft.com.au/projects/mssql/ The page is a bit alarmist, but is it worth trying the module - what can you lose? I stopped doing development when I realised that MS have effectively abandoned the DB library in favour of ADO. - Dave -- http://www.object-craft.com.au From johnroth at ameritech.net Mon Jun 17 07:44:16 2002 From: johnroth at ameritech.net (John Roth) Date: Mon, 17 Jun 2002 07:44:16 -0400 Subject: [development doc updates] References: Message-ID: "Michael Hudson" wrote in message news:lku1o2l062.fsf at pc150.maths.bris.ac.uk... > "John Roth" writes: > > > "Fred L. Drake" wrote in message > > news:mailman.1024057266.26182.python-list at python.org... > > > The development version of the documentation has been updated: > > > > > > http://www.python.org/dev/doc/devel/ > > > > > > Updated to reflect recent changes. > > > > I'm not certain I understand item 5. Extended Slices. > > Where specifically? In the whatsnew document? That section isn't > finished yet. > > > Does this mean that the standard sequence types now support > > the stride operand, > > Yes. Well, at least lists, tuples, strings (both flavours), arrays. > > > or that the stride operand is being depreciated and will eventually > > vanish? > > No. Assuming you mean "deprecated" -- a common typo!. Possibly I didn't make myself clear. Item 5 in the What's New document contains two paragraphs. It's not clear that the second paragraph is talking about something completely different than the topic in the header (Extended Slices). Hence my original question. John Roth > > Cheers, > M. > > -- > 93. When someone says "I want a programming language in which I > need only say what I wish done," give him a lollipop. > -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html From printers at sendme.cz Thu Jun 27 02:24:37 2002 From: printers at sendme.cz (A) Date: Thu, 27 Jun 2002 08:24:37 +0200 Subject: How to find out operating system Message-ID: <3D1ACBC5.22482.D4313A4@localhost> Hi, What is the best way of finding out the kind operating system? I can use os.name but if the system is Windows I would like also know if the system is Windows98 or Windows ME or W2K or Windows XP. Thanks for help. Ladislav From siegfried.gonzi at kfunigraz.ac.at Sat Jun 22 09:59:10 2002 From: siegfried.gonzi at kfunigraz.ac.at (Siegfried Gonzi) Date: Sat, 22 Jun 2002 15:59:10 +0200 Subject: Python hits the spot Message-ID: <3D1482AE.8FA299D8@kfunigraz.ac.at> A few weeks ago I complaint here that Python on Windows XP sucks. I had a problem which would took theoretically about 1.5 hours; but in reality it takes 6 hours on Windows XP and Python 2.2. After that 6 hours I must reboot my system in order to work on. In the following I got the advice to install a real user system on my laptop. Okay, I bought Linux SuSE 8.0 and installed it on my laptop (256 MB RAM, 1000 MHz Celeron). I also installed Python 2.2 (the ActivePython version, otherwise I couldn't install idle due to the annoying "free_software_garbage_2_weeks_installation_nightmare"). SWIG helped me to make my external Python C function (with gcc); and F2PY helped me to create my external Python Fortran 90 function (with the Intel Fortran 95 compiler). The directories and all the other programs and data are the same as on Windows. 1. After starting the process from within idle the complete system freezes after the first wavelength (after about 20 minutes). I couldn't kill a process or open a different session (via F2) in order to kill python. The last resort: turn off the power supply. 2. I thought it is better to start the process from the command line and in a X terminal: python forcing.py The same behavior as aforementioned: last resort: power supply. That is really good and fine because a Linux system really is greedy for "shut down immediately". 3. I thought it has to do with Gnome and I logged in to a KDE session. Same behavior as in point 1. and 2. My conclusion: I will rewrite my simulation in Fortran 90 and will abadon Python. Python is maybe good for some small scripts but not appropiate for serious programming. Thank you Billy Boy for a forgiving user system Windows XP which in turn relieves Python's "wreak havoc" behavior. I cannot believe that Linux is responsible for Python's ill behavior under Linux. Before you start ranting about note the following: In a first step it has nothing to do with my programming style (admittedly not very good and famous) it has to do that the same calculation cannot be performed on Linux and Python 2.2! S. Gonzi From Mitch.Chapman at bioreason.com Tue Jun 25 17:57:38 2002 From: Mitch.Chapman at bioreason.com (Mitch Chapman) Date: Tue, 25 Jun 2002 15:57:38 -0600 Subject: Memory Monitor References: <3D1894B5.720EB7F7@bioreason.com> <200206252139.QAA88038@starbase.neosoft.com> Message-ID: <3D18E752.7A5A4EAC@bioreason.com> Cameron Laird wrote: > Mitch Chapman wrote: > > os.system("cat /proc/self/status | grep VmSize") > Rather than > os.system("grep VmSize /proc/self/status") > ? No, that's also concise =8) -- Mitch From maxm at mxm.dk Fri Jun 14 03:56:33 2002 From: maxm at mxm.dk (Max M) Date: Fri, 14 Jun 2002 09:56:33 +0200 Subject: Date formats Message-ID: <3D09A1B1.6040705@mxm.dk> I have a project where I have defined the following date format: gDateFormat = '%d-%m-%Y' This give dates of the type: 01-01-2002 For some reason my customer wants dates of the type: 1-1-2002 Without the leading zero in single digit dates. But when I look in the docs for date time formats there is no way to specify days and months in that format. Off course it's easy to write a function which returns the correct date format but can this really be true that I have to do it? I want batteries dam'n it! ;-) regards Max M From lailian98 at hotmail.com Sat Jun 1 06:01:48 2002 From: lailian98 at hotmail.com (Hazel) Date: 1 Jun 2002 03:01:48 -0700 Subject: Extracting data from HTML References: <82096df4.0205311152.5891a17b@posting.google.com> <1022883953.6150.5802.camel@localhost> Message-ID: <82096df4.0206010201.736c4b2c@posting.google.com> Geoff Gerrietts wrote in message news:... > Quoting Ian Bicking (ianb at colorstudy.com): > > On Fri, 2002-05-31 at 14:52, Hazel wrote: > > > how do i write a program that > > > will extract info from an HTML and print > > > of a list of TV programmes, its Time, and Duration > > > using urllib? > > > > You can get the page with urllib. You can use htmllib to parse it, but > > I often find that regular expressions (the re module) are an easier way > > -- since you aren't looking for specific markup, but specific > > expressions. You'll get lots of false negatives (and positives), but > > when you are parsing a page that isn't meant to be parsed (like most web > > pages) no technique is perfect. > > Definitely agree with this sentiment. > > I'll go a step farther, and do a little compare/contrast. > > Once upon a time, I wanted to grab data from the > weatherunderground.com website. I know there are lots of better ways > to go about getting this information, these days, but I was not so > well-informed back then. > > So I wanted to grab this information, and I tried using regular > expressions to mangle the page. But truthfully, it was just too hard > to do. I could guess about where in the file the table with all the > info would appear, but getting a regular expression that was inclusive > enough to catch all the quirks, yet exclusionary enough to filter out > all the other embedded tables, proved a very large challenge. > > That's when the idea of a parser made a lot of sense. > > I could push the whole page through a parser, looking for one > particular phrase in a element, and from that point forward, map > elements to elements effectively. It became a very simple > exercise, because I knew how to find that info. > > But as Ian rightly points out, htmllib and a real parser can be very > heavy if you're just looking to grab unformatted info -- or if you > can't rely on the formatting to be reliable. > > Both techniques are worth knowing -- but better than either would be > finding a way to get the information you're after via XML-RPC or some > other protocol that's designed to carry data rather than rendering > instructions. > > Best of luck, > --G. Dear Geoff, Ian I'm relying onsgmllib to do the work.... since htmllib requires heavy coding. Here, an instance of what I want to extract.... the time of the TV programme >> 12:15:00AM " 12:15:00 AM" So what do u think? -Thanx Hazel From mike at radiomag.com Mon Jun 17 23:35:16 2002 From: mike at radiomag.com (Michael Steuer) Date: Tue, 18 Jun 2002 13:35:16 +1000 Subject: Listing all available (not just loaded) modules Message-ID: I've been searching the newsgroup for information on this but so far have been unsuccessful: Is there a way to dynamically list all available modules (not just those that are already loaded) in python? By available I mean those modules, which are installed on the machine executing python (in the lib path(s)). Cheers, Mik.e From in-call at gmx.net Thu Jun 20 20:28:03 2002 From: in-call at gmx.net (Pablo Ripolles) Date: 20 Jun 2002 17:28:03 -0700 Subject: Passing inner functions as arguments Message-ID: Hello all! I am new to python, so sorry if i am asking the obvious. Here it comes. Is there anything wrong with this code? # Module to define math tools. def momentum(f, k, a, b): # Momentum of kth order of the given function f in [a, b]. from Quadrature import quadrature def integrand(x): # Momentum's integrand in terms of the passed function f and k. return (f(x)) ** k return quadrature(integrand, a, b) I am not sure if it is correct. It runs OK in Python 2.2.1 but not at all in Jython 2.1 (java1.4.0). I am not sure about the scoping rules. I there's something strange, please let me know! Thanx in advance, Pablo. From jdhunter at nitace.bsd.uchicago.edu Sat Jun 22 10:03:03 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Sat, 22 Jun 2002 09:03:03 -0500 Subject: text search again?????????? References: Message-ID: >>>>> "jubafre" == jubafre writes: jubafre> self.text.search(st, 0.0, regexp='true') is it correct??? jubafre> i?m not a exact string, i?m searchin for winzip, but in jubafre> the text appears WinZip and the search doesn?t work, how jubafre> use regexp flag????? What kind of object is self.text? You say, 'I'm not a exact string'. I'm not either, but this confuses me in the context of your question. My guess is that self.text is a string, and you'll be fine with the string 'find' method. You don't need a regex to search for 'winzip'. self.text.lower().find('winzip') will do a case insensitive search for winzip and return the index into the string, or '-1' if nothing is found. self.text.find('WinZip') will do a case sensitive search. If self.text is a rgx object, then you could use it's search method, but the syntax would be: self.text = re.compile('WinZip') # see the docs for case insensitive self.text.search(s) # s is the string you want to search. But if this is the case, text would be a bad name. self.rgxWinzip would be better than self.text. Good luck, John Hunter The re search method: `search(string[, pos[, endpos]])' Scan through STRING looking for a location where this regular expression produces a match, and return a corresponding `MatchObject' instance. Return `None' if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string. The optional POS and ENDPOS parameters have the same meaning as for the `match()' method. The string find method: `find(s, sub[, start[,end]])' Return the lowest index in S where the substring SUB is found such that SUB is wholly contained in `S[START:END]'. Return `-1' on failure. Defaults for START and END and interpretation of negative values is the same as for slices. From sgt at outline.ru Tue Jun 4 08:49:19 2002 From: sgt at outline.ru (Sergei Barbarash) Date: Tue, 04 Jun 2002 16:49:19 +0400 Subject: sharing data in list sub-classes Message-ID: <87znybyzsg.fsf@zaraza.fep.ru> Hello, Is there a way to share list data in classes that inherit the "list" class? Example: ,---- | class A(list): | | | mem = [1,2,3,4,5] | | a1 = A(mem) | a2 = A(mem) | | a1[0] = 1024 | if a2[0] == 1024: | print "Everything's fine" `---- With obsolete UserList module it works fine, because it stores the data in self.data variable. Is there a "right" 2.2-ish way to do the same thing? Thanks, -- Sergei From dryose at juno.com Mon Jun 3 10:46:25 2002 From: dryose at juno.com (yose) Date: 3 Jun 2002 07:46:25 -0700 Subject: mySQL on Solaris .8 Message-ID: <79d1869.0206030646.512af52c@posting.google.com> I am trying to install a mySQL database in solaris 2.8. I have a copy of the distro for mySQL-python-0.9.1. When I try to run setup.py, I am told that I am missing distutils.core Where do I get this? What package is it part of? Thanks! From tdelaney at avaya.com Sun Jun 16 20:59:58 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Mon, 17 Jun 2002 10:59:58 +1000 Subject: filter2 Message-ID: # Baseline 1 def filter2a (test, l): l1 = filter(test, l) l2 = filter(lambda x, test=test: not test(x), l) return l1, l2 # Baseline 2 def filter2b (test, l): l1 = [] l2 = [] l1append = l1.append l2append = l2.append for x in l: if test(x): l1append(x) else: l2append(x) return l1, l2 # Based on Jeff Epler's - won't work < Python 2.0 def filter2t (test, l): l1 = [] l2 = [] funcs = (l1.append, l2.append,) map(lambda x: funcs[not test(x)](x), l) return l1, l2 # Based on Jeff Epler's - won't work < Python 2.0 def filter2l (test, l): l1 = [] l2 = [] funcs = [l1.append, l2.append,] map(lambda x: funcs[not test(x)](x), l) return l1, l2 # Based on Jeff Epler's def filter3t (test, l): l1 = [] l2 = [] map(lambda x, test=test, funcs=(l1.append, l2.append,): funcs[not test(x)](x), l) return l1, l2 # Based on Jeff Epler's def filter3l (test, l): l1 = [] l2 = [] map(lambda x, test=test, funcs=[l1.append, l2.append,]: funcs[not test(x)](x), l) return l1, l2 # Based on Bengt Richter's - won't work < Python 2.0 def filter4 (test, l): l2 = [] append = l2.append return [x for x in l if test(x) or append(x)], l2 # Based on Bengt Richter's def filter5 (test, l): l2 = [] return filter(lambda x, test=test, append=l2.append: test(x) or append(x), l), l2 import operator def test (x, truth=operator.truth): return truth(x) def bench (f, r, l, t): """""" import time clock = time.clock start = clock() for i in r: f(t, l) t = clock() - start print '%-10s %s' % (f.__name__ + ':', t,) r = range(1000) l = range(1000) filters = (filter2a, filter2b, filter2t, filter2l, filter3t, filter3l, filter4, filter5,) print 'Python function' print for func in filters: bench(func, r, l, test) print print 'C function' print for func in filters: bench(func, r, l, operator.truth) --- Python 2.2.1 Windows 2000 Python function filter2a: 6.18176173589 filter2b: 3.81115916127 filter2t: 4.99432009837 filter2l: 4.9499274483 filter3t: 4.8721376543 filter3l: 4.75815178722 filter4: 3.86890220203 filter5: 3.73075037996 C function filter2a: 3.6114880356 filter2b: 2.18989099755 filter2t: 3.73375104874 filter2l: 3.60997196065 filter3t: 3.68825664697 filter3l: 3.58173029097 filter4: 2.21596360152 filter5: 2.64008410331 So, the most naive version (with common optimisations) works fastest for C functions (operator.truth *is* a C function, isn't it?) but the difference is minimal, Bengt's works fastest for Python functions with a fair difference. I actually expected it to be the other way around ... Tim Delaney From pyth at devel.trillke.net Thu Jun 13 14:58:52 2002 From: pyth at devel.trillke.net (holger krekel) Date: Thu, 13 Jun 2002 20:58:52 +0200 Subject: why not "'in' in 'in'"? In-Reply-To: <60FB8BB7F0EFC7409B75EEEC13E20192158ED1@admin56.narex.com>; from BPettersen@NAREX.com on Thu, Jun 13, 2002 at 11:35:09AM -0600 References: <60FB8BB7F0EFC7409B75EEEC13E20192158ED1@admin56.narex.com> Message-ID: <20020613205852.E6609@prim.han.de> Bjorn Pettersen wrote: > > From: Grant Griffin [mailto:not.this at seebelow.org] > > That's not a bad suggestion, Mark, but if I did that I guess > > I would be forever wondering if I was testing whether the > > first one was in the second or the second one was in the > > first. Again, it doesn't read nearly as well as: > > > > if x in subject: > > ... > > > > which leaves no doubt. > > Ok, how about: > > >>> class mystr(str): > ... def __contains__(self, s): > ... return self.find(s) >= 0 > ... > >>> 'hello' in mystr('hello world') > 1 > >>> 'foo' in mystr('hello world') > 0 > >>> that's fine. but usually you don't want to make up an instance for every string you get from somewhere. I still think that patching 'stringobject.c' to get the reasonable behaviour might be worth a try for python2.3. holger From shagshag13 at yahoo.fr Sat Jun 1 09:34:42 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Sat, 1 Jun 2002 15:34:42 +0200 Subject: Which is fastest dict or list.index() ? Message-ID: I need a structure to hold a correspondence between toons and id like {'Bugs' : 0, 'Mickey' : 1, 'Babs' : 2, 'Jerry' : 3, 'Tom' : 4, 'Babs' : 5} I must be able to alpha sort these toons (without loosing their id), and access a toon from an id or an id from a toon. By now a use a dict and a list : the dict gives index from a toon, and the list gives me a toon from an index. {'Bugs' : 0, 'Mickey' : 1, 'Babs' : 2, 'Jerry' : 3, 'Tom : 4, 'Babs' : 5} ['Bugs', 'Mickey', 'Babs', 'Jerry', 'Tom', 'Babs'] (the id is used somewhere else a key to a collection of elements) My question is which is the best way (best = quickest and memory safe) to handle this ? Should i subclasse from dict or list ? Should i consider using only one list with toons (and use their index as id) ? Should i use 2 dicts ? Many thanks to you for helping s13. From aahz at pythoncraft.com Thu Jun 6 20:45:20 2002 From: aahz at pythoncraft.com (Aahz) Date: 6 Jun 2002 20:45:20 -0400 Subject: Medium to Large Scale Python Deployments References: Message-ID: In article , Sam Penrose wrote: > >I'm also curious about large amounts of Python, period. Who knows of >~50K Python lines-of-code (LOC) systems? 100K LOC? More? Well, there's Zope. My last formal employment was at a job where we had something like 30-40K LOC. I'd imagine it's moderately rare to get much larger than that, simply because Python is so compact. (A good refactoring run at my last job ought to have shrunk the code by at least 10K, IMO.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I had lots of reasonable theories about children myself, until I had some." --Michael Rios From rnd at onego.ru Sat Jun 8 01:57:54 2002 From: rnd at onego.ru (Roman Suzi) Date: Sat, 8 Jun 2002 09:57:54 +0400 (MSD) Subject: Efficient python programming... In-Reply-To: <3D013FB1.3D7477EA@engcorp.com> Message-ID: On Fri, 7 Jun 2002, Peter Hansen wrote: >Roman Suzi wrote: >> >> On Fri, 7 Jun 2002, Peter Hansen wrote: >> > You forgot the even more important first thing for a beginner: >> > get it correct! The only good way to do this is to write unit >> > tests that prove it. If you don't have tests, you don't have >> > working code (or how can you prove it?). >> >> To prove that code is correct is very difficult (practically impossible). >> Unittests are there to prove that you have errors, not the other way >> around. >> >> Of course, they can increase your confidence in that optimized code is >> equivalent to what you had before. > >I disagree, if the tests are written first (and run, proving that >they will fail when the code is wrong or missing). > >The tests are executable requirement specifications. Running >them "proves" (yes, not 100%... nothing could) that the code >meets the specs. The specs could be wrong of course, but that >doesn't mean the code is broken... I can agree that tests give practical confidence in the tested code, but I was speaking about rigourous verification that code is 'correct'. And tests can test only some subset of input-output mapping. Making tests is an art, is not formal act. I had no intention to say tests are useless, only that they are not a method of proving the correctness of code or correctenss of code modifications. Sincerely yours, Roman Suzi -- \_ Russia \_ Karelia \_ Petrozavodsk \_ rnd at onego.ru \_ \_ Saturday, June 08, 2002 \_ Powered by Linux RedHat 7.2 \_ \_ "Things are getting worse. Please send chocolate." \_ From peter at engcorp.com Mon Jun 24 11:19:00 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 24 Jun 2002 11:19:00 -0400 Subject: sys.exc_info() into string References: <3D1635B2.99BCD944@engcorp.com> <00GR8.44905$n4.10556369@newsc.telia.net> Message-ID: <3D173864.EF3A6AE9@engcorp.com> Magnus wrote: > > Peter Hansen wrote: > > try: > > 1/0 > > except Exception, ex: > > print "Error: %s" % ex > > > > Good enough?? > > Thanks both of you. I'm still learning Python and issues that are trivial to > solve for some isn't trivial for me yet. I'm converting from C++ and Java > and perhaps in a few months I might be a more experienced Python > programmer. Hi Magnus, don't think just because our replies are sometimes very concise that we think the solutions are trivial. I remember having to go through the same learning curve as you (short and fun though it is with Python) and not knowing how to do the above. This newsgroup operates by throwing a dozen small answers at people, and the odd monster response by one of the bots. Usually, but not always, we try to teach you how to catch fish rather than just handing you the bowl of chowder. Welcome to Python. :) -Peter From mwh at python.net Tue Jun 18 07:31:42 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 18 Jun 2002 11:31:42 GMT Subject: "Fatal Python error: GC object already in linked list" References: Message-ID: Alexander Schmolck writes: > Just got the following in an interactive session: > > >>> reload(awmstools) > Exception exceptions.RuntimeError: 'maximum recursion depth exceeded' in ignored > Fatal Python error: GC object already in linked list > > Process Python aborted > > Any ideas as to what might be the cause? Is this the lastest version of Python? Is it reproducible? Cheers, M. -- You can lead an idiot to knowledge but you cannot make him think. You can, however, rectally insert the information, printed on stone tablets, using a sharpened poker. -- Nicolai -- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html From aahz at pythoncraft.com Fri Jun 14 23:47:30 2002 From: aahz at pythoncraft.com (Aahz) Date: 14 Jun 2002 23:47:30 -0400 Subject: Using Python to script a game? References: Message-ID: In article , Gerhard =?iso-8859-15?Q?H=E4ring?= wrote: > >Yes. And it would be a pretty good match, too. There's even been a >commercial game that uses Python for internal scripting, its name >escapes me, though. Blade of Darkness. It's a first-person shooter, too, so that ought to be all the evidence needed to prove that Python is fast enough. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From bowman at montana.com Sat Jun 8 21:03:29 2002 From: bowman at montana.com (bowman) Date: Sat, 08 Jun 2002 19:03:29 -0600 Subject: Program mysteriously STOPS! References: Message-ID: LJD wrote: > > The following code is designed (at least thats my intent) to run forever. > The program should sit in a loop until it connects with the server.??It > should just loop and loop and loop. where do you close the socket, other than in the exception handler? you may be using up all the file descriptors allowed for a process. From nookieNO_SP_AM at online.no Wed Jun 5 12:00:19 2002 From: nookieNO_SP_AM at online.no (Erlend J. Leiknes) Date: Wed, 05 Jun 2002 16:00:19 GMT Subject: distutils and distributing "scripts" References: Message-ID: do not call the files .pyw, just use py when you then use py2exe, do the following python setup.py py2exe -w the -w means --window or --windows (dont remember), anyway, this will use the pythonw.exe. "Hugo van der Merwe % str (33) >" < wrote in message news:adl4e4$19ep$1 at news.adamastor.ac.za... > I have recently started using distutils. I have a .pyw file for the windows > users, how do I get this to be a part of my ... sdist, for example? > > I have added this to the scripts list passed to "setup()", this seems to me > the "correct" place for it (I want to eventually play with py2exe). > > It seems "python setup.py sdist" does not add "scripts" by default though, > just the py_modules. The docs seem to confirm this. How do I get my .pyw > file distributed, do I really have to go and do all that MANIFEST.in stuff, > just for this one file? > > Thanks, > Hugo van der Merwe From jimmy at retzlaff.com Tue Jun 4 00:24:44 2002 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Mon, 3 Jun 2002 21:24:44 -0700 Subject: Fatal Python error: GC object already in linked list Message-ID: Amit Mongia [mailto:mongiaamit at yahoo.com] writes: > I am running a program using pycurl, to upload files on a server. I > am using Python 2.2.1. I am using threads and lists in my program. the > application just keeps waiting for new files to arrive and uploads > them. There are times my program errors out and crashes with this > error message. > > Fatal Python error: GC object already in linked list I had a similar problem where a background thread was periodically checking if the main thread had added anything to a list and my program would crash with this same message (the crash didn't occur anywhere near the list however). It was quite random and many different things would make it disappear. One of those things was using the Queue class from the standard library instead of a list to communicate between my two threads. Maybe something to try. Good luck. Jimmy From skip at pobox.com Tue Jun 11 10:09:41 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 11 Jun 2002 09:09:41 -0500 Subject: MySQLdb warnings problem In-Reply-To: References: Message-ID: <15622.1189.268647.346102@12-248-41-177.client.attbi.com> Andy> There isn't (as far as I know) a MySQLdb mailing list, but Andy> questions of this type are very welcome at the db-sig mailing list Andy> (db-sig at python.org or Andy> http://mail.python.org/mailman/listinfo/db-sig). The mysql-python project on SourceForge has two forums (help and open discussion): http://sourceforge.net/forum/?group_id=22307 Andy Dustman's pretty prompt at answering questions. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) Boycott Netflix - they spam - http://www.musi-cal.com/~skip/netflix.html From bokr at oz.net Mon Jun 24 13:04:18 2002 From: bokr at oz.net (Bengt Richter) Date: 24 Jun 2002 17:04:18 GMT Subject: converting an array of chars to a string References: <3d12dda2_6@news.newsgroups.com> <3d17038e_6@news.newsgroups.com> Message-ID: On Mon, 24 Jun 2002 13:40:51 +0200, JB wrote: >Bengt Richter wrote: > >> Have a look at the array module. It can construct an array >> of signed or unsigned character elements optionally >> initialized with values from a list or string. >[...] > >Thank you very much. In principle, this was exactly, for >what I was looking. But most unforunately if I declare such >an array a, then > >a[0]=210 >a[0] += 46 > >produces an error instead of the correct result 0. Now I am >a bit desperate. No cause for desperation ;-) Are you saying that you want modulo 256 arithmetic on unsigned 8-bit data? No problem. But what does your data represent? And what does adding a number to such a data item mean in the real world? Let's look at the problem: >>> import array >>> a = array.array('B',[210]) >>> a array('B', [210]) >>> a[0] 210 >>> a[0] += 46 Traceback (most recent call last): File "", line 1, in ? OverflowError: unsigned byte integer is greater than maximum It's just saying you tried to store 256 in a byte. You can't expect the array module to know what policy you want to use in dealing with oversize numbers. For another person's application it might be just as reasonable to clamp >255 at the max value of 255, and clamp <0 at 0. If you want to enforce modulo 256, you can: >>> a[0] 210 >>> a[0] = (a[0]+46)%256 >>> a[0] 0 Or do it with a bit mask and bitwise '&' operation: >>> a[0]=210 >>> a[0] 210 >>> a[0] = (a[0]+46)&255 >>> a[0] 0 Or you could write yourself a wrapper to hide that stuff just for indexed single item access: >>> class A256: ... def __init__(self, byte_arr): self.a = byte_arr ... def __getitem__(self, i): return self.a[i] ... def __setitem__(self, i, v): ... self.a[i] = v&255 ... def __len__(self): return len(self.a) ... Now make the array as usual >>> import array >>> a = array.array('B',[210,46,0,255]) Wrap it >>> w = A256(a) Try some indexed sequence things >>> w[0] 210 >>> len(w) 4 >>> [x for x in w] [210, 46, 0, 255] Note that we can see the original array as an attribute of the wrapper >>> w.a array('B', [210, 46, 0, 255]) And the same thing directly, since we kept a separate 'a' binding >>> a array('B', [210, 46, 0, 255]) Add some recognizable stuff using array methods (that aren't available as methods of this wrapper) >>> w.a.fromstring('') Notice that 'a' refers to the same >>> a array('B', [210, 46, 0, 255, 60, 65, 66, 67, 62]) >>> a.tostring() '\xd2.\x00\xff' Now your complaint: >>> a[0] +=46 Traceback (most recent call last): File "", line 1, in ? OverflowError: unsigned byte integer is greater than maximum Which is what it was designed to do, but we now have a wrapper >>> w[0] +=46 >>> w[0] 0 Which gave the "correct" result, and is also visible through 'a' >>> a[0] 0 Look at another item both ways >>> a[1],w[1] (46, 46) Add with no expected overflow >>> w[1]+=209 >>> a[1],w[1] (255, 255) Now expect overflow and "correction" >>> w[1]+=1 >>> a[1],w[1] (0, 0) See it in the array both ways >>> a array('B', [0, 0, 0, 255, 60, 65, 66, 67, 62]) >>> w.a array('B', [0, 0, 0, 255, 60, 65, 66, 67, 62]) >>> Wrapping like that will cost a little speed, but you'll have to balance benefits vs ease etc. Unless you're processing megabytes regularly, you probably don't have to worry. If speed is a problem, there will be ways to improve that. > >This is like many things in the Python library: they look >good at first sight but when you take a closer look at >them, you see, that... ... you have a great basis for solving almost any problem, and all you need is some imagination to tailor them to your specific requirements? ;-) Regards, Bengt Richter From peter at engcorp.com Fri Jun 7 08:17:26 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 07 Jun 2002 08:17:26 -0400 Subject: Efficient python programming... References: Message-ID: <3D00A456.4315EDA3@engcorp.com> Eddie Corns wrote: > > A friend is fond of quoting this to me: > > Rules of Optimization: > Rule 1: Don't do it. > Rule 2 (for experts only): Don't do it yet. > -- M.A. Jackson > > I wasn't going to bother contributing since others have said the same thing > but the more people say the more you'll believe it :) > > Especially for a beginner the important thing is to get clear and obvious > code. Later, IF IT ISN'T FAST ENOUGH, then you think about ways to speed it > up. You forgot the even more important first thing for a beginner: get it correct! The only good way to do this is to write unit tests that prove it. If you don't have tests, you don't have working code (or how can you prove it?). -Peter From martin at v.loewis.de Thu Jun 6 16:35:32 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 06 Jun 2002 22:35:32 +0200 Subject: 64-bit Python? References: Message-ID: "Bjorn Pettersen" writes: > Are you using Win64 on IA-64? Last time I checked (using the MS > compiler) a long was still 32 bits, and you had to use __int64 to > get a 64 bit integer... Yes, Win64 is known for not using LP64. Many people consider this a mistake. Of those, a majority is not surprised since it comes from Microsoft :-) Regards, Martin From mkelly2002 at adelphia.net Sat Jun 8 13:21:17 2002 From: mkelly2002 at adelphia.net (Michael Kelly) Date: Sat, 08 Jun 2002 13:21:17 -0400 Subject: Removing ^M References: Message-ID: Michael Hall wrote: > Python ... I love it! I knew about dos2unix but it's not on my box for > some reason, and downloading and installing it seemed like overkill. > This script worked like a charm. > If you're on a unix flavor this works pretty well tr -d '\015' outfile -- "Only choice is an oxymoron." From holger at trillke.net Mon Jun 3 17:43:13 2002 From: holger at trillke.net (holger at trillke.net) Date: Mon, 3 Jun 2002 23:43:13 +0200 Subject: optimize lambda usages with strings Message-ID: <20020603234313.A22545@prim.han.de> Hello fellow-minimalists, While skimming the python-standard library (2.3a0) i noticed some inefficient usages of lambdas, e.g.: asyncore.py: info = '[' + '] ['.join(map(lambda x: '|'.join(x), tbinfo)) + ']' cgi.py: plist = map(lambda x: x.strip(), line.split(';')) inspect.py: formatvarargs=lambda name: '*' + name, inspect.py: formatvarkw=lambda name: '**' + name, inspect.py: formatvarargs=lambda name: '*' + name, inspect.py: formatvarkw=lambda name: '**' + name, For example the last line can be rewritten as: formatvarkw='**'.__add__ or the 'asyncore.py' line as .... map ('|'.join, tbinfo) resulting in shorter and faster code. Besides i have often seen and used myself the idiom: filter(lambda x: x=='whatever', list) which can be rewritten as filter('whatever'.__eq__, list) (*) I didn't bother to actually time the speed-increase. But i guess it's significant for these simple cases. Anyway, i wanted to share these little thoughts just in case someone finds it interesting. have fun, holger (*) although i somewhat dislike the '.__eq__, line noise and would prefer to write '.equals, From dm_top at hotmail.com Fri Jun 21 12:04:10 2002 From: dm_top at hotmail.com (Dmitri) Date: 21 Jun 2002 09:04:10 -0700 Subject: Python+Cygwin+XML SAX build failure of PyXML 0.7.1 Message-ID: <59d8a5f6.0206210804.25353aa3@posting.google.com> Hello, (possibly this is the second message, I have had a little prob., so sorry if it is, but this message contains the source info :) Source from http://sourceforge.net/project/showfiles.php?group_id=6473: PyXML-0.7.1.tar.gz 606480 2060 Platform-Independent Source .gz Target: I need the XML SAX parser for Python under Cygwin. (And I can not find precompiled version for Cygwin) --------------------------------------------------------------- Precondition: *Windows 2000 Prof. *CygWin ver.: 2.194.2.22 *GCC ver.: 2.95.3-5 Reading specs from /usr/lib/gcc-lib/i686-pc-cygwin/2.95.3-5/specs gcc version 2.95.3-5 (cygwin special) *Python ver.: 2.2.1 $ python Python 2.2.1 (#1, Jun 6 2002, 16:53:43) [GCC 2.95.3-5 (cygwin special)] on cygwin --------------------------------------------------------------- Description of the problem: After unpacking of the tarball, the issuing the python setup.py build cause the following compiling error during building the expat extention: . . -- copying --- . . copying xml/xslt/_4xslt.py -> build/lib.cygwin-1.3.10-i686-2.2/_xmlplus/xslt copying xml/xslt/__init__.py -> build/lib.cygwin-1.3.10-i686-2.2/_xmlplus/xslt running build_ext building '_xmlplus.parsers.pyexpat' extension creating build/temp.cygwin-1.3.10-i686-2.2 gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -DUSE_DL_IMPORT -DHAVE_EXPAT_H -DV ERSION="1.95.2" -DXML_NS=1 -DXML_DTD=1 -DXML_BYTE_ORDER=12 -DXML_CONTEXT_BYTES=1 024 -Iextensions/expat/lib -I/usr/local/include/python2.2 -c extensions/pyexpat. c -o build/temp.cygwin-1.3.10-i686-2.2/pyexpat.o extensions/pyexpat.c:1709: initializer element is not constant extensions/pyexpat.c:1709: (near initialization for `handler_info[2].setter') extensions/pyexpat.c:1712: initializer element is not constant extensions/pyexpat.c:1712: (near initialization for `handler_info[3].setter') extensions/pyexpat.c:1715: initializer element is not constant extensions/pyexpat.c:1715: (near initialization for `handler_info[4].setter') extensions/pyexpat.c:1718: initializer element is not constant extensions/pyexpat.c:1718: (near initialization for `handler_info[5].setter') extensions/pyexpat.c:1727: initializer element is not constant extensions/pyexpat.c:1727: (near initialization for `handler_info[8].setter') extensions/pyexpat.c:1736: initializer element is not constant extensions/pyexpat.c:1736: (near initialization for `handler_info[11].setter') extensions/pyexpat.c:1739: initializer element is not constant extensions/pyexpat.c:1739: (near initialization for `handler_info[12].setter') extensions/pyexpat.c:1742: initializer element is not constant extensions/pyexpat.c:1742: (near initialization for `handler_info[13].setter') extensions/pyexpat.c:1745: initializer element is not constant extensions/pyexpat.c:1745: (near initialization for `handler_info[14].setter') extensions/pyexpat.c:1754: initializer element is not constant extensions/pyexpat.c:1754: (near initialization for `handler_info[17].setter') extensions/pyexpat.c:1757: initializer element is not constant extensions/pyexpat.c:1757: (near initialization for `handler_info[18].setter') extensions/pyexpat.c:1760: initializer element is not constant extensions/pyexpat.c:1760: (near initialization for `handler_info[19].setter') extensions/pyexpat.c:1763: initializer element is not constant extensions/pyexpat.c:1763: (near initialization for `handler_info[20].setter') error: command 'gcc' failed with exit status 1 --------------------------------------------------------------- Workaround: the simple code review and primitive test like: void funcA(int a, int b) { printf("from A: %d, %d\n", a, b); } void funcB(int a, int b) { printf("from B: %d, %d\n", a, b); } typedef void (*PF)(int, int); struct S { const char * _F; PF _pf; }; extern struct S ars[2]; static struct S ars[] = { {"funcA", funcA }, {"funcB", funcB }, }; int main() { printf("%s ", ars[0]._F); ars[0]._pf(1, 2); printf("%s ", ars[1]._F); ars[1]._pf(3, 4); return 0; } and $ gcc -o test main.c shows that everything should be all right. But it is not... --------------------------------------------------------------- Searching the net: 1. I did not find the precompiled version of the PyXML for cygwin. Does someone know where can I get it, it it does exist? 2. The problem like "initializer element is not constant" is shown but the recommendations goes to the updating of the gcc compiler with unclear direction. That's possibly true, but instalation of the GNU's projects under cygwin is a different story. And it's hard to beleive that the upgrating compiler would fix this problem... Thank you. With the best regards, Dmitri From K.Rdt at TU-Berlin.DE Fri Jun 28 02:27:29 2002 From: K.Rdt at TU-Berlin.DE (Klaus Reinhardt) Date: Fri, 28 Jun 2002 08:27:29 +0200 Subject: crypt for windows? In-Reply-To: <7x6604vsj3.fsf@ruckus.brouhaha.com> Message-ID: Am 28.06.02 08:14:40, schrieb Paul Rubin : >I don't understand your question then. ------------------------------------------------------------------- Hi Well I have some batch-files with my login and password and want to encrypt them with another password. Meanwhile I got fcrypt .. K at Rdt --------------------------------------------------------------------- From james.kew at btinternet.com Sat Jun 29 15:22:48 2002 From: james.kew at btinternet.com (James Kew) Date: Sat, 29 Jun 2002 20:22:48 +0100 Subject: Most efficient way to write data out to a text file? References: <3d1a6993.248534625@netnews.attbi.com> <3d1dc547.468619140@netnews.attbi.com> Message-ID: "Dave Kuhlman" wrote in message news:afkv73$f2274$1 at ID-139865.news.dfncis.de... > candiazoo at attbi.com wrote: > > 4) I localized constants I was using in boolean > > tests (there were declared at the beginning of the module, I moved > > them to the function call just before the loop). > > Is finding things in globals slower than finding them in locals? Yes: you have to look, and fail to find, in the locals before you look in the globals. James From jubafre at zipmail.com.br Mon Jun 24 10:44:44 2002 From: jubafre at zipmail.com.br (jubafre at zipmail.com.br) Date: Mon, 24 Jun 2002 11:44:44 -0300 Subject: =?iso-8859-1?Q?HELP=2DME=20pLEASE?= Message-ID: <3D172BFB00000167@www.zipmail.com.br> i don?t know how to make a .exe,i?m atachin the file .py SOmebody can compile for me please a need the .exe urgently!!!! Juliano www.gebrasil.hpg.com.br ------------------------------------------ Use o melhor sistema de busca da Internet Radar UOL - http://www.radaruol.com.br -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: lfa.py URL: From mfranklin1 at gatwick.westerngeco.slb.com Mon Jun 17 08:47:39 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Mon, 17 Jun 2002 12:47:39 +0000 Subject: unhashable type when using pickle.load() In-Reply-To: References: Message-ID: <200206171151.g5HBpMB12546@helios.gatwick.geco-prakla.slb.com> On Monday 17 Jun 2002 10:03 am, you wrote: > I wonder if anyone can shed some light on a troublesome intermittent > problem I am having. > > Firstly the necessary: > I am running on windows XP, using jython 2.1 and java 1.3.1_03. > > A pickled file is created as follows: > pickle.dump((self.seq.getMotifs(), self.s[self.seqIdx]), > newFile) > > self.seq.getMotifs() simply returns a dictionary containing various complex > python objects (which will have been created and used sucessfully) > > self.s[self.seqIdx] is a python sequence object. > > > Intermittently, when I try and reload from this pickle file I get the > following exception: > > > Exception occurred during event dispatching: > Traceback (innermost last): > File "pars.py", line 129, in OpenFile > File "D:\program files\jython-2.1\Lib\pickle.py", line 947, in load > File "D:\program files\jython-2.1\Lib\pickle.py", line 567, in load > File "D:\program files\jython-2.1\Lib\pickle.py", line 885, in > load_setitem > TypeError: unhashable type > > I have read that this error typically can occur when a pyDictionary or > pyList is inserted into a hashtable. Is this a problem that anyone else is > familiar with, is it a limitation of the jython implementation of pickle? > > Any help will be appreciated > > Blobby Mark, Could you be falling foul of a file close() problem IOW are you closing the file explicitly? This could be a GC thing (discussed recently) where java rather than python's GC is not closing the file when it goes out of scope.... Could be way off but worth saying. Cheers, Martin From oren-py-l at hishome.net Sat Jun 15 09:59:15 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Sat, 15 Jun 2002 16:59:15 +0300 Subject: Pronouncing '__init__' In-Reply-To: <20020615134410.A15079@prim.han.de>; from pyth@devel.trillke.net on Sat, Jun 15, 2002 at 01:44:10PM +0200 References: <20020615132519.A14452@hishome.net> <20020615134410.A15079@prim.han.de> Message-ID: <20020615165915.A17174@hishome.net> On Sat, Jun 15, 2002 at 01:44:10PM +0200, holger krekel wrote: > for oral language: > > init constructor > > and if the context allows > > init > > for written languange __init__ > > Isn't it obvious? :-) > > holger I used __init__ just as an example. I meant how do you pronounce names with leading and trailing double underscore in general. The magic name __init__ may be by far the one most commonly encountered in everyday programming but __there__ __are__ __many__ __others__. Oren From jimmy at retzlaff.com Mon Jun 3 16:08:51 2002 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Mon, 3 Jun 2002 13:08:51 -0700 Subject: Version strings in executable created by Py2exe Message-ID: Robert L. Oelschlaeger [mailto:roelsch at comtrak.com] wrote: > Running with Python 2.2. I've created myAppName.exe using Py2exe, with > the "version_companyname" and "version_legalcopyright" specified in > the setup .cfg file as follows: ... > Why are the version_companyname and version_legalcopyright strings not > installed for the "Company Name" and "Copyright"? "version" should be followed by a dash rather than an underscore. So, for example, you should use "version-companyname" rather than "version_companyname". Jimmy From giulio.agostini.remove.this at libero.it Thu Jun 6 17:39:11 2002 From: giulio.agostini.remove.this at libero.it (Giulio Cespuglio) Date: Thu, 6 Jun 2002 21:39:11 +0000 (UTC) Subject: Extracting data from HTML References: <82096df4.0205311152.5891a17b@posting.google.com> <1022883953.6150.5802.camel@localhost> <82096df4.0206010201.736c4b2c@posting.google.com> <23891c90.0206050321.d6a64c3@posting.google.com> Message-ID: <4slvfucpesg4ikfs3dfrjo8deio5de24ph@4ax.com> > http://www.boddie.org.uk/python/HTML.html Hi Paul, Thanks a lot for this resource. To be honest, I wonder how you could work out how to use htmllib, IMHO the documentation is very poor. Actually, I am happily using the flexibility of regular expressions to do these things ATM, but I'm willing to give this library a try. Cheers, Giulio From eppstein at ics.uci.edu Thu Jun 20 19:39:23 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Thu, 20 Jun 2002 16:39:23 -0700 Subject: Are generators in nested functions possible? References: Message-ID: In article , David Eppstein wrote: > This is a no-op. Did you mean > for x in genInd(res+[val],length-1): return x > ? Oops, that should be yield, not return, of course... -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From donn at u.washington.edu Wed Jun 19 17:01:10 2002 From: donn at u.washington.edu (Donn Cave) Date: 19 Jun 2002 21:01:10 GMT Subject: What If..... Strong Types References: <3D10D17B.6070004@bgb.cc> Message-ID: Quoth Don Garrett : | brueckd at tbye.com wrote: |> Worse, to make it be "good code" I'll |> probably define -1 to be NOT_WEIGHED or something, and check against it so |> I'm not using magic numbers. | | I might suggest the use of None over -1, since it has a real meaning of | 'not really there'. But not defining the member would have the same meaning as | well. I do get your point here. The statically typed languages I've been fooling around with, like Haskell, allow for this with a type that's basically a union of whatever value, or Nothing. You can have a non-value, but you can't write code that treats it as a value without resolving that ambiguity. |> It's sometimes hard for me to model my objects this way because of having |> had to always do it the other (completely statically defined) way, but |> when this approach works the solutions are often quite elegant and |> straightforward (btw - I believe that a good portion of bugs and program |> cruftiness is related to forcing the programmer to clearly define, up |> front, what the complete type of the object is. In many cases this forces |> the programmer to make decisions without enough information, in others it |> is too constricting, and in others it's just too tedious to make the |> programmer worry about all those details, and in all cases general |> hackiness ensues). | The point about programmers having to make decisions about the data before | they are ready is a very good one. I've certainly run into that myself, but | I've never heard it phrased that way, so it never clicked the way it just did. | | Don't you find that you miss the advantages of a clear definition of what a | class is and/or does? That's more important with group development, but even | when it's just me.... I need memory aids. Some languages, again like Haskell, manage to infer types and don't require declarations. In this case, you might actually add declarations later in the development process, for the kind of clarity you're talking about - Haskell software already tends to be pretty damned abstract. It also can help clarify the source of the problem when there's an error. I'm not in a position to be writing big projects in Haskell, but in my casual experiments with static type inferring languages so far, I like it. I'm no big picture architect, any software more than the simplest thing usually takes me several general rewrites. Static typing catches a very large number of errors in my program, and in fact that helps me rewrite more rapidly, because the compiler is doing work that I would otherwise have to do myself. Type inference makes the compiler do a lot more of that work, and allows me to express functions at an appropriate level of abstraction. Put together, the result is much stricter and more type safe than a language like C, which allows all kinds of casting and promotion and so forth, and yet more convenient to work with. (Note that I'm talking strictly about typing here, and not making any more general claim about Haskell or other similar languages.) The place I find dynamic typing particularly annoying is in exception handling. The handler receives this parameter that is of some type, whose value may or may not be a tuple, may or may not have an 'errno' attribute, etc. Even qualified by exception, for example the structure of a socket exception is somewhat variable. And of course one would like to avoid raising an exception from the damned exception handler. Wouldn't it be nice if there were some way for the socket module to export the complete type information for its exception, and for the interpreter to check your operations on the exception value against that type? Like, except socket.error, v: # socket.error :: { args :: (Int, String) | (String,) } # phrase = v.args[1] # ^ oops! Here v.args is (a, String, ...) # but was declared as (Int, String) | (String,) phrase = v.args[-1] # ... ahh, that's better. sys.stderr.write('ouch: ' + phrase + '\n') Maybe an interpreter flag meaning "compile this module to byte-code and check against exported type signatures." Donn Cave, donn at u.washington.edu From whisper at oz.net Wed Jun 5 05:35:31 2002 From: whisper at oz.net (David LeBlanc) Date: Wed, 5 Jun 2002 02:35:31 -0700 Subject: writing a chat program In-Reply-To: Message-ID: If you want control of the console layout, you might care to have a look at PySlang and sLang, which are curserish. Should be possible to split the console into two sub-windows for sending/receiving. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Shaun Whelden > Sent: Tuesday, June 04, 2002 9:41 > To: python-list at python.org > Subject: writing a chat program > > > Hi all, > I'm trying to throw together a simple text-based chat program in > Python. Here's the problem I have right now: I need a way to allow > the user to be entering in a message they want to send, while at the > same time waiting for any data that may come through the socket. If > data does come through the socket, I need the user to be able to > continue typing while the data is printed to the screen. > > I'm writing this on a Windows machine, so curses is out of the > question. Also, I want this to be a text based program, so I don't > want to have to mess around with Tkinter or any other forms of GUI > unless I have to. I'm pretty sure that I need to do something > involving thread.py and/or threading.py, but I've never used a thread > before in my life. Can anyone help? > > Shaun Whelden > shaunw at liberateschool.com > -- > http://mail.python.org/mailman/listinfo/python-list From mcfletch at rogers.com Fri Jun 7 01:15:32 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 07 Jun 2002 01:15:32 -0400 Subject: How do you read unicode files? References: Message-ID: <3D004174.5070200@rogers.com> Well, on my win2k machine, I can create a text file using notepad and specify that it's in "Unicode" format (utf16) and load it with: unicode( open( filename, 'r').read(), 'utf16' ) That works even if there's ANSI characters > 128, and even if I specify "big-endian unicode" in notepad. unicode( open( filename,'r').read(), 'utf8' ) works if I specify "UTF-8" format in notepad. Depending on what format you want for the "standard string", you'd then just call, for instance .encode( 'utf8') on the resulting unicode object. Here's a sample session: >>> data = open( filename,'r').read() >>> data '\xff\xfeT\x00e\x00s\x00t\x00i\x00n\x00g\x00 \x00u\x00n\x00i\x00c\x00o\x00d\x00e\x00\r\x00\n\x00\xe1\x00\xed\x00' >>> u = unicode( data, 'utf16' ) >>> u u'Testing unicode\r\n\xe1\xed' >>> u.encode( 'utf8') 'Testing unicode\r\n\xc3\xa1\xc3\xad' >>> u.encode( 'iso8859-1' ) 'Testing unicode\r\n\xe1\xed' >>> That last is a plain, windows-native-encoding (well, my windows-native encoding ;) ) of the unicode as a simple Python string. HTH, Mike Matt Gerrans wrote: > How do you read in a unicode file and convert it to a standard string? > > It seems that when you open a file and read it, what you get is a string of > single-byte characters. I've tried all kinds of permutations of calls to > unicode(), decode(), encode(), etc. with different flavors of encoding > ('utf-8', 'utf-16' and so on). > > I could parse the data myself (skipping the initial two bytes and then every > other one -- I'm only working with ASCII in double byte format, so the high > order byte is always 0), but I imagine there must be a way to get the > existing tools to work. > > What I want to be able to do is write a search and replace tool that will > work equally well on ANSI and Unicode (or double-byte) text files (without > changing the file type, of course)... > > -- _______________________________________ Mike C. Fletcher http://members.rogers.com/mcfletch/ From candiazoo at attbi.com Wed Jun 26 21:28:22 2002 From: candiazoo at attbi.com (candiazoo at attbi.com) Date: Thu, 27 Jun 2002 01:28:22 GMT Subject: Most efficient way to write data out to a text file? Message-ID: <3d1a6993.248534625@netnews.attbi.com> I assume some sort of block i/o or preallocating a large block of file space would be the best way to do it? I am outputting about 700,000 records to a text file and my program only spits out about 20 records per second. This is using standard file open and write... This is on a W2K machine... perhaps I should use the win32file interface? Any thoughts/opinions? Thank you! Mike J. From peter at engcorp.com Wed Jun 19 08:40:08 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 19 Jun 2002 08:40:08 -0400 Subject: Python+ASP->import problem References: Message-ID: <3D107BA8.87696860@engcorp.com> J?rvinen Petri wrote: > > When importing my modules, I always get AttributeError for attributes that > surely exist on imported module. > > > Response.Write(enactHTML.defineCSS('Enact Main')) > AttributeError: 'module' object has no attribute 'defineCSS' > Not familiar with ASP, but is it possible to troubleshoot this by using Response.Write(dir(enactHTML)) instead? Then you'll know exactly what is available in that module... if it works. -Peter From gerhard at bigfoot.de Wed Jun 19 11:04:12 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Wed, 19 Jun 2002 17:04:12 +0200 Subject: procmail replacement in Python In-Reply-To: <20020619181953.E4127@phd.pp.ru> References: <20020619181953.E4127@phd.pp.ru> Message-ID: <20020619150411.GB11789@lilith.my-fqdn.de> * Oleg Broytmann [2002-06-19 18:19 +0400]: > On Wed, Jun 19, 2002 at 09:08:53AM -0500, Mark McEahern wrote: > > http://www.qcc.sk.ca/~charlesc/software/getmail-2.0/ > > "A POP3 mail retriever..." Hence, it is not fetchmail replacement, as > fetchamil also does IMAP, and does it very well. I don't need to retrieve emails from an IMAP server, and the whole point of the exercise for me is to put them into my IMAP server at home. It also looks an easy task to enhance getmail to include imap support. Hey, it's written in Python, not C, where you'd need to reinvent to protocol handling for the n-th time. > Fetchmail also has good GUI configuration program, written in Python > and Tkinter. Pointless. fetchmail (and getmail even more) configuration is very easy. If there were a GUI tool to write procmail rules, now that would make sense. But even then only if it included a regex-wizard ;-) Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From phr-n2002b at NOSPAMnightsong.com Fri Jun 28 03:35:41 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 28 Jun 2002 00:35:41 -0700 Subject: crypt for windows? References: Message-ID: <7xk7ojq2ia.fsf@ruckus.brouhaha.com> Klaus Reinhardt writes: > Hi > Well I have some batch-files with my login > and password and want to encrypt them > with another password. > Meanwhile I got fcrypt .. Here's a module you can try: http://www.nightsong.com/phr/crypto/p2.py This version still has a date check in it but I I'll try to a real version with no date check in the next few days (I couldn't mess with it last month because I was away). I may make one further change, removing the nonce from the authentication key, which might speed up some as yet nonexistent alternate implementaitons. Comments are welcome and anyone who hasn't checked this thing for bugs, please do so now. From dfackrell at DELETETHIS.linuxmail.org Tue Jun 25 10:38:52 2002 From: dfackrell at DELETETHIS.linuxmail.org (Daniel Fackrell) Date: Tue, 25 Jun 2002 08:38:52 -0600 Subject: GOTO w/ Python? References: Message-ID: <3d18807d$1_1@hpb10302.boi.hp.com> "Delaney, Timothy" wrote in message news:mailman.1024964672.10880.python-list at python.org... > > From: Daniel Fackrell [mailto:dfackrell at DELETETHIS.linuxmail.org] > > > > After skimming the linked page to get a feel for the CAME > > FROM statement, is > > it conceptually different from short procedures? Does the > > only difference > > lie in the fact that for compiled languages one of the > > instances will be > > inline? I do understand that it would have some effect on > > variable scoping, > > but this can be easily handled in other ways. > > > > So what's the benefit that might outweigh the opacity of the > > code created? > > I hope you're not serious ... :) > > COME FROM is a joke. Literally. It is a parody of GOTO whose only redeeming > feature is that it is not GOTO. > > Tim Delaney *WHOOSH* I missed that one completely. Maybe I'm trying too hard. I was actually trying to figure out any possible reason that one would want to use such a construct. I got thinking about compiler-level optimizations, but the overhead involved would outweigh any possible savings in time or compiled code size in almost all cases. Thanks for straightening me out. -- Daniel Fackrell (dfackrell at linuxmail.org) When we attempt the impossible, we can experience true growth. From peter at engcorp.com Sun Jun 2 10:37:31 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 02 Jun 2002 10:37:31 -0400 Subject: How to delete file? References: Message-ID: <3CFA2DAB.140ABF0C@engcorp.com> Ken wrote: > > How do you delete file? os.remove() > If you write to file from beginning position of an existing file, do you > overwrite the existing data or insert from it? You overwrite the data. It's not possible to insert data except by writing the data to a new file, appending the contents of the old file, deleting the old file, then renaming the new one to the old name. -Peter From mhammond at skippinet.com.au Mon Jun 3 21:53:38 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 04 Jun 2002 01:53:38 GMT Subject: using getopt References: Message-ID: <3CFC1E18.4070205@skippinet.com.au> Fernando P?rez wrote: > getopt sucks. Period. Take a look at DPyGetOpt, which implements the > Getopt::Long perl facilities. It's very very nice. I've also heard good > things about optik, but haven't used it myself. It looks like optik will be incorporated into the core Python library (but possibly inside the getopt module). However it actually appears, using optik now will almost certainly make your future transition to the standard library simpler. Mark. From occeanlinux at linuxmail.org Mon Jun 3 17:32:03 2002 From: occeanlinux at linuxmail.org (Gold Fish) Date: Mon, 03 Jun 2002 21:32:03 GMT Subject: Time Message-ID: <3cfbdf0c_1@news.iprimus.com.au> Anyone know how to determine the time in python. If the mtime in the file filename.py is Mon Jun 3 03:25:57 2002 ,if i want to set the time forward or backwards in 5 days time, how can i do that. From jadestar at idiom.com Mon Jun 10 21:31:12 2002 From: jadestar at idiom.com (James T. Dennis) Date: 11 Jun 2002 01:31:12 GMT Subject: Another newbie question References: Message-ID: SA wrote: > I am trying to find a way to list the contents of a directory into a list so > that the contents of the list are then read into an html doc as hrefs. > What I'm looking for is a way to ls a directory. Is there a way to access > the shell command ls from within a python script and dumping the output into > a list for further manipulation? Or does this have to be built from the > ground up inside the python script? > Thanks. > SA You could use popen(): import os listing = os.popen('ls -l').readlines() for eachLine in listing: htmlify(eachLine[:-1]) ... where "htmlify()" is a hypothetical function that you provide to wrap each line in your preferred HTML tags. I'm assuming you DON'T want the trailing linefeeds, so I'm trimming them using the slice ([:-1] is sort of like perl's chop() function). Of course this comes with the stock caveats about using popen() --- the string you pass to popen() is passed to a shell, parsed and executed by that shell and thus subject to many exploits (you *DON'T* want to pass foreign/alien string variables to popen() and you probably don't want to try "sanitizing" them yourself; you probably can't account for all of the ways that an attacker could trick your sanitizer into passing a "dirty" string to the shell). It's probably much safer to use os.listdir() with os.stat(), and some processing of the stat() info using the pwd and grp modules (to look up user and group names given UIDs and GIDs) and the time module to convert the st_mtime field into a readable date/time stamp. You can write your own function to convert octal st_mode values into the usual '-rwxr-x---' format and you'd want to use the stat module to help with that (especially to set the "type" character (- for regular files, l for symlinks, s for UNIX domain sockets, etc) and you'd have to fuss with lstat vs stat for symlinks. In other words re-implementing a basic "ls -al" in Python is likely to take about five or six modules and probably about 100 lines of code. Supporting any significant number of ls options would add quite a bit more code (and maybe require the glob and/or fnmatch modules). On the one hand that's not really alot of work (and you can take shortcuts if you don't need the output to be "just like" ls' -- for example if you don't care to support non-regular files, don't care about the file modes and/or don't care about ls' handling of dates, where it shows one form for files within the last year and another for older files.) That might bring it down to 50 lines of code; which might be considerably less then you'd spend "sanitizing" data to be suitable for passing to popen(). On the other hand, it is alot more work than two lines that it takes to get the ls -l from popen(). Alot also depends on what else you're going to do and how robust you want the app. to be (how you want to to exception handling). using popen(), popen2(), popen3(), and popen4() provides limited exception and error handling). In fact you might have to use the popen2.Popen3() or Popen4() *classes* in the popen2 module in order to get exit code values from your ls commands. That's assuming that you want to gracefully handle some of the errors that you know *could* happen under the circumstances that exist on your system(s) when your script is running. [As usually, writing sometthing that works for optimal input and conditions is reasonably straightforward, accounting for degenerate input and handling exceptional conditions is more challenging]. From peter at engcorp.com Sun Jun 23 22:48:16 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 23 Jun 2002 22:48:16 -0400 Subject: Python hits the spot References: Message-ID: <3D168870.FFC96651@engcorp.com> "Delaney, Timothy" wrote: > > > From: Peter Hansen [mailto:peter at engcorp.com] > > Aahz wrote: > > > Ya know, you could have saved yourself a lot of typing by > > > simply saying PBCAK. ;-) > > > > To save us from those who can't Google: Problem Between > > Chair And Keyboard. > > That's always been PEBCAK to me ... > ^ > Problem Exists Between Chair and Keyboard Ah, /that/ one has 100 times as many google hits... -Peter From merkosh at hadiko.de Sun Jun 9 06:09:41 2002 From: merkosh at hadiko.de (Uwe Mayer) Date: Sun, 9 Jun 2002 12:09:41 +0200 Subject: xml.* getting the hang... Message-ID: hi, i am working myself into the xml.* packages and am just about to start getting an idea of what works together with what in wich order. basically i want to read in xml packages from a byte stream and from these "request" objects i want to create frame-response xml objects, just taking the attributes of a request object and copy them into a response object, leaving the rest blank. i figured that xml.sax and xml.parsers.expat is where to look for. problem number first: - in order to build an xml dom object i have to get started on a Document(); and this is the problem: i couldn't find anything; with one exception, i can create xml documents using xml.dom.minidom.Document(), if this is the regular case then i don't quite see how xml.sax.* and xml.dom.minidom relate to eachother. it feels strange if i use functions from various packages when i'd expect them to be of importance for all sub packages. any expenations? Secondly i found the package xml.dom.pulldom which seems to be just what i'm looking for, however the documentation is very poor on these classe. what, f.e. is a "documentFactory"? I don't want to do xml validating, so xml.parsers.expat could be used, too. So now i don't know what to use at all: 1. xml.parsers.expat: i don't do validating 2. xml.dom.pulldom: i want to create partial dom trees from sax events 3. xml.sax.xmlreader.IncrementalParser(): i read xml from a byte stream Any idea or comments on this? Thanks in advance Uwe From merkosh at hadiko.de Fri Jun 14 23:17:25 2002 From: merkosh at hadiko.de (Uwe Mayer) Date: Sat, 15 Jun 2002 05:17:25 +0200 Subject: file.tell() -- obscure IOError References: Message-ID: In article , merkosh at hadiko.de says... [...] now I did it. I isolated a piece of code which produces the same error in the command line: ---------------------------------- >>> f = file('test.riff.txt') >>> f.seek(0,2) >>> f.tell() 109L >>> f.seek(0,0) >>> while f.tell() < 109L: ... f.read(3) ... '//d' 'ies' Traceback (most recent call last): File "", line 1, in ? IOError: (0, 'Error') >>> ---------------------------------- test.riff.txt contains the following: -------------------------- //dies ist ein beispielkommentar hier nichtmehr\r hier auch nicht //hier schon und hier ist schluss //ende -------------------------- <--- some time later: 5:17 o'clock in the morning ---> i ound the mistake. that is: i know what went wrong, but i still don't know why: f was opened in text mode. calling f = file('test.riff.txt','rb') works fine. assumingly read() took \r and the new line characters as control characters... grml... Ciao Uwe From shagshag13 at yahoo.fr Sun Jun 2 05:44:32 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Sun, 2 Jun 2002 11:44:32 +0200 Subject: Pop a list from beginning ? and memory saving... Message-ID: I had a huge list containing consuming data, as i only need a one pass in a for statement, i'm wondering if by doing this with a pop i could save memory ? (as i think that python free it after the pop...) and is there a way to pop from the beginning of the list ? (i think i could use reverse but i don't know if this memory consuming) >>> a = [1,2,3,4,5,6,7] >>> while 1: try: f = a.pop() except IndexError: break print f thanks, s13. From logiplexsoftware at earthlink.net Tue Jun 18 14:02:25 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Tue, 18 Jun 2002 11:02:25 -0700 Subject: python version? In-Reply-To: <9YBP8.44418$GY.13865843@twister.nyroc.rr.com> References: <3tingu8psfmefoab93pl8gips8hg7sgpvp@4ax.com> <9YBP8.44418$GY.13865843@twister.nyroc.rr.com> Message-ID: <20020618110225.5e83167b.logiplexsoftware@earthlink.net> On Tue, 18 Jun 2002 08:12:53 GMT George Hester wrote: > I think you guys don't how to do it. I think you wouldn't know an answer if it bit you: [You] What is a simple script that will tell me the version of python I am currently running? IIS 5.0 Windows 2000. [Jeremy Yallop] Look up sys.version and sys.version_info. [You] Traceback (innermost last): File " Perhaps you'd like someone to come out and type it for you as well. Please remember that the people on this list aren't being paid to help you write your program. They expect you to do at least /a little/ of the research yourself. It's understandable if you don't know where to look, but when someone points you to the relevant portion of the docs, you should at least read it before asking again. It's clear from your postings that you haven't even read the tutorial. If you can't do that then you should pay someone to write your program for you. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From gcordova at hebmex.com Mon Jun 3 18:47:52 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Mon, 3 Jun 2002 17:47:52 -0500 Subject: Behavior of += (was Re: [Python-Dev] Customization docs) Message-ID: > > The fact that it shows the change is most likely due > to the list not having moved in memory. I hope that > the reference count was handled properly! > > AFIC, this is clearly wrong - operators should > be atomic - no side effects. Either they work, or > they don't. > The thing is that += MUST work also for immutable objects, as well as mutables. So, it does a rebind of the final value obtained --which in a list or dictionary, being mutable, is the same as the initial reference, but in the case of immutable objects, it's a different one than before--. BUT, since it's trying to rebind a tuple's item, and it's not allowed, an exception is raised; this is correct behaviour. So, it's not actually a bug, but an artifact of the hoops Python needs to jump through in order to maintain total dynamism in data types. Instead of this: a = ([1],[2],[3]) a[0] += [3] do this: a = ([1],[2],[3]) t = a[0] t += [3] there won't be any exception, because 't' *can* be rebinded to the value emmited by the += operation; *and* 'a' will also contain the same reference. It's not *totally* equivalent, because it's missing a single, last step: a[0] = t *that* is what's raising the exception, which is what the += operator is trying to do in you're original version. Happy hunting :-) -gustavo From syver-en+usenet at online.no Thu Jun 20 12:15:18 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Thu, 20 Jun 2002 16:15:18 GMT Subject: python cgi + IIS References: <3D0F1813.3010304@gmx.de> <3D102AF2.5010204@gmx.de> Message-ID: Axel Grune writes: > Steve Holden schrieb: > > > http://www.e-coli.net/pyiis.html > > Thats what i read and did ;-( > Hi Axel, you really should put the %s in double quotes ("%s") because the python interpreter won't find the file if you don't (if there are spaces in the path name that is). If you would tell us exactly what you have done, (where you put your .py file, which web application you have modified the app mappings for, and so forth) give an account of all the steps you have performed and it will be easier to tell where you went wrong, we should be able to help you out and get python cgi under IIS on the road. -- Vennlig hilsen Syver Enstad From syver-en+usenet at online.no Thu Jun 20 19:29:26 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Thu, 20 Jun 2002 23:29:26 GMT Subject: Windows versions of Python---pros and cons? References: <3D110B55.4D8AD7FA@astro.cornell.edu> <3D1214B6.E9BB77D2@noaa.gov> Message-ID: Chris Barker writes: > > On that note: does anyone know if there is a way to turn a Python > script > > into something that acts like an application on Windows...without > resorting to Py2exe and the like. What I want is something just like: > > chmod +x scriptname > and a #! line at the top > > on Unix. I want it to work on the windows command line. > Make a text file, save it as something.bat, put the line below in the first line of the file. @python -x "%~f0" %* & goto :EOF or @python -x -OO "%~f0" %* & goto :EOF Put python code in the lines underneath. If you're using emacs and want syntax highlighting: Put # Local Variables: *** # mode:python *** # End: *** at the end of the file I think that this only works on win2k because it uses extensions to the batch language that is not part of win9x family of os'es. -- Vennlig hilsen Syver Enstad From brueckd at tbye.com Tue Jun 4 18:23:16 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Tue, 4 Jun 2002 15:23:16 -0700 (PDT) Subject: urllib, urllib2, httplib -- Begging for consolidation? In-Reply-To: Message-ID: On Tue, 4 Jun 2002, John J. Lee wrote: > On 4 Jun 2002, Dave Brueck wrote: > [...] > > together. For example, what is the correct way to do a HTTP HEAD > > request that follows redirects? It's not hard, but it's silly to have > > to code it yourself if somebody already did the work for you. Well, > > httplib doesn't know how to follow an HTTP redirect, but lo and > > behold, urllib does. Unfortunately, there's no way to use it because > > in this case because urllib is for opening URLs (the GET is hardcoded > > and not easily overridable). > > I suppose the standard answer applies here: it isn't there because > nobody has written it yet. Argh... this misses the whole point of the thread. Never mind, I repent for having revived this topic. -Dave From gcordova at hebmex.com Fri Jun 7 12:52:53 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Fri, 7 Jun 2002 11:52:53 -0500 Subject: Detect events positively Message-ID: > > Hello, > > The following code display two button: > > from Tkinter import * > def Calculate(event = None): > while 1: > pass This loop will never exit, hence, will never return control to Tkinter (and your GUI). > def Exit(event = None): > import sys > sys.exit(0) > root = Tk() > btn_cal = Button(root, text="calculate", command = Calculate) > btn_cal.pack() > btn_exit = Button(root, text="exit", command = Exit) > btn_exit.pack() > root.mainloop() > > if clicked the "calculate" button, the program will fall in a > loop that will never end. So program will not response to clicking > to the "exit" button, so it cannot be terminated normally. If we > don't use multithread, can we add some code in the loop of the > function Calculate to let it exit the loop after the user clicks > the "exit" button or press a "Esc" key? > Well, you're little program is doing what you asked it to do, :-) You can use some multithreading, like: # This function does all the hard work. def Do_Calculations(): do_lotsa_calculations() save_results_somewhere() set_finished_flag() raise SystemExit() def Calculate(event=None): if calculation_thread_not_set(): import thread set_calculation_thread_flag() thread.start_new_thread(Do_Calculations, (,)) Now the calculations are done independantly from the GUI management thread; this is good. But, you should NOT DO ANY GUI MANIPULATION from the thread doing the calculations, because Tkinter WILL CRASH AND BURN. Hence, the set_finished_flag() thing, where you inform the main thread by any means you like that the calculations are done; that flag can be picked up by your main thread, which can update the GUI. Good luck :-) > Many thanks from, > Xiao-Qin Xia > -gustavo From merkosh at hadiko.de Thu Jun 13 11:40:02 2002 From: merkosh at hadiko.de (Uwe Mayer) Date: Thu, 13 Jun 2002 17:40:02 +0200 Subject: modifying string objects Message-ID: [This followup was posted to comp.lang.python and a copy was sent to the cited author.] hi, strings are immutable in python. so what do i do if i need to pass a function a string as parameter and need it to be modified within the function so that changes are reflected outside of the function body? f.e. a class constructor must return None class foobar: def __init__(text): text = text[-1] #this is what i actually want however: teststr = 'dummy' foobar(teststr) print(teststr) prints "dummy" to the screen. i _could_ use the globals() function in the object. how 'bad' is this style considered to be? can i do it or will i be flamed by other python programmers afterwards? ;-) another question. from perl i konw that f.e. foo(text = 'some value') works in the way that first "text" is assigned 'some value' which is then passed to the function "foo". i know that the above syntax is used to assign the named parameter "text" the value 'some value' and if there is no such parameter an error message is produce by the interpreter, but why do such language constructs not work in python? another example: if (value = myFile.read(10)) == '': ... ? Thanks in advance Uwe From guido-clpy at a-nugget.de Sat Jun 22 09:00:22 2002 From: guido-clpy at a-nugget.de (Guido Goldstein) Date: 22 Jun 2002 15:00:22 +0200 Subject: urllib POST question References: <644f6688.0206200930.48110837@posting.google.com> <644f6688.0206210900.68dd930c@posting.google.com> Message-ID: Hi! On 21 Jun 2002 10:00:44 -0700 rdacker at pacbell.net (rdack) wrote: > Ben Beuchler wrote in message news:... > > In article <644f6688.0206200930.48110837 at posting.google.com>, rdack wrote: > > > i am doing a POST to a server using urllib and it works. > > > is there some way i can see exactly what is being posted? > > > a way to get the post object out of urllib - the exact lines it is sending? > > > > I'm a big fan of Ethereal... > > "Sniffing the glue that holds the internet together!" > > > > http://www.ethereal.com/ > > i am looking into it. seems overkill for wanting to see a few bytes > that python is generating. > No way within python to see what urllib intends to send out for the > POST? If you're on *NIX (like GNU/Linux) there might be a program call netcat (or nc on some machines). >From the man-page: -- cut -- NAME nc - TCP/IP swiss army knife SYNOPSIS nc [-options] hostname port[s] [ports] ... nc -l -p port [-options] [hostname] [port] DESCRIPTION netcat is a simple unix utility which reads and writes data across network connec? tions, using TCP or UDP protocol. It is designed to be a reliable "back-end" tool that can be used directly or easily driven by other programs and scripts. At the same time, it is a feature-rich network debugging and exploration tool, since it can create almost any kind of connection you would need and has several interesting built-in capabilities. Netcat, or "nc" as the actual program is named, should have been supplied long ago as another one of those cryptic but standard Unix tools. [...] -- cut -- When you start it in listening mode it will sit and wait for connections. So when you connect with your program, nc will show what it has received. BTW: nc is a *must* on all machines <0.5 wink> HIH Guido -- no, not this one... From hesterloli at hotmail.com Wed Jun 19 04:47:03 2002 From: hesterloli at hotmail.com (George Hester) Date: Wed, 19 Jun 2002 08:47:03 GMT Subject: python version? References: Message-ID: You did it again. Why are you spamming me? -- George Hester _________________________________ "Gerhard H?ring" wrote in message news:slrnagvdp4.1sg.gerhard at lilith.my-fqdn.de... > George Hester wrote in comp.lang.python: > > I just cannot believe what I ran into in this newsgroup. [...] > > > .:\:/:. > +-------------------+ .:\:\:/:/:. > | PLEASE DO NOT | :.:\:\:/:/:.: > | FEED THE TROLLS | :=.' - - '.=: > | | '=(\ 9 9 /)=' > | Thank you, | ( (_) ) > | Management | /`-vvv-'\ > +-------------------+ / \ > | | @@@ / /|,,,,,|\ \ > | | @@@ /_// /^\ \\_\ > @x@@x@ | | |/ WW( ( ) )WW > \||||/ | | \| __\,,\ /,,/__ > \||/ | | | jgs (______Y______) > /\/\/\/\/\/\/\/\//\/\\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ > -- > mail: gerhard bigfoot de registered Linux user #64239 > web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 > public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 > reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From gerhard at bigfoot.de Thu Jun 13 12:00:48 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 13 Jun 2002 16:00:48 GMT Subject: modifying string objects References: Message-ID: Uwe Mayer wrote in comp.lang.python: > hi, > > strings are immutable in python. so what do i do if i need to pass a > function a string as parameter and need it to be modified within the > function so that changes are reflected outside of the function body? You _could_ use a mutable wrapper object, like a custom class or simply a list, like in: def add_an_a(swrap): swrap[0] = swrap[0] + "a" x = ["b"] add_an_a(x) print x[0] But it's generally much better to just let the function return the new value, as in: def add_an_a(s): return s + "a" print add_an_a("b") HTH, Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From skip at pobox.com Fri Jun 14 22:31:55 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 14 Jun 2002 21:31:55 -0500 Subject: file.tell() -- obscure IOError In-Reply-To: References: Message-ID: <15626.42779.744955.97247@12-248-41-177.client.attbi.com> Uwe> when does tell() raise an IOError? When the underlying ftell() call returns -1 for the position, that is, an error was detected. My ftell man page suggests the only possible error condition that ftell detects directly is EBADF The stream specified is not a seekable stream. however it also says The function fgetpos, fseek, fsetpos, and ftell may also fail and set errno for any of the errors specified for the routines fflush(3), fstat(2), lseek(2), and malloc(3). -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From sarmstrong13 at mac.com Thu Jun 13 23:04:18 2002 From: sarmstrong13 at mac.com (SA) Date: Thu, 13 Jun 2002 22:04:18 -0500 Subject: More Tkinter Help please... Message-ID: Hi Everyone- I have another Tkinter question for you. I'm still trying to translate "that previously mentioned" Tcl/Tk program into Python/Tkinter. The following is all of the code I've managed so far: from Tkinter import * import sys import os class PyShell: def __init__(self, top): f = Frame(top) f.pack() self.t1 = Text(f, height="12", width="84", font="Courier 12") self.t1.pack(side=TOP, pady=2) self.t2 = Text(f, height="12", width="84", bg="lightblue", font="Courier 12") self.t2.pack(side=TOP, pady=2) self.b1 = Button(f, text="Execute", command=self.expyth) self.b1.pack(side=LEFT) self.b2 = Button(f, text="Clear Input", command=self.clearin) self.b2.pack(side=LEFT) self.b3 = Button(f, text="Clear Output", command=self.clearout) self.b3.pack(side=LEFT) self.b4 = Button(f, text="Save Input", command=self.savin) self.b4.pack(side=LEFT) def clearin(self): self.t1.delete(0,END) def clearout(self): self.t2.delete(0,END) def expyth(self): output = os.popen("python -c").t1() self.t2.delete(0,END) sys.stdout.write.t2(output) def savin(self): pass root = Tk() app = PyShell(root) root.mainloop() When I run this I get the following error: Traceback (most recent call last): File "PyShell.py", line 45, in ? app = PyShell(root) File "PyShell.py", line 17, in __init__ self.b1 = Button(f, text="Execute", command=self.expyth) AttributeError: PyShell instance has no attribute 'expyth' Any ideas on what I'm doing wrong here? Thanks. SA From emile at fenx.com Sat Jun 8 18:57:55 2002 From: emile at fenx.com (Emile van Sebille) Date: Sat, 08 Jun 2002 22:57:55 GMT Subject: Program mysteriously STOPS! References: Message-ID: LJD > The following code is designed (at least thats my intent) to run forever. > The program should sit in a loop until it connects with the server. It > should just loop and loop and loop. > > It does, for a while, maybe five or ten minutes, but then the process just > seems to vanish. It's in the c1==0 loop when it quits. When I do a PS AUX, > the process is just gone. Obviously it quit, but more importantly WHY???, > and what can I do so it doesn't? If you get rid of all the 'c1=...' lines after the first does it run longer? HTH, -- Emile van Sebille emile at fenx.com --------- From sholden at holdenweb.com Wed Jun 19 15:02:10 2002 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 19 Jun 2002 15:02:10 -0400 Subject: Caching query resuls References: Message-ID: "Pawel Lewicki" wrote in message news:aentug$m8d$1 at news.onet.pl... > Hallo, > Is there any good solution to cache the results of SQL queries? I found the > great cache manager in dmtools (http://csl.anu.edu.au/ml/dm/), but I wonder > if there is any alternative. I will start with MySQL database, but it would > be great to be able to plug it into other RDBMS's. I am interested in both - > file and memory caching. I also know ZSQL Method in Zope. > I developed this (primitive) solution for "Python Web PRogramming". It might be a starting point for you. regards Steve import mx.DateTime import dtuple ################################################################# # $Revision: 7 $ # $Date: 10/19/01 1:37p $ ################################################################# class CacheQuery: """Defines a database query that caches database row sets. This object is initialized with tbl table name in the database colnames list of field names retrieved keynames list of keys used for retrieval conn database connection refresh caching refresh interval Individual results are read by calling the object with a tuple of key values as an argument. If the row set associated with this particular set of keys is not present, or was read longer than the refresh interval ago, it is re-read from the database and stored in the content table as a list of database tuples, which allow columns to be accessed by name. Otherwise the already-cached database tuple set is returned. Refinements might be added, such as registering with an observer that might clear down all cache entries periodically to force a global database refresh, and using a second SQL query on record modified timestamps to determine whether a refresh is really required (which may or may not be a win for a given set of columns). """ def __init__(self, tbl, colnames, keynames, conn, refresh=0, ORDER=None): """Create a caching data set for the given table, columns and keys.""" self._flush() self.tbl = tbl self.keynames = keynames self.refresh = refresh self.cursor = conn.cursor() self.sql = "SELECT %s FROM %s" % (",".join(colnames), tbl) if keynames: condition = " AND ".join(["%s=?" % f for f in keynames]) self.sql += " WHERE %s" % condition if ORDER: self.sql += " ORDER BY " + ", ".join(ORDER) self.desc = dtuple.TupleDescriptor([[n, ] for n in colnames]) print "Descriptor:", self.desc print "SQL:", self.sql def _flush(self): """Remove all trace of previous caching.""" self.recs = {} self.when = {} def __call__(self, keyvals=(), debug=0): """Return the data set associated with given key values.""" assert len(keyvals) == len(self.keynames) now = mx.DateTime.now() if self.recs.has_key(keyvals) and self.refresh and (now - self.when[keyvals] < self.refresh): if debug: print "Interval:", now - self.when[keyvals] return self.recs[keyvals] else: self.cursor.execute(self.sql, keyvals) rows = self.cursor.fetchall() result = [dtuple.DatabaseTuple(self.desc, row) for row in rows] if self.refresh: if debug: print "Caching", self.tbl, keyvals, " at", now self.recs[keyvals] = result self.when[keyvals] = now return result def close(self): self.recs = None self.when = None self.cursor.close() if __name__ == "__main__": # # Sorry, you'll need your own database details in here # import mx.ODBC.Windows as odbc conn = odbc.connect("prom2000") s1 = CacheQuery("department", # table "DptName DptWelcome DptLnksTxt".split(), # columns ("DptCode",), # key columns conn, refresh=0) # other stuff while 1: dc = raw_input("Department Code: ") if not dc: break rows = s1((dc, ), debug=1) if len(rows) == 0: print "No such department" else: for row in rows: print """ Department: %s Full Name: %s Welcome Text: %s Links Text: %s """ % (dc, row.DptName, row.DptWelcome, row.DptLnksTxt) s1.close() conn.close() -- ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From skip at pobox.com Wed Jun 12 11:52:38 2002 From: skip at pobox.com (Skip Montanaro) Date: Wed, 12 Jun 2002 10:52:38 -0500 Subject: JIT Complier for python? In-Reply-To: <20020612120936.W6609@prim.han.de> References: <8d3f4438.0206111905.7934664b@posting.google.com> <20020612120936.W6609@prim.han.de> Message-ID: <15623.28230.744872.342655@12-248-41-177.client.attbi.com> holger> d2002xx wrote: >> Is there any JIT Compiler for Python? holger> you might want to take a look at holger> http://homepages.ulb.ac.be/~arigo/psyco/ I think the Psyco project on Sourceforge might be more up-to-date: http://sourceforge.net/projects/psyco -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From bowman at montana.com Tue Jun 4 00:08:34 2002 From: bowman at montana.com (bowman) Date: Mon, 03 Jun 2002 22:08:34 -0600 Subject: getting windows processes list References: Message-ID: <80XK8.386$ZM.143854@newsfeed.slurp.net> David LeBlanc wrote: > > I'm not sure that mere mortal programs are allowed access to that > information due to Window's (NT's) arcane idea of what constitutes > security. I think you're doing well to get your own PID. A User cannot get quite as much information as an Administrator, but there is quite a bit available. If WMI is installed, that is probably the easiest way. The psapi.dll offers another handy interface. The last ditch is to open the PerformanceData and paw around, but this tends to be a little slow since it really isn't a static part of the Registry, but is built on the fly. From leaf00 at linuxfreemail.com Thu Jun 27 18:49:43 2002 From: leaf00 at linuxfreemail.com (coh) Date: Thu, 27 Jun 2002 23:49:43 +0100 Subject: Newbie: GUI Message-ID: <3D1B9687.8060606@linuxfreemail.com> Is there a native gui, widget set, for python, or any in the works? coh From ark at research.att.com Fri Jun 7 14:05:20 2002 From: ark at research.att.com (Andrew Koenig) Date: Fri, 7 Jun 2002 14:05:20 -0400 (EDT) Subject: Python 2.2.1 vs. gcc 3.1? In-Reply-To: <15616.62758.469825.704384@12-248-41-177.client.attbi.com> (message from Skip Montanaro on Fri, 7 Jun 2002 13:02:14 -0500) References: <15616.57963.519636.730290@12-248-41-177.client.attbi.com> <200206071649.g57GnmC00708@europa.research.att.com> <15616.62131.521803.383860@12-248-41-177.client.attbi.com> <200206071756.g57HulT01147@europa.research.att.com> <15616.62758.469825.704384@12-248-41-177.client.attbi.com> Message-ID: <200206071805.g57I5KW01219@europa.research.att.com> Andrew> No -- LD_LIBRARY_PATH tells the runtime system ... LD_RUN_PATH Andrew> tells the linker ... Skip> Like I said, it's been ages... ;-) I'm just glad for the assistance. Somehow, I doubt I'm going to be the the only person who encounters this problem... From jarvin24 at lehtori.cc.tut.fi Wed Jun 19 07:05:01 2002 From: jarvin24 at lehtori.cc.tut.fi (=?iso-8859-1?Q?J=E4rvinen?= Petri) Date: Wed, 19 Jun 2002 11:05:01 +0000 (UTC) Subject: Python+ASP->import problem Message-ID: Hey, I'm doing little project in combination Python+ASP. Now I have mystical problem which I cannot solve on my own. When importing my modules, I always get AttributeError for attributes that surely exist on imported module. Response.Write(enactHTML.defineCSS('Enact Main')) AttributeError: 'module' object has no attribute 'defineCSS' Here is my .asp page. <-- select Python as scripting engine for ASP -!> <%@Language="Python" %> <-- Import enact modules --> <% import enactHTML %> <% Response.Write(enactHTML.defineCSS('Enact Main')) Response.Write("Python gets ready to rumble inside a server-side scripting block!") %> And here I always got error on enactHTML.defineCSS('Enact Main') And when I import same module (located in root of python directory) form the interactive shell all works fine. Could you guys help me a bit. -Petri From candiazoo at attbi.com Fri Jun 14 06:45:18 2002 From: candiazoo at attbi.com (candiazoo at attbi.com) Date: Fri, 14 Jun 2002 10:45:18 GMT Subject: Help with ADO and dynamic insert statement... References: <3d0826ec.240888125@netnews.attbi.com> Message-ID: <3d09c924.347952062@netnews.attbi.com> Path: rwcrnsc51.ops.asp.att.net!rwcrnsc53!attbi_slave52!attbi_master51!attbi_feed3!attbi.com!rwcrnsc52.ops.asp.att.net.POSTED!not-for-mail From: candiazoo at attbi.com Newsgroups: comp.lang.python Subject: ADO Command object/Parameters problem... Message-ID: <3d09426d.313465031 at netnews.attbi.com> X-Newsreader: Forte Free Agent 1.21/32.243 Lines: 62 NNTP-Posting-Host: 24.128.120.33 X-Complaints-To: abuse at attbi.com X-Trace: rwcrnsc52.ops.asp.att.net 1024017522 24.128.120.33 (Fri, 14 Jun 2002 01:18:42 GMT) NNTP-Posting-Date: Fri, 14 Jun 2002 01:18:42 GMT Organization: AT&T Broadband Date: Fri, 14 Jun 2002 01:18:42 GMT Xref: attbi_master51 comp.lang.python:38572 X-Received-Date: Fri, 14 Jun 2002 01:18:42 GMT (rwcrnsc51.ops.asp.att.net) I am still having problems using dynamic sql statements to perform lookups and inserts into a MS Access database and an Oracle database. I've looked up the error at Microsoft and the solution is to find the OLEDB provider and add "OLEDB_SERVICES" DWORD value to the registry entry... did this (actually, it already HAD it)... no go. I used MakePy... no go. The code I used works in a VB application. I used the errors collection from the connection object and it only gives me a more concise version of what you see below. Does anyone have any idea why I cannot create a command object with parameter objects?? I am using only adVarChar and adNumeric values... no dates, no blobs, nothing odd at all...!!! Has anyone else run into this (note: I have seen other entries for the same error, which is rather generic, but not for my specific reason). Thank you, in advance... Mike J. ----------------------------------------------------------------------------------------------------------------------------------------- begin updating recType[s] on Thu Jun 13 12:15:39 2002 Traceback (most recent call last): File "C:\Documents and Settings\mjessop\My Documents\Python Development\Catalo g\BuildCatalog.py", line 1300, in ? setRecordType() File "C:\Documents and Settings\mjessop\My Documents\Python Development\Catalo g\BuildCatalog.py", line 506, in setRecordType rstOracle, status = cmdOracle.Execute() File "C:\Python22\Lib\site-packages\win32com\gen_py\00000205-0000-0010-8000-00 AA006D2EA4x0x2x5.py", line 1698, in Execute return self._ApplyTypes_(0x5, 1, (9, 0), ((16396, 18), (16396, 17), (3, 49)) , 'Execute', '{00000556-0000-0010-8000-00AA006D2EA4}',RecordsAffected, Parameter s, Options) File "C:\Python22\Lib\site-packages\win32com\client\__init__.py", line 341, in _ApplyTypes_ return self._get_good_object_(apply(self._oleobj_.InvokeTypes, (dispid, 0, w Flags, retType, argTypes) + args), user, resultCLSID) pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft OLE DB Provider for ODBC Drivers', 'Multiple-step OLE DB operation generated errors. C heck each OLE DB status value, if available. No work was done.', None, 0, -21472 17887), None) HERE is an example of what I am doing... (note, I added the long() typecasting to make sure the value was coerced into a long integer)... sql = "select pty.orgname " + \ "from ccc_party pty, ccc_right_rightsholder rgh, ccc_right rgt " + \ "where pty.pty_inst = rgh.rgh_inst " + \ "and rgh.rgt_inst = rgt.rgt_inst " + \ "and rgt.rgt_inst = ?" cmdOracle.ActiveConnection = cnnOracle cmdOracle.CommandType = 1 cmdOracle.CommandText = sql trsInst = long(rstTempDB.Fields("trs_inst").Value) aasInst = long(rstTempDB.Fields("aas_inst").Value) anyInst = trsInst or aasInst cmdOracle.Parameters.Append(cmdOracle.CreateParameter("orgname", 200, 2, 80)) cmdOracle.Parameters.Append(cmdOracle.CreateParameter("rgt_inst", 3, 1, 4, long(anyInst))) rstOracle, status = cmdOracle.Execute() From jjl at pobox.com Tue Jun 4 17:12:49 2002 From: jjl at pobox.com (John J. Lee) Date: Tue, 4 Jun 2002 22:12:49 +0100 Subject: telnet functionality In-Reply-To: <9013d0b4.0206040622.f78f95a@posting.google.com> References: <9013d0b4.0206040622.f78f95a@posting.google.com> Message-ID: On 4 Jun 2002, Ben wrote: [...] > the script to the point where I can open a telnet account, change to > new directory, and list the directory's contents...but, I can't seem > to figure out how to grab the last file in the directory and append it > to the list. It seems that telnetlib doesn't offer that ability. [...] Why should it? Telnet isn't ftp. Just parse the output of ls yourself. John From rjones at ekit-inc.com Sun Jun 23 23:08:33 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Mon, 24 Jun 2002 13:08:33 +1000 Subject: PIL, Python and CGI In-Reply-To: References: Message-ID: <200206241308.33270.rjones@ekit-inc.com> On Mon, 24 Jun 2002 13:02, Sascha Ferley wrote: > On Mon, 24 Jun 2002, Richard Jones wrote: > > Your web server environment most likely doesn't have /usr/local/lib in > > its LD_LIBRARY_PATH. > > You probly mean Apache... I'll take a look for at the conf files for it.. > Any ideas where to statically define the lib paths for apache.. i doubt in > the httpd.conf file.. You've basically got three choices as I see it: 1. recompile PIL to statically link libjpeg etc. 2. recompile PIL to use -R (or whatever the flag is) so it remembers where the dynamic libs are 3. modify your apache start script to set the environment var appropriately. 1 or 2 are going to be the easiest, and safest options. Richard From huaiyu at gauss.almadan.ibm.com Fri Jun 21 22:20:42 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Sat, 22 Jun 2002 02:20:42 +0000 (UTC) Subject: How to represent the infinite ? References: Message-ID: Tim Peters wrote: > >I intended that x**y act the same as math.pow(x, y). OK, here it is: >>> from math import * >>> pow (1e200, 2) inf >>> 1e200**2 inf Here's the new patch (without any testing for other effects). Are there documentations of the circumstances where the commented-out code is supposed to be useful? Are there unit tests for them? Huaiyu diff -rcN Python-2.2.1/Include/pyport.h Python-2.2.1.i/Include/pyport.h *** Python-2.2.1/Include/pyport.h Mon Mar 11 02:16:23 2002 --- Python-2.2.1.i/Include/pyport.h Wed May 8 15:20:30 2002 *************** *** 301,311 **** */ #define Py_ADJUST_ERANGE1(X) \ do { \ ! if (errno == 0) { \ if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL) \ errno = ERANGE; \ } \ ! else if (errno == ERANGE && (X) == 0.0) \ errno = 0; \ } while(0) --- 301,311 ---- */ #define Py_ADJUST_ERANGE1(X) \ do { \ ! /*if (errno == 0) { \ if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL) \ errno = ERANGE; \ } \ ! else */ if (errno == ERANGE && (X) == 0.0) \ errno = 0; \ } while(0) *************** *** 313,320 **** do { \ if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL || \ (Y) == Py_HUGE_VAL || (Y) == -Py_HUGE_VAL) { \ ! if (errno == 0) \ ! errno = ERANGE; \ } \ else if (errno == ERANGE) \ errno = 0; \ --- 313,320 ---- do { \ if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL || \ (Y) == Py_HUGE_VAL || (Y) == -Py_HUGE_VAL) { \ ! /* if (errno == 0) \ ! errno = ERANGE; */ \ } \ else if (errno == ERANGE) \ errno = 0; \ diff -rcN Python-2.2.1/Modules/mathmodule.c Python-2.2.1.i/Modules/mathmodule.c *** Python-2.2.1/Modules/mathmodule.c Thu Sep 6 01:16:17 2001 --- Python-2.2.1.i/Modules/mathmodule.c Fri Jun 21 19:06:48 2002 *************** *** 35,44 **** * overflow, so testing the result for zero suffices to * distinguish the cases). */ ! if (x) ! PyErr_SetString(PyExc_OverflowError, ! "math range error"); ! else result = 0; } else --- 35,44 ---- * overflow, so testing the result for zero suffices to * distinguish the cases). */ ! /* if (x) ! PyErr_SetString(PyExc_OverflowError, ! "math range error"); ! else */ result = 0; } else diff -rcN Python-2.2.1/configure.in Python-2.2.1.i/configure.in *** Python-2.2.1/configure.in Mon Mar 11 02:14:23 2002 --- Python-2.2.1.i/configure.in Wed May 8 15:47:07 2002 *************** *** 1777,1786 **** # (none yet) # Linux requires this for correct f.p. operations ! AC_CHECK_FUNC(__fpu_control, ! [], ! [AC_CHECK_LIB(ieee, __fpu_control) ! ]) # Check for --with-fpectl AC_MSG_CHECKING(for --with-fpectl) --- 1777,1787 ---- # (none yet) # Linux requires this for correct f.p. operations ! #AC_CHECK_FUNC(__fpu_control, ! # [], ! # [AC_CHECK_LIB(ieee, __fpu_control) ! #]) ! AC_CHECK_LIB(ieee, __fpu_control) # Check for --with-fpectl AC_MSG_CHECKING(for --with-fpectl) diff -rcN Python-2.2.1/pyconfig.h.in Python-2.2.1.i/pyconfig.h.in *** Python-2.2.1/pyconfig.h.in Wed Oct 24 10:10:49 2001 --- Python-2.2.1.i/pyconfig.h.in Wed May 8 15:53:51 2002 *************** *** 748,754 **** #undef HAVE_LIBDLD /* Define if you have the ieee library (-lieee). */ ! #undef HAVE_LIBIEEE #ifdef __CYGWIN__ #ifdef USE_DL_IMPORT --- 748,754 ---- #undef HAVE_LIBDLD /* Define if you have the ieee library (-lieee). */ ! #define HAVE_LIBIEEE #ifdef __CYGWIN__ #ifdef USE_DL_IMPORT From baf at texas.net Sun Jun 23 11:08:17 2002 From: baf at texas.net (Ben Fairbank) Date: Sun, 23 Jun 2002 15:08:17 GMT Subject: (Newbie) Counting Instances ("Hits") with Regular Expressions Message-ID: <3d15e215.43448155@news.texas.net> I am new both to Python and to regular expressions, which may account for my difficulty. I must count the frequenies of certain words in files of moderate length (about150 k bytes). I have been reading files and then using count(s,sub), which is fast and easy. I now have to allow for punctuation and eliminate words within words, etc, and so am trying to use regular expressions instead of simple words as targets. I do not, however, find a similarly easy to use count function in the re module. Yet this is such common operation it must be there, or easy to implement. What is the usual way of simply counting "hits" in the re module? (And what have I missed in the documentation; where is this to be found? I have looked through Lutz and Ascher) Thanks for any help. BAF From from-020625011948-4b56 at secretlab.mine.nu Mon Jun 24 19:21:53 2002 From: from-020625011948-4b56 at secretlab.mine.nu (Walter Hofmann) Date: Tue, 25 Jun 2002 01:21:53 +0200 Subject: working with secure shell References: Message-ID: Jon J. Morin schrieb im Artikel : > One question: Is there a python library or module for working with the > secure shell (ssh)? Yes, see http://pyssh.sourceforge.net/ Walter From g at g.com Mon Jun 3 03:52:54 2002 From: g at g.com (d) Date: Mon, 03 Jun 2002 07:52:54 GMT Subject: test Message-ID: test From cliechti at gmx.net Mon Jun 24 17:34:58 2002 From: cliechti at gmx.net (Chris Liechti) Date: 24 Jun 2002 23:34:58 +0200 Subject: Embed terminal into a Tkinter application References: <3D1758B4.8FA63EBE@club-internet.fr> Message-ID: Fabien H?non wrote in news:3D1758B4.8FA63EBE at club-internet.fr: > The title says it all. > Has someone already managed to include a Linux terminal into a Tkinter > GUI ? > > Redirecting the output of a console into the application does not do > what I want. well, what do you want? let us help you! there is also popen[2,3,4] - you can also redirect stdin. chris -- Chris From phr-n2002b at NOSPAMnightsong.com Sun Jun 30 02:51:42 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 29 Jun 2002 23:51:42 -0700 Subject: yield equivalent in C/JavaScript? References: <7xy9cxhlvx.fsf@ruckus.brouhaha.com> Message-ID: <7xit41i7i9.fsf@ruckus.brouhaha.com> Robin Becker writes: > the generators here are things associated with compression or > decompression methods. The complexity is such that a severe > reformulation will be tough. I understand the concept, but I think it's > easier to just try and consume the whole input at one go and pass it on. If you are trying to implement data compression in javascript with large enough inputs that memory consumption is a problem, you probably have worse problems than absence of "yield". Javascript is so slow your program will probably be near unuseable. What's the JS environment and the application? If it's client side JS in a web browser, you're probably using the wrong approach to the problem. If it's something like Netscape server side JS, use the LiveConnect stuff to implement the compression in C. From sholden at holdenweb.com Sun Jun 2 14:08:41 2002 From: sholden at holdenweb.com (Steve Holden) Date: Sun, 2 Jun 2002 14:08:41 -0400 Subject: semi-concatenated strings References: Message-ID: "Skip Montanaro" wrote in message news:mailman.1022874291.30340.python-list at python.org... > >> rows = self.executesql(("select cities.city, state, country" + > >> " from cities, venues, events, addresses" + > >> " where cities.city like %s" + > >> " and events.active = 1" + > >> " and venues.address = addresses.id" + > >> " and addresses.city = cities.id" + > >> " and events.venue = venues.id"), > >> (city,)) > > Grant> I dunno...I don't know anything about SQL, but your code looks > Grant> sortta Pythonic. > > Yeah it does. It serves two purposes. One it makes it clear to me where > the various clauses of the select statement begin ("from ...", "where ..."). > It also guarantees I have at least one space between the different > fragments. This: > > ("select cities.city, state, country" > "from cities, venues, events, addresses" > "where cities.city like %s" > "and events.active = 1" > "and venues.address = addresses.id" > "and addresses.city = cities.id" > "and events.venue = venues.id") > > might appear correct, but there are no spaces between the end of one > substring and the start of the next... > I would personally much prefer to see this written as ("""select cities.city, state, country from cities, venues, events, addresses where cities.city like %s and events.active = 1 and venues.address = addresses.id and addresses.city = cities.id and events.venue = venues.id""", (city,)) Perhaps the reason that Python's conventional wisdom states "there should be oine obvious way to do it" is because, given alternatives, people like you and me will spend endless time debating which is to be preferred! regards Steve -- ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From xah at xahlee.org Sat Jun 29 19:19:16 2002 From: xah at xahlee.org (Xah Lee) Date: 29 Jun 2002 16:19:16 -0700 Subject: newbie Q: delete list few lines in file Message-ID: <7fe97cc4.0206291519.1c95ce31@posting.google.com> i have a folder full of individual email text file, whose ending may be the following: _______________________________________________ some mailing list some at list.com http://some.com/ttt I want to delete them, but only if they are the last few lines in the file. if you can show me a script that'll be great otherwise my question can be broken down as: * how to write to file inplace? (or, do i write to a new file, then delete original, and rename the new file?) * as far as a newbie, i use "xreadlines" module. I wasn't able to get the total number of lines in a file. li=xreadlines.xreadlines(f) num=len(li) fails. I'm much more interested in learning python idiom and correctness here. I'm not interested in just "get it to work". For the latter, i can do well with perl. (also, is there a site or mailing list that collect very small trivial python programs for learning purposes?) Thanks. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From timr at probo.com Sat Jun 1 01:23:49 2002 From: timr at probo.com (Tim Roberts) Date: Fri, 31 May 2002 22:23:49 -0700 Subject: semi-concatenated strings References: Message-ID: Grant Griffin wrote: > >I discovered today that strings can sometimes be concatenated without using a >"+": > > ActivePython 2.2.1 Build 222 (ActiveState Corp.) based on > Python 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> a = 'one' ' plus ' 'two' > >>> a > 'one plus two' It is interesting (but only marginally relevant) to note that this exact same feature is part of ISO standard C: #include int main() { puts( "one" " plus " "two" ); } -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From maxm at mxm.dk Tue Jun 25 11:04:42 2002 From: maxm at mxm.dk (Max M) Date: Tue, 25 Jun 2002 17:04:42 +0200 Subject: Suggestions for good programming practices? References: Message-ID: <3D18868A.4050002@mxm.dk> Jeff Epler wrote: >>class myData: >> def __init__ (self, foo, bar): >> self.foo = foo >> self.bar = bar >> >>you've added quite a bit of functionality. First, the code becomes a >>little more self-documenting. "power = ckt.volts * ckt.amps" is a lot >>easier to read and understand than "power = ckt[0] * ckt[1]". > > > (the following applies most obviously to modern versions of python. I > use subclassing of builtin objects, __slots__ and zip(). Even so, the > myStruct class is useful in any version of Python back to at least 1.5, > if you make myStruct a regular class, and include a definition > of zip()) > > You can do even better (lower memory overhead) with > class myData(object): > __slots__ = ['foo', 'bar'] > def __init__ (self, foo, bar): > self.foo = foo > self.bar = bar You can also make it even more general: class MyData: def __init__(self, **args): self.__dict__.update(args) d = MyData(firstName='Max M', lastName='Rasmussen') print d.firstName, d.lastName >>> Max M Rasmussen regards Max M From kragen at pobox.com Sat Jun 1 16:08:55 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 01 Jun 2002 16:08:55 -0400 Subject: wxPython performance References: <3CF8E382.3A44F0DA@engcorp.com> Message-ID: <83ptzavk14.fsf@panacea.canonical.org> Peter Hansen writes: > How fast do you need it to be? (That's a serious question. > Are you planning to open and close the application so frequently > that six seconds is unacceptable?) >From a human interface perspective, having to wait six seconds for a response to a command (including "start program") is annoying; this is the reason for "splash screens". You don't want people to be annoyed every time they start your program. Worse, six seconds is plenty of time for a user's thoughts to wander; it means that the user may have forgotten what they wanted to do by the time the program starts. From tim.one at comcast.net Tue Jun 11 21:26:18 2002 From: tim.one at comcast.net (Tim Peters) Date: Tue, 11 Jun 2002 21:26:18 -0400 Subject: Sorting list (maybe stupid) In-Reply-To: Message-ID: [Ken Seehof] > >>> a = [1,1.0,3.0,3,2.0,2,0,0.0] > >>> a > [1, 1.0, 3.0, 3, 2.0, 2, 0, 0.0] > >>> a.sort() > >>> a > [0, 0.0, 1, 1.0, 2.0, 2, 3.0, 3] > > So yes, sort() is stable. No, it's not. > I suppose it's theoretically possible for a different > python implementation to use a different sort algorithm, > but practically speaking, that is very unlikely. In fact it's almost certain . Small lists are handled by binary insertion sort, for peak speed, and the way that was coded just so happens to be stable. That's why small examples will always lead you to believe .sort() is stable. The full-blown samplesort used for non-trivial lists isn't stable and can't be made stable efficiently. From lewy0lewy at poczta.onet.pl Wed Jun 19 10:11:00 2002 From: lewy0lewy at poczta.onet.pl (Pawel Lewicki) Date: Wed, 19 Jun 2002 16:11:00 +0200 Subject: Caching query resuls References: Message-ID: > * Pawel Lewicki [2002-06-18 20:25 +0200]: > > Hallo, > > Is there any good solution to cache the results of SQL queries? > > Your database has one. It should save at least the query execution plan. > > > I found the great cache manager in dmtools (http://csl.anu.edu.au/ml/dm/), but I wonder > > if there is any alternative. I will start with MySQL database, but it would > > be great to be able to plug it into other RDBMS's. I am interested in both - > > file and memory caching. I also know ZSQL Method in Zope. > > I'm sceptical. How does this help? How does the cache manager get > notified of changes in the database? How is it different from just > storing the queries I'm interested in away on disk if they deliver large > resultsets? Probably not much. :) But dmtools give the out-of-the-box solution. It takes the function (sql query execution in that case), arguments (query) and checks given dependency files, which in case of MySQL are table files. It deals perfectly with my needs and I wondered if there was any other option. Pawel Lewicki From BPettersen at NAREX.com Thu Jun 20 18:57:21 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Thu, 20 Jun 2002 16:57:21 -0600 Subject: do...while Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192158EEC@admin56.narex.com> > From: Michael P. Soulier [mailto:msoulier at nortelnetworks.com] > > On Thu, Jun 20, 2002 at 10:42:56AM -0700, Sean 'Shaleh' Perry wrote: > > > > On 20-Jun-2002 Michael P. Soulier wrote: > > > Greetings. > > > > > > How do you people handle the lack of a do...while in > Python? I > > > find that at times, I must initialize variables for a loop with > > > identical code to the loop, which feels like a waste to me. > > > > > > ie. > > > > > > line = filehandle.readline() > > > while len(line) > 5: > > > line = filehandle.readline() > > > > > > A do...while here would be nice. > > > > > > Just curious. > > > > > > > while 1: > > line = filehandle.readline() > > if len(line) <= 5: break > > .... > > .... > > > > is a typical way to implement it. > > Right, I've used that in the past. It doesn't seem nearly > as clean though, as making the conditions for terminating the > loop plain in the loop declaration. Considering the Python > community's leaning towards readable code, necessitating a > break for code factoring goes against that philosophy. Doing a quick search over our C++ libraries (~900KLoc), "do {} while()" seems to be used in right around 3% of the loops (including while, for; excluding recursion). Seems like overkill to add special syntax for a feature used so rarely... -- bjorn From phr-n2002b at NOSPAMnightsong.com Thu Jun 20 03:44:33 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 20 Jun 2002 00:44:33 -0700 Subject: Variable Interpolation - status of PEP 215 References: Message-ID: <7xptym4cny.fsf@ruckus.brouhaha.com> aahz at pythoncraft.com (Aahz) writes: > Peter already told you what you really wanted to know, but for the > benefit of other people, PEP 215 is dead and PEP 292 is currently the > subject of a LARGE thread on python-dev. Another suggestion: rather than adding the clumsy sub() method, how about overloading a unary prefix operator on strings? For example the unary minus sign: say print -"my name is ${name}" instead of print "my name is ${name}".sub() Note that unlike PEP 215, this is not a syntax change. It's just operator overloading. I think it can already be implemented in Python 2.2 using a string subclass. In fact perhaps PEP 215 can be implemented the same way, using "-" as the prefix instead of "$". From aoeu at go.com Mon Jun 17 07:17:03 2002 From: aoeu at go.com (Thinkit) Date: 17 Jun 2002 04:17:03 -0700 Subject: coding python by web? Message-ID: <3eeda89d.0206170317.100549db@posting.google.com> Is there any way to test out simple python code with only a web browser (no input or files, just printing text)? I'm guessing a simple cgi setup could do this, but has it been implemented anywhere? From bokr at oz.net Sun Jun 23 00:42:47 2002 From: bokr at oz.net (Bengt Richter) Date: 23 Jun 2002 04:42:47 GMT Subject: Python hits the spot References: <3D1482AE.8FA299D8@kfunigraz.ac.at> <3D14CF95.4030501@kfunigraz.ac.at> Message-ID: On Sat, 22 Jun 2002 21:27:17 +0200, Siegfried Gonzi wrote: >Bengt Richter wrote: > >> >> You apparently have a lot of different stuff glued together. Have you tested the >> separate pieces separately? Do you have some test problems that you can use to validate >> numerical results *exactly* (trailing decimal differences need an explanation. They >> can be benign/acceptable or not). > >The Mie code (C function) works, because on Windows I wrote a program >under DISLIN in order to depict the phase function, and I can use the >same program under Linux without problems. [my line break] "without problems" presumably means "without apparent problems". IOW, you could have had a memory leak that didn't cause enough of a problem for you to notice. Or it may have worked because you interfaced to it differently, or you may have linked all compatible libraries, versions, etc. >The Fortran function works >too (the Fortran function is really a tiny piece and straightforward in >contrast to the C function which is a third party insane pointer hell). What is this C function? >The C code itself is essentially the same: on Windows I compiled it >with SWIG and Microsoft Visual C++ and on Linux I used gcc and SWIG; but >the name of the function is actually the same. The same goes for all the >other functions and directories. > What _didn't_ you compile? How many different compilers and run time support libraries were involved? Could there have been name clashes or incompatibilities? > >> I hate to see Python (or anything) bashed without proof. So far I haven't seen the proof, >> nor an explanation. >> >> If your code is open source, maybe someone will be interested in discovering why >> it bogs Python down (or Python bogs it down ;-) > >The code is open source but not very well documented. But I can send it >to you if you like. You can also get the data if you like. > I'm not exactly chomping at the bit, but I'd be curious to see the Python if you want to zip it up and send it attached. How many bytes of python etc. does it add up to? And how much data? Just curious. >First, I thought there is something wrong with my data because I have it >converted from DOS to UNIX with: dos2unix. > Have you hex-dumped a little to make sure? >There is an interesting thing to observe: On Windows I am likely to hit >the 100MB threshold, but on Unix I only hit 10MB (and sometimes 20MB). >At least "top" shows me that. > > >You can get all the functions if you like. I would only have to get it >from my laptop back to my stationary machine. > >Drop me a note if you want the functions and data. I can prepare it that >way that it will be ready to use for you. > Maybe you will have it solved before I have that amount of time ;-) >What I further noticed. On Windows the Task manager tells me that in the >first 20 minutes Python uses constantly 99% of the processor power. The >same goes under Linux, but after that 20 minutes it sucks down to 87% on >Linux and on Windows! Note: same functions and that 8 times! Unless you are doing a lot of i/o from the program, sounds like maybe that 13% (100-87) may be waiting for swapping to get more virtual space? Or it could be coincidental background stuff? (Do you trigger any other processes at some point?) Regards, Bengt Richter From look at replyto.address.invalid Tue Jun 4 01:21:57 2002 From: look at replyto.address.invalid (Greg Ewing) Date: Tue, 04 Jun 2002 17:21:57 +1200 Subject: Why does this work: 5<"five" ? References: <3CF80435.689AE006@icc-computer.de> <831ybprot3.fsf@panacea.canonical.org> Message-ID: <3CFC4E75.BA7EC3DE@replyto.address.invalid> Kragen Sitaker wrote: > > So if you put complex numbers into your binary search tree, you will > have problems. > > Oh, enjoy this: > >>> (1,) < (2,) > 1 > >>> (1j,) < (1j,) > 0 > > I'm not sure what's going on there. I think what's going on is that the tuple elements are being compared for equality first, and if that fails, compared again for ordering: >>> (1j,) < (2j,) Traceback (most recent call last): File "", line 1, in ? TypeError: cannot compare complex numbers using <, <=, >, >= Incidentally, I believe that Python ought to have a separate notion of compare-for-arbitrary-ordering that can be explicitly invoked for things like the b-tree situation. In fact, I think that's what cmp() should do. But currently it doesn't -- it seems that if the inequality operators don't work on a type, cmp() won't work either. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From loredo at astro.cornell.edu Fri Jun 28 15:41:33 2002 From: loredo at astro.cornell.edu (Tom Loredo) Date: Fri, 28 Jun 2002 15:41:33 -0400 Subject: C API for Python's RNG? References: <3D1CBB3A.E1C43D8A@astro.cornell.edu> Message-ID: <3D1CBBED.58EAC61E@astro.cornell.edu> Tom Loredo wrote: > > I'll dig in the source to try to puzzle > it out, but I thought I should ask publicly: Oops! I should have dug first---the standard lib RNG is pure Python. So I guess it's Numeric or some third-party RNG if I want to do this quickly. Any suggestions? Thanks, Tom From hamish_lawson at yahoo.co.uk Tue Jun 11 04:51:40 2002 From: hamish_lawson at yahoo.co.uk (Hamish Lawson) Date: 11 Jun 2002 01:51:40 -0700 Subject: Iterators vs. Generators References: Message-ID: <915a998f.0206110051.5605201d@posting.google.com> aahz wrote: > So when would one actually write an iterator instead of a generator? When you need to ensure that any allocated resources get cleared up even if the iteration is abandoned early. This can be handled by an iterator that has a clear-up method and a __del__ method that calls that clear-up method. That gives you the option of explicitly initiating the clear-up immediately on abandoning an iteration, or else leaving the clear-up to be done automatically when the iterator object is destroyed. Hamish Lawson From gerhard at bigfoot.de Tue Jun 18 18:34:40 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 18 Jun 2002 22:34:40 GMT Subject: tomorrow in yyyymmdd format References: Message-ID: Giulio Cespuglio wrote in comp.lang.python: > Hello everybody, > > We all know that if I want to get the present GMT date in yyyymmdd > format I should say > > print time.strftime("%Y%m%d", time.gmtime() ) > > Now, what about tomorrow? Note that a simple string manipulation is > not the solution I'm looking for, as tomorrow might be next month, > next year, the 29th of February and such. > Do you confirm that there's nothing better than the following > silly-looking expression? > > time.strftime("%Y%m%d", time.gmtime(time.time() + 60*60*24)) No, there's nothing better. Unless you're using the DateTime type from the eGenix mxExtensions: >>> import mx.DateTime as DateTime >>> DateTime.today() >>> print DateTime.today() 2002-06-19 00:00:00.00 >>> print DateTime.today() + 1 2002-06-20 00:00:00.00 >>> Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From emile at fenx.com Thu Jun 27 10:54:42 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 27 Jun 2002 14:54:42 GMT Subject: Most efficient way to write data out to a text file? References: <3d1a6993.248534625@netnews.attbi.com> <3D1A8CD9.C8B8EC28@engcorp.com> <3d1b1bd7.294171125@netnews.attbi.com> Message-ID: candiazoo at attbi.com > I am a newbie... this is my first Python "project" so I am probably writing > horribly inefficient code... I have never used the profiler but I'll try it! > > I am not opening/closing the file each time. I am extracting 700000 rows from a > mysql database, extracting additional data from our primary, Oracle database per > row, then stuffing each piece of data into a class which preformats the data (I > need to output the data into a fixed format string/record for another > application which reads them) and returns a single string... which I write out > to the file. > This is not the most efficient way, but for comparison purposes this wrote almost 3 million records using ~400Mb in a minute: >>> rec = 'this is a test'*10 >>> import time >>> def test(rec): ... global count ... t = time.time()+60 ... while time.time() < t: ... outfile.write(rec) ... count += 1 ... >>> count = 0 >>> outfile = open(r'f:\test.out', 'w') >>> test(rec) >>> print count 2982620 -- Emile van Sebille emile at fenx.com --------- From brueckd at tbye.com Tue Jun 25 10:39:05 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Tue, 25 Jun 2002 07:39:05 -0700 (PDT) Subject: Suggestions for good programming practices? In-Reply-To: Message-ID: On 25 Jun 2002, Chris Liechti wrote: > >> * Avoid exec, execfile, eval, and input. > > > > Might one ask why? What do you have to know to use them successfully? > > where does the string you exec come from? from the user: is he a python > programmer? could he make subtle errors that break your code and then blame > you? could it be somebody that like to play tricks with others and insert > harmful expression or satements (like os.system('rm -fR * /*')? How do you > handle exceptions, as any exception could be raised by the unknown code > (hint: 'try: ... except: pass' is bad too...)? > > if you don't want to deal with such problems, avoid exec* and eval. they > are fine for a throw away script, and they're needed when you embedd a > python interpreter in your app (for this case there is code.interact and > even better reexec). for all the other cases they're a risk. This view is a overly extreme. Rather than teaching people to fear certain features like eval/exec, it's better to explain the risks so that they can make informed decisions as to when it's wise to use them. For example, eval/exec are incredibly useful in building mini-languages based on Python, in which you execute user code in some dictionary that includes your set of custom functions (you basically end up with a context-specific superset of Python). I've found this to be very useful in several production systems (not 'throw away script[s]') as well as in creating programmable test harnesses for the QA department (the non-programmer QA engineers aren't scared off because they don't realize it's programming, and the more technical QA engineers are pleased that you've built them such a "rich" test harness language...hehehe). Can malicious users do malicious things? Of course! But that's like saying Guido should disable os.system! So... rather than teaching "avoid W!", let's say "be careful with W because of X, Y, and Z". I still wouldn't use eval/exec on code posted through a web form, for example, but there are times when they are very useful and I can use them in good confidence because I understand their risks. -Dave From observer at NOSPAM.space.pl Tue Jun 18 04:28:52 2002 From: observer at NOSPAM.space.pl (Johann) Date: Tue, 18 Jun 2002 10:28:52 +0200 Subject: PythonWorks Pro problem! References: <3lwP8.112157$pw3.6716@sccrnsc03> Message-ID: <8nrtgusniqrs9r3fs7l4nt8qka5fm7imi3@4ax.com> On Tue, 18 Jun 2002 01:49:52 GMT, "Emile van Sebille" wrote: >> I registered some examples from above link. The problem is, I cannot >> find this "small, coloured icon" , so I cannot cycle through avalable >> settings. :-( >> >> I tried to clink on everything, but without results :( Anybody can >> help? > >Hmmm... that icon appears to be missing from 1.3... > >It's there in 1.2 So, it is a bug. :( I wrote to authors, but without response. How to get 1.2 if they allow to d-l 1.3 only? -- Johann From m.faassen at vet.uu.nl Thu Jun 20 15:53:03 2002 From: m.faassen at vet.uu.nl (Martijn Faassen) Date: 20 Jun 2002 19:53:03 GMT Subject: GOTO w/ Python? References: <3d10ed95@xpl-sdf1-sec1.> Message-ID: John Roth wrote: [snip] > There's no equivalent of a goto command in Python, for good reason, > which I won't repeat here. Prof. Djikstra did it very well in 1974, > in his letter "Goto Considered Harmful." The good old Djikstra! You know, some years ago in another newsgroup I saw so many posts referring to some computer scientist called 'Djikstra', I started to doubt myself and had to confirm that he really is called 'Dijkstra'. Now I realize that there is a Djikstra, and a Dijkstra as well. Djikstra is an evil clone of Dijkstra, which the Python Secret Underground is keeping on ice in case they need any evil clones. Regards, 'Martjin' -- History of the 20th Century: WW1, WW2, WW3? No, WWW -- Could we be going in the right direction? From skip at pobox.com Sat Jun 15 16:52:59 2002 From: skip at pobox.com (Skip Montanaro) Date: Sat, 15 Jun 2002 15:52:59 -0500 Subject: IDE recommendations?? In-Reply-To: References: Message-ID: <15627.43307.695989.311162@12-248-41-177.client.attbi.com> Detlev> I have googled this list for IDE recommendations, but have found Detlev> none that satisfied me. Two suggestions. One, check the editors page on the Python website: http://www.python.org/editors/ Two, I guess you should take a look at PyUnitTestBrowser. The announcement yesterday said This build bonds with PyChecker. That means you can click on a file, get a list of warnings, click on a warning, and your editor will pop up with the file open and the cursor on the line with the warning. Spin: http://www.c2.com/cgi/wiki?PyUnitTestBrowser Source: http://flea.sourceforge.net/browser005.zip That means PUB now tests your code with PyUnit, lints your code with PyChecker, and edits your code with PyShell. It's an IDE in a deceptively small package. -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From gerhard at bigfoot.de Sat Jun 15 15:24:30 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Sat, 15 Jun 2002 21:24:30 +0200 Subject: IDE recommendations?? In-Reply-To: <83lm9gtla9.fsf@panacea.canonical.org> References: <3d0b06bd$0$52043$e4fe514c@dreader3.news.xs4all.nl> <83lm9gtla9.fsf@panacea.canonical.org> Message-ID: <20020615192430.GA1923@lilith.my-fqdn.de> * Kragen Sitaker [2002-06-15 15:05 -0400]: > Boudewijn Rempt writes: > > I've tried to use most IDE's out there -- from Pythonwin to Pythonworks. > > None was really comfortable, except for Wing IDE, which is really powerful. > > It doesn't include integration of a GUI designer, though, which makes it > > little more than a glorified editor/debugger (but _very_ glorified). At one > > point there was a version of KDevelop that supported Python development, but > > that has disappeared, it seems. > > > > I use bash & XEmacs & Designer nowadays, and that gives me a fair > > productivity. > > I'd like to improve XEmacs to be a better Python IDE. Does it have an integrated user-friendly debugger (not gdb/pdb-like), something like right-click on a line and set a breakpoint? If that GUD thing is only a crude interface like gdb/pdb, then no thanks, I don't need it. Otherwise, it would be really useful to have a web page that described how to use it for Python development. Would be a nice addition to www.python.org's Emacs page. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From mikeb at mitre.org Sun Jun 16 13:03:35 2002 From: mikeb at mitre.org (Mike Brenner) Date: Sun, 16 Jun 2002 13:03:35 -0400 Subject: MS Word -- finding text Message-ID: <3D0CC4E7.5460F610@mitre.org> The COM objects (like Project, Word, Excel, etc.) sometimes return stuff in Unicode format. When they do, the python str() function dies when converting non-ASCII unicode characters. To avoid this problem, I use the following conversion routine. After making the necessary check for None, it attempts a quick conversion str() first. When necessary, it slowly goes through each character, handling the exceptions that are raised. The default is a prime because that is the most common character that hits me in Word and Excel documents. Instead of coding it as an ASCII single-quote characters, these applications code it as a more "beautiful" character, so it kills the python str() function. You may or may not wish to change the return to eliminate the string.strip there, depending on your needs. You could make a separate function that has just the TRY and the EXCEPT in it, in order to use the MAP function instead of the for loop. Mike Brenner def phrase_unicode2string(message): """ phrase_unicode2string works around the built-in function str(message) which aborts when non-ASCII unicode characters are given to it. """ if type(message)==types.NoneType: return "" try: st=str(message) except: # untranslatable unicode character list=[] for uc in message: try: c=str(uc) except: c="`" list.append(c) # Note: because it raises exception instead of returning # a default characters, we cannot use map() here. st=string.join(list,"") return string.strip(st) ------------------------ Mike Prema wrote: ####### from win32com.client import Dispatch W=Dispatch('Word.Application') D=W.Documents.Open('c:\\windows\\Desktop\\TOR.doc') ## Test Doc FindRange=D.Content F=FindRange.Find.Execute('Conman','True') print FindRange.Text ####### str() doesn't seem to work in this case I tried using the codecs library but I think I am missing something From mlh at vier.idi.ntnu.no Sat Jun 8 18:22:05 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Sat, 8 Jun 2002 22:22:05 +0000 (UTC) Subject: [ANN] constraint-0.2 References: Message-ID: In article , Alexandre wrote: >Logilab has released constraint-0.2. > >The constraint package is an extensible Constraint Satisfaction Problem >(CSP) solver using constraint propagation algorithms written in 100% >pure Python (tested with Python 2.1) [snip] >How well does it perform? > * 8-queens problems solved in 15 seconds on my 1GHz PC Interesting... The package looks really cool, but the performance in this example is truly abysmal. The simple queens.py found in the standard Python distribution solves the 8-queens problem (finds all solutions) in 0.11 seconds on an 800MHz PC. I guess maybe that't the price you have to pay for generality... On the other hand, a speedup factor of well over 100 seems to indicate a potential for streamlining... Maybe? - Magnus (who hasn't looked at the internals, and who looks forward to playing around with the package :) -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From christophertavares at earthlink.net Sun Jun 2 17:10:17 2002 From: christophertavares at earthlink.net (Chris Tavares) Date: Sun, 02 Jun 2002 21:10:17 GMT Subject: Python Turing machine References: Message-ID: "G. Willoughby" wrote in message news:ade0mc$j4r$1 at newsg3.svr.pol.co.uk... > > hint: post some URLs of those implementations to the list. that way we > > don't need to look up what it is and people here have fun trying to solve > > things pythonic... > > I belive he means a chat bot that tries to fool humans into beliving its a > real person. > > --G. Willoughby > No, that's the Turing TEST. The universal Turing Machine (both were created by Alan Turing) is the theoretically minimal general purpose computer. It's an interesting bit of CS theory, but not particularly useful in day-to-day life. -Chris From edream at tds.net Mon Jun 3 07:57:28 2002 From: edream at tds.net (Edward K. Ream) Date: Mon, 03 Jun 2002 11:57:28 GMT Subject: Using tcl/tk 8.3.4.2 with Python 2.2 on XP Message-ID: <3CFB5994.5B2F9839@tds.net> Hi all, This may be something trivial, but the answer doesn't seem to jump out at me from the FAQ or the Tkinter page at: http://python.org/topics/tkinter/download.html I would like to use tcl/tk 8.3.4.2 with Python/tkinter 2.2 on Windows XP. Apparently the Python 2.2 distribution uses tcl/tk 8.3.2. Is there some way to use tcl/tk 8.3.4.2 with the binary Python 2.2 distribution on XP? The thoughts I have: 1. set an environment variable somewhere or 2. just move the 8.3.4.2 dll's into the Python22/tcl folder. Neither seems likely to work well, as there may be problems with header compatibility, and there are more 8.3.4.2 dll's than dll's in Python22/tcl. I hope the next version of Python will come with tcl/tk 8.3.4 or higher right out of the box. This will allow us to use wm_iconbitmap(bitmap) to set (at last!) the default icon for tk frames. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From btjenkins at att.net Tue Jun 4 10:22:41 2002 From: btjenkins at att.net (Ben) Date: 4 Jun 2002 07:22:41 -0700 Subject: telnet functionality Message-ID: <9013d0b4.0206040622.f78f95a@posting.google.com> I am trying to write a script that combines telnet, FTP, and gzip functionalities. Here is the process: open telnet connection, change to new directory, list directory, grab last file in directory (the file most recently added), and append it to a list. Then, close the telnet connection and open an FTP connection and place the list I created in a folder specified by user (through FTP connection). I will then use gzip to open file and perform other actions. Initially, I designed this to work with FTP only, but the project has changed and I need to add telnet functionality. I have worked with the script to the point where I can open a telnet account, change to new directory, and list the directory's contents...but, I can't seem to figure out how to grab the last file in the directory and append it to the list. It seems that telnetlib doesn't offer that ability. Here is what I am working with currently: from ftplib import FTP import getpass import string, sys import telnetlib import gzip HOST = sys.argv[1] user = sys.argv[2] password = sys.argv[3] pw = 'sample' tn = telnetlib.Telnet(HOST) tn.read_until("login: ") tn.write(user + "\n") if password: tn.read_until("Password: ") tn.write(password + "\n") tn.read_until('$' ) tn.write('su') tn.write(pw + "\n") tn.write('cd /home/dir\n') tn.write("ls\n") #flist = [] # I used these lines from my previous script #sdr = [] #tn.ls(flist.append) tn.write("exit\n") print tn.read_all() ___________________________________________ Any help would be greatly appreciated. My efforts to find advice has not been very successful to date. Thank you, in advance. - Ben From sandeep182 at hotmail.com Tue Jun 25 16:20:43 2002 From: sandeep182 at hotmail.com (Sandeep Gupta) Date: 25 Jun 2002 13:20:43 -0700 Subject: Pychecker and /var/tmp/python2-2.2-root/usr/lib/python2.2/..... References: Message-ID: Neal Norwitz wrote in message news:... > On Mon, 24 Jun 2002 17:27:30 -0400, Sandeep Gupta wrote: > > > I'm using pychecker on my application, which uses BaseHTTPServer.py and > > unittest.py. Both those files have "No method" warnings that are > > displayed as: > > /var/tmp/python2-2.2-root/usr/lib/python2.2/BaseHTTPServer.py and > > /var/tmp/python2-2.2-root/usr/lib/python2.2/unittest.py > > > > Does anyone know why /var/tmp/python2-2.2-root gets prepended to the > > file name? > > How can I remove the warnings for these files? > > I had this same problem. From what I remember, Redhat compiles > the .py -> .pyc/.pyo files in the /var/tmp/.... directory. > > I didn't find a great way to fix it in pychecker, but to > fix your problem, you should just have to do: > > cd /usr/lib/python2.2 > python compileall.py . > > Neal I tried the above steps replacing the second line with: sudo python2 compileall.py . Successful compile. I verified that /usr/lib/python2.2/BaseHTTPServer.pyo and unittest.pyo exist. But I'm still receiving the same error message from pychecker. Any other ideas? Thanks Sandeep From fredrik at pythonware.com Thu Jun 20 15:06:17 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 20 Jun 2002 19:06:17 GMT Subject: do...while References: Message-ID: Michael P. Soulier wrote: > Right, I've used that in the past. It doesn't seem nearly as clean though, > as making the conditions for terminating the loop plain in the loop > declaration. this has been debated hundreds of times (google can show you all arguments for and against adding yet another control structure). unless you really don't have something better to do with your time, I suggest you get over it and write some code... From lhudson at geminidataloggers.com Thu Jun 27 11:19:21 2002 From: lhudson at geminidataloggers.com (Lawrence Hudson) Date: Thu, 27 Jun 2002 16:19:21 +0100 Subject: How to find out operating system References: Message-ID: <3D1B2CF9.1000605@geminidataloggers.com> If you have PyWin32, try this: d:\>python Python 2.0 (#8, Jun 12 2002, 10:20:16) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> import win32api >>> win32api.GetVersionEx() (5, 0, 2195, 2, 'Service Pack 2') >>> majorVersion: Identifies the major version number of the operating system. minorVersion: Identifies the minor version number of the operating system. buildNumber: Identifies the build number of the operating system in the low-order word. (The high-order word contains the major and minor version numbers.) platformId: Identifies the platform supported by the operating system. May be one of VER_PLATFORM_WIN32s, VER_PLATFORM_WIN32_WINDOWS or VER_PLATFORM_WIN32_NT version: Contains arbitrary additional information about the operating system. Thanks, Lawrence A wrote: > Hi, > What is the best way of finding out the kind operating system? > I can use os.name but if the system is Windows I would like also > know if the system is Windows98 or Windows ME or W2K or > Windows XP. > Thanks for help. > Ladislav > > > > From mdk at mdk.com Thu Jun 20 13:37:59 2002 From: mdk at mdk.com (mdk) Date: 20 Jun 2002 17:37:59 GMT Subject: Function to add commas in numbers? References: <3d11f8d2$1_1@hpb10302.boi.hp.com> Message-ID: "Daniel Fackrell" wrote in news:3d11f8d2$1_1 at hpb10302.boi.hp.com: > mdk, > > The following thread is about formatting numbers for Danish, but it > should give the info you need (paste it as one line): > > http://groups.google.com/groups?hl=en&lr=&ie=UTF8&oe=UTF8&threadm=3D0A1 > 791.3 > 060307%40mxm.dk&rnum=5&prev=/groups%3Fas_q%3Dnumber%2520format%26ie%3DU > TF8%2 6oe%3DUTF8%26as_ugroup%3Dcomp.lang.python%26lr%3D%26hl%3Den This worked great, thanks. From radix at twistedmatrix.com Sun Jun 9 20:16:00 2002 From: radix at twistedmatrix.com (Christopher Armstrong) Date: 09 Jun 2002 20:16:00 -0400 Subject: Source formatting for long expressions. In-Reply-To: <874rgcxy99.fsf@twistedmatrix.com> References: <874rgcxy99.fsf@twistedmatrix.com> Message-ID: <87wut8vvi7.fsf@twistedmatrix.com> >>>>> "ca" == Christopher Armstrong writes: >>>>> "mvl" == Martin v Loewis writes: mvl> As you can see, it tries to align further arguments to a function mvl> together with the opening parenthesis. I would assume that any other mvl> auto-formatters use the same style, so you won't get any "sane" mvl> indentation until you drop the nesting level (perhaps in favour of mvl> method invocations). [snip..] ca> I'm probably going to end up doing this myself, and I thought of ca> something while reading your message. I could have two steps for ca> formatting: template- generation and indentation. the first step would ca> generate something like a repr() of all of my objects, but with \ns and ca> \ts embedded at strategic locations. Then I could replace all \ts with ca> current_indent_level, calculating current_indent_level by counting (s, ca> {s, and [s. I'm going to try this out now. :-) I got this working. It was fairly easy, once I got a templated source representation:: def indentify(s): out = [] stack = [] for ch in s: if ch in ['[', '(', '{']: stack.append(ch) elif ch in [']', ')', '}']: stack.pop() if ch == '\t': out.append(' '*len(stack)) else: out.append(ch) return string.join(out, '') This is a fairly stupid indenter, but it works for my needs:: >>> print aot.indentify("Instance('twisted.internet.app.Application', \ \n\tfoo=bar, \n\tbaz={\n\t'quux': 1, \n\t'spam': \n\tInstance('Eggs', \ \n\tmore='state')})") #this source will really be generated by my __repr__s. Instance('twisted.internet.app.Application', foo=bar, baz={ 'quux': 1, 'spam': Instance('Eggs', more='state')}) -- Chris Armstrong << radix at twistedmatrix.com >> http://twistedmatrix.com/users/carmstro.twistd/ From prema at prema.co.nz Sat Jun 15 15:40:40 2002 From: prema at prema.co.nz (Prema) Date: 15 Jun 2002 12:40:40 -0700 Subject: MS Word -- finding text References: Message-ID: Hi David ! Thanks for your response. The script I am building is intended to provide a search facility over a group of word docs. The strategy is to pull plain text from the doc in numbered paragraphs then search each para in Python and return any found ones. Simplified code so far ..... ####### from win32com.client import Dispatch W=Dispatch('Word.Application') D=W.Documents.Open('c:\\windows\\Desktop\\TOR.doc') ## Test Doc FindRange=D.Content F=FindRange.Find.Execute('Conman','True') print FindRange.Text ####### str() doesn't seem to work in this case I tried using the codecs library but I think I am missing something Thanks for your help with this !! Kind regards Mike "David LeBlanc" wrote in message news:... > Please post some snippets. That's always more likely to get useful > assistance then stating a general problem. > > Where are you encountering the unicode decoding problem? > > Regards, > > David LeBlanc > Seattle, WA USA > > > -----Original Message----- > > From: python-list-admin at python.org > > [mailto:python-list-admin at python.org]On Behalf Of Prema > > Sent: Friday, June 14, 2002 23:50 > > To: python-list at python.org > > Subject: MS Word -- finding text > > > > > > Hi All ! > > Just wondering if anyone has some sample code around how to open a > > document, find a string and return the paragraph(s) containing the > > string. > > > > I have got a good part of the way but running up against Unicode > > decoding > > > > Can post some snippets if needed > > Thanks very much in advance > > > > Kind regards > > Mike > > -- > > http://mail.python.org/mailman/listinfo/python-list From peter at engcorp.com Sun Jun 23 17:51:32 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 23 Jun 2002 17:51:32 -0400 Subject: Zope References: <3D163DC7.739A83FD@NOSPAM_hotmail.com> Message-ID: <3D1642E4.C85BDE4E@engcorp.com> Marc Bigler wrote: > > I would like to know how I can generate a navigation bar in zope ? > > Something like that: [...] > Home > Flowers > Orchidee > > Is that somehow possible examining the BASE0, BASE1,... and so on > variables or is there a better method ? The Zope mailing list is the best place to ask this sort of question. There is little Zope discussion here. You might try doing a Zope.org or Google search for "breadcrumbs" since I think that's what they call the thing you're trying to do. -Peter From duncan at NOSPAMrcp.co.uk Wed Jun 19 06:56:59 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 19 Jun 2002 10:56:59 +0000 (UTC) Subject: CPU Usage Windows References: Message-ID: zaka07 at hotmail.com (Rad) wrote in news:ad381f5b.0206190233.4fa1bf58 at posting.google.com: > Hi, > > I've noticed that when I run Python script on > Windows 2k Pro > Dual Intel Xeon (2.2GHz) > CPU Usage for pythonw.exe is only 50%?! > Is it something to do with python not being able to use the power of > both processors? Yes, although if your scripts are suitably threaded, and some time is being spent outside of Python (reading files/querying databases) I think you should be able to get some usage above 50%. If you can run two of your programs at the same time then CPU usage should go up to about 100%. Running 3 will probably be able to soak up any idle time still left waiting for disc or network responses. The single processor limitation only applies within each process. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From tlirobot at tlirobotics.cc Wed Jun 12 19:09:40 2002 From: tlirobot at tlirobotics.cc (Dylan Appleman) Date: Wed, 12 Jun 2002 23:09:40 GMT Subject: Compiling to .exe Message-ID: Is it possible to compile Python to .exe? If so, what program(s) do I need? Windows XP, no other programming experience but Python. From aahz at pythoncraft.com Wed Jun 19 13:25:33 2002 From: aahz at pythoncraft.com (Aahz) Date: 19 Jun 2002 13:25:33 -0400 Subject: any users of ExtensionClass out there? References: <8b04704.0206190855.5696145b@posting.google.com> Message-ID: In article <8b04704.0206190855.5696145b at posting.google.com>, Rodrigo Senra wrote: >Jeremy Hylton wrote in message news:... >> >> There has been little perceived interest in ExtensionClass releases >> because Zope is moving away from ExtensionClass. I wonder, though, if >> there are other users of ExtensionClass who would be interested in a >> new release. Please let me know if you are. > > Even though I have no production code based in ExtensionClass, I'd > used it sometimes to explore Python reflection capabilities over C > extensions. Therefore, I'm interested in any changes you & your team > may have come up with. In that case, you're better off continuing any future explorations in Python 2.2+; new-style classes are intended to replace ExtensionClass, and the dev team is *far* more interested in hearing about issues with new-style classes. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From hjwidmaier at web.de Fri Jun 21 03:56:04 2002 From: hjwidmaier at web.de (Hans-Joachim Widmaier) Date: 21 Jun 2002 00:56:04 -0700 Subject: Advice sought on ps module References: <6e990e29.0206200325.355f0413@posting.google.com> Message-ID: <6e990e29.0206202356.544eb696@posting.google.com> eddie at holyrood.ed.ac.uk (Eddie Corns) wrote in message news:... > I'm not sure that I understand completely what you're trying to do so maybe > I'm barking up the wrong gum tree here but ... I admit that my writing wasn't very clear ... > Surely you want to use postscript itself to do all the work. PS already has > an operator called stringwidth and a complete set of programming constructs so > the trick usually is to generate the appropriate PS commands. That's how I do it today. Well, I should have given a more concrete example. I've written a program that creates good looking timing diagrams for documentation purposes. These consist of a drawing part and signal names to the left. While the python program knows exactly how large the drawing itself is, it has no way of knowing how far the signal names extend to the left, making it all but impossible to give a valid boundig box for the whole thing -- which is required, as it's going to be an EPS file. Sure, I can get at the BBox by piping the finished file through one of the ps utils programs, but this is kinda cumbersome. And it still doesn't allow me to adjust the right-hand drawing width so the combined width is of some fixed size. > As an example, > to draw a border around some arbitrary text I guess you could generate code to > do something like: save current position, for each string you draw calculate > the bounding box and remember the highest X value and at the end use the new > position along with the saved position and highest X value to define the four > corners of a rectangle. It does require a fair degree of competence in PS but > you wouldn't tackle such a project without it (or a desire to achieve it) > would you :) Another example: In my CD cover/inlay generator I have to do insert line breaks if the Title+Singer+Time line doesn't fit. I do this in PostScript, as I don't know the width in the Python program. This has the drawback that the height of the title list changes and my careful layout (not to be taken too seriously) is disrupted. And no, I do *not* want to write a layout engine in PostScript. Despite having read most of the PostScript Reference Manual, the AFM spec, the DSC specs, etc., ... and having written a bunch of programs that output PostScript, I still consider myself a novice (at best!). This reverse notation thing with all those stacks gives me the creeps. ;-) Hope these explanations make the misery I'm in somewhat more clear. Hans-Joachim From peter at engcorp.com Mon Jun 3 22:14:03 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 Jun 2002 22:14:03 -0400 Subject: Interfacing to 1-Wire LAN, especially Dallas temperature sensors? References: <3CF82E8E.23C6FA10@engcorp.com> <3cfb83e2$1_4@goliath.newsgroups.com> Message-ID: <3CFC226B.B6CB8995@engcorp.com> Brad Clements wrote: > > There is a technique where you can use a UART at some whacky baud rate and > bits/byte setting to communicate. There's an APPNOTE somewhere, I don't have > it handy. If someone can dig that out (I searched before and couldn't find it in all the noise) I'd appreciate it. I would also be happy to try to implement it under Python, since we'd have some uses for such a beast. (But I still don't believe it can be done reliably. Maybe I'm wrong. Would be cool.) -Peter From cbrown at metservice.com Sun Jun 23 22:19:02 2002 From: cbrown at metservice.com (Colin Brown) Date: Mon, 24 Jun 2002 14:19:02 +1200 Subject: Socket Disconnection References: <3d1304d0$0$224$4d4ebb8e@news.nl.uu.net> Message-ID: <3d16817e$1@news.nz.asiaonline.net> Hi Guyon I assume here that you are talking TCP/IP. If you are waiting on a receive [ data = connection.recv() ] then you will have an empty data string returned when the client disconnects. If you are sending you will get an error telling you the link was shut down. Colin Brown PyNZ "Guyon Mor?e" wrote in message news:3d1304d0$0$224$4d4ebb8e at news.nl.uu.net... > Hi! > > I have written a small and simpel server and I was wondering how do you find > out that a client has disconnected? > > thnax, > > Guyon > > From deathtospam43423 at altavista.com Fri Jun 7 11:17:35 2002 From: deathtospam43423 at altavista.com (netvegetable) Date: 7 Jun 2002 15:17:35 GMT Subject: Newby: How do I strip HTML tags? Message-ID: I'm mucking around with cgi, and I'm trying to work out a way to strip the html tags of a string. e.g, I want to convert this... >Really Big String to this this ... >Really Big String ... and store it as a value. I worked out a crude, but effective way of doing it (see code below), but I can't escape the feeling there must be a built in way of doing it more. If nothing else, I'm sure somebody who knows their regular expressions could neaten it up (please?). def strip_html_tags(it): left = it[:(len(it)/2)] right = it[(len(it)/2):] final = left[left.rfind('>')+1:] + right[:right.find('<')] return final -- netvegetable at excite.com From johnroth at ameritech.net Fri Jun 21 08:13:56 2002 From: johnroth at ameritech.net (John Roth) Date: Fri, 21 Jun 2002 08:13:56 -0400 Subject: GOTO w/ Python? References: <3d10ed95@xpl-sdf1-sec1.> <3D11A21D.9010809@mxm.dk> <3D11DA9B.163A7BD0@info.unicaen.fr> <3D12EEAA.9C3A3D29@info.unicaen.fr> Message-ID: "Jerzy Karczmarczuk" wrote in message news:3D12EEAA.9C3A3D29 at info.unicaen.fr... > John Roth comments my observation concerning the relation between gotos > and continuations: > > > > ... in order to speak about genuine gotos *you don't need to think > > > assembler*. > > > What you need is to understand correctly the notion of continuation > > > (something quite standard - again - in the Functional Programming > > > world). This is a high-level model of "flat" branching, but may be > > > used to more exquisite constructions, such as backtracking. > > > > That's still not a goto in the classical sense. In the classical sense, > > a goto allows you to go to any statement. The point you're missing is > > that the goto statement is a denial of structure - since it can go > > anywhere, you can't make any assumptions about the program > > structure. The piece of code you're looking at can be mysteriously > > activated from somewhere else at any time. > > I am not sure I am "missing a point". Perhaps I have a different vision > of the computational process, hm? What is the "classical sense" for one > may be just an orthodox, restricted view for somebody from another galaxy. > I tend to apply often a Functionalist, sometimes too formal view on the > semantics of computations, you don't need to accept it, but I assure you > that for many people gotos *ARE* continuations. Continuation in a broad > sense is just the *specification* of what your <> is. Well, yes. My vision of what a GOTO is comes from my experiance in the '60s, with early versions of Fortran, COBOL, various assemblers, and so forth. This is what Dijkstra was talking about when he wrote "GOTO considered harmful." It's completely unstructured. To put it bluntly (because I can't think of a way to be more diplomatic this early in the morning, sorry) attempting to redefine GOTO in terms of some other structure misses the point completely: a major thread of programming language development since Dijkstra's letter has been to find language structures that can do the job while eliminating the completely unstructured GOTO. Functional programming, continuations, structured exceptions, and similar stuff are all attempts to provide structures that are powerful enough to get the job done, and structured enough that you can reason about them. To delve into the history of language development a bit: immediately following Dijkstra, there was a minimalist structured programming movement, and a horrible debate about the Case statement, and similar constructs. The minimalists didn't want it, the people who wanted to get the job done did. > (Oh, I adored that wonderful piece of programming madness, an "article" > where somebody proposed a new super-Fortran where GO TO was replaced by > CAME FROM statement, and the language had an inspiring non-deterministic > conditional: If <> THEN WHAT?. > Any references, anybody?) It's been around for quite a while - I remember it from GUIDE meetings in the '70s. There's a COBOL variant, and I'm certain there are others. Once Dijkstra focused attention on the GOTO, someone came up with COME FROM. It's actually very logical in a very warped way. If the problem is that you can GOTO anywhere, leading to perplexity as to how you got there, then why not have a construct that allows you to say where you came from, thus removing the perplexity? I knew people back then whose eyes glazed over considering it! You might try the history of computing people - although they might want this one to escape! > > Thank you for this interesting exchange. > > Jerzy Karczmarczuk > Caen, France From kaci_tizi_ouzou2000 at yahoo.ca Mon Jun 3 09:14:08 2002 From: kaci_tizi_ouzou2000 at yahoo.ca (Kaci Tizi Ouzou) Date: 3 Jun 2002 06:14:08 -0700 Subject: WIN32 Decimal point/coma Message-ID: <68599ccc.0206030514.4364e899@posting.google.com> Greetings all, I am having a problem running my application on Win32 for if in the regional settings the user changes the decimal dot to say ',' then floating point operations do not work anymore!!! After few experiments, I came to the conclusion that, it is at 'compile' time that the dot/coma is decided. This means if one compiles py files with dot as the decimal 'separator' and then changes the settings so that coma is the new separator then the code won't work anymore! My question is: Is there a call to make so that to ignore the regional settings ? Is there a solution/suggestion for this problem? Thanks all From tebeka at cs.bgu.ac.il Thu Jun 20 04:45:04 2002 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 20 Jun 2002 01:45:04 -0700 Subject: Help: win32gui & threads References: <33803989.0206170318.9d3a225@posting.google.com> <3D0E6849.3050909@skippinet.com.au> <33803989.0206190041.43b788ac@posting.google.com> Message-ID: <33803989.0206200045.490e3d55@posting.google.com> Hello Mark, I've set the writer and tcp server threads to be deamonic and this seems to solve the problem. Thanks for you help. Miki From tack at cscs.ch Mon Jun 24 07:25:31 2002 From: tack at cscs.ch (Davide Tacchella (CSCS)) Date: Mon, 24 Jun 2002 13:25:31 +0200 Subject: 64-bit Python? References: <87elfl3yvu.fsf@mathdogs.com> <83660wgvrm.fsf@panacea.canonical.org> Message-ID: <3D1701AB.C862F82F@cscs.ch> Kragen Sitaker wrote: > > Yes, this is correct. Even the buffer interface, which my > arrayfrombuffer package[0] uses to provide access to mmapped files as > Numeric arrays inexplicably uses int instead of size_t. > > The problem is that all of the 64-bit platforms I have access to > (various Linuxes on Alpha and IA-64, Tru64 on Alpha) have 4-byte ints > and 8-byte longs, at least by default. This is called "LP64": longs > and pointers are 64, but ints are 32, so all the code that assumes > ints are 32 will continue to work. > Did somebody successfully built Python on AIX with 64 bit support ? dynload_aix.c seems not to be 64 bit safe code ... ---- (function aix_getoldmodules) offset = (unsigned int)ldiptr->ldinfo_next; ldiptr = (struct ld_info *)((unsigned int)ldiptr + offset); --- Davide From david.bear at asu.edu Wed Jun 12 12:31:07 2002 From: david.bear at asu.edu (David Bear) Date: Wed, 12 Jun 2002 09:31:07 -0700 Subject: postscript processing in python Message-ID: I'm looking for tools to assist in postscript processing and pdf generation in python. Hoping to find 'free' code - I'm looking for something that will 1) validate and correct questionable postscript (check document structure) 2) convert postscript to pdf 3) convert text to postscript I know these are tall orders but I've written a filter in python that takes a postscript stream generated by an IBM mainframe and uses ghostscript to convert it to pdf. The problem is ghostscript seems rather picky about some strange things that the mainframe puts in the postscript stream -- so I was hoping to do some cleanup on it and conversion without having to depend on ghostscript. Any pointers appreciated. -- David Bear College of Public Programs/ASU 480-965-8257 ...the way is like water, going where nobody wants it to go From gregor at hoffleit.de Tue Jun 4 10:34:02 2002 From: gregor at hoffleit.de (Gregor Hoffleit) Date: Tue, 4 Jun 2002 16:34:02 +0200 Subject: libpython as a shared library? In-Reply-To: <20020604124540.E9162@phd.pp.ru> References: <20020604124540.E9162@phd.pp.ru> Message-ID: <20020604143402.GB22993@hal.mediasupervision.de> * Oleg Broytmann [020604 10:51]: > On Mon, Jun 03, 2002 at 08:24:28PM +0000, Gregory (Grisha) Trubetskoy wrote: > > Has there been any progress in making an option of building libpython as a > > shared lib (.so)? I saw some feature requests, but couldn't quite figure > > out the ultimate status of this. > > Implemeneted in Python 2.3. Download CVS version or nightly tarball. Debian has had libpython as a shared lib since a while. Recently, we got a report that the performance of the shared version is dramatically slower than the statically linked version (e.g. about 30%). I made some pystone tests on different architectures of our GNU/Linux, and tried different flags for building and linking the library (and different Python versions), and in fact there seems a significant speed penalty involved as soon as the interpreter is linked against the shared library. The penalty has some correlation to the architecture, but it is significant on all tested constellations. I'll give a try at the 2.3 tree and see if the problem can be confirmed there as well. I would be interested if people could try to confirm this with other operating systems and other variants of GNU/Linux as well. Gregor From claird at starbase.neosoft.com Tue Jun 25 08:38:42 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 25 Jun 2002 07:38:42 -0500 Subject: Python daemon References: Message-ID: In article , Roman Suzi wrote: . . . >> 3. restarting of the program if it fails, or the watchdog doesn't trigg= >er > >Run the program from the /etc/inittab - if it terminates,=20 >init will restart it for you. . . . This is one of the great FMMs under Unix--the under-utilization of init(1). From everything I know, Roman's exactly right, that /etc/inittab is the right way to set up a process that you truly want to keep running. However, many, MANY Unix hosts have all kinds of ugly home-brewed hacks to duplicate this functionality. I don't have an explanation, beyond the rather tautologous ob- servation that init(1) simply isn't as widely understood as it deserves to be. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From markus.vonehr at ipm.fhg.de Mon Jun 3 06:11:10 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Mon, 03 Jun 2002 12:11:10 +0200 Subject: Python program problem involving reading a web site. References: Message-ID: <3CFB40BE.8B822E69@ipm.fhg.de> You can use win32com to access IE or netscape if you are on a win32 system. Look at the testNetcape.py example. Mike Varney schrieb: > Hello. > > I wrote a quick little program that is supposed to read the html from a web > site and to update the web counter to show another hit. > I am able to read the html code fine, but the counter on the web site is not > updating. > Here is the code. > > Any suggestions? > Thanks. > > import urllib # imports url library > from time import sleep # imports sleep timer > > # Initilize variables > a = 0 > t = 0 > > # User Input > x = input("How many hits do you want to add to counter? ") > t = input("How long do you want to pause between each hit? (Recommend > 1 > min) ") > > # while loop > > while a < x: > # open and reads page > sock = urllib.geturl(http://foo.bar) > hampage = sock.read() > sock.close() > print a > sleep(t) > a = a+1 > # print goodbye > print "you have increased the page count by " > print a > print "hits" From zayats at blue.seas.upenn.edu Mon Jun 3 10:39:41 2002 From: zayats at blue.seas.upenn.edu (Salim Zayat) Date: 3 Jun 2002 14:39:41 GMT Subject: Changing TK Message-ID: Hey all. I have a quick question about something. If I were to install a newer version of Tcl/Tk on my computer, would Tkinter.py recoginze it automatically, or do I need to tweak the Tkinter.py code itself? Salim From fperez528 at yahoo.com Wed Jun 19 18:24:18 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Wed, 19 Jun 2002 16:24:18 -0600 Subject: OS X debugger? References: Message-ID: Aahz wrote: > From some quick Googling, it appears that a bigger issue would be lack > of support for Python 2.2. Have you used DDD with 2.2? No, sorry. I only used ddd/python back in 2001, with 2.1. So I have no idea about the issues with 2.2 (didn't even know there were issues to begin with). On the other hand, if you can make it work it's quite nice. It integrates withh gnuplot for array display, which is nifty. good luck, f. From bl at netgroup.dk Mon Jun 3 04:01:56 2002 From: bl at netgroup.dk (Bo Lorentsen) Date: 03 Jun 2002 10:01:56 +0200 Subject: Embedding and threads ? In-Reply-To: References: <1022771667.689.136.camel@netgroup> <1022830475.893.17.camel@netgroup> <1022839266.823.66.camel@netgroup> Message-ID: <1023091316.685.40.camel@netgroup> On Sun, 2002-06-02 at 11:35, Martin v. L?wis wrote: > I see. This is necessary indeed. The builtins are normally inherited > from some context when doing "exec" or "eval" at the Python level; on > the C API, no such inheritance happens automatically. Ok, I see. Its just that I assumed that the interpreter state was more isolated, regarding real threads, because of this. For me it looked more like the library had i thread problem than the core interpreter. > Nearly everything in Python > - changing and accessing dictionaries > - changing and accessing lists > - writing to files > - allocating memory (atleast with pymalloc) Ok, so the word "everything" is really more appropriate :-) > etc. None of these operations is thread-safe per se; it is only the > GIL that prevents breakage. And only one CPU thread can execute it at a time. As You may have more threads but only one can execute Python code at a time, because the GIL will serialize the execution ! > > Arhh, so Python can execute in a MT environment, but only one > > interpreter at a time, the rest is pseudo MT ? > > I don't think I understand this question. As I said before, restrict > yourself to "one interpreter" (in the sense of PyInterpreterState*). > This is the normal case even in the presence of threads. What I meant is that, it is only possible to make threads that are software scheduled (Python (and its lib functions) deside when to release the GIL), and if I try to use real threads the result will still be limitet by this software threading. > I don't know what pseudo MT is (in what sense is it pseudo?). It > certainly has multiple concurrent threads. I'm not sure it a proper term, but this is how I se it : software thread = pseudo thread Pseudo, is because it can't really take advantage of SMP (or the system process scheduler), and its the software that controlles the "scheduling". > For most people, it is "real" MT today, since they have only one > processor in their computers, anyway. I know, and as for now I don't know how important it is for me. But as I looked into the Python interface, I was in the beginning hoping that the threads was more "naturly" implimentet in the language engine, and I was hoping to take advantage of this in the future :-) > To make it "more real", you would have to introduce what is known as > "free threading". People have tried this (ask Google) and found that > it slows down the interpreter significantly. Hmm, this sounds like they had not done it the proper way :-) But I will take a look in Deja/Google ! But ok, I'll use what Python provide, and I'm sure it will work out just fine, and then I'll see hov things in Python progress regarding threads in the future :-) /BL From bokr at oz.net Tue Jun 25 21:35:44 2002 From: bokr at oz.net (Bengt Richter) Date: 26 Jun 2002 01:35:44 GMT Subject: SOLVED (Re: Python hits the spot) References: Message-ID: On 26 Jun 2002 01:09:39 GMT, bokr at oz.net (Bengt Richter) wrote: >On Tue, 25 Jun 2002 15:12:47 -0700, "Jimmy Retzlaff" wrote: > >>Bengt Richter wrote: >>>>> Well, lucky guess on the heat. That _probably_ accounts for laptop >>>>> going to 87% and then shutting down, but how about the other huge >>>>> slowdowns in your big loop of 8? Did you get that diagnosed too? >>>>> Just curious ;-) >>>> >>>>On my stationary machine definitely not. The 8 steps remain constant. >>I=20 >>> >>>Still curious ;-) >> >>I believe that newer mobile CPUs will throttle back their clock speed in >>response to heat. This could explain the slow down. Apparently the > ^^^-- or "some of the" >>lowest clock speed wasn't low enough to keep the CPU happy... >> >Yeah, I understood that (having introduced the concept into this thread, I think ;-) ^^^^ oops, original, not this one Siegfried certainly advertised the many shutdowns/slowdowns/"freezes". I just hypothesized: "I wonder how/whether the percentage calculated is affected by power management that slows down the CPU clock to keep it cool? Wonder if that could be happening. I've never looked into power management stuff. I guess there is a temperature where it just shuts down too, to protect itself?" RPM1 was apparently also onto it when he cryptically said, "Just curious, is your laptop a Hewlitt Packard?" >But it was not clear to me whether that explained _everything_ (see other post re two >readings of "On my stationary machine definitely not. The 8 steps remain constant." ;-) > Regards, Bengt Richter From R.Barrett at ftel.co.uk Mon Jun 24 06:23:55 2002 From: R.Barrett at ftel.co.uk (Richard Barrett) Date: Mon, 24 Jun 2002 11:23:55 +0100 Subject: Python and remote sensing In-Reply-To: <3D16E528.5040207@kfunigraz.ac.at> Message-ID: <5.1.0.14.2.20020624104306.0341dd48@pop.ftel.co.uk> At 11:23 24/06/2002 +0200, Siegfried Gonzi wrote: >Hi, > > >a technician of us asked me whether it is possible to do the following: > > >Starting a script on Unix at lets say 2 am and calling a remote site >(http://www.whatever...) and that site should become passively processed >(the site holds 41 observing stations). Is it possible to start a remote >script (automatically) connect to a http page and retrieve information >from that html-page? >I answerd Perl or Python can do the job. But I am not sure whether that is >correct. > >I am sure the above topic has been asked 1000 times. Or is there a tool or >program availabe which can do the job better?; I mean our technican has >never heard of Python and I am not interested to make web based (put in >the right term here) programming or the like. > >If Python can do it - okay; if not please say so (if Python is dead - >okay; if Python lives - okay)! > > >Thanks, >S. Gonzi You can write a script in Python or Perl to be executed by the UNIX cron daemon at the time you specify (see the UNIX crontab command man page). There is nothing out of the ordinary about such scripts beyond their being listed in an appropriate user's installed crontab and you will not want it to prompt for input parameters. In the case of Python you can simply use the urllib, urllib2 or httplib to retrieve data using HTTP; these modules being listed in order of reducing simplicity of use. Try using urllib from the python command line and you'll see how easy it is. Probably the biggest issue will be if you have to use any form of authentication in order to get a response from the HTTP server. But that isn't a problem Perl almost certainly has equivalent modules if you prefer it to Python. With Python 2.2.1 a basic script like the one that follows will do it if you have to use HTTP basic authentication. You'll need to add some extras to handle problems with opening the URLs, supplying parameters if the URLs need to incorporate them etc. But basically its really quite easy to do. #! /usr/bin/env python import urllib # Hardwired HTTP basic authentication parameters basic_auth_username = '....' basic_auth_passwd = '....' # URL we want data from url = 'http://.......' # Destination filename for data retrieved destination_filename = '.....' class myURLopener(urllib.FancyURLopener): def prompt_user_passwd(self, host, realm): return basic_auth_username, basic_auth_passwd urllib._urlopener = myURLopener() stuff = urllib.urlretrieve(url) open(destination_filename, 'w').write(open(f[0], 'r').read()) From python at tykebsd.net Thu Jun 6 07:56:02 2002 From: python at tykebsd.net (Dave Moor) Date: 6 Jun 2002 04:56:02 -0700 Subject: Interfacing to 1-Wire LAN, especially Dallas temperature sensors? References: Message-ID: <1bf96e7f.0206060356.417a7394@posting.google.com> Hi I have just started producing a PyOneWire module it currently can search the one wire network for families of devices and read the temperatures from DS1820 devices. What platform are you wanting to run it on, I could send you a prerelease versiob to try. Dave Moor Christian Aastorp wrote in message news:... > I'm considering doing some temperature control and logging, both > enviromental and inside computers. Did a google search, and found > references to the range of temperature sensors from Dallas > Semiconductors. > > I also found schematics for interfacing with the serial port, and > timing diagrams for implementing 1-Wire Lan using direct control of > the port. > > As I'm using Python for my programming, these days, I would like some > pointers to modules or techniques to use Python to read the > temperature sensors. > > Christian Aastorp From tmagna at online.no Sun Jun 2 17:59:20 2002 From: tmagna at online.no (Tobias Brandvik) Date: Sun, 02 Jun 2002 21:59:20 GMT Subject: Python Turing machine References: Message-ID: On 2 Jun 2002 20:19:05 +0200, Chris Liechti wrote: >hint: post some URLs of those implementations to the list. that way we >don't need to look up what it is and people here have fun trying to solve >things pythonic... Here is a page describing the implementation of a UMT in Scheme (together with the code): http://web.mit.edu/manoli/turing/www/turing.html --Tobias Brandvik From carel.fellinger at iae.nl Fri Jun 28 23:15:56 2002 From: carel.fellinger at iae.nl (Carel Fellinger) Date: Sat, 29 Jun 2002 05:15:56 +0200 Subject: I'm an idiot In-Reply-To: References: Message-ID: <20020629031556.GB2953@schaduw.felnet> On Sat, Jun 29, 2002 at 01:00:22AM +0000, David wrote: > OK, I am the first to admit it. I am an idiot. I have RTFM on this over Hm, that makes you the first idiot to admit he's an idiot, not likely so. ... > And just to explain my stupidity, my reference langauge is BASIC. I Hm, nothing wrong with having BASIC as your reference language, it just indicates that you haven't had the time to familiarize yourself with Python. Don't worry, in a few days all will be swell. > f=open('c:\\temp\\temp.txt', 'r') Windows allows / in dir path, less error prone, and "r" is the default mode and hence often left out. > g=open('c:\\temp\\temp1.txt', 'w') > while 1: > try: > s=f.readline here you merely create an extra name for the file readline function. The ( and ) are really needed to instruct the interpreter to perform the function instead of creating a new name for it. > g.write(s.split()) the split method removes all spaces/newlines/tabs from a string, braeking the string in those places and returning a list of al the leftovers. "a bc d".split() == ["a", "bc", "d"] > except IOError: > break In python the file read(line) method(s) don't bark at the end of file, they simply return an empty string. So you won't get an EndOfFile Exception. The easiest thing is to test here for the empty string. > > g.close > f.close again, without the ()'s nothing happens here. Fixing the above and replacing the non-working try-except you get: f = open('c:/temp/temp.txt') g = open('c:/temp/temp1.txt', 'w') while 1: line = f.readline() line = line.strip() if not line: # line is empty break g.write(line) g.close() f.close() But we can do better then this by replacing the while loop with a for loop: f = open('c:/temp/temp.txt') g = open('c:/temp/temp1.txt', 'w') for line in f.readlines(): g.write(line.strip()) g.close() f.close() And in Python2.* the above for line can be further simplified as: f = open('c:/temp/temp.txt') g = open('c:/temp/temp1.txt', 'w') for line in f: g.write(line.strip()) g.close() f.close() Many people would rely on Python's automatic file closing behaviour and write it like this: g = open('c:/temp/temp1.txt', 'w') for line in open('c:/temp/temp.txt'): g.write(line.strip()) -- groetjes, carel From geoff at gerrietts.net Fri Jun 7 20:14:32 2002 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Fri, 7 Jun 2002 17:14:32 -0700 Subject: Medium to Large Scale Python Deployments In-Reply-To: <38C31EBA-79A4-11D6-9A7D-003065B33450@intersight.com> References: <38C31EBA-79A4-11D6-9A7D-003065B33450@intersight.com> Message-ID: <20020608001432.GA18346@isis.gerrietts.net> Quoting Sam Penrose (spenrose at intersight.com): > [Domenic R. Merenda raises the topic of Python used in large contexts] > > I'm also curious about large amounts of Python, period. Who knows of > ~50K Python lines-of-code (LOC) systems? 100K LOC? More? I'm working on a large web project whose name I hafta jump thru permission hoops to reveal (though a little perfunctory Googling old newsgroup posts would probably give you the answers if you care). I don't have a nice summary version printing out of the version of pycount I found on starship, so mine may not be as good as others, but I show: lines: 173810 code: 127443 doc: 1387 comment: 17873 blank: 27107 I would put the number of python enthusiasts working on this code somewhere around 50%; others appreciated its merits but were largely indifferent to concerns of language, and still others were inductees in the cult of Java. Some of the code indexed above is autogenerated, for use with ILU-based services. Some is boilerplate, for similar reasons. But most has been seen by human eyes and shaped by human minds. --G. -- Geoff Gerrietts "Punctuality is the virtue of the bored." --Evelyn Waugh From ianb at colorstudy.com Mon Jun 3 02:05:13 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 03 Jun 2002 01:05:13 -0500 Subject: What is a classmethod for? In-Reply-To: References: Message-ID: <1023084314.10680.12551.camel@localhost> On Sun, 2002-06-02 at 19:06, Dennis Peterson wrote: > > The point is that you can call class methods *without* creating an > > instance: > > >C.foo() > > But you can do that with a static method: > > class C: > def foo(x): > print x > foo = staticmethod(foo) > > C.foo(1) Maybe a better example would be per-class caching. Like: class C: cache = {} # Contains values of (expire_time, cache_value) def cleanCache(klass): for key, (expire_time, value) in klass.cache.items(): if expire_time < time.time(): del[klass.cache[key]] In general it only makes sense when you use class variables -- just like if you don't use any instance variables it might make more sense to use a plain function instead of a method. Ian From loewis at informatik.hu-berlin.de Sun Jun 2 05:35:24 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 02 Jun 2002 11:35:24 +0200 Subject: Embedding and threads ? In-Reply-To: <1022839266.823.66.camel@netgroup> References: <1022771667.689.136.camel@netgroup> <1022830475.893.17.camel@netgroup> <1022839266.823.66.camel@netgroup> Message-ID: Bo Lorentsen writes: > > I lost track. How do you set the builtins, and why do you have to? > Before calling "PyEval_EvalCode", I have to make this call, or I was not > even able to use the build in functions like "range" ! > > PyDict_SetItemString( pDict, "__builtins__", PyEval_GetBuiltins()); > > pDict is both the local and the global dict. for the PyEval_EvalCode > function. I see. This is necessary indeed. The builtins are normally inherited from some context when doing "exec" or "eval" at the Python level; on the C API, no such inheritance happens automatically. > One day I may understand this, but until then I hope you bear with me > :-) So, besides the ThreatStates, what else does GIL protect ? Nearly everything in Python - changing and accessing dictionaries - changing and accessing lists - writing to files - allocating memory (atleast with pymalloc) etc. None of these operations is thread-safe per se; it is only the GIL that prevents breakage. > Arhh, so Python can execute in a MT environment, but only one > interpreter at a time, the rest is pseudo MT ? I don't think I understand this question. As I said before, restrict yourself to "one interpreter" (in the sense of PyInterpreterState*). This is the normal case even in the presence of threads. I don't know what pseudo MT is (in what sense is it pseudo?). It certainly has multiple concurrent threads. > Now, this makes more sense ! Do you know if there is any plans to make > Python more flexible for (real) MT processing in the future ? When > looking into the code, it looks like someone have tried to modulize it > so that it could be real MT in the future, at least as far as the core > language goes. For most people, it is "real" MT today, since they have only one processor in their computers, anyway. To make it "more real", you would have to introduce what is known as "free threading". People have tried this (ask Google) and found that it slows down the interpreter significantly. Regards, Martin From akuchlin at ute.mems-exchange.org Mon Jun 10 14:22:06 2002 From: akuchlin at ute.mems-exchange.org (A.M. Kuchling) Date: 10 Jun 2002 18:22:06 GMT Subject: M2Crypto: select() behaves weird on SSL sockets References: <3D04ECED.2030202@NOSPAMREMOVETHISxs4all.nl> Message-ID: In article <3D04ECED.2030202 at NOSPAMREMOVETHISxs4all.nl>, Irmen de Jong wrote: > Basically, it seems that a SSL socket is no longer in ready > state when entering select() again, after reading *a part* > of the available data on the socket. Perhaps there really is no more data on the socket because OpenSSL has read it all, but the decrypted data is now sitting in a buffer somewhere, probably inside an OpenSSL data structure. --amk From aahz at pythoncraft.com Tue Jun 25 17:49:38 2002 From: aahz at pythoncraft.com (Aahz) Date: 25 Jun 2002 17:49:38 -0400 Subject: Suggestions for good programming practices? References: Message-ID: In article , Bengt Richter wrote: > >Do you recommend using def foo(*args) and testing len(args) instead? Only if you really want a list of unnamed parameters. Personally, I usually prefer to pass a sequence directly in such cases, to distinguish between None (i.e. no list) and the empty list. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From oren-py-l at hishome.net Sun Jun 30 16:38:56 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Sun, 30 Jun 2002 16:38:56 -0400 Subject: yield equivalent in C/JavaScript? In-Reply-To: References: <20020630180139.GA38821@hishome.net> Message-ID: <20020630203856.GA59010@hishome.net> On Sun, Jun 30, 2002 at 09:05:37PM +0100, Robin Becker wrote: > In message <20020630180139.GA38821 at hishome.net>, Oren Tirosh l at hishome.net> writes > > very smart! That Duff did it Fortran as I recall. I don't think there is switch with case fallthrough in fortran. Duff's device is most definitely a unique abuse of the C language. http://www.lysator.liu.se/c/duffs-device.html Oren From christophe.delord at free.fr Wed Jun 12 18:27:37 2002 From: christophe.delord at free.fr (Christophe Delord) Date: Thu, 13 Jun 2002 00:27:37 +0200 Subject: map -> class instance References: Message-ID: <20020613002737.09044c6c.christophe.delord@free.fr> self.x=y is a call to self.__setattr__, so if you write self.x=y in __setattr__ it is an infinite recursion. (see http://www.python.org/doc/current/ref/attribute-access.html#l2h-112) in __setattr__, self.m[key]=val may be written self.__dict__['m'][key]=val in __init__, self.m=m may be written self.__dict__['m']=m $ cat map2class.py class Map2Class: def __init__(self,m): self.__dict__['m'] = m def __getattr__(self, key): return self.m[key] def __setattr__(self, key, val): self.__dict__['m'][key] = val def __delattr__(self, key): if self.m.has_key(key): del self.m[key] m = {'first' : 'John', 'last' : 'Hunter', 'age' : 34} c = Map2Class(m) print c.first, c.last, c.age $ python map2class.py John Hunter 34 $ Christophe. On Wed, 12 Jun 2002 16:49:32 -0500 John Hunter wrote: > > I want to convert dictionary instances to instances of a class that > has the keys of the map as attributes. I naively tried this: > > class Map2Class: > def __init__(self,m): > self.m = m > > def __getattr__(self, key): > return self.m[key] > > def __setattr__(self, key, val): > self.m[key] = val > > def __delattr__(self, key): > if self.m.has_key(key): > del self.m[key] > > m = {'first' : 'John', > 'last' : 'Hunter', > 'age' : 34} > > c = Map2Class(m) > print c.first, c.last, c.age > > But got an infinite recursion: > > ~/python/test $ python map_to_class.py > Traceback (most recent call last): > File "map_to_class.py", line 20, in ? > c = Map2Class(m) > File "map_to_class.py", line 3, in __init__ > self.m = m > File "map_to_class.py", line 8, in __setattr__ > self.m[key] = val > File "map_to_class.py", line 5, in __getattr__ > return self.m[key] > File "map_to_class.py", line 5, in __getattr__ > return self.m[key] > [snip ... lots more line fivers ] > > Is there a better/right way to do what I want? > > Thanks, > John Hunter -- (o_ Christophe Delord _o) //\ http://christophe.delord.free.fr/ /\\ V_/_ mailto:christophe.delord at free.fr _\_V From gmcm at hypernet.com Fri Jun 7 08:53:32 2002 From: gmcm at hypernet.com (Gordon McMillan) Date: 07 Jun 2002 12:53:32 GMT Subject: problem with isinstance and relative/absolute import References: <87adq8jsq1.fsf@tux.ntw23.fr> Message-ID: Sylvain Thenault wrote: > does someone can explain to me the following test case, or should it be > considered as a bug ? > > [syt at tux syt]$ ls tests/ > __init__.py module2.py module.py [snip] > [syt at tux syt]$ cd tests Bad move. This makes the modules in the tests directory accessable in 2 ways - as a direct import (sys.path[0]), or as a package. The way you do your imports, you end up getting module twice, once as module, once as tests.module. Just look at the repr's of a, b and A to see. And stay out of package directories. -- Gordon http://www.mcmillan-inc.com/ From whisper at oz.net Sun Jun 9 18:16:22 2002 From: whisper at oz.net (David LeBlanc) Date: Sun, 9 Jun 2002 15:16:22 -0700 Subject: Socket error problem In-Reply-To: Message-ID: Ok, that solved the problem. It was caused by the app using it's own version of sockets; overriding the default implementation to create something called a "TimeoutSocket", which don't work on Windows for some reason (something to worry about later if necessary). Fortunately, all that was required to go back to using standard sockets was to remove the override. After chasing down a few additional bugs (it seems to ignore it's own config options or the doc isn't good enough to describe how to set them properly), it now actually slurps mail!! :) The author of the package said it would never work on Windows - hah! :) (Actually, I'm not even going to bother with the QT GUI interface, although I'm sure that's doable as well.) Thanks for the help! David LeBlanc Seattle, WA USA > -----Original Message----- > From: martin at v.loewis.de [mailto:martin at v.loewis.de] > Sent: Sunday, June 09, 2002 14:03 > To: David LeBlanc > Cc: python-list at python.org > Subject: Re: Socket error problem > > > "David LeBlanc" writes: > > > I've put print statements around all this before I first tryed > the ml, but > > here they are again: > > This is still not the right place. > > > print 'poplib._init__: self.host = %s ' % self.host, > 'self.port = > > %s' % self.port > > Notice that host and port are not passed directly to socket. Instead, > getaddrinfo is used > > > for res in socket.getaddrinfo(self.host, self.port, 0, > > socket.SOCK_STREAM): > > af, socktype, proto, canonname, sa = res > > try: > > Please add a line printing res inside of this try statement. Also add > a print statement between the socket call and the connect call, so > that we know which call it is that fails. > > Regards, > Martin From Blobbybirdman at hotmail.com Mon Jun 17 06:03:33 2002 From: Blobbybirdman at hotmail.com (Mark Robinson) Date: Mon, 17 Jun 2002 11:03:33 +0100 Subject: unhashable type when using pickle.load() Message-ID: I wonder if anyone can shed some light on a troublesome intermittent problem I am having. Firstly the necessary: I am running on windows XP, using jython 2.1 and java 1.3.1_03. A pickled file is created as follows: pickle.dump((self.seq.getMotifs(), self.s[self.seqIdx]), newFile) self.seq.getMotifs() simply returns a dictionary containing various complex python objects (which will have been created and used sucessfully) self.s[self.seqIdx] is a python sequence object. Intermittently, when I try and reload from this pickle file I get the following exception: Exception occurred during event dispatching: Traceback (innermost last): File "pars.py", line 129, in OpenFile File "D:\program files\jython-2.1\Lib\pickle.py", line 947, in load File "D:\program files\jython-2.1\Lib\pickle.py", line 567, in load File "D:\program files\jython-2.1\Lib\pickle.py", line 885, in load_setitem TypeError: unhashable type I have read that this error typically can occur when a pyDictionary or pyList is inserted into a hashtable. Is this a problem that anyone else is familiar with, is it a limitation of the jython implementation of pickle? Any help will be appreciated Blobby From deltapigz at telocity.com Thu Jun 13 23:45:34 2002 From: deltapigz at telocity.com (Adonis) Date: Thu, 13 Jun 2002 23:45:34 -0400 Subject: More Tkinter Help please... References: Message-ID: <3d096af6_1@nopics.sjc> i ran the code, and i had no errors on loading it, you might want to try placing all your functions above the __init__ call, i.e.: class PyShell: def expyth ... def ... def __init__ ... hope thie helps Adonis "SA" wrote in message news:B92EC762.70EC%sarmstrong13 at mac.com... > Hi Everyone- > > I have another Tkinter question for you. I'm still trying to translate > "that previously mentioned" Tcl/Tk program into Python/Tkinter. The > following is all of the code I've managed so far: > > from Tkinter import * > import sys > import os > > class PyShell: > def __init__(self, top): > > f = Frame(top) > f.pack() > > self.t1 = Text(f, height="12", width="84", font="Courier 12") > self.t1.pack(side=TOP, pady=2) > > self.t2 = Text(f, height="12", width="84", bg="lightblue", > font="Courier 12") > self.t2.pack(side=TOP, pady=2) > > self.b1 = Button(f, text="Execute", command=self.expyth) > self.b1.pack(side=LEFT) > > self.b2 = Button(f, text="Clear Input", command=self.clearin) > self.b2.pack(side=LEFT) > > self.b3 = Button(f, text="Clear Output", command=self.clearout) > self.b3.pack(side=LEFT) > > self.b4 = Button(f, text="Save Input", command=self.savin) > self.b4.pack(side=LEFT) > > def clearin(self): > self.t1.delete(0,END) > > def clearout(self): > self.t2.delete(0,END) > > def expyth(self): > output = os.popen("python -c").t1() > self.t2.delete(0,END) > sys.stdout.write.t2(output) > > def savin(self): > pass > > root = Tk() > > app = PyShell(root) > > root.mainloop() > > When I run this I get the following error: > > Traceback (most recent call last): > File "PyShell.py", line 45, in ? > app = PyShell(root) > File "PyShell.py", line 17, in __init__ > self.b1 = Button(f, text="Execute", command=self.expyth) > AttributeError: PyShell instance has no attribute 'expyth' > > > Any ideas on what I'm doing wrong here? > > Thanks. > SA > From fgeiger at datec.at Thu Jun 6 14:50:11 2002 From: fgeiger at datec.at (F. GEIGER) Date: Thu, 6 Jun 2002 20:50:11 +0200 Subject: Emulating classmethod in Python 2.1 References: <915a998f.0206060833.12ad76a8@posting.google.com> Message-ID: There's a receipe about this in the ASPN, by Alex Martelli. Concise and effective. Strongly recommended. Cheers Franz "Hamish Lawson" schrieb im Newsbeitrag news:915a998f.0206060833.12ad76a8 at posting.google.com... > Is it possible to define a 'classmethod' class or function for Python > 2.1 that would effectively provide the functionality of Python 2.2's > built-in classmethod function and have the same usage pattern? I'd > like to be able run code like that below against both 2.2 (using its > builtin classmethod function) and 2.1 (using some added-in wrapper). > > class SomeClass: > def hello(cls, name): > print "Hi there", cls, name > hello = classmethod(hello) > > SomeClass.hello("Peter") > > I've come across Thomas Heller's recipe in the online Python Cookbook, > but this would require SomeClass to be modified, and so fails my > criteria. > > I've also come across Alex Martelli's recipe for emulating > staticmethod, but of course that doesn't deal with passing a class to > the wrapped method. > > > Hamish Lawson From gerhard.haering at gmx.de Wed Jun 19 23:27:10 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Thu, 20 Jun 2002 05:27:10 +0200 Subject: working with secure shell In-Reply-To: References: Message-ID: <20020620032709.GA13875@lilith.my-fqdn.de> * Jon J. Morin [2002-06-20 03:13 +0000]: > One question: Is there a python library or module for working with the > secure shell (ssh)? Yes. http://pyssh.sourceforge.net/ Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From gyromagnetic at excite.com Tue Jun 11 08:29:28 2002 From: gyromagnetic at excite.com (gyromagnetic) Date: 11 Jun 2002 05:29:28 -0700 Subject: using m2crypto to encrypt credit card numbers References: Message-ID: <4620daca.0206110429.1417b389@posting.google.com> Hi, Managing keys is a fundamental problem with encryption. I would highly recommend that you not store the credit card numbers at all. Instead, store a (SHA, MD5) hash of the number, and then validate against the hash. -g "Mark McEahern" wrote in message news:... > I'm considering using M2Crypto (http://www.post1.com/home/ngps/m2/) to > encrypt credit card numbers. My part of the problem starts when the credit > card arrives at the web server. I plan to encrypt it with a public key and > send it to a database that the web server only has write access to. > From Jeff_Donahoo at Baylor.edu Wed Jun 12 09:03:35 2002 From: Jeff_Donahoo at Baylor.edu (Jeff Donahoo) Date: Wed, 12 Jun 2002 08:03:35 -0500 Subject: Wanted: Potential Python Authors Message-ID: I'm looking for somebody to author a short book on Python in my programming technology series. Who do you think would make a great author that hasn't already written a book on Python? Candidates include: - Competent and frequent posters to this newsgroup - Author of articles in the various trade magazines - Expert programmer From opengeometry at NOSPAM.yahoo.ca Thu Jun 27 14:30:15 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 27 Jun 2002 18:30:15 GMT Subject: How to get rid the new line References: Message-ID: SiverFish wrote: > Anyone tell me how to skip the empty line when you read through the file > and copy the information in to the list(no empty line ) A bit off topic... but this question just cries out for sed 's/^$/d' -- William Park, Open Geometry Consulting, 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin From gherron at islandtraining.com Thu Jun 6 16:27:46 2002 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 6 Jun 2002 13:27:46 -0700 Subject: numeric limits? In-Reply-To: References: Message-ID: <200206061327.46814.gherron@islandtraining.com> On Thursday 06 June 2002 01:15 pm, David Abrahams wrote: > Is there some straightforward way to find out the range of a Python Int (in > code)? Use sys.maxint : >>> import sys >>> sys.maxint 2147483647 Gary Herron From Chris.Barker at noaa.gov Thu Jun 20 15:56:46 2002 From: Chris.Barker at noaa.gov (Chris Barker) Date: Thu, 20 Jun 2002 12:56:46 -0700 Subject: How to represent the infinite ? References: <3d11ee9b$1@news.swissonline.ch> <20020620193230.53d58f8f.christophe.delord@free.fr> <3D121A29.A733609F@noaa.gov> Message-ID: <3D12334C.59EB9911@noaa.gov> Chris Barker wrote: > whether > this works is a function of the machine, compiler and library used to > compile Python. I'm not sure how common it is, but if you want your code > portable, it may not be reliabel on all machines, which is too bad, > because IEEE 754 is pretty darn good standard. After posting that, I went and read some more: http://cch.loria.fr/documentation/IEEE754/wkahan/754story.html A quote from that article: "Programming languages new ( Java ) and old ( Fortran ), and their compilers, still lack competent support for features of IEEE 754 so painstakingly provided by practically all hardware nowadays. S.A.N.E., the Standard Apple Numerical Environment on old MC680x0-based Macs is the main exception. Programmers seem unaware that IEEE 754 is a standard for their programming environment, not just for hardware." Too bad. Python can't do anything that isn't supported by the compilers it is built with. Full disclosure: I took a Numerical Analysis course with Kahan when I was at Berkeley. I understood about 1/10 of what he was trying to teach us, but I did learn this: Floating point is hard! -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From missive at frontiernet.net Mon Jun 10 18:31:55 2002 From: missive at frontiernet.net (Lee Harr) Date: Mon, 10 Jun 2002 22:31:55 -0000 Subject: ZODB and non-python languages References: Message-ID: > Hi. I am working with a group of people who have an extensive Zope > system with lots of data in their ZODB database. I am obliged to > implement my parts in JSP. Can anybody point me in the right direction > for using ZODB from Java? > How about xml-rpc? From johnsogg at cs.colorado.edu Mon Jun 10 14:09:57 2002 From: johnsogg at cs.colorado.edu (Gabe Johnson) Date: 10 Jun 2002 11:09:57 -0700 Subject: ZODB and non-python languages Message-ID: Hi. I am working with a group of people who have an extensive Zope system with lots of data in their ZODB database. I am obliged to implement my parts in JSP. Can anybody point me in the right direction for using ZODB from Java? Thanks -gabe From whisper at oz.net Wed Jun 5 05:39:52 2002 From: whisper at oz.net (David LeBlanc) Date: Wed, 5 Jun 2002 02:39:52 -0700 Subject: writing a text in hyphenless justification In-Reply-To: <32d0f89.0206042221.1910798c@posting.google.com> Message-ID: Justifying text, with or without hyphens, is SO not a trivial job to do right. I think the tkinter edit control has a justification setting (I'm almost positive) which does not do hyphenation and so pouring your text into a Tk edit control and then reading it out line by line would be the simpliest solution imo. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Backflip > Sent: Tuesday, June 04, 2002 23:22 > To: python-list at python.org > Subject: writing a text in hyphenless justification > > > Hi everybody, > i?ve got a little problem again...... > i want to take a raw_input and makes it to a hyphenless > justification output..... > how is this possible????? > The most beautiful solution would be the one, that i can define > the width.... > has got smb a idee??? it would be very nice, if smb can help me > with my problem..... > THankfull > Backflip > -- > http://mail.python.org/mailman/listinfo/python-list From peter at engcorp.com Tue Jun 11 00:12:55 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 11 Jun 2002 00:12:55 -0400 Subject: Correct code/unit testing (was Re: Efficient python programming...) References: <3D00A456.4315EDA3@engcorp.com> <834rgd5isv.fsf@panacea.canonical.org> <3D02FB3B.CF75E925@engcorp.com> <83u1oaq0jt.fsf@panacea.canonical.org> Message-ID: <3D0578C7.ACDBF41A@engcorp.com> Kragen Sitaker wrote: > > Peter Hansen writes: > > Have you never spent a large amount of time carefully > > designing and coding a wonder little program, and checked it over > > very carefully, even with a peer, and later found a bug in it? > > Of course! People are fallible, it's much easier to do a bad code > review than a good one. I have to confess I have never seen a successful code review, nor an environment in which they were used regularly and which had a high level of code quality. Clearly as a result I'm fairly biased against them -- I should keep a more open mind on the issue perhaps. I'm swayed also by the thought that programmers generally rebel against them, and that therefore they are likely not the best approach in most shops. Learning XP has taught me that a process which works in a way programmers find natural is much more likely to succeed than one which goes against the grain. > I think now we have each committed the same arrogant gaffe in this > discussion: "It is only possible to disagree with me if you do not > know what I am talking about." I was wrong, and so are you. Point taken; my apologies. (I'm about to go on vacation to NYC for the rest of the week, so if I suddenly go silent, it's not personal. :) > I think inspection can find bugs that are very difficult to find by > testing, and vice versa. That is the reason for my second statement; > a balance of careful reasoning and testing can produce better code > than the same amount of time spent on either alone. For code not written test first, I would strongly concur. For code written test first, I believe the resulting modularity and cohesion in the code mostly negates the value of inspection. Again, other practices from XP are probably polluting my mind against such things -- in this case pair programming. Assuming the formal 'inspection' advocated by some heavy-weight processes, I think it's of little use on code pair-programmed. (We could also be more general and just say that pair programming is on par with inspection and that either is effective in an appropriate context.) Cheers, -Peter From emile at fenx.com Tue Jun 11 09:01:30 2002 From: emile at fenx.com (Emile van Sebille) Date: Tue, 11 Jun 2002 13:01:30 GMT Subject: Defining a method final References: <6glN8.35376$86.884025@twister1.libero.it> Message-ID: "Fabio Corneti" wrote in message news:phmN8.36164$K4.893500 at twister2.libero.it... > I would like to define a method for a class which has > not to be overriden. Of course, since the developer of > this project are two, this could be established by > convention, but if the project will grow consistently > another developer could override the method by mistake, > causing unpleasant side effects. > Accepted practice is to use a single underscore for objects to be considered private. This does not prevent their use, but strongly signals that re-use ought not to be done. >>> class Test: ... def _private(self): pass ... HTH, -- Emile van Sebille emile at fenx.com --------- From shalehperry at attbi.com Thu Jun 6 20:29:36 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Thu, 06 Jun 2002 17:29:36 -0700 (PDT) Subject: Efficient python programming... In-Reply-To: Message-ID: On 06-Jun-2002 Shagshag13 wrote: > > I'm looking for any state of art, optimizing techniques, tips, that a > python beginner couldn't know by itself, but should learn and > would be aware to write "efficient and good looking"python's code... > > (not the kind of thing which made you an obfuscated python nerd, > but that "map" should be preferred to "for in loop" if possible, that > dictionary are very well optimized, etc.) > the consensus on this list over the last year seems to be that optimized code is usually the simplest implementation. If you feel you are going through hoops getting something working you probably need to take a step back, ponder and maybe ask a question. BTW tutor at python.org is a great place for new python coders to hang out, read, and learn. From tom at huno.net Fri Jun 28 15:52:13 2002 From: tom at huno.net (thomas) Date: Fri, 28 Jun 2002 21:52:13 +0200 Subject: generate all combinations of a list (with variable output length) Message-ID: <3D1CBE6D.30002@huno.net> hi, i'm looking for a way to generate all possible combinations of all items in a list. list = ["A","D","$","5","R"] but i also want it to use one item several times or not at all and in no particular order. the length of the string is 1-10. so a possible output would be: DD$ A5RD$D555 A 5RR$$A DRRR55$5$A ... i find it particualy difficult to tell python to use one item several times or not at all, and the variable length thing. i don't want to reinvent the wheel so someone probably has already a soultion for that :) and if not someone can probably push me in some direction. thx, thomas From garrett at bgb.cc Mon Jun 10 21:04:50 2002 From: garrett at bgb.cc (Don Garrett) Date: Tue, 11 Jun 2002 01:04:50 GMT Subject: if number is 1-2, 4 or 6-8 or 12-28, 30, 32... References: Message-ID: <3D054C64.50406@bgb.cc> Gustaf Liljegren wrote: > Cliff Wells wrote: > > Thanks both of you. I tried both solutions. Since some intervals are very > high (1000000+), it takes too long to add them to a list. Cliff's solution > was really fast, but it took a while to understand. :) > > Gustaf In all truth, I didn't pay attention to the subject line, and slightly misunderstood the question. I was thus considering it to be a mostly newbie question..... yes, his answer is much better for what you are doing. -- Don Garrett http://www.bgb.cc/garrett/ BGB Consulting garrett at bgb.cc From russblau at hotmail.com Fri Jun 28 15:00:43 2002 From: russblau at hotmail.com (Russell Blau) Date: Fri, 28 Jun 2002 15:00:43 -0400 Subject: testing type of an object References: Message-ID: "Rajarshi Guha" wrote in message news:pan.2002.06.28.14.49.33.858327.1787 at presidency.com... > Hi, > I'm writing some code that depends on the type of an argument > passed to it. > > Is there a standard trick to do this? My versions don't seem to work: > > if type(s) == 'str': > do something > > or > > if string.find(type(s), 'str') != -1: > do something > > dont seem to work They don't work because the type() function returns a type _object_, not a string containing the type name. You can use if type(s) == type('abc'): do something or, even better, import the types module (which you can look up in the docs). -- I don't actually have a hotmail account; but I do have one on excite.com if you really want to get in touch with me. From fredrik at pythonware.com Sat Jun 29 08:32:02 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 29 Jun 2002 12:32:02 GMT Subject: question od default args References: Message-ID: <6NhT8.45584$n4.10824585@newsc.telia.net> Mark Jackson wrote: > More quickly: > > def myfunc(arg=[]): > if arg is myfunc.func_defaults[0]: > print "no argument" > else: > ... while the func_ attributes are documented, a quick peek in the standard library should tell you that it's best to treat them as an implementation detail. the less such stuff you depend on in your production code, the more portable it gets... From a.schmolck at gmx.net Fri Jun 21 13:21:03 2002 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 21 Jun 2002 18:21:03 +0100 Subject: What language - platform use to data acquisiton/numerical work? References: <1c849ea9.0206130130.6cdaa36f@posting.google.com> <1c849ea9.0206210457.36d494db@posting.google.com> Message-ID: mdtorre at freemail.it (Matteo) writes: > Thank you all for the contributions. > > I have understood that Python is good for GUIs, for serial port data > acquisition and for numercal computation. > > My only problem is that MatLab has some huge numerical libraries that > Phyton does not have. I have to do experiments with pattern recognitin > algoritmhs (pca, neural networks etc.) and these are already > efficently coded in MatLab. I can't afford the effort to code a radial > basis function network from scratch (I'm able to do it, but it's > tiring and very time consuming). > So I'd like to use pyhon for all except numerical computation. I've > seen Pymat to conetct MatLab to Python, but it seem a little outdated > and unsupported. Is there any other way to embed MatLab into Python? > I've hacked up a module based on pymat, so that you now can use matlab pretty much like it were just some python library. Examples: >>> mlab.plot([1,2,3]) [plots a line] or >>> mlab.sort([[3.,2.,1.]]) array([ [ 1., 2., 3.]]) You can even do things like >>> help(mlab.sort) [prints the docu of sort] and pickle objects in matlab. Speaking of objects, unlike pymat you can not only work with arrays and strings but also with other types of matlab objects. I have been using it for my work for some time, but I haven't yet got around to release it (as open source). If you are interested I could send you the code, but you'll need python2.2.1 and it might still have rough edges. > Thank you in advance, > > Matteo Della Torre alex From bokr at oz.net Thu Jun 27 12:36:23 2002 From: bokr at oz.net (Bengt Richter) Date: 27 Jun 2002 16:36:23 GMT Subject: Most efficient way to write data out to a text file? References: <3d1a6993.248534625@netnews.attbi.com> <3D1A8CD9.C8B8EC28@engcorp.com> <3d1b1bd7.294171125@netnews.attbi.com> Message-ID: On Thu, 27 Jun 2002 14:09:09 GMT, candiazoo at attbi.com wrote: >I am a newbie... this is my first Python "project" so I am probably writing >horribly inefficient code... I have never used the profiler but I'll try it! > >I am not opening/closing the file each time. I am extracting 700000 rows from a >mysql database, extracting additional data from our primary, Oracle database per Are you by chance opening and closing your mysql connection for each row? Easy to do if you just wrote a quick get-me-one-row wrapper function and forgot to revise it. >row, then stuffing each piece of data into a class which preformats the data (I >need to output the data into a fixed format string/record for another >application which reads them) and returns a single string... which I write out >to the file. > If it's working, probably the best thing is to measure actual timing before optimizing. Regards, Bengt Richter From ark at research.att.com Fri Jun 7 13:56:47 2002 From: ark at research.att.com (Andrew Koenig) Date: Fri, 7 Jun 2002 13:56:47 -0400 (EDT) Subject: Python 2.2.1 vs. gcc 3.1? In-Reply-To: <15616.62131.521803.383860@12-248-41-177.client.attbi.com> (message from Skip Montanaro on Fri, 7 Jun 2002 12:51:47 -0500) References: <15616.57963.519636.730290@12-248-41-177.client.attbi.com> <200206071649.g57GnmC00708@europa.research.att.com> <15616.62131.521803.383860@12-248-41-177.client.attbi.com> Message-ID: <200206071756.g57HulT01147@europa.research.att.com> Andrew> That could be it, but I have been setting LD_RUN_PATH explicitly Andrew> when building Python, so I don't understand why it would have Andrew> changed. Skip> It's been ages since I used a Solaris system, but shouldn't that be Skip> LD_LIBRARY_PATH? Perhaps there is no ldconfig command (anymore) on Solaris. No -- LD_LIBRARY_PATH tells the runtime system which libraries to use for this particular execution; LD_RUN_PATH tells the linker to generate .so files that use particular libraries whenever they are run, regardless of the value of LD_LIBRARY_PATH. I want to build python in such a way that its users do not have to set LD_LIBRARY_PATH in order for it to work; setting LD_RUN_PATH does just that. Or at least it did until I installed gcc 3.1 :-( From markus.vonehr at ipm.fhg.de Mon Jun 17 05:40:26 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Mon, 17 Jun 2002 11:40:26 +0200 Subject: bug in Tkinter? Message-ID: <3D0DAE8A.E7637F07@ipm.fhg.de> Hi everybody, I am marking a region in a photo (photoimage in canvas) with a rectangle: self.canvas.create_rectangle(..., outline="white") Then I bind the functions to mouse events: self.canvas.bind("",self.Down) self.canvas.bind("",self.Drag) self.canvas.bind("",self.Release) and I change the coordinates using: def Drag(self, ev): self.canvas.coords(item, ...new_coords...) there still remain wrong white pixels over my photo, this seems to happen only in the lower left corner. How can I eliminate them??? Thanks for any comments, Markus -------------- next part -------------- A non-text attachment was scrubbed... Name: markus.vonehr.vcf Type: text/x-vcard Size: 245 bytes Desc: Visitenkarte f?r Markus von Ehr URL: From fperez528 at yahoo.com Thu Jun 20 12:29:30 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Thu, 20 Jun 2002 10:29:30 -0600 Subject: changing the viewing area with gnuplot in python References: <3D1200B6.639CEBE5@lanl.gov> Message-ID: Nathan Given wrote: > right now gnuplot auto scales everything (I don't have control over the > viewing area)... > > > How do I change it? (I want to view from -4 to 2 on the x axis, and 0 > to 10 on the y axis.... right now gnuplot automatically chooses -4 as > xmin, 2 as xmax, 4 as ymin, and 10 as ymax) Assuming 'g' is your gnuplot instance: g('set xrange [-4:2]') g('set yrange [0:10]') Open a gnuplot session in a separate terminal and use its builtin help. Once you figure out which commands you need interactively, you can just pass them to the python-controlled gnuplot by calling it as a function with the command you want in a string. cheers, f. From dfackrell at DELETETHIS.linuxmail.org Thu Jun 13 13:07:03 2002 From: dfackrell at DELETETHIS.linuxmail.org (Daniel Fackrell) Date: Thu, 13 Jun 2002 11:07:03 -0600 Subject: why not "'in' in 'in'"? References: Message-ID: <3d08d139$1_2@hpb10302.boi.hp.com> When all else fails, lets try throwing in some newbie exploration: Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> print type("a") >>> print type("ab") >>> print type([1]) >>> print type([1,2]) >>> print type(1) >>> if "a" in "ab": print "yes" else: print "no" yes >>> if [1] in [1, 2]: print "yes" else: print "no" no >>> if 1 in [1, 2]: print "yes" else: print "no" yes >>> I can see the rationale here, as there isn't really a "character" type in Python. So what the "in" operator does in the case of a string as the second operand is check the first operand to see if it can be interpreted as a element of a string, which would be a character. It does in fact appear to be inconsistent, but I'll have to leave it up to people who know more about what they are doing than myself to figure out what to do about it, if anything. I'm not sure that the ideas that come to mind (creating an actual "character" type or modifying the behavior as proposed since we really have an exception here already) are any good. -- Daniel Fackrell (dfackrell at linuxmail.org) When we attempt the impossible, we can experience true growth. "Grant Griffin" wrote in message news:aeadtt06rq at drn.newsguy.com... > That's not a bad suggestion, Mark, but if I did that I guess I would be forever > wondering if I was testing whether the first one was in the second or the second > one was in the first. Again, it doesn't read nearly as well as: > > if x in subject: > ... > > which leaves no doubt. > > Ironically, that's already perfectly legal--so long as x has no more than one > character: > > >>> subject = "i like spam, i do." > >>> x = "s" > >>> y = "h" > >>> if x in subject: > ... print "x is in subject and x has no more than one character" > ... > x is in subject and x has no more than one character > >>> if y in subject: > ... print "same goes for y" > ... else: > ... print "can't say the same for y" > ... > can't say the same for y > >>> > > reluctant-to-discard-my-hard-won-near-mastery-of-"find"-ly y'rs, From peter at engcorp.com Mon Jun 10 12:52:00 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 10 Jun 2002 12:52:00 -0400 Subject: Is python suitable for embedded programming? References: Message-ID: <3D04D930.DFC50E26@engcorp.com> Dennis Nash wrote: > > I am considering using Python to control embedded hardware, and would > like to know whether other people have done this, what their experiences > were, and whether they recommend it. We've been doing similar things for the last two and half years with a great deal of success. We use serial ports, CAN interfaces (connected via USB), and GPIB interfaces to control various RF equipment and embedded systems. > The system in question is in three parts: Industrial hardware talks to a > control system (a Linux or Windows2000 box). The control system outputs > the data from the hardware onto a web server. A 3rd computer contains a > web browser which will interact with the web server, allowing an operator > to view what's happening with the hardware and change parameters. > > I am thinking of using Python for the middle part, i.e. the control > system which polls the hardware continually to get its state, and updates > the web pages accordingly. > > Some specific questions: > > * how good is serial port access in Python? It was poor when we started, but we hacked together our own wrapper on win32comm (at the time), then win32file in the more recent Windows extensions to Python. There are now at least two, maybe three released serial port packages for Python, running on Linux and Windows. (When we get a chance, we're going to either integrate their best bits into ours and release it, or vice versa.) A quick google search would turn up the various options. > * the program will be running forever, in a big loop. Is it liable to > gradually use all the memory up and then fall over? No, never in my experience. We have applications running for months. Python is an excellent choice for long-running applications. > * output to web pages: how good is Python Server Pages? is this the best > way to do it? "Best" is entirely dependent on your own needs of course, not all of which you've presented. :) You might, for example, output the data as simple XML and just dump it into folders somewhere with a web server in front serving them up. No need for any Python (or code) at that point, if you're willing to write a little XSLT. You could also use something like Zope and make the data available through that. Anything in between these two would work okay too, depending on what you really care about. -Peter From robin at jessikat.fsnet.co.uk Sun Jun 30 16:05:37 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sun, 30 Jun 2002 21:05:37 +0100 Subject: yield equivalent in C/JavaScript? In-Reply-To: <20020630180139.GA38821@hishome.net> References: <20020630180139.GA38821@hishome.net> Message-ID: In message <20020630180139.GA38821 at hishome.net>, Oren Tirosh writes very smart! That Duff did it Fortran as I recall. >On Sat, Jun 29, 2002 at 07:12:46PM +0100, Robin Becker wrote: >> Is there any way to do yielding easily in C? I have a bunch of programs >> which are normally connected together using unix pipes. I would like to >> merge them and the problem is then how to get them to communicate nicely >> using a single process. > >It's possible to implement this in C using Duff's Device: > >#define BEGIN_GENERATOR static int _GenState=0; \ > switch(_GenState) { \ > case 0: > >#define END_GENERATOR } \ > _GenState = 0; > >#define YIELD(x) _GenState=__line__; return (x); case __line__: > > >int generator(arguments) { > > static int foo, bar, etc; /* Make all variables static */ > > BEGIN_GENERATOR > for(...) { > if(...) { > ... > YIELD(x) > ... > } else { > ... > } > ... > YIELD(y) > ... > } > END_GENERATOR >} > >If you want this to be reentrant use a struct passed as an argument >to the function instead of static variables. > > Oren > > -- Robin Becker From peter at engcorp.com Mon Jun 17 20:33:04 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 17 Jun 2002 20:33:04 -0400 Subject: a question on SOAP References: Message-ID: <3D0E7FC0.8C35FCF8@engcorp.com> Rajarshi Guha wrote: > > Hi, > I'm, using SOAP.py (0.9.7) and Python 2.2. I have a small python script > acting as a 'server' and another script calls functions on the server. > Currently both client and server are on the same machine. However when > the client calls the server I get the following errors: > ' > Traceback (most recent call last): [...] > File "/usr/local//lib/python2.2/httplib.py", line 379, in connect > raise socket.error, msg > socket.error: (111, 'Connection refused') > > My firewall is off, nmap shows that the port 8080 is open, so why would > the server be refusing connections? Presumably you've already checked the basic things like that your code is really connecting on port 8080 and not the standard http port? Have you also tried connecting manually with telnet? Something like "telnet localhost 8080" should work, and if you type "get / HTTP/1.0" and hit enter a couple of times you ought to get some reply if an HTTP server is listening. You don't give enough for anyone to do more than suggest that "you're right, it doesn't look like it's working". :-) -Peter From duncan at NOSPAMrcp.co.uk Wed Jun 12 06:09:38 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 12 Jun 2002 10:09:38 +0000 (UTC) Subject: Python Virtual File System: A spike test References: Message-ID: "Mike C. Fletcher" wrote in news:mailman.1023872902.2540.python-list at python.org: > An initial implementation (spike test) exploring the viability of the > approach. Implementation provides: > > equality testing > parent/child/ancestor/descendent retrieval/testing > filesystem-role testing (file/dir/root) > root retrieval and root comparisons > "walking" (callback-based recursive iteration) > listing (returning Paths which include their parent directory) > fragment determination (i.e. c:\\temp\\test -> "c:\\", "temp", > "test" recursive directory-tree removal (including files) > open( ) method for path specifiers > > The current implementation is a sub-class of str which provides a > number of new methods (and overrides some built-in methods) to provide > the above functionality. > My initial thoughts: What is your use-case for equality testing? Especially given that it is virtually impossible to implement this reliably. For example the normcase implementation in the standard library lowercases all pathnames under windows. While this is useful most of the time, not all filesystems are case insensitive, even on windows. Your class should support iterators: probably three flavours, one for contained files, one for contained directories and one for everything. The list, walk, and remove methods would probably then benefit from reusing the iterators. The FileSystemPath seems a bit windows oriented with drive() and unc() methods. The root method returns a drive such as 'c:'. This means that: >>> temp = filepath.path('c:\\temp') >>> temp FileSystemPath('c:\\temp') >>> temp.root() FileSystemPath('c:') >>> temp.root()+'fred' FileSystemPath('c:fred') I would have expected temp.root()+'fred' to give a reference to 'fred' in the root directory, not a relative reference. There seems to be a problem with the implementation of canonical() when working with some UNC pathnames (watch w2): >>> from filepath import path >>> w = path(r'\\osprey\work') >>> w1 = path(r'd:\work') >>> w2 = path('\\.\d:\work') >>> w==w1 0 >>> w1==w2 0 >>> w.root() FileSystemPath('\\\\osprey\\work') >>> w1.root() FileSystemPath('d:') >>> w2.root() FileSystemPath('d:') >>> w2.canonical() 'd:\\d:\\work' >>> w.canonical() '\\\\osprey\\work' I suspect however, this is a problem with the underlying os.path functions. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From marc at informatik.uni-bremen.de Sat Jun 15 09:39:11 2002 From: marc at informatik.uni-bremen.de (Marc Recht) Date: Sat, 15 Jun 2002 15:39:11 +0200 Subject: IDE recommendations?? References: Message-ID: > but this lacks some comfort. I would appreciate any recommendation for a > suitable IDE IMHO WingIDE is the best IDE around. From not.this at seebelow.org Thu Jun 13 18:34:22 2002 From: not.this at seebelow.org (Grant Griffin) Date: 13 Jun 2002 15:34:22 -0700 Subject: Type subclassing: bug or feature References: Message-ID: In article , aahz at pythoncraft.com says... > >Consider the following code: > >class MyStr(str): > def contains(self, value): > return self.find(value) >= 0 > >s = MyStr("hello, world!") >s = s.capitalize() >if s.contains('Hello'): > print "Found it!" > >It fails with an AttributeError when it calls s.contains(), because >s.capitalize() returned a str instead of a MyStr. Anyone want to take a >whack at defending this as the correct behavior? Sounds like a bug to me, but perhaps fixing it at some point was part of the plan from the beginning. Editorially speaking, although I hadn't thought of this problem specificially, I guess it might be another reason to use subclassing to augment behavior, not change it. I haven't figured out whether this sort of thing could happen with other, more usefully subclassed types like list and dict, but I guess it could occur whenever a built-in type returns its own (er, "parent") type. I bet somebody can think of an example. straight-man-ly y'rs, =g2 _________________________________________________________________________ Grant R. Griffin g2 at dspguru.com Publisher of dspGuru http://www.dspguru.com Iowegian International Corporation http://www.iowegian.com From pinard at iro.umontreal.ca Tue Jun 25 20:01:49 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 25 Jun 2002 20:01:49 -0400 Subject: RELEASED: Pymacs 0.17 Message-ID: Hi! A new release of Pymacs is available as: http://www.iro.umontreal.ca/~pinard/pymacs/Pymacs.tar.gz Pymacs allows Emacs users to extend Emacs using Python, where they might have traditionally used Emacs LISP. Pymacs runs on systems having sub-processes. The oldish `import pymacs; from pymacs import lisp' interface is gone. The usual interface is definitely `from Pymacs import lisp'. The `setup' script has been reduced even more, it now only takes care of installing the Emacs Lisp side of Pymacs. The Distutils `setup.py' script does the rest. So, the `-P', `-b', `-p' and `-x' options of `setup' are gone. Syver also gave me a few hints about how to modify `setup' for Win32 systems. Some tuning was needed for Python 2.2 hexadecimal escape sequences, which Emacs does not grok in some cases. This is the reason for this release. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From cben at tx.technion.ac.il Mon Jun 17 08:47:51 2002 From: cben at tx.technion.ac.il (Beni Cherniavksy) Date: Mon, 17 Jun 2002 15:47:51 +0300 Subject: '__builtin__' vs. __builtins__ Message-ID: Why is the '__builtin__' module available under the __builtins__ name? By what's the logic one is supposed to remember it? (If I do remember that it's different I would still confuse which is what...) -- Beni Cherniavsky From estama at dblab.ntua.gr Wed Jun 19 16:20:39 2002 From: estama at dblab.ntua.gr (Freeman Stopjohn) Date: 19 Jun 2002 13:20:39 -0700 Subject: Extending long Message-ID: <69310ed7.0206191220.3bbf68d8@posting.google.com> I'm trying to extend the long basic type with some bit manipulation methods (using Python 2.2). Below is the code fragment. ----- class bitnum(long): def getbit(self,bitn): if self & (1 << bitn) >0: return 1 else: return 0 def setbit(self,bitn): self=self ^ ( 1 << bitn ) ----- The getbit method works ok. The setbit doesn't (it doesn't change the number). What am i doing wrong? thanks. From geoff at elj.com Wed Jun 5 10:03:00 2002 From: geoff at elj.com (Geoff Eldridge) Date: 5 Jun 2002 07:03:00 -0700 Subject: new SmallEiffel elj-win32 release (-0.74) Message-ID: <8cd6cc47.0206050602.1d69a237@posting.google.com> A new version of elj-win32 has been prepared and is now available from .. * http://www.elj.com/elj-win32/ * http://www.elj.com/elj-win32/download/ It is based on .. * SmallEiffel -0.74 (07 May 2002) [1,2,3] * lcc-win32 v3.8 (02 Jun 2002) [4] * GOBO library [5] * GOBO's gexace [6] and geant [7] tools This version of SmallEiffel brings ace file support and agents (see small example below). This release of elj-win32 is that which is needed for the elj project .. * http://elj.sourceforge.net/ which provides interfaces to: * ewxw - a wxWindows interface .. * http://elj.sourceforge.net/projects/gui/ewxw/ * win32-api .. * http://elj.sourceforge.net/projects/os/win32api/ * databases: FireBird, mysql, Postgres, SleepyCat (ie Berkeley DB) ... * http://elj.sourceforge.net/projects/db/firebird/ * http://elj.sourceforge.net/projects/db/mysql/ * http://elj.sourceforge.net/projects/db/postgres/ * http://elj.sourceforge.net/projects/db/sleepycat/ * the Pervasive btrieve .. * http://elj.sourceforge.net/projects/db/btrieve/ We hope this distribution is useful to you. Any comments and suggestions appreciated. Geoff Eldridge -- geoff at elj.com -- http://elj.sourceforge.net/ References: [1] http://smalleiffel.loria.fr/ [2] http://smalleiffel.loria.fr/misc/HISTORY.html#-0.74 [3] http://groups.google.com/groups?selm=e416d3df.0205100712.18847189% 40posting.google.com [4] http://www.cs.virginia.edu/~lcc-win32/ [5] http://elj.sourceforge.net/projects/other/gobo/ [6] http://elj.sourceforge.net/phpwiki/index.php/GeXace [7] http://elj.sourceforge.net/phpwiki/index.php/GeAnt SmallEiffel Agent Example: --8<-- from a cle post by Greg Compestine -- Here's a simple program that takes an array of strings, converts all the strings to uppercase and then prints them out. class UPPER creation make feature make is local lines: ARRAY[STRING] do create lines.from_collection (<<"These ","are ","some strings.">>) lines.do_all (agent {STRING}.to_upper) lines.do_all (agent print) end end Compiled with SmallEiffel -0.74, the output is: c:\test\eiffel\agent\upper>compile upper c:\test\eiffel\agent\upper>upper THESE ARE SOME STRINGS. -->8-- From mkc+dated+1024627496.6928dd at mathdogs.com Wed Jun 5 22:49:09 2002 From: mkc+dated+1024627496.6928dd at mathdogs.com (Mike Coleman) Date: 05 Jun 2002 21:49:09 -0500 Subject: 64-bit Python? Message-ID: <87elfl3yvu.fsf@mathdogs.com> Has anyone looked at making Python 64-bit clean? I was looking at trying to use the new mmap module to map in a large (>2G) file, and the comments in the source note that the mmap regions are limited to int-size (31 bits), primarily because Python objects are also limited to this size. Does anyone know if there's an inherent reason why it would be impossible or difficult to make Python 64-bit clean (say as a compilation option)? Mike From dfaken at brandeis.edu Wed Jun 5 09:49:18 2002 From: dfaken at brandeis.edu (Daniel Faken) Date: 5 Jun 2002 06:49:18 -0700 Subject: Simple implementation of tail-call-elimination Message-ID: <541988bb.0206050549.48d5ee28@posting.google.com> Hello, Just thought I'd share this. For more info. about tail-call-elimination, continuations, etc. see the Scheme language or articles about functional programming in Python. Anyone have a suggestion for a better way to do this? (more efficient, elegant, etc..) This should be easy to implement in C, for speed. cheers, Daniel dfaken at brandeis.edu --------------- import types # Tail-Recursion-Elimination tools # # Usage: include a keyword parameter with initial value 'TRE' in the function(s) # from which you wish to eliminate tail-recursion - e.g. 'cont=TRE'. # Then, where you would normally use "return Fn(a,b,c..)", instead # call the keyword with the function and its arguments as parameters # - e.g. 'cont(Fn,a,b,c,...)' # This allows TRE to control the program flow, and eliminate deep recursion. # # Example: # def factorial(n,acc=1,cont=TRE): # if n <= 1: return acc # else: return cont(factorial,n-1,acc*n) # # N.B. this is not yet set up for use with functions # which accept keywords or return multiple values TRE_magic = "TRE magic string" def TREcont(fn, *rest): return (TRE_magic, fn, rest) def TRE(fn, *rest): x = fn(cont=TREcont, *rest) while isinstance(x, types.TupleType) and (x[0] is TRE_magic): x = x[1](*x[2]) return x From robin at jessikat.fsnet.co.uk Sun Jun 30 12:20:07 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sun, 30 Jun 2002 17:20:07 +0100 Subject: yield equivalent in C/JavaScript? References: <7xy9cxhlvx.fsf@ruckus.brouhaha.com> <7xit41i7i9.fsf@ruckus.brouhaha.com> <14ms5VAygsH9Eww2@jessikat.fsnet.co.uk> <7xelepnk84.fsf@ruckus.brouhaha.com> <5GFT8.369062$cQ3.24122@sccrnsc01> Message-ID: In article <5GFT8.369062$cQ3.24122 at sccrnsc01>, Emile van Sebille writes >Robin Becker >> The IE stuff seems to rely too much on the URL extension so provided >it >> thinks it's htm or html IE 5.x seems OK. >> > >Cool... last time I looked into this it didn't work on IE, and I found >this on msdn > >If the server-provided MIME type is either known or ambiguous, the >buffer is scanned in an attempt to verify or obtain a MIME type from the >actual content. > >... that I read to mean 'if you tell it, it will make its own check >anyway and ignore you' so I gave it up. > >Can you post an example url that causes IE to properly interpret >Content-Encoding: x-gzip? > >Thanks, > I'll try and do that tomorrow, due to the latest apache worm scare I'm rebuilding the reportlab.co.uk server at the moment. According to my latest info this won't work for IE 4/5 on Macs, but I may be mistaken on that. The URL that I tried looked something like http://www.reportlab.co.uk/cgi-bin/tgzenc.cgi?ttt.html ie it had an extension '.html' when I tried with the extension .html.gz IE only wanted to save the file. -- Robin Becker From cliechti at gmx.net Sat Jun 29 12:52:55 2002 From: cliechti at gmx.net (Chris Liechti) Date: 29 Jun 2002 18:52:55 +0200 Subject: exception handing References: Message-ID: Rhymes wrote in news:pan.2002.06.29.17.41.28.926443.440 at myself.com: ... >>>> ex1 = "spam" >>>> try: > ... raise ex1 > ... except ex1: > ... print 'got it' > ... > got it ... exceptions are instances of classes nowdays... don't use strings. and avoid troubles... >>> class Ex1(Exception): pass #inherit from the root of all exceptios ... >>> try: raise Ex1("hello") #raise instances ... except Ex1: print "got it" #catch by specifying classes ... got it >>> try: raise Ex1("hello") ... except Exception: print "got it" #baseclass works too ... got it as you can see, you have much finer control with classes than strings as exceptions. e.g. you can catch the baseclass etc... chris -- Chris From emile at fenx.com Wed Jun 5 09:50:28 2002 From: emile at fenx.com (Emile van Sebille) Date: Wed, 05 Jun 2002 13:50:28 GMT Subject: python cookbook at oreilly's web site References: Message-ID: F. GEIGER > Yes, and I'd really like to know the difference. > I guess we'll have to wait for the book. ;-) -- Emile van Sebille emile at fenx.com --------- From cliechti at gmx.net Wed Jun 12 18:24:05 2002 From: cliechti at gmx.net (Chris Liechti) Date: 13 Jun 2002 00:24:05 +0200 Subject: map -> class instance References: Message-ID: John Hunter wrote in news:m2r8jcp3pv.fsf at video.paradise.lost: > I want to convert dictionary instances to instances of a class that > has the keys of the map as attributes. I naively tried this: > > class Map2Class: > def __init__(self,m): self.__dict__['m'] = m > def __getattr__(self, key): > return self.m[key] > > def __setattr__(self, key, val): > self.m[key] = val > > def __delattr__(self, key): > if self.m.has_key(key): > del self.m[key] see above... you have to avoid __setattr__ for your attributes and __dict__ is found witouth calling __gettattr__ thus the above works. chris -- Chris From -$P-W$- at verence.demon.co.uk Wed Jun 26 05:49:11 2002 From: -$P-W$- at verence.demon.co.uk (Paul Wright) Date: 26 Jun 2002 10:49:11 +0100 Subject: Reminder of a python Project. References: <2218.941T781T12224051threeseas@earthlink.net> Message-ID: In article <2218.941T781T12224051threeseas at earthlink.net>, Timothy Rue wrote: >First off, it's ok that I got such a high level of resistance to my >initial posting here about this project. Thanks to some research that /. >had an article on, regarding the size of GPL project teams. > >But anyway.... Remember the autocoding project I mentioned? ______ / \ .' PLEASE `. | DO NOT | _____ | FEED THE | ,'.....`. `. TROLLS ,' ,'........ ) \_ _/ |........ ,' | | `. .... _/ | | ,'.,'-' | | /../ | | ,'.,' | | /../ . | | /..' .\_\| |/_/, ___ | | ___ . `--' . . . -- Paul Wright | http://pobox.com/~pw201 | From catunda at pobox.com Tue Jun 25 10:59:14 2002 From: catunda at pobox.com (Marco Catunda) Date: Tue, 25 Jun 2002 11:59:14 -0300 Subject: Thread Memory Leak References: <3D18745D.554A7C44@engcorp.com> Message-ID: Hummmm. The sounds like good. Perhaps, python 2.0 doesn't have this problem. I will test it in Python 2.0. I have RedHat 7.3, Python 2.2.1 -- Marco Catunda On Tue, 25 Jun 2002 10:47:09 -0300, Peter Hansen wrote: > Skip Montanaro wrote: > Actually, the list is rebound to a new empty list each pass through the > while loop... > > I can't duplicate the symptoms on my machine (RedHat 7.1, Python 2.0). > > -Peter From sameer_ at email.com Mon Jun 10 19:23:58 2002 From: sameer_ at email.com (sameer) Date: 10 Jun 2002 16:23:58 -0700 Subject: getting files from a windows network Message-ID: <6bd9f01b.0206101523.7af66fc8@posting.google.com> is there a way to read files in python that are found on a windows network, i.e. files that users choose to share on their computers on a windows network. thanks ahead for the info. From shagshag13 at yahoo.fr Wed Jun 5 04:58:48 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Wed, 5 Jun 2002 10:58:48 +0200 Subject: How could i get execution times ? Message-ID: I'm looking for a way to get execution time at different points of a program, by now i use the code below, but i've seen in some post that time.clock() could be a better way to measure this, So my question, is how you pythoners do it ??? and to understand _why_ ? Thanks s13. ------ import time class Chrono: def __init__(self): self._tags = [] self._time = [] self._t0 = time.time() def add(self, tag = ''): self._time.append(time.time()) self._tags.append(tag) def __str__(self): maxL = 0 for tag in self._tags: maxL = max(maxL, len(tag)) tp = self._t0 s = ' ' for i in range(maxL + 13): s += '-' for i in range(len(self._time)): s += "\n " + '[' for j in range(maxL - len(self._tags[i])): s += ' ' s += self._tags[i] s += '] : ' + time.strftime("%H:%M:%S", time.gmtime(self._time[i] - tp)) tp = self._time[i] s += "\n " + '[' for j in range(maxL): s += '=' try: s += '] : ' + time.strftime("%H:%M:%S", time.gmtime(self._time[-1] - self._t0)) except IndexError: pass return s From BPettersen at NAREX.com Tue Jun 11 12:27:48 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Tue, 11 Jun 2002 10:27:48 -0600 Subject: Changing the path on Win2k/XP Message-ID: <60FB8BB7F0EFC7409B75EEEC13E2019221519B@admin56.narex.com> > From: David LeBlanc [mailto:whisper at oz.net] > > > From: Bjorn Pettersen > > Subject: Changing the path on Win2k/XP > > > > Is there a way to change the path on Win2k/XP through Python? (I'm > > trying to write a .dll deployment script for our production > > department, and I'd like to give them a "one button" install...) > > > You should be able to modify the path on Win2k/XP by > modifying the associated registry key(s). There is one for > the "system" environment one for the "per user" environment. > This won't take effect for the current process though, but > only for new ones (at least comd.exe processes). > > Take a look in (changes depending on user logged in): > HKEY_CURRENT_USER\Environment > and: > HKEY_LOCAL_MACHINE\SYSTEM\Current Control Set\Control\Session > Manager\Environment > HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session > Manager\Environment > HKEY_LOCAL_MACHINE\SYSTEM\ControlSet002\Control\Session > Manager\Environment > > Of the 3 in HKLM\SYSTEM, I think only "Current Control Set" > is relevent. > > You can modify these with the _winreg package ("import > _winreg"). BE VERY CAUTIOUS! Incorrect modifications of your > registry can render your machine unusable and possibly > requiring an OS reinstall. There is a procedure for creating > a backup copy of your registry and a backup disk and I > suggest you do both until you are comfortable with what you're doing. Thanks! Hers's what I came up with (use at your own risk etc. etc.) -- bjorn import _winreg def setpath(entry): assert(type(entry) == unicode) assert(entry[-1] == u';') SYSTEM = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SYSTEM') CurrentControlSet = _winreg.OpenKey(SYSTEM, 'CurrentControlSet') Control = _winreg.OpenKey(CurrentControlSet, 'Control') SessionManager = _winreg.OpenKey(Control, 'Session Manager') Environment = _winreg.OpenKey(SessionManager, 'Environment') EnvironmentWrite = _winreg.OpenKey(SessionManager, 'Environment', 0, _winreg.KEY_SET_VALUE) path, type = _winreg.QueryValueEx(Environment, 'Path') path = entry + path assert(len(path) < 2048) _winreg.SetValueEx(EnvironmentWrite, 'Path', 0, _winreg.REG_EXPAND_SZ, path) _winreg.CloseKey(EnvironmentWrite) _winreg.CloseKey(Environment) _winreg.CloseKey(SessionManager) _winreg.CloseKey(Control) _winreg.CloseKey(CurrentControlSet) _winreg.CloseKey(SYSTEM) From greg at cosc.canterbury.ac.nz Thu Jun 6 23:42:48 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 07 Jun 2002 15:42:48 +1200 Subject: ANN: Pyrex 0.3 -- Extension Types Message-ID: Pyrex 0.3 is now available: http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ Major new feature: EXTENSION TYPES You can now define new built-in types in Pyrex, and use them to wrap arbitrary C data structures. See the Language Overview for details. For an example, see Demos/spam.pyx in the distribution. What is Pyrex? -------------- Pyrex is a new language for writing Python extension modules. It lets you freely mix operations on Python and C data, with all Python reference counting and error checking handled automatically. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From rotundo52 at hotmail.com Wed Jun 12 01:18:57 2002 From: rotundo52 at hotmail.com (Jon J. Morin) Date: Wed, 12 Jun 2002 05:18:57 GMT Subject: newbie: copying dictionaries References: Message-ID: <5RAN8.8438$nn1.3203473@news1.news.adelphia.net> Jon J. Morin wrote: > Hi. I'm a newbie to python and have a question about copying dictionary > objects. I'm working out of Learning Python by Mark Lutz & David Ascher > (O'Reilly). The following bit of code was an exercise in the book and it > works, but what I'm asking is why? I see where the dictionary keys get > copied from one object to the other, but how do the values get copied over > as well? > > #!/usr/bin/python > # copyDict.py - copy a dictionary argument and return it > > def copyDict(aDict): > newDict = {} > for key in aDict.keys(): > newDict[key] = aDict[key] > return newDict > > D = {'jon':1, 'allison':2, 'zachary':3} > print copyDict(D) > > Output: > [jmorin at cisx1 python]$ ./copyDict.py > {'zachary': 3, 'jon': 1, 'allison': 2} > > Any help with this is appreciated. Thanks. > > Jon J. Morin Thanks, guys. I think that I understand this now. Thanks for the help. Jon From kurlberg at math.chalmers.se Sun Jun 23 16:19:51 2002 From: kurlberg at math.chalmers.se (=?iso-8859-1?q?P=E4r?= Kurlberg) Date: 23 Jun 2002 22:19:51 +0200 Subject: Python hits the spot References: Message-ID: > It's no wonder that 1000 lines of uncommented code behave like that, taking > into account that you were trying to integrate several (Tcl/Tk, Fortran, C, > Python) systems in a hurry, and, I presume, not knowing most of them. Funny you should mention this. On my laptop (IBM Thinkpad with 128 megs of ram) the following two-liner gets me a lockup (i.e. keyboard and mouse completely unresponsive, powertoggle needed): for i in range(50*1000*1000): pass (I am serious.) Happened some time ago, but I never got around to filing a bug report (this thread was a good reminder.) Seems like the python code exercises the linux VM/swap to the breaking point. It is rather annoying that a user space program can do this... Can someone else reproduce this behaviour? (Make sure to quit all important applications before you try!) Some trivia: Python 2.2.1 (#1, Jun 12 2002, 17:57:17) [GCC 2.96 20000731 (Mandrake Linux 8.1 2.96-0.62mdk)] on linux2 From neal at metaslash.com Tue Jun 4 18:26:14 2002 From: neal at metaslash.com (Neal Norwitz) Date: Tue, 04 Jun 2002 22:26:14 GMT Subject: Fatal Python error: GC object already in linked list References: Message-ID: On Tue, 04 Jun 2002 00:05:00 -0400, Amit Mongia wrote: > Hi, > I am running a program using pycurl, to upload files on a server. I > am using Python 2.2.1. I am using threads and lists in my program. the > application just keeps waiting for new files to arrive and uploads them. > There are times my program errors out and crashes with this error > message. > > Fatal Python error: GC object already in linked list > > I am not using the Garbage Collector anywhere in my program. Any idea > what can cause this error? Any solutions. I desperately need one. There > is nothing given anywhere in any of the books. I am not even sure if its > an error with the Garbage Collector. Any comments? The problem is within the interpreter and could be a bug in Python or within curl (or any other module). Have you talked to the curl people? What version of curl are you using? If you believe this is a bug in Python, post a bug in SF: https://sourceforge.net/tracker/?func=add&group_id=5470&atid=105470 Neal From fperez528 at yahoo.com Wed Jun 19 18:44:34 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Wed, 19 Jun 2002 16:44:34 -0600 Subject: GOTO w/ Python? References: <3d10ed95@xpl-sdf1-sec1.> Message-ID: Fredrik Lundh wrote: > > you can find more Python tutorials here: > > http://www.python.org/doc/Newbies.html > I've always been curious. Why isn't the standard tutorial linked to here? It seems like the obvious first link to have, no? Cheers, f From bernie at 3captus.com Tue Jun 11 12:38:55 2002 From: bernie at 3captus.com (Bernard Yue) Date: Tue, 11 Jun 2002 10:38:55 -0600 Subject: getopt References: <3D061A9F.7CDC7132@3captus.com> <15622.9979.675543.351236@12-248-41-177.client.attbi.com> Message-ID: <3D06279E.2452DA86@3captus.com> Skip Montanaro wrote: > > Bernard> I was expecting an exception from the following getopt.getopt() > Bernard> called, but didn't. Is it normal? > > Yes. There's nothing invalid about "-d" as an argument to the "-c" flag, so > getopt gobbles it up. > Fair enough. Thx. > -- > Skip Montanaro (skip at pobox.com - http://www.mojam.com/) > Boycott Netflix - they spam - http://www.musi-cal.com/~skip/netflix.html Bernie From scholeyd at logica.com Tue Jun 18 03:56:14 2002 From: scholeyd at logica.com (Dan Scholey) Date: Tue, 18 Jun 2002 08:56:14 +0100 Subject: Newbie - Process Management Message-ID: <1024387201.371093@ernani.logica.co.uk> Hi, I am hoping you can help me, I am fairly new to python (and Unix) but am trying to solve the following problem... I want to be able to check if a parent process has died. At the moment I can check that a child process has died using... status = (os.waitpid(child, os.WNOHANG))[0] if status!=0: I've looked at several manuals and can't find a similar function for parent processes. Obviously I know both the parent and child process id ( get_pid() / get_ppid() ). I have a workaround of.... ps_line=string.split(commands.getoutput("ps -lp %s"%my_pid),"\012") if string.atoi(string.split(ps_line[1])[4])!=daddy: ... but I would rather not use ps. Any ideas? Cheers Dan From fperez528 at yahoo.com Fri Jun 28 15:52:36 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Fri, 28 Jun 2002 13:52:36 -0600 Subject: C API for Python's RNG? References: <3D1CBB3A.E1C43D8A@astro.cornell.edu> <3D1CBBED.58EAC61E@astro.cornell.edu> Message-ID: Tom Loredo wrote: > So I guess it's Numeric or some third-party RNG if > I want to do this quickly. Any suggestions? The Numeric RNG is reasonably fast and versatile. Otherwise just code your own from one of the bazillion RNGs out there. Something that simple can be wrapped up in a minute using weave or even SWIG. cheers, f From amuys at shortech.com.au Mon Jun 24 00:25:52 2002 From: amuys at shortech.com.au (Andrae Muys) Date: 23 Jun 2002 21:25:52 -0700 Subject: Iterating through two lists References: <7934d084.0206031700.377c691e@posting.google.com> Message-ID: <7934d084.0206232025.3d7d9ce5@posting.google.com> Curtis Taylor wrote in message news:... > In article <7934d084.0206031700.377c691e at posting.google.com>, > amuys at shortech.com.au (Andrae Muys) wrote: > > > "Denis S. Otkidach" wrote in message > > news:... > > > On Fri, 24 May 2002, jb wrote: > > > > > > j> I have two lists, x and y with the property len(x) = len(y). > > > j> > > > j> I should like to achive this (x is a list of class instances) > > > j> > > > j> for (a,b) in (x,y): a.f(b) > > > j> > > > j> Is there a fancy way of doing this or have I to introduce an > > > j> auxillary > > > j> counter (that is very easy but maybe not very "lispy", that > > > j> is > > > j> "python-like"). > > > > > > If lists are not very lange try this: > > > > > > for a, b in zip(x, y): a.f(b) > > > > If the lists are large then you probably need something along the lines of > > xzip. > > > > def xzip(*args): > > iters = [iter(a) for a in args] > > while 1: > > yield tuple([i.next() for i in iters]) > > > > Andrae Muys > > > Hi Andrae, > > I've got a similar situation I'm dealing with, in that I have 2 lists of > dictionaries, each of which is of equal length. What's different > however, is that I need to do an equality check for the values of 2 of > the keys (both of which exist in each dictionary), then set the value of > the 2nd dictionary's key to the value of that of the first's, e.g.: > > if dict2[key1] == dict1[key1]: > dict2[key2] = dict1[key2] > > I'm concerned with overhead, as the 2 lists could potentially be very > large. Can your xzip function be extended to do such a thing? > 1. I don't understand where you're getting key1 or key2 from? 2. xzip() is reasonably well defined semantically, so I doubt you really want to extend it, rather I suggest you consider a custom generator (or 2). 3. I suspect you should probably read the section on iterators and generators in the What's New in Python 2.1 bulletin. 4. One useful thing to note is that you can always collapse a generator/iterator into a tuple/list by using the tuple()/list() builtin functions. Andrae From whisper at oz.net Thu Jun 6 15:40:05 2002 From: whisper at oz.net (David LeBlanc) Date: Thu, 6 Jun 2002 12:40:05 -0700 Subject: Using AT on XP to run python script - MARK HAMMOND PLEASE READ In-Reply-To: Message-ID: I did my tests on Win 2000 pro - what OS are you using? When it comes to using sockets etc. you might be right that some permissions are involved. Would be interesting to know what user account 'at' runs under. Since this isn't strictly a Python issue, maybe comp.os.windows (or something like that) might better be able to answer the question. You might also check the discussion boards on http://www.codeguru.com/index.shtml or http://www.codeproject.com/ If you discover the answer I would be interested in knowing too! Regards, David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Chris > Sent: Thursday, June 06, 2002 12:07 > To: python-list at python.org > Subject: Re: Using AT on XP to run python script - MARK HAMMOND PLEASE > READ > > > Interesting findings. I know mine didn't work bcs the script I want > AT to execute sends me an email. The script sends an email, then I > want it to run another AT command to set itself up to run again at a > later time. But I can't get it to work. If I run the script > manually, it runs, sends email and executes the proper AT command. > But when AT fires off the task the script set up, nothing happens and > no more AT commands are set up. > > "David LeBlanc" wrote in message > news:... > > This is most curious, but I believe the commands _are_ getting executed! > > > > I tried the following (assume time is 16:30) "at 16:32 pythonw > > j:\python22\tools\idle\idle.py" (without the qoutes of course). At the > > appointed time, there was disk activity, but no idle window > popped up (idle > > was chosen just to get something to pop up!). However, there > _was_ a pythonw > > process running in the task manager! I think there might be a > way to attach > > a console or get access to the GUI, but i'm not sure - maybe > Mark Hammond > > might have a clue (he being the Python Win guru :) ). > > > > I tried the following: > > #at_test.py > > import sys > > import time > > > > tst = open("testfile.txt", 'a+') > > > > tst.write(time.asctime() + "\n") > > > > tst.close() > > > > put into an 'at' job as: at xx:xx python j:\python22\at_test.py > > > > I expected the output from this to be in j:\python22, but to my > surprise, it > > was in c:\winnt\system32 where cmd.exe resides! testfile.txt > contained the > > exact time the 'at' job was set to run at too! > > > > I suspect your last example that produced no visible output did > in fact work > > :) > > > > In any case, it works - now if one could just get visible output! > > > > David LeBlanc > > Seattle, WA USA > > > > > -----Original Message----- > > > From: python-list-admin at python.org > > > [mailto:python-list-admin at python.org]On Behalf Of Chris Stromberger > > > Sent: Tuesday, June 04, 2002 17:35 > > > To: python-list at python.org > > > Subject: Using AT on XP to run python script > > > > > > > > > I'm having trouble getting AT on XP to run a python script for me. > > > Have tried: > > > > > > at xx:xx "c:\python21\python.exe c:\scripts\script.py" > > > at xx:xx "start c:\scripts\script.py" > > > at xx:xx "c:\scripts\script.py" > > > > > > and get "the system cannot find the file specified" for the first two. > > > The last version does nothing apparently--no error indication or > > > anything. > > > > > > I imagine it is related to user accounts and such. Anyone have any > > > pointers? > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > -- > http://mail.python.org/mailman/listinfo/python-list From ak at silmarill.org Sat Jun 1 12:25:51 2002 From: ak at silmarill.org (Andrei Kulakov) Date: Sat, 01 Jun 2002 16:25:51 GMT Subject: wxPython performance References: <3CF8E382.3A44F0DA@engcorp.com> Message-ID: In article <3CF8E382.3A44F0DA at engcorp.com>, Peter Hansen wrote: > Andrei Kulakov wrote: >> >> Hello, >> >> "hello world" type program from wxPython tutorial takes 6 >> seconds to start on my cel 366 128mb system (running Debian). Is >> this typical? Why is it so slow? I'm looking for a graphic >> toolkit that'd be fairly quick. I don't want to use Tk because of >> the looks. > > How fast do you need it to be? (That's a serious question. > Are you planning to open and close the application so frequently > that six seconds is unacceptable?) > For me it's not a big deal, but I plan to write apps for other people, and this 6 seconds just feels wrong. I guess it's more of a psychological thing than anything else.. Anyway, it's still not that big a deal, I was just hoping someone would say "of course, you have to use this flag or option: --start-in-one-second" or "pygtk will start in 2 sec". If everythign is this slow, I'll just use wxPython and won't mind it too much :-). > > On my blazing 233 MHz Windows 98 machine, with Python 2.2.1 > and WxPython 2.3.2.1, a hello world program I just wrote > runs in about two seconds, for what it's worth. > > -Peter Odd.. if not too much trouble, could you please try this one (from wxpython tutorial)? from wxPython.wx import * class MyApp(wxApp): def OnInit(self): frame = wxFrame(NULL, -1, "Hello from wxPython") frame.Show(true) self.SetTopWindow(frame) return true app = MyApp(0) app.MainLoop() -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From aoeu at go.com Wed Jun 19 20:15:19 2002 From: aoeu at go.com (Thinkit) Date: 19 Jun 2002 17:15:19 -0700 Subject: Unicode hexadecimal characters Message-ID: <3eeda89d.0206191615.71b0629d@posting.google.com> It's a bit OT but does Unicode support the digits ten through fifteen (for hexadecimal)? From maxm at mxm.dk Mon Jun 17 13:52:15 2002 From: maxm at mxm.dk (Max M) Date: Mon, 17 Jun 2002 19:52:15 +0200 Subject: Long pathes on windows References: Message-ID: <3D0E21CF.7010405@mxm.dk> Roman Yakovenko wrote: > Good evening. I have big problem Windows 2000 and small one. > The small one is long pathes on windwos. How can I convert long path with ' ' > into short path? come agan? Max M From johnroth at ameritech.net Sat Jun 29 18:35:37 2002 From: johnroth at ameritech.net (John Roth) Date: Sat, 29 Jun 2002 18:35:37 -0400 Subject: private References: <3D1DE132.4A890D9D@engcorp.com> Message-ID: "Dave Reed" wrote in message news:mailman.1025382159.23425.python-list at python.org... > > From: Peter Hansen > > X-Accept-Language: en > > Newsgroups: comp.lang.python > > Xref: news.baymountain.net comp.lang.python:170296 > > Sender: python-list-admin at python.org > > Date: Sat, 29 Jun 2002 12:32:50 -0400 > > > > Rhymes wrote: > > > > > > Is there any possibility to build up a _real_ private attribute? > > > > Please define what "_real_" means to you. It's not apparent. > > > > > Such as C++ private data members... > > > > You realize that it's quite possible to get at private data members > > in C++, don't you? > > Kind of off-topic, but this got me curious. The only way I could think > of is to assume (which I think is always true) that the private data > members are in order from the starting address so based on the offset > from the address of the object you could access each one. > > Is there another way? I believe he's talking about the preprocessor macro trick of redefining the word 'private' as 'public.' John Roth > > Dave > > From peter at engcorp.com Sat Jun 8 09:43:37 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 08 Jun 2002 09:43:37 -0400 Subject: Medium to Large Scale Python Deployments References: <38C31EBA-79A4-11D6-9A7D-003065B33450@intersight.com> <3D003EC7.C72D27BE@engcorp.com> <3D006320.5040805@web.de> <3D00A209.EC24F671@engcorp.com> <3D0140BF.A239E39E@engcorp.com> Message-ID: <3D020A09.7BF6F985@engcorp.com> Nicola Larosa wrote: > > > (we rarely use doc strings, having avoided that aspect of > > Python when writing on an embedded system where all the .pyc > > files were stored in our limited 1MB of flash along with the > > interpreter...). > > python -OO ? I don't recall whether we actually didn't know about that at the time (I think that was it), or were not willing to accept the /other/ changes -OO made to the output. -Peter From djc at object-craft.com.au Sun Jun 23 06:11:07 2002 From: djc at object-craft.com.au (Dave Cole) Date: 23 Jun 2002 20:11:07 +1000 Subject: Web templating/db tool with best designer/coder separation? References: <3D159696.9010209@mxm.dk> Message-ID: >>>>> "Max" == Max M writes: Max> Jon Ribbens wrote: >> In article , Bengt Richter wrote: Take >> a look at http://jonpy.sourceforge.net/ . It almost completely >> separates code and HTML so that the designer and the coder do not >> interfere with each other. Max> I do understand that argument, but I almost certainly don't agree Max> that it is of much use. I agree, I am not sure it is such a good argument myself. If you are working in an environment where HTML editors do not understand the templating system then you are going to need at least one person who can post process the HTML and integrate it with the templating logic. No magic templating system is going to solve that problem. Max> In smaller one-of systems it makes sense, but in an app-server Max> like Zope where the idea is that different components can be Max> joined together to create a bigger application, there has to be Max> stronger rules for layout and design of the components so that Max> they will automatically fit into the bigger whole. Whenever you have a medium to large size system you need to establish rules to ensure that components fit together. Zope is certainly not unique in this regard. Max> Page template languages is the wrong approach in this regards. Are you able to explain why? Max> The development of the Cmf and Plone are good examples of this Max> wrongfull approach. They make it easy to create one single type Max> of application, but makes it very hard to re-use their components Max> to build other types of applications. Whenever you build any toolkit you have to decide on the set of problems that you wish to solve with the toolkit. The smaller the problem domain the more useful you can make the toolkit. If your problem falls within the domain of the toolkit then you will like the toolkit. If your problem is not addressed by the toolkit then you are likely to question the usefulness of the approach. Max> And I believe that the reason is that they are using pagetemplate Max> languages to bind it together, which leads to this kind of Max> design. I suggest that the problem that they are trying to solve has lead to the implementation. I could be misunderstanding you, but could you explain an alternative approach to solving the problem which would deliver a more general solution? Max> I my experience, tools which separates logic from view in the Max> "pagetemplate" approach is doing it wrong. Again, can you explain why? Max> The layout may be separated, but reuse of code/componentes Max> greatly suffers from this approach. Not sure I agree here. Maybe I am missing something because I think that a clear separation of presentation and implementation increases the cohesiveness of code and reduces the incidence of pathological coupling. - Dave -- http://www.object-craft.com.au From guy at lightwork.co.uk Thu Jun 27 09:57:29 2002 From: guy at lightwork.co.uk (Guy) Date: 27 Jun 2002 06:57:29 -0700 Subject: Var substitution Message-ID: Hi What i'm wanting to know, is there any way of looking at a variables value rather than its name. Example Unix : ${MyVar} Dos : %MyVar% Both of the above will be subtituted with the values. Example python script (below causes error): >>> guy="name" >>> import os >>> os.guy This is what should happen : >>> import os >>> os.name 'nt' From mcfletch at rogers.com Sun Jun 16 15:16:17 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sun, 16 Jun 2002 15:16:17 -0400 Subject: [Extending] Py_BuildValue( "((OiiO))",...) creates empty string? References: <3D0CDEEB.2070208@rogers.com> Message-ID: <3D0CE401.8030605@rogers.com> Argh. Sorry about that, was operator error (the test was wrong, not the C code it was testing). I was receiving the test value and forgetting to store it before checking it. Sorry for the wasted bandwidth, Mike Mike C. Fletcher wrote: > I'm working on a C module, and have come across something I don't > understand. Basically, I have a method definition/specification which > says I will pass my clients a 4-item tuple to their append method. From bokr at oz.net Thu Jun 27 10:44:21 2002 From: bokr at oz.net (Bengt Richter) Date: 27 Jun 2002 14:44:21 GMT Subject: Most efficient way to write data out to a text file? References: <3d1a6993.248534625@netnews.attbi.com> Message-ID: On Thu, 27 Jun 2002 15:16:46 +0300, Christos "TZOTZIOY" Georgiou wrote: >On 27 Jun 2002 02:01:35 GMT, rumours say that bokr at oz.net (Bengt >Richter) might have written: > >>Try accumulating your chunks in a list, >>like sl=[] followed by sl.append('chunk') instead, and then do f.write(''.join(sl)) >>instead of the f.write(s) you would have done. > >A minor correction, if I may add: > >f.writelines(sl) >might be quite more efficient than >f.write(''.join(sl)) > >AFAIK the output is the same, as long as one remembers to insert the >necessary '\n' for line breaks where needed :) Thank you for pointing that out. (That should teach me to throw phrases around like "typical newbie performance killer." ;-) I have not been in the habit of using writelines, and did not remember that since readlines preserves newlines, writelines would presumably, for symmetry, not add them. I expect to be using writelines more in the future ;-) Regards, Bengt Richter From BPettersen at NAREX.com Tue Jun 25 13:39:34 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Tue, 25 Jun 2002 11:39:34 -0600 Subject: How do i COPY files from 1 directory to another.. Message-ID: <60FB8BB7F0EFC7409B75EEEC13E201922151AD@admin56.narex.com> > From: Dirgesh Patel [mailto:Kemp100 at attbi.com] > > How do i Copy multiple files from 1 directory to > another..this is the code I have so far..but it gives me a > PERMISSION DENIED ERROR.. > > > import shutil > import os > > shutil.copy2(r"C:\test",r"C:\test1") > > I wanna copy everythign from C:\test to C:\test1.... I'm guessing you really want shutil.copytree()? -- bjorn From cliechti at gmx.net Sun Jun 23 15:17:39 2002 From: cliechti at gmx.net (Chris Liechti) Date: 23 Jun 2002 21:17:39 +0200 Subject: sys.exc_info() into string References: Message-ID: Magnus wrote in news:KZoR8.44805$n4.10504231 at newsc.telia.net: > in my program I am catching exceptions that I might have missed by > using something like: > > try: > doMyStuff() > except: > type = sys.exc_info()[0] > syslog.syslog(syslog.LOG_EMERG, "My program: unexpected error" > + type) > > The thing is that I can not figure out how to make "type" into a > string above so I can use it for e.g. syslog(). Is there an easy way > of doing this? yes, the traceback module has functions to format an exception as string or to print. format_exc is a candidate for you. it return a list of lines from which you can select to mosr informative or just join it the one big string. chris -- Chris From kragen at pobox.com Sat Jun 8 20:31:42 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 08 Jun 2002 20:31:42 -0400 Subject: check on numerical value? References: <3cff56b4.511834453@news.skynet.be> Message-ID: <83lm9p5m35.fsf@panacea.canonical.org> "Shagshag13" writes: > can't you use (after importing types) type(x) == types.FloatType (or type.IntType) Don't do that. See "isinstance considered harmful", http://lists.canonical.org/pipermail/kragen-tol/2002-January/000659.html. From usenet at thinkspot.net Sat Jun 1 12:23:27 2002 From: usenet at thinkspot.net (Sheila King) Date: Sat, 01 Jun 2002 09:23:27 -0700 Subject: How to open a HTML file when the python cgi program is executing? References: Message-ID: On Sat, 1 Jun 2002 18:16:28 +1000, "Ken" wrote in comp.lang.python in article : > Yes, I want to display the content of another html file (main.html in this > example) onto the browser. How do I do that? And also, how do I set target > to which frame to display? If you are trying to open some file and output it to the browser, then: f = open('main.html', 'r') myhtml = f.read() f.close() print myhtml Depending on what else the script has already done. For example, if you are printing the HTML output, instead of redirecting, you do need to print the Content-type before printing the contents of main.html: print "Content-type: text/html\n" But, if you are redirecting to another URL instead, then omit the line show above and print this line: print "Location: http://replacement-url\n" -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From rjones at ekit-inc.com Sun Jun 23 21:38:19 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Mon, 24 Jun 2002 11:38:19 +1000 Subject: PIL, Python and CGI In-Reply-To: References: Message-ID: <200206241138.19665.rjones@ekit-inc.com> On Mon, 24 Jun 2002 11:30, Sascha Ferley wrote: > Thanks for replying back to me, this thing has been driving me nuts for a > while now. Anyways, i removed the try/catch block from the Image.py lib, > and checked the error output: > > Traceback (most recent call last): > File "/export/server/web/CPSC461/cgi-bin/interfce.py", line 15, in ? > print Image.open(urlretrieve(sourcePath, '/tmp/img1')[0]).histogram() > File "/usr/local/lib/python2.2/site-packages/PIL/Image.py", line 577, in > histogram > self.load() > File "/opt/sfw/lib/python2.2/site-packages/PIL/ImageFile.py", line 126, > in load > self.load_prepare() > File "/opt/sfw/lib/python2.2/site-packages/PIL/ImageFile.py", line 180, > in load_prepare > self.im = Image.core.new(self.mode, self.size) > AttributeError: 'module' object has no attribute 'core' "core" is assigned just after the "import _imaging" line in Image.py. Are you sure there isn't another traceback we're missing? What happens if you just have a simple CGI script that just does "import _imaging"? Richard From krissepu at vip.fi Wed Jun 5 03:28:21 2002 From: krissepu at vip.fi (Pekka Niiranen) Date: Wed, 05 Jun 2002 10:28:21 +0300 Subject: Fastest way to read / procsess / write text? References: <3CFD5229.2060803@excite.com> Message-ID: <3CFDBD95.D6DFE028@vip.fi> Use map() instead of for -loop: pdata = [] pdata = map(re.sub(whatever), data) I managed to get 10x speed increase myself with map() Try alsol earning mxtexttools for further speedups (so I can ask help from you ;)) -pekka- Brent Miller wrote: > I'm somewhat new to python and programing in general and I trying to > write a simple script that I can use to format large text files so that > they are suitable for importing into MySQL. So far, I have came up with > this: > > #!/usr/bin/python2 > > import sys, re > > infile = sys.stdin > data = infile.read() > infile.close() > > data = re.sub('[.](?=\d\d\d\d\d\d)|[.](?=\w+[ ][<|>])|[.](?=\w+[:])|[ > ](?!0x)', '\t', data) > > outfile = open("/mnt/storage/output.txt", "w") > outfile.write(data) > outfile.close() > > This works beautifully most of the time (it's super fast), except when I > pipe large files (>50megs) to it and then it usually dies half way > through complaining of memory errors because it ran out of ram. > > Short of buying more ram, is there a way I can make this more effecient > without taking a big peformance hit? I tried the above where I used a > "for line in data:" loop so it would only process one line at a time but > this seemed to take forever! I'm imagining there's a way to process the > data in something like 1 meg chunks, but I'm not too sure how to do that. > > I'm using python 2.2.1 on a RH linux 7.2 system with 256 ram and a > Athlon XP1700 if it makes any diffrence. > > Any suggestions? > > TIA, > Brent From lmbrtmarc at aol.comlaissermoi Wed Jun 26 13:41:20 2002 From: lmbrtmarc at aol.comlaissermoi (Marc) Date: 26 Jun 2002 17:41:20 GMT Subject: Python and Windows XP References: <3d193d85$0$20999$afc38c87@news.optusnet.com.au> Message-ID: <20020626134120.09399.00000674@mb-cp.aol.com> Dans l'article <3d193d85$0$20999$afc38c87 at news.optusnet.com.au>, "Steven Adams" a ?crit: > >I just open up python.exe in my Python directory and it brings up the Python >interpreter, the standard 2.2 install setup shortcuts to it as Well I do that, too. > >Start->Programs->Python -->Python (command line) > >There is a command prompt that behaves like a DOS prompt - though I can't >recall where it sits in the default menu. > >I'm using XP Pro so YMMV Me too, and my problem has be solved, thank you. -- Marc if we can't benefit from an error by making jokes, what's the point of being here? From smarsh at hotmail.com Sat Jun 29 00:53:23 2002 From: smarsh at hotmail.com (scott) Date: Sat, 29 Jun 2002 04:53:23 GMT Subject: Is Python growing? References: Message-ID: <3D1D3D34.6080001@hotmail.com> Gerhard H?ring wrote: > Mark McEahern wrote: > >>[...] What's so >>beautiful about Python is that all I had to do was fire up the interactive >>interpreter and do this to remind myself of what map does: >> >> >>> print map.__doc__ > > > help(map) in 2.2. > > Gerhard Or 2.1.1. From gerhard.haering at gmx.de Wed Jun 5 13:55:54 2002 From: gerhard.haering at gmx.de (Gerhard =?unknown-8bit?Q?H=E4ring?=) Date: Wed, 5 Jun 2002 19:55:54 +0200 Subject: [Pypgsql-users] Re: [ANN] pyPgSQL 2.1 released In-Reply-To: <20020605170847.2631.qmail@www4.nameplanet.com> References: <20020605170847.2631.qmail@www4.nameplanet.com> Message-ID: <20020605175554.GB33711@gargamel.hqd-internal> * paul at boddie.net [2002-06-05 17:08 -0000]: > On Wed, 5 Jun 2002 18:40:11 +0200 Gerhard H?ring wrote: > >CC-ing to pypgsql-users list, maybe other users have comments on this issue, > >too. > > [Arrays vs. 'IN'] > > >QUERY: DECLARE PgSQL_08120A6C CURSOR FOR select * from cages where name > > in '{"mammals","apes"}' > > > >... which obviously cannot work. The reason is that if pyPgSQL encounters a > >tuple or a list in the statement parameters, it will quote them suitable for > >use as an ARRAY. Unfortunately, the ARRAY syntax is different from what you > >would need for the IN operator in SQL. > > Right, and there's no way of knowing what the database engine expects for > that parameter until it has parsed the statement. Unless you also parse at the client side, which I'd rather not ;-) There might be a solution with controlling the behaviour using a flag in the cursor object, for example. > I suppose there isn't a way of getting type information from PostgreSQL about > parameters - indeed, does PostgreSQL actually support parameters in the way > that other database systems do? You mean prepared statements? No, PostgreSQL doesn't currently support these. All it gets is a query string. From what I hear on IRC and on postgresql-hackers, people are working on prepared statements. Unfortunately, we'll have a problem with them and pyPgSQL, as as far as I see, prepared statements don't play nice with the DB-API 2.0 'format' and 'pyformat' parameter quoting styles. I believe that the 'qmark' or 'numeric' styles are designed exactly for prepared statement use. It might be possible to rewrite the query and continue using our 'pyformat' style, but I haven't tried, yet. > > [Unicode patch] > That would be great. Where XML data and PostgreSQL come together, it quickly > becomes a requirement to handle the data gracefully or transparently, > although I suspect that many database systems still struggle with Unicode. Hopefully, pyPgSQL with PostgreSQL works fine. PostgreSQL can even use the UTF-8 encoding at server side. With the Unicode patch and appropriate parameters for the connect() call, you should be able to use full Unicode: >>> from pyPgSQL import PgSQL >>> conn = PgSQL.connect(client_encoding="utf-8", unicode_results=1) >>> cursor = conn.cursor() >>> cursor.execute("insert into test(name) values (%s)", unicode("?sterreich", "latin1")) >>> cursor.execute("select * from test") >>> res = cursor.fetchone() >>> print repr(res.name) u'\xd6sterreich' Btw. the Unicode support that PySQLite recently gained is based on the same patch, and it includes an example for mass-importing Freshmeat project data from XML into a database. As you said, XML is Unicode-based, so this is a relatively practical example, I hope. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From tim at vegeta.ath.cx Wed Jun 5 16:33:45 2002 From: tim at vegeta.ath.cx (Tim Hammerquist) Date: Wed, 05 Jun 2002 20:33:45 GMT Subject: Detecting OS and Window Manager References: Message-ID: Andrew Wilkinson graced us by uttering: > I'm writing a program that integrates with a number of different OSes > and Window Managers (under Linux), but I need to check what the user > is running. I know that... > > import os > if os.name == 'nt': > > will tell me they're running NT. But under Linux I'd like to know if > they are running KDE or Gnome, does anyone know a (preferably) simple > test for this? Well, windowmanagers aren't as static as operating systems are. It's actually possible to run more than one wm at a time. In any case, I went and experimented with the various wms on my system and in all cases the $WINDOWMANAGER shell var was set to the full path of the running wm executable. This appears to be the only consistent and reliable var in my environment; for instance, here's a dump of my wm-related vars: QTDIR=/usr/lib/qt2 GNOME_PATH=:/opt/gnome:/usr:/opt/gnome:/usr KDEDIR=/opt/kde2 GNOMEDIR=/opt/gnome EROOT=/usr/X11R6/share/enlightenment WINDOWMANAGER=/usr/X11R6/bin/enlightenment The qt lib on my box is used only by KDE apps. I am indeed running KDE2 apps. Gnome is in fact located under the /opt/ dir. The Enlightenment tree does start at $EROOT. There are, of course, more KDE-related vars in a KDE session, and more Gnome-related vars in a Gnome session, but $WINDOWMANAGER confirms that I'm actually running Enlightenment (with the Gnome panel and one KDE app). However, I'm not sure how this works in instances (which I've had) when the window manager and desktop environment are different. eg: KDE env with sawfish wm. KDE apps run fine under Gnome, Gnome apps run under KDE, and both KDE and Gnome run under E. As long as you have the correct libs available (gtk, qt, etc) you shouldn't need to know what windowmanager is running anyway. Thoughts? Ideas? Tim Hammerquist -- Ford, you're turning into a penguin. Stop it. -- Arthur Dent, "The Hitchhiker's Guide to the Galaxy" From lt6789remove at hotmail.com Thu Jun 13 14:28:08 2002 From: lt6789remove at hotmail.com (Larry Taitt) Date: Thu, 13 Jun 2002 11:28:08 -0700 Subject: Post installation problem with Python References: <9dafguci28vdiv5lr3qbhset2jko78t6lm@4ax.com> <3d07b91c$0$21420$91cee783@newsreader02.highway.telekom.at> Message-ID: That's exactly what it was. Thanks. On Wed, 12 Jun 2002 23:12:37 +0200, "Guenter Szolderits" wrote: >"Larry Taitt" wrote: >> Installed ActivePython 2.2.1 build 222 on my NT4.0 (sp6a) workstation. >> After the installation I'm unable to execute any .exe, .com and .bat. >> program (e.g. notepad). It tells me that it can't find the files. >> However, if I add the proper extension (e.g., notepad.exe), the >> programs execute without a problem. I checked the associations and >> filetypes, and everything appears normal. Any ideas? > >Maybe your PATHEXT environment variable is damaged. It should look similar >as mine: > >PATHEXT=.COM;.EXE;.BAT;.CMD;.py;.pyw;.pyc;.pys;.pyo > >It should at least include .COM;.EXE;.BAT > >G?nter > -----------== Posted via Newsfeeds.Com - Uncensored Usenet News ==---------- http://www.newsfeeds.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Ulimited Fast Downloads - 19 Servers =----- From skip at pobox.com Thu Jun 20 18:20:10 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 20 Jun 2002 17:20:10 -0500 Subject: Bug in Python 2.3 ? In-Reply-To: <20020620205335.0c1d31b4.christophe.delord@free.fr> References: <20020620205335.0c1d31b4.christophe.delord@free.fr> Message-ID: <15634.21786.425480.991507@beluga.mojam.com> Christophe> It seems there's a bug in python 2.3 (available on CVS). I won't comment on your note except to say that if you think there is a bug (getting a segfault sure sounds like it), you should submit a bug report on SourceForge: http://sourceforge.net/projects/python/ -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From cliechti at gmx.net Thu Jun 20 15:23:28 2002 From: cliechti at gmx.net (Chris Liechti) Date: 20 Jun 2002 21:23:28 +0200 Subject: Inter Process Communication with Numeric arrays References: Message-ID: Ian McConnell wrote in news:wx1yb2uvt3.fsf at velocita.nasoftware: > I want to send the results of some calculation on a Numeric array to a > second process. These arrays will be fairly large (about 1Mb) so can > anyone recommend a package for simple IPC? you could use pickle and send it trough a pipe or socket. pyro.sf.net solves remote objects problems in python. it uses pickle over sockets and the other app can be on any machine on th net. > I'm writing both processes (though one might be in C) so ORB/CORBA > seems to be overkill and I can't get through to the memory mapped > files at > http://pobox.com/~kragen/sw/arrayfrombuffer/ > (Internal server error) the link works for me. but it seems that you would still need some locking/communication mechanism. > Suggestions? -- Chris From rayed at saudi.net.sa Sat Jun 1 05:10:51 2002 From: rayed at saudi.net.sa (Rayed Al-Rashed) Date: Sat, 01 Jun 2002 12:10:51 +0300 Subject: Interactive socket connection Message-ID: <3CF88F9B.1080308@saudi.net.sa> Hello, I am trying to build POP3 proxy, I want it to run from "inetd" so it should communicate with the user using regular stdin, stdout. I built a small code that should run as general proxy for any protocol, but I faced the following problem, it doesn't show any output from the server until I pass it a command, for example: ----------------------------------------- user rayed +OK POP3 pop.mydomain.com server ready pass mypass +OK User name accepted, password please rert 1 -ERR Bad login quit -ERR Unknown AUTHORIZATION state command +OK Sayonara ----------------------------------------- Any ideas what the problem is? Thanks in advance, - rayed This the proxy code -------------------------- #!/usr/bin/python # POP3 proxy import sys import string import socket import asyncore import select class proxy (asyncore.dispatcher): def __init__(self, server, port): asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET,socket.SOCK_STREAM) self.connect ((server, port)) def handle_connect (self): pass def handle_read (self): buf = self.recv(8012) sys.stdout.write( buf ) def handle_write (self): buf = sys.stdin.readline() self.send(buf) def handle_close (self): print "Closed" if __name__ == '__main__': p = proxy("pop.mydomain.com", 110) asyncore.loop() From cotemark at globetrotter.net Sun Jun 9 19:58:59 2002 From: cotemark at globetrotter.net (Marc Cote) Date: Sun, 09 Jun 2002 23:58:59 GMT Subject: python interacting with other programs References: <64eb9145.0206041454.4f70e86e@posting.google.com> Message-ID: <7ZRM8.9358$bt2.116439@charlie.risq.qc.ca> "Jakob" wrote in message news:64eb9145.0206041454.4f70e86e at posting.google.com... > now I know python can interact with programs like Microsoft wor and > access and all but has anyone ever tried to interact with Lotus Notes? > Is it possible? Jakob, Google Search: "Lotus Notes Python" gives: Using Python to create a command line interpreter for Notes URL: http://www.dominopower.com/issues/issue200008/command001.html From maxm at mxm.dk Mon Jun 17 03:24:47 2002 From: maxm at mxm.dk (Max M) Date: Mon, 17 Jun 2002 09:24:47 +0200 Subject: I feel stoopid ... this code is to verbose References: <3D0A1791.3060307@mxm.dk> Message-ID: <3D0D8EBF.3050804@mxm.dk> Joseph Wilhelm wrote: > On Fri, 2002-06-14 at 09:19, Max M wrote: > > >>def stringSlicer(string, chunkSize=3): >> chunkList = [] >> reverseString = list(string) >> reverseString.reverse() >> for i in range(0, len(string), chunkSize): >> chunk = reverseString[i:i+chunkSize] >> chunk.reverse() >> chunk = ''.join(chunk) >> chunkList.append(chunk) >> chunkList.reverse() >> return '.'.join(chunkList) > import string > > def stringSlicer( str, chunkSize=3 ): > parts = list( str ) > for x in range( ( len( parts ) - chunkSize ), 0, -chunkSize ): > parts.insert( x, "." ) > return string.join( parts, "" ) > > print stringSlicer( '42000000' ) Yeah ... this was the one I was looking for. Why the h... didn't I do this one myself? Well I know why! I didn't take the time to do a pseudo-run on paper before coding. Let this be a lesson to me... once more :-) I gotta stop eating all those simple Carbo hydrates. It makes the brain implode into uselessness. Well I made a few stylechanges and it fit me perfectly: def stringSlicer(str, chunkSize=3): parts = list(str) for x in range((len(parts) - chunkSize), 0, -chunkSize): parts.insert(x, ".") return ''.join(parts) Easy on the eyes and the mind. I find it really amusing that even in Python there is such a wide array of approaches to such a relatively simple and well defined problem. Thanks to all for the suggestions. regards Max M From shalehperry at attbi.com Wed Jun 5 23:18:04 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 05 Jun 2002 20:18:04 -0700 (PDT) Subject: simple pattern matching question In-Reply-To: <20020606022819.GA72435@attbi.com> Message-ID: On 06-Jun-2002 Corey G. wrote: > Gurus, > > How would I match with an item from a list? I would imagine something > this simple would not require a regular expression. > > web_servers=('www01','www02','www03') > > for server_match in web_servers: > if (trap == "Service:"server_match "State:down"): > print "found match" > > The comparsion should be: if trap == Service:www01 State:down > > server_match prints "as is, but not from the list". I tried many > combinations but decided to leave the most obviously wrong one. > if trap == ("Service:%s State:down" % server_match): print "found match" From phd at phd.pp.ru Mon Jun 24 05:49:51 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 24 Jun 2002 13:49:51 +0400 Subject: mimedecode.py version 1.1.4 Message-ID: <20020624134951.D24065@phd.pp.ru> Hello! mimedecode.py WHAT IS IT Mail users, especially in non-English countries, often find that mail messages arrived in different formats, with different content types, in different encodings and charsets. Usually this is good because it allows us to use apropriate format/encoding/whatever. Sometimes, though, some unification is desireable. For example, one may want to put mail messages into an archive, make HTML indicies, run search indexer, etc. In such situations converting messages to text in one character set and skipping some binary atachmetnts is much desireable. Here is the solution - mimedecode.py. This is a program to decode MIME messages. The program expects one input file (either on command line or on stdin) which is treated as an RFC822 mesage, and decoded to stdout. If the file is not an RFC822 message it is just piped to stdout one-to-one. If the file is a simple RFC822 message it is just decoded as one part. If it is a MIME message with multiple parts ("attachments") all parts are decoded. Decoding can be controlled by command-line options. WHAT'S NEW in version 1.1.4 Fixed a minor bug with decoding of empty headers. WHERE TO GET Master site: http://phd.pp.ru/Software/Python/#mimedecode Faster mirrors: http://phd.by.ru/Software/Python/#mimedecode http://phd2.chat.ru/Software/Python/#mimedecode Requires: Python 2.0+ (actually tested with 2.1 and 2.2), configured mailcap database. Documentation (also included in the package): http://phd.pp.ru/Software/Python/mimedecode.txt http://phd.by.ru/Software/Python/mimedecode.txt http://phd2.chat.ru/Software/Python/mimedecode.txt AUTHOR Oleg Broytmann COPYRIGHT Copyright (C) 2001-2002 PhiloSoft Design LICENSE GPL Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From erict at millfilm.co.uk Thu Jun 27 10:06:31 2002 From: erict at millfilm.co.uk (Eric Texier) Date: Thu, 27 Jun 2002 15:06:31 +0100 Subject: How to get rid the new line References: Message-ID: <3D1B1BE7.D482AE@millfilm.co.uk> ## remove all the leading and tail white space line = string.strip(aline) if line: # this is an emptyLine or better def isNotEmpTxt(text): empty = re.compile('^\s*$') if empty.match( text): return 0 else: return 1 SiverFish wrote: > Anyone tell me how to skip the empty line when you read through the file > and copy the information in to the list(no empty line ) From aahz at pythoncraft.com Fri Jun 14 02:31:56 2002 From: aahz at pythoncraft.com (Aahz) Date: 14 Jun 2002 02:31:56 -0400 Subject: newbie: from .. import * References: <56e1eff0.0206131437.4ca8ed9e@posting.google.com> Message-ID: In article <56e1eff0.0206131437.4ca8ed9e at posting.google.com>, =?ISO-8859-1?Q?Jean-S=E9bastien_Bolduc?= wrote: > >I've been working with Python for a while, but never really felt >confortable with the way namespaces are imported. What you're dealing with isn't, strictly speaking, a namespace issue but a scope issue. Python uses lexical scope to determine visibility of module globals and locals, so that static analysis of source can determine visibility of names. Therefore, when you define a function, its scope stays with the module where you defined the function. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I had lots of reasonable theories about children myself, until I had some." --Michael Rios From gerhard.haering at gmx.de Fri Jun 21 03:47:46 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Fri, 21 Jun 2002 09:47:46 +0200 Subject: compile python witout tkinter In-Reply-To: References: Message-ID: <20020621074746.GA765@lilith.my-fqdn.de> * kosh at aesaeion.com [2002-06-21 01:26 -0600]: > On a machine I need to build python on I need to build it without tkinter. Why? Even if Tkinter gets compiled, it doesn't change anything for the rest. You could even delete the tkinter modules afterwards, if you're short on disk (quota). > How can I do that. I didn't notice any configure options to do that > and I also looked at Modules/Setup and that seems to have _tkinter > commented out. That's all there is to it. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From mdk at mdk.com Thu Jun 20 14:05:50 2002 From: mdk at mdk.com (mdk) Date: 20 Jun 2002 18:05:50 GMT Subject: Proper number alignment Message-ID: I am using \t\t (tabs) to align these numbers (disregard the math): Total RAM 2,141,056 Available RAM 12,934,032 Used RAM 1,024 But they are left justified and I need them right justified. Any ideas? Thanks. From mhuening at zedat.fu-berlin.de Wed Jun 26 13:14:10 2002 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: 26 Jun 2002 17:14:10 GMT Subject: how to remove HTML attributes from web pages ( HTML parseing) References: <63170f57.0206260345.2b61b7ec@posting.google.com> Message-ID: sanjay2kind at yahoo.com (sanjay) wrote in news:63170f57.0206260345.2b61b7ec at posting.google.com: > Hi, > > New to python and doing one application. i would like to web page > content after removing specific html tag, attribute etc. Below you find some sample code that uses htmllib. Hope this helps. - Matthias ----------- import htmllib, formatter, StringIO, urllib class HTMLStripper(htmllib.HTMLParser): def __init__(self): self.bodytext = StringIO.StringIO() writer = formatter.DumbWriter(self.bodytext) htmllib.HTMLParser.__init__(self, formatter.AbstractFormatter(writer)) def anchor_end(self): if self.anchor: self.handle_data('') self.anchor = None def gettext(self): return self.bodytext.getvalue() f = urllib.urlopen('http://www.python.org/').read() st = HTMLStripper() st.feed(f) st.close() print st.gettext() print st.anchorlist ----------- From maxm at mxm.dk Fri Jun 14 12:19:29 2002 From: maxm at mxm.dk (Max M) Date: Fri, 14 Jun 2002 18:19:29 +0200 Subject: I feel stoopid ... this code is to verbose Message-ID: <3D0A1791.3060307@mxm.dk> Hmm ... I am working on a problem. In Danish we have a number format that looks like: 42.000.000,00 which is 42 millions So I need to insert dot's at every three character from end of the string for the integer value of the number. Let's discard decimal points and just focus on the meat. I have written a funcion which works:: def stringSlicer(string, chunkSize=3): chunkList = [] reverseString = list(string) reverseString.reverse() for i in range(0, len(string), chunkSize): chunk = reverseString[i:i+chunkSize] chunk.reverse() chunk = ''.join(chunk) chunkList.append(chunk) chunkList.reverse() return '.'.join(chunkList) print stringSlicer('42000000') >>> 40.000.000 I just find that it's a lot of code for such a little function an it annoys my sense of aestetics. I have tried a lot of different approaches including using zip on a list like ['','','.'], and other weird stuff :-) I just cannot seem to find the nice 3-liner I expected from the beginning. Has anybody got a better solution ? I thought somebody might find it a fun exercise. Well I have... regards Max M From listuser at nicetomeetyou.to Fri Jun 28 01:52:38 2002 From: listuser at nicetomeetyou.to (Markus) Date: Fri, 28 Jun 2002 07:52:38 +0200 Subject: crypt for windows? References: Message-ID: Klaus Reinhardt wrote: > Am 27.06.02 19:29:52, schrieb Gerhard H?ring : > >>> Is there a crypt for windows-python, so >>> I can manage some password-files? >> >>Probably not. I believe Cygwin's Python has this module. Is that an >>option for you? I use a module named fcrypt. It is a pure Python implementation and works fine for Unix *and* Windows. I'm sure a search on Parnassus or Google will find it. --Markus From tim.one at comcast.net Thu Jun 27 23:47:01 2002 From: tim.one at comcast.net (Tim Peters) Date: Thu, 27 Jun 2002 23:47:01 -0400 Subject: Python 2.2 __slots__ Bug? In-Reply-To: Message-ID: [Jonathan Hogg] > It appears that GjR is on the case ;-) Na, I assigned the bug to GvR just to irritate him <0.7 wink>: he wrote the __slot__ deallocation code that's blowing up, yet has also called the funky trashcan mechanism (which you described well later) "evil" more than once. The irritating part is that the evil trashcan mechanism is the only hope of avoiding stack overflow in absurd cases like this. > ... > I can't see an easy way to fix this without changing the way that the > "delete later" list is constructed. Sometimes we just agree to pretend that we never saw the bug report . more-than-one-way-to-close-a-bug-ly y'rs - tim From osuchw at ecn.ab.ca Fri Jun 14 02:03:40 2002 From: osuchw at ecn.ab.ca (waldekO) Date: 13 Jun 2002 23:03:40 -0700 Subject: Help with ADO and dynamic insert statement... References: <3d0826ec.240888125@netnews.attbi.com> Message-ID: You should at least post a traceback if you expect a resonable answer to your question. candiazoo at attbi.com wrote in message news:<3d0826ec.240888125 at netnews.attbi.com>... > I have a program written in VB that creates an ado COMMAND object, sets the text > to a dynamic sql string (insert into table (?, ?, ?, etc))... it works in VB... > this is my first foray into doing something similar with Python and it isn't > working. Could someone take a gander at this and tell me what I might be doing > incorrectly? > > Thanks! > > Mike > > ============================================ > segment of code below > ============================================ > > if status == SUCCESS: > # Generate our dynamic insert statement, create new > # ADODB connection and command objects which we'll > # use to connect to our access database (via the > # CatalogMDB DSN object)... > > sql = "insert into works (title, wrk_inst, trs_inst, aas_inst) " + \ > "values (?, ?, ?, ?)" > > cnnTempDB = win32com.client.Dispatch('ADODB.Connection') > cmdInsert = win32com.client.Dispatch('ADODB.Command') > > cnnTempDB.Open(TEMP_DB) > cmdInsert.ActiveConnection = cnnTempDB > cmdInsert.CommandType = 1 > cmdInsert.CommandText = sql > > if not rstOracle.EOF: > # Let's bind up our dynamic sql statement... > > cmdInsert.Parameters.Append(cmdInsert.CreateParameter("title", 200, > 1, len(rstOracle.Fields("title").Value), rstOracle.Fields("title").Value)) > cmdInsert.Parameters.Append(cmdInsert.CreateParameter("wrk_inst", > 131, 1, 4, rstOracle.Fields("wrk_inst").Value)) > cmdInsert.Parameters.Append(cmdInsert.CreateParameter("trs_inst", > 131, 1, 4, rstOracle.Fields("trs_inst").Value)) > cmdInsert.Parameters.Append(cmdInsert.CreateParameter("aas_inst", > 131, 1, 4, rstOracle.Fields("aas_inst").Value)) > cmdInsert.Execute() > rstOracle.MoveNext() From mcfletch at rogers.com Tue Jun 4 12:03:57 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 04 Jun 2002 12:03:57 -0400 Subject: Looking for a list subclassing example... References: Message-ID: <3CFCE4ED.5000105@rogers.com> Well, here's a generic list-subclass example... class rlist( list ): """Sub-class of list which calls a method before any addition is allowed""" def __setslice__( self, start, stop, value ): """__setslice__ with value checking""" value = self.beforeMultipleAdd([ self.beforeAdd(item) for item in value ]) return list.__setslice__( self, start, stop, value ) def extend( self, value ): """extend with value checking""" value = self.beforeMultipleAdd([ self.beforeAdd(item) for item in value ]) return list.extend( self, value ) __iadd__ = extend def append( self, value ): """append with value checking""" value = self.beforeAdd( value ) return list.append( self, value ) def insert( self, index, value ): """insert with value checking""" value = self.beforeAdd( value ) return list.insert( self, index, value ) def __setitem__( self, index, value ): """__setitem__ with value checking""" value = self.beforeAdd( value ) return list.__setitem__( self, index, value ) def beforeAdd( self, value ): """Called before all attempts to add an item""" return value def beforeMultipleAdd( self, value ): """Called before attempts to add more than one item (beforeAdd has already be called for each item)""" return value HTH, Mike Shagshag13 wrote: > Hello, > > I'm looking for a list subclassing example, and i can't find it... > > Do you have one to show ? > > Thanks, > > s13. > > > -- _______________________________________ Mike C. Fletcher http://members.rogers.com/mcfletch/ From dan at eevolved.com Mon Jun 3 14:37:34 2002 From: dan at eevolved.com (Daniel Parisien) Date: Mon, 03 Jun 2002 14:37:34 -0400 Subject: encoding and decoding repr'd version of strings References: Message-ID: Gustavo Cordova wrote: >> >> Hi >> is there an codec that bundles with python so you can >> transform strings into the repr'd (escaped) version and >> back? If not, how easy would it be to code? I don't want >> to use eval(...) because I don't trust the source of the >> string and I might mistakenly eval an expression like "' >> '*(2**30)" which would allocate about 1 GB of data (eek!) >> >> Thanks, >> Dan >> > > I might be going out on a limb here, but how about using pickle > or cpickle? > > -gustavo Valid suggestion, but it's a lot of overhead for naught (I just want to store escaped strings, not data of all types). It's also a little too python-specific. Dan From peter at engcorp.com Thu Jun 20 21:22:40 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 20 Jun 2002 21:22:40 -0400 Subject: Dispatching a Win32 COM in the background? References: <9OpQ8.90552$ks6.8015@nwrddc02.gnilink.net> Message-ID: <3D127FE0.74D47795@engcorp.com> "Steven M. Castellotti" wrote: > > Thanks a lot guys, your suggestions have worked perfectly! > > Just for the record, here's what the full implementation looks like. Beautiful... thanks for the followup Steven. I especially like your use of deferred imports to speed up initial program loading. [...] > if not(self.text_queue.empty()): > text = self.text_queue.get() > speech.Speak(text) > time.sleep(.001) Note that the time.sleep() as shown above is doing nothing useful for you. I suspect you had it unindented but your posting probably used tabs and spaces which makes it hard to see properly on some readers. The reason it does nothing useful is that Python will automatically switch between different threads every so often anyway, so the concept of giving up the CPU for what amounts to a tiny fraction of a second is somewhat unnecessary. -Peter From dbasch at yahoo.com Sat Jun 29 23:14:23 2002 From: dbasch at yahoo.com (Derek Basch) Date: Sat, 29 Jun 2002 20:14:23 -0700 (PDT) Subject: Win32/Python serial port event character problem Message-ID: <20020630031423.93113.qmail@web20806.mail.yahoo.com> Thanks for the ideas Peter and Chris. I would use pySerial but I have spent the last few months building my own serial module that is very similiar to pySerial but with some extra features. It was probably silly of me to build my own from scratch but it was a good challange and I certainly understand serial ports much better now. So you think I should ditch the event character and just read a preset number of characters from the buffer on each loop? That sounds like a good idea for OS compatability. I will use something like this (from pySerial): http://www.geocities.com/dbasch/tempers.txt I dont understand what Chris is doing in the middle though. Maybe you can answer that Chris? I hadn't had a chance to write any code for detecting the termination character and breaking up the data but your pseudocode was just what I needed Peter. Thanks!, Derek Basch P.S. Next time I will be more patient. Need to drink less tea ;) Derek Basch wrote: > > If anyone reads this and can show me a better way to > work with serial event characters in win32 please feel > free to :) I second Chris' comments about using something like PySerial and just handling this in a thread. Event characters are probably non-portable, while you could easily write code with PySerial that runs under Linux or Windows. But give it time... you definitely didn't give it enough time before you reposted. :) By the way, here's some typical (?) code for handling a termination sequence on incoming data for something like this (while inside of some kind of serial port object): def read(self, timeout=None): buf = self.leftover self.leftover = '' while true: data = FUNCTION_TO_READ_A_RAW_BLOB_OF_DATA() # if new data received, add to the buffer and check for # a contained input termination sequence if data: buf = buf + data termIndex = string.find(buf, self.inputTerminator) if termIndex >= 0: # move past the terminator termIndex = termIndex + len(termIndex) # preserve anything lying after input termination # sequence in the leftover buffer for next time buf, self.leftover = buf[:termIndex], buf[termIndex:] break return buf Each time you call it, it reads raw data and adds it to a buffer which it then rescans for the termination sequence. If the buffer contains the sequence, it splits it on that and returns everything up to and including the sequence, preserving everything after it for the next call. -Peter __________________________________________________ Do You Yahoo!? Yahoo! - Official partner of 2002 FIFA World Cup http://fifaworldcup.yahoo.com From db3l at fitlinxx.com Thu Jun 6 21:58:42 2002 From: db3l at fitlinxx.com (David Bolen) Date: 06 Jun 2002 21:58:42 -0400 Subject: Compiling Python References: <3CFE23DB.994F8A6C@engcorp.com> <3CFFC67E.3070609@bgb.cc> Message-ID: Don Garrett writes: > It would be even more useful if there was an easy way to produce a > standalone RPM or MSI file (depending on the plateform). The MSI file is > probably more useful. The unix people are more capable of dealing with the > extra steps of getting a python program to work. While not MSI, there are free setup programs (I'm a fan of InnoSetup) that will produce a perfectly standard looking Windows installation executable for your application. You can couple that with the installer/py2exe output to look like a standard Windows setup. If you're already doing this and just specifically want an MSI format, then ignore the point. :-) -- -- David -- /-----------------------------------------------------------------------\ \ David Bolen \ E-mail: db3l at fitlinxx.com / | FitLinxx, Inc. \ Phone: (203) 708-5192 | / 860 Canal Street, Stamford, CT 06902 \ Fax: (203) 316-5150 \ \-----------------------------------------------------------------------/ From -$P-W$- at verence.demon.co.uk Sun Jun 9 13:15:17 2002 From: -$P-W$- at verence.demon.co.uk (Paul Wright) Date: 9 Jun 2002 18:15:17 +0100 Subject: Python MTA References: Message-ID: In article , David LeBlanc wrote: >Has anyone developed a simple/stupid Mail Transfer Agent using Python >that does't rely on any external mail agents (and thus would be >platform independent)? > >What I have in mind is an app that sits between my mail client (outlook >(dev/null=flames)) and, at most, a few mail hosts. It would act like a >client to those mail hosts and as a host to outlook. The idea is to be >able to insert a spam filter like ASK (or something better?). You don't want an SMTP MTA then, you want a filtering POP3 proxy. I have the beginnings of such a thing in Python but my motivation to finish it kind of went away when SpamPal was released: http://www.twinlobber.org.uk/spampal/ It is not written in Python and the source is not open, but I'm told it works well. Should I ever finish my proxy I'll let this group know, I should think. -- Paul Wright | http://pobox.com/~pw201 | From schaffer.SPAM at optonline.net Thu Jun 20 16:41:23 2002 From: schaffer.SPAM at optonline.net (Les Schaffer) Date: Thu, 20 Jun 2002 16:41:23 -0400 Subject: Problems with mayavi, pyvtk References: <7396d2b2.0206191025.3351a888@posting.google.com> <7396d2b2.0206201046.4f0530fa@posting.google.com> Message-ID: Fernando P?rez wrote: > Keep in mind that Prabhu doesn't use windows either (at all). Maybe > someone on the mayavi list does use windows and can lend you a hand > though I am in the process of updating the Python 2.2 DLLs for VTK on my page in the next several days. so if there are problems getting it to work, write me directly and we'll get them fixed. Les Schaffer From peter at engcorp.com Sat Jun 1 14:03:45 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 01 Jun 2002 14:03:45 -0400 Subject: wxPython performance References: <3CF8E382.3A44F0DA@engcorp.com> Message-ID: <3CF90C81.5A141A97@engcorp.com> Andrei Kulakov wrote: > > > On my blazing 233 MHz Windows 98 machine, with Python 2.2.1 > > and WxPython 2.3.2.1, a hello world program I just wrote > > runs in about two seconds, for what it's worth. > > > > -Peter > > Odd.. if not too much trouble, could you please try this one > (from wxpython tutorial)? > [snip short hello world] First time running: 4 seconds. Subsequent invocations: 2 seconds. -Peter From kragen at pobox.com Tue Jun 4 18:37:48 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 04 Jun 2002 18:37:48 -0400 Subject: Problems with exec scoping (solved) References: Message-ID: <83it4y4qmb.fsf@panacea.canonical.org> Erik Walthinsen writes: > Well, it turns out that I was being an idiot and not checking the source > of the returned HTML page. When repr() is run on an object, it returns a > string such as: > > ... > I will now go and see about writing a HTML-textizer for use in such > situations. Take a look at http://lists.canonical.org/pipermail/kragen-hacks/2002-January/000291.html --- it's an HTML version of repr() called htmlstr(). It generates CSS-skinnable HTML that renders builtin types much more nicely than the builtin repr() or str() do, using tables to make things wrap nicely. There's also HTMLRepr from pydoc. From hesterloli at hotmail.com Sat Jun 15 18:58:36 2002 From: hesterloli at hotmail.com (George Hester) Date: Sat, 15 Jun 2002 22:58:36 GMT Subject: python version? References: Message-ID: Python ActiveX Scripting Engine error '80020009' Traceback (innermost last): File " > > > > > -- > Duncan Booth duncan at rcp.co.uk > int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" > "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From tdelaney at avaya.com Tue Jun 18 20:13:18 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Wed, 19 Jun 2002 10:13:18 +1000 Subject: If you use Python -OO is it a permanent condition?? Message-ID: For some reason, I parse the subject line as "If you use Python in an object-oriented way, is it a permanent condition?" I'm not sure if that's a philosophical question, but it confused the hell out of me ;) Tim Delaney From duncan at NOSPAMrcp.co.uk Fri Jun 14 04:24:04 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 14 Jun 2002 08:24:04 +0000 (UTC) Subject: Date formats References: <3D09A1B1.6040705@mxm.dk> Message-ID: Max M wrote in news:3D09A1B1.6040705 at mxm.dk: > > gDateFormat = '%d-%m-%Y' > > This give dates of the type: > > 01-01-2002 > > For some reason my customer wants dates of the type: > > 1-1-2002 > > Without the leading zero in single digit dates. But when I look in the > docs for date time formats there is no way to specify days and months in > that format. The documentation says that on some platforms an optional field width and precision specification can follow the initial '%'. This is obviously highly non-portable, but might provide a suitable solution if you are not desperate for portability. For example, if you are running under Windows using "%#d-%#M-%Y" as the format string gives the format you require. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From vvainio at tp.spt.fi Thu Jun 20 05:07:36 2002 From: vvainio at tp.spt.fi (Ville Vainio) Date: 20 Jun 2002 02:07:36 -0700 Subject: 'else' clause in 'for' and 'while' Message-ID: How do you people use the else clause in for and while constructs? Are they used widely for some specific applications? Do they offer elegant, idiomatic solutions to some problems? I haven't found any use for them yet myself, but knowing that they exist and still not using them troubles me, core python being quite 'small' after all. -- Ville From jiscmail-support at jiscmail.ac.uk Tue Jun 11 11:47:46 2002 From: jiscmail-support at jiscmail.ac.uk (jiscmail-support at jiscmail.ac.uk) Date: Tue, 11 Jun 2002 16:47:46 +0100 Subject: Your mail sent to mailbase.ac.uk with subject Hello,introduction on ADSL Message-ID: <200206111547.g5BFlkl10314@ori.rl.ac.uk> This Mailbase list has moved to JISCmail. For further information see http://www.jiscmail.ac.uk/docs/transition.htm. The email message that you sent has not been delivered, if you want your email to be delivered you must re-address it as described on the pages referenced above. If you have any queries about this message then please contact jiscmail-helpline at jiscmail.ac.uk From rotundo52 at hotmail.com Thu Jun 20 00:42:15 2002 From: rotundo52 at hotmail.com (Jon J. Morin) Date: Thu, 20 Jun 2002 04:42:15 GMT Subject: can I call operator overloader in superclass? Message-ID: Hi all. I have a particularly trivial bit of code I'm working with to learn Python and I have a question about operator overloading. Say I have class AList which is partially defined: class AList: def __init__(self, other=[]): self.data = [] for x in other: self.data.append(x) def __repr__(self): return "List: " + `self.data` ... ... ... I have a subclass AListSub which is partially defined as follows: classAListSub(AList): repr_calls = 0 def __init__(self, list=[]): AList.__init__(self, list) def __repr__(self): AListSub.repr_calls = AListSub.repr_calls + 1 print "Calling __repr__ in superclass" AList.__repr__(self) print "Method called %d times." % (AListSub.repr_calls) ... ... ... I can create instances on AListSub by passing in a string, or a list as in >>> x = AListSub('sasquatch') >>> x Calling __repr__ in superclass Method called 1 times. Traceback (innermost last): File "", line 1, in ? TypeError: repr not string For one, I don't understand the error. For seconds, can I call __repr__ in the superclass from __repr__ in the subclass? Jon J. Morin From marklists at mceahern.com Sat Jun 29 11:44:24 2002 From: marklists at mceahern.com (Mark McEahern) Date: Sat, 29 Jun 2002 10:44:24 -0500 Subject: private In-Reply-To: Message-ID: > Is there any possibility to build up a _real_ private attribute? > Such as C++ private data members... > I know that with double-underscore prefix (and the name mangling related) > I can " hide " data members but I think it's not a so crafty trick... > Is there any PEP about it? Will Guido insert a private keyword > in a future release of Python ? What problem are you trying to solve? Cheers, // m - From tismer at tismer.com Wed Jun 19 11:28:50 2002 From: tismer at tismer.com (Christian Tismer) Date: Wed, 19 Jun 2002 17:28:50 +0200 Subject: [Python-Dev] Tcl adept wanted for Stackless problem References: <3D108966.9050402@tismer.com> <200206191507.g5JF7ag02088@pcp02138704pcs.reston01.va.comcast.net> Message-ID: <3D10A332.7010909@tismer.com> Guido van Rossum wrote: >>My big question is: >>When does Tcl use C stack entries as globals, which >>are passed as function arguments to interpreter calls? > > > It's a performance hack, just as stackless :-). Where the effect of my hack is slightly bigger. We can fight that out in Charleroi. :-) > Tcl's interpreter data structure has a return value field which can > receive a string of arbitrary length. In order to make this > efficient, this is initialized with a pointer to a limited-size array > on the stack of the caller; when the return value is longer, a > malloc()'ed buffer is used. There is a little dance you have to do to > free the malloc()'ed buffer. The big win is that most calls return > short strings and hence you save a call to malloc() and one to free() > per invocation. This is used *all over* the Tcl source, so good luck > getting rid of it. Thank you! I should better not try this. Instead, I'd like not to touch it at all. I have patched tkinter in a way that it does not slice the stack while some Tcl stuff is running (maybe I didn't catch all). That should mean that the small stack stings are all alive. That is, in the context of Tcl, I dispensed with the "stackless" concept. The remaining problem is switching of tasklets which contain Tcl invocations. I thought so far that this is no problem, since these are disjoint contexts, but Jeff Senn reported problems as well. I fear I have the problem that Tcl thinks it is still using the same interp, or it creates a nested one, while the tasklets are not nested, but seen as independent. Somehow I need to create a new Tcl frame chain for every tasklet that uses Tcl. Can this be the problem? Still no clue how to do it but thanks - ciao - 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 pager +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 kfw at woeltje.org Thu Jun 13 19:59:53 2002 From: kfw at woeltje.org (Keith Woeltje) Date: Thu, 13 Jun 2002 19:59:53 -0400 Subject: Python 2.2.1 References: Message-ID: <3D0931F9.4030103@woeltje.org> Dave, I concur with the above--good choice in language. If you get frustrated with that particular tutorial (it didn't look that great on first glance), be sure to look at all of the resources on the Python web site at: http://www.python.org/doc/Newbies.html In particular, if you are new to programming, you owe it to yourself to check out Alan Guald's site: http://www.freenetpages.co.uk/hp/alan.gauld/ if you can spring for it, the print version is an excellent starting point (I'm fond of real books personally). Best of luck. >K Dave wrote: > Hi, I am 12 years old and would like to begin learning Python over > the summer. I have Windows 98 SE. I have python 2.2.1 and all of its > utilities on my computer. I am taking a tutorial > from http://softwaredev.earthweb.com/sdopen/article/0,,12382_626311,00.html > If you go to it and scroll down to the paragraph entitled *Getting > Started* there is a paragraph that says, *"You will need to cause the > directory containing the file named python.exe to be listed in your > system environment variable named path. If you already know how to set > the path, go ahead and do it. If you don't already know how, you may > need to get some help." * > ** > > How do I set the path and what should the name of the path be? All > help and information would be appreciated. Thanks.:) From gleki at gol.ge Fri Jun 7 06:51:24 2002 From: gleki at gol.ge (Giorgi Lekishvili) Date: Fri, 07 Jun 2002 12:51:24 +0200 Subject: map References: <3D007666.2B6D3582@gol.ge> Message-ID: <3D00902C.DF2CC70@gol.ge> Ok, there is a function in Numeric, and Numeric.power(a, y) works as expected. Anyway, I still would like to know wether there's an opportunity to employ map function as stated. Giorgi Lekishvili wrote: > Hi all! > > Is there a way to map a function with several arguments to a list? E.g., > > >>>import math > >>>import MLab > >>>a=MLab.rand(3,5) > >>>b=map(math.pow,a) > > of course, this doesn't work. > > What to do? My task is to optimize the power (i.e., y in pow(x,y)) to > achieve maximal performance. > > thanx, > Giorgi > > PS: Perhaps I have missed the needed functionality, that's presented in > NumPy? From mwarden22 at hotmail.com Tue Jun 11 14:36:18 2002 From: mwarden22 at hotmail.com (nealj) Date: 11 Jun 2002 11:36:18 -0700 Subject: Embedded Python script debugger??? References: <3ceceec6$1_3@goliath.newsgroups.com> Message-ID: That is exactly what I hope to do with Hap - you could start debugging by importing the hapclient module. The dll would still need to be ported to CE but that shouldn't be too big of a hurdle, we are planning a mac port in the near future. "Brad Clements" wrote in message news:<3ceceec6$1_3 at goliath.newsgroups.com>... > I'm keeping an eye on HAP because I think it will be useful for debugging > Python CE applications. > > The holdup is that I need a seperate .exe on the client to do this. > > What would be very interesting .. is a HAP client DLL that is also a Python > module. > > So, from python I could instantiate a HAP client debug session (the HAP > client module would create a new interpreter to do this). Just need some > options for hooking up debug output text so it could be sent back to the > original interpreter if needed (rather than a console, because CE doesn't > have a console). > > -- > Novell DeveloperNet Sysop #5 > > _ > "nealj" wrote in message > news:d3768569.0205221233.8079de2 at posting.google.com... > > Hap could be adapted to do this quite easily (in fact I will be doing > > it in the next few weeks). Currently, Hap uses an app that takes the > > place of python.exe to execute the python scripts. This app handles > > the socket and the debugging stuff - instead of "hapclient.exe", it > > could just as easily be your application that gets run. > > > > My plan is to repackage the code in the app to make this easier - then > > all you would have to do is to link to a dll and you're off. Keep an > > eye on the Hap site on sourceforge - there will be important and > > interesting updates coming soon. > > > > If you are intersted in trying it out, get the source from SourceForge > > (its currently only there in .zip format) and take a look at > > ConsoleEmbed.cpp in the HapClient directory - you'll see it doesn't > > really do much other than setup the debugging and run the script. Let > > me know if you have any questions - the best way to get in contact is > > through the sourceforge email https://sourceforge.net/users/nealj/ > > > > Good Luck! > > Neal > > > > > -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- > http://www.newsfeed.com The #1 Newsgroup Service in the World! > -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From steve at ferg.org Fri Jun 21 09:10:30 2002 From: steve at ferg.org (Stephen Ferg) Date: 21 Jun 2002 06:10:30 -0700 Subject: a Tree data-structure class? Message-ID: I do a lot of processing of tree-structured data, so I'm thinking it would be useful to develop a generic Tree class that I could adapt to various applications. Or perhaps a Tree class and a generic Node class. But before I start trying to re-invent the wheel, I thought I'd ask if anybody knows of something like this that has already been developed. Note that I'm not talking about a Tree GUI widget, but about a tree data structure, like a list, a queue, etc. -- Steve Ferg (steve at ferg.org) From mlh at vier.idi.ntnu.no Thu Jun 6 20:01:10 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Fri, 7 Jun 2002 00:01:10 +0000 (UTC) Subject: email: msg.add_payload not synonymous with msg.attach? Message-ID: I've been fiddling with the email package, and tried to construct a Message object, using add_payload to add the email body (It's a text/plain message). This worked fine, except for a deprecation warning telling me to use attach instead. But when I did, my program crashed with the message "TypeError: string payload expected: " (from Generator.py). Well... My payload was indeed simply a string, so I don't understand the error message. Also, I don't understand how this discrepancy could have occurred if, as the docs claim, add_payload and attach are synonymous. (The code is very simple -- basically just instantiating Message and adding a payload.) I'm using the email package from CVS (downloaded everything a day or two ago). -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From thenemesisjaguar at aol.com Thu Jun 6 20:43:30 2002 From: thenemesisjaguar at aol.com (TheNemesisJaguar) Date: 07 Jun 2002 00:43:30 GMT Subject: Movie on Mac Message-ID: <20020606204330.08563.00000041@mb-fr.aol.com> How do I get a movie or .bik file to open and play in a python program if I am using a mac. Tell me exactly (if it is on my desktop) From db3l at fitlinxx.com Thu Jun 6 21:07:33 2002 From: db3l at fitlinxx.com (David Bolen) Date: 06 Jun 2002 21:07:33 -0400 Subject: Installer vs py2exe: Windows DLLs References: Message-ID: Gordon McMillan writes: > _winreg.pyd didn't exist as of Py 1.5, but your patch looks > good. Perhaps I'm one of the only guys left, but I'm still successfully using installer 5 with Python 1.5.2 scripts, so if this would be the only reason to break that compatibility, it would be great to make it dynamic in some way so as to remain compatible while removing the dependency for later Python releases. -- -- David -- /-----------------------------------------------------------------------\ \ David Bolen \ E-mail: db3l at fitlinxx.com / | FitLinxx, Inc. \ Phone: (203) 708-5192 | / 860 Canal Street, Stamford, CT 06902 \ Fax: (203) 316-5150 \ \-----------------------------------------------------------------------/ From pinard at iro.umontreal.ca Sun Jun 30 10:36:46 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 30 Jun 2002 10:36:46 -0400 Subject: Preforked server in Python In-Reply-To: <3D1EB82C.1000501@awal.net.sa> References: <3D1EB82C.1000501@awal.net.sa> Message-ID: [rayed] > I am looking for module similar to SocketServer that prefork chlidren instead > of forking on each request. I wonder. Is there a way to transmit opened sockets to pre-forked children? -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From evan at 4-am.com Mon Jun 24 21:35:05 2002 From: evan at 4-am.com (Evan) Date: Tue, 25 Jun 2002 01:35:05 GMT Subject: Web templating/db tool with best designer/coder separation? References: Message-ID: <3D17C8D4.6090704@4-am.com> Bengt Richter wrote: > No one mentioned ZPT (Zope Page Templates), > http://www.zope.org//Wikis/DevSite/Projects/ZPT/FAQ > > and from the description, this would seem to have a real advantage over all of > the above, in that it uses attributes of html tags as opposed to special tags > that browsers or design tools won't generally understand and render usefully. > > This is touted as enabling the "round trip" from graphic designer to template logic > programmer and back using the same html source. I assume this is the "round trip" > Paul was referring to. To me, it seems a winning point for ZPT, though I don't know > how ZPT works out in practice. It works out quite well, if you're using Zope. I haven't seen much feedback from people using it independently of Zope, so I can't say one way or another in that case. > Opinions on ZPT? I like it, but then I would :-) My wife (graphic designer) and I were major contributors to the design of ZPT, so it suits our tastes. There are also plans in the works for a stylesheet-like extension to ZPT that would allow the logic (even the presentation logic) to be further separated from the HTML, without plunging the programmer into the dark mists of DOM-walking. Cheers, Evan @ 4-am From mgilfix at eecs.tufts.edu Fri Jun 14 10:05:47 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Fri, 14 Jun 2002 10:05:47 -0400 Subject: Writing a simple linux daemon type thing... In-Reply-To: ; from dysfate@gmx.de on Fri, Jun 14, 2002 at 03:35:42PM +0200 References: Message-ID: <20020614100547.D4109@eecs.tufts.edu> Wouldn't it be nice if some daemonizing code and basic log support was built into SocketServer? SocketServer aims at simplifying the infrastructure for people who don't need a full-blown server app. Might also be a nice addition for smaller projects who don't want to deal with this sort of thing... Might make an interesting patch IMHO. -- Mike On Fri, Jun 14 @ 15:35, Johannes Stiehler wrote: > I suppose you would have to redirect all output to stdout and log directly > to a specified log file. That's usually in the code for all daemonizing > processes. > The point is to completely unconnect the process from the console where it > was started. -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From gerhard.haering at gmx.de Wed Jun 19 18:58:00 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Thu, 20 Jun 2002 00:58:00 +0200 Subject: Windows versions of Python---pros and cons? In-Reply-To: <20020619154654.C619@ActiveState.com> References: <3D110B55.4D8AD7FA@astro.cornell.edu> <20020619154654.C619@ActiveState.com> Message-ID: <20020619225800.GB12907@lilith.my-fqdn.de> * Trent Mick [2002-06-19 15:46 -0700]: > My understanding is that for C extensions to work they must be built > with the same compiler as that used to build the Python with which they > will run. (I may be wrong. Someone please correct me if I am.) You are wrong. As long as you link to the python{major}{minor}.dll you are binary compatible, no matter which compiler you use. It's just a matter of providing an additional compiler option to distutils, like in: python setup.py build --compiler=mingw32 Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From whisper at oz.net Mon Jun 24 22:40:11 2002 From: whisper at oz.net (David LeBlanc) Date: Mon, 24 Jun 2002 19:40:11 -0700 Subject: Windows versions of Python---pros and cons? In-Reply-To: <7934d084.0206241750.221bbff2@posting.google.com> Message-ID: > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Andrae Muys > Sent: Monday, June 24, 2002 18:51 > To: python-list at python.org > Subject: Re: Windows versions of Python---pros and cons? > > > Tom Loredo wrote in message > news:<3D124575.2A1393FF at astro.cornell.edu>... > > Fernando P?rez wrote: > > > > > > Don't know if there's a misunderstanding here: > > > > Very likely! (On my part!) > > > > > cygwin is a unix-like > > > environment under Windows. > > > > Okay, my concern was that it wouldn't work with or be able to produce > > Windows binaries---like if I had to produce binary extension modules > > to ship to others, or a McMillan-ized install that used PythonWin > > and Tk or wxWindows. Cygwin is so huge that I got the impression > > it was a self-contained "subenvironment" so to speak, so I didn't > > realize I could use it to produce stuff that non-cygwin Windows users > > could use. > > If redistribution of executables that use the cygwin.dll is important, it should be noted that you can only do this if it's a GPL app (or maybe even that requires permission) - commercial redistribution definately requires a licen$e from RedHat. At one time it was $100 per developer. Dave LeBlanc Seattle, WA USA From olc at ninti.com Sat Jun 8 21:27:56 2002 From: olc at ninti.com (Michael Hall) Date: Sun, 9 Jun 2002 10:57:56 +0930 (CST) Subject: Removing ^M In-Reply-To: <004501c20efb$386ad1e0$0101010a@local> Message-ID: Python ... I love it! I knew about dos2unix but it's not on my box for some reason, and downloading and installing it seemed like overkill. This script worked like a charm. Thanks Mick On Sat, 8 Jun 2002, Chris Gonnerman wrote: > ----- Original Message ----- > From: "Michael Hall" > > > > I am trying remove ^M characters (some kind of newline character) from an > > HTML file. I've tried all sorts of string.replace and sed possibilities > > but the > > things just won't go away. Does anyone have a way of removing such > > characters? > > Unixoid OS, right? > > ------------------------------------ > > import sys > > data = sys.stdin.read() > > for ch in data: > if ch != "\r": > sys.stdout.write(ch) > > ------------------------------------ > > Run it like this: > > python cleaner.py destination.html > > Yeah, it could have a bunch more nice stuff... This is the Q&D > version. > > If the file is really large this won't be real efficient, but for > small files it's probably the best way. > > > Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net > http://newcenturycomputers.net > > > > -- -------------------------------- n i n t i . c o m php-python-perl-mysql-postgresql -------------------------------- Michael Hall ninti at ninti.com -------------------------------- From syn_uw at NOSPAM_hotmail.com Sun Jun 23 17:29:43 2002 From: syn_uw at NOSPAM_hotmail.com (Marc Bigler) Date: Sun, 23 Jun 2002 23:29:43 +0200 Subject: Zope Message-ID: <3D163DC7.739A83FD@NOSPAM_hotmail.com> Hello, I would like to know how I can generate a navigation bar in zope ? Something like that: when you are at the home page you get: Home When you are at a new page let say flowers you get: Home > Flowers and when you are at a subpage from Flowers called Orchidee you get: Home > Flowers > Orchidee Is that somehow possible examining the BASE0, BASE1,... and so on variables or is there a better method ? Any suggestions are welcomed ! Many thanks... Regards From ak at silmarill.org Sat Jun 1 10:28:23 2002 From: ak at silmarill.org (Andrei Kulakov) Date: Sat, 01 Jun 2002 14:28:23 GMT Subject: What does Python offer? References: Message-ID: In article , Solosnake wrote: > Hello > > I have beome curious about Python after playing a game called 'Severance - > Blade of Darkness', which uses python scripts. I know very little about the > language. I am a C++ programmer, and would like to ask the Python community >: > > What is unique or special about Python? > On one hand, it's very high-level (like perl or basic), so that it's very easy to quickly write a prototype; on the other hand, it is very scalable in the sense that you can write huge programs that perl and basic would be too "small" for. As someone said.. it bridges the gap between scripting and programming languages. > Why would it be useful to a games programmer? > You can quickly prototype a game in python and then decide whether you want to re-write it in C++ and most likely you'll find python is fast enough to use for most of the game except for the most expensive graphics code. > Could it be used for allowing users to customize games, eg reprogramming AI > bots etc? > Certainly! - Andrei -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From logiplexsoftware at earthlink.net Mon Jun 10 17:59:30 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Mon, 10 Jun 2002 14:59:30 -0700 Subject: if number is 1-2, 4 or 6-8 or 12-28, 30, 32... In-Reply-To: References: Message-ID: <20020610145930.5201949e.logiplexsoftware@earthlink.net> On Mon, 10 Jun 2002 21:25:06 +0000 (UTC) Gustaf Liljegren wrote: > I'm making a function that takes one integer and returns a boolean that > says if the integer matches a number in a certain group of numbers. This > group consists of single numbers aswell as ranges spanning thousands of > numbers. I'm looking for an elegant way to write this function. def isin(n, ranges): for r in ranges: try: s, e = r if s <= n <= e: return 1 except TypeError: if n == r: return 1 return 0 ranges = [(1, 999), 1004, 1006, (1050, 2000)] print isin(0, ranges) print isin(1, ranges) print isin(2, ranges) print isin(1000, ranges) print isin(1999, ranges) -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From db3l at fitlinxx.com Fri Jun 7 00:53:39 2002 From: db3l at fitlinxx.com (David Bolen) Date: 07 Jun 2002 00:53:39 -0400 Subject: Problem pickling class instance References: <3D000D77.7040008@erols.com> Message-ID: "Edward C. Jones" writes: > First I run mod.py then top.py. The latter give the message: > > AttributeError: 'module' object has no attribute 'A' > > Please explain the problem to me. Is there a standard work-around? Pickle only pickles object instance data, not the code representing the object (class) itself. Instead it includes a reference to the name of the class which the object data represents. When you pickled your instance of class A, that's the name used in the resulting pickle. It tries to instantiate a new instance of that object class when de-pickling in order to populate that instance with the instance data from the pickle. But when you try to load it, you've imported the mod module, so that same class is now known in your namespace as "mod.A", and thus pickle can't find the normal "A" class it expects for the data it is de-pickling. In this specific case, you could either: * Do a "from mod import A" (whether or not you're importing mod itself) * After doing an "import mod" somewhere before the pickle do "A=mod.A" Both of these will add a local module-level binding for the name "A" to the actual class in the module "mod". Note that you need to have these statements at module level since pickle expects to find the class definition at that level. Whether or not that's an appropriate overall solution depends on the problem. If a class is something that is going to be used in a pickle that is common between two parts of the system, it probably makes sense to isolate it to its own module (or package), and have all users of it be in a separate module and import that module to access the class. Either that or include the pickling/de-pickling operations both within the same module as the class so they are always local. -- -- David -- /-----------------------------------------------------------------------\ \ David Bolen \ E-mail: db3l at fitlinxx.com / | FitLinxx, Inc. \ Phone: (203) 708-5192 | / 860 Canal Street, Stamford, CT 06902 \ Fax: (203) 316-5150 \ \-----------------------------------------------------------------------/ From jepler at unpythonic.net Tue Jun 25 16:24:43 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 25 Jun 2002 15:24:43 -0500 Subject: bug in os.getgroups? In-Reply-To: <1025033152.17806.TMDA@nightshade.la.mastaler.com> References: <1025033152.17806.TMDA@nightshade.la.mastaler.com> Message-ID: <20020625202442.GG4435@unpythonic.net> This is liely to be because /tmp is "sticky": The `sticky' bit (S_ISVTX) on a directory means that a file in that directory can be renamed or deleted only by the owner of the file, by the owner of the directory, and by root. (from my system's manpage for stat(2)) You aren't root, so you can't delete this file in /tmp, which is typically a "sticky" directory. It doesn't matter that the group matches. I can observe this behavior on my own system from the shell: $ id uid=229(jepler) gid=15(man) groups=15(man),20(games),22(utmp),23(document) $ ll blah -rw-rw-r-- 1 root man 0 Jun 25 15:23 blah $ rm blah rm: cannot unlink `blah': Operation not permitted Jeff From gscott at peregrine.com Fri Jun 7 11:43:23 2002 From: gscott at peregrine.com (Gordon Scott) Date: Fri, 7 Jun 2002 08:43:23 -0700 Subject: Program to an interface, not an implementation Message-ID: "My next problem is on nearly the same page (17) of the GoF book: class versus interface (== type) inheritance, but in the python context. In C++ and Eiffel inheritance means both interface and implementation inheritance and in Smalltalk inheritance means just implementation inheritance. I don't know any of these languages." To understand this comment that they make you have to make sure you've got the previous distinction they make between an objects class and an objects type. An objects CLASS is an objects IMPLEMENTATION, while an objects TYPE is the INTERFACE or functions it has. Note that an object has ONE implementation but can have MANY types. Unfortunately the best example I have is the C++/Java vs Smalltalk/Python example. Perhaps if you said what languages you were familiar with we might be able to provide more relevant examples. But I hope you'll get enough to make sense of this... In C++ (and perhaps to some extent) Java, a class is simply a template for instantiating objects. Because of the static typing of C++/Java an objects class and type are directly tied together. The class directly defines an objects type You can't have one w/o the other. Meaning you can't try and call an operation on an object unless it was explicitly defined when the code was compiled. Example, if you want to have a piece of client code that performs the same operation on two different objects, those two different objects must both be subclasses of a common parent. This is class inheritance. C++ is going to force you to cast these objects to a specific type (the parent) before you can call the common method. So now you have two different objects of the same type, but they are forced to share implementation since you had to use class inheritance to do it. I'll avoid the technicalities of pure virtual/abstract classes here, the point is the same. Example again of the common widgets..in c++ the classes would be forced to inherit from a common parent. Class Widget would define Draw() operation. Class Button and Class Text would be subclasses of Widget and would override Draw(). If you want to place both of these objects into a collection you'd have to specifically cast them to a Wdiget. With Smalltalk and Python things are much different. Not only do you have dynamic typing, but classes are themselves objects that you can manipulate and call operations on. The dynamic typing brings us back to the answers from your previous question. Due to the dynamic typing, two objects only have to have the same operations defined to share types, REGARDLESS of their implementations or class relationships. You can TRY and call any operation on ANY object, if its there great all is well, if not you'll get a runtime exception. Example again in Python of file-like object. Assume your client code has a collection of objects that it performs reads and writes to. In python those objects can be sockets, files, or stringIO's since those object share the same type, ie all have read and write methods. However none of those objects share any sort of implementation, meaning they are not subclasses of a common ancestor. So class inheritance is standard classing and subclassing, whereas interface inheritance is multiple objects having the same type. With interface inheritance you can swap in and out different objects into your client code regardless of the implementation/class that they are, and all will work well. For C++ interface inheritance REQUIRES class inheritance. For Python/Smalltalk, it does not. -----Original Message----- From: Eric Brunel [mailto:eric.brunel at pragmadev.com] Sent: Friday, June 07, 2002 9:31 AM To: python-list at python.org Subject: Re: Program to an interface, not an implementation Egbert Bouwman wrote: > All your comments are crystal clear. Thanks. > > My next problem is on nearly the same page (17) of the GoF book: > class versus interface (== type) inheritance, but in the python context. > > "In C++ and Eiffel inheritance means both interface and implementation > inheritance" and > "in Smalltalk inheritance means just implementation inheritance". > I don't know any of these languages. > > Now in my simplistic worldview, if you inherit from a class, > you inherit everything, implementation and interface, > because the implementation defines the interface as well. > Even if all methods of the superclass only contain 'pass'. > But I may be wrong. I know C++ and I looked at SmallTalk a bit, and it seems the line between "implementation + interface" and "implementation only" inheritance is very thin... Apparently, it's quite directly related to strong typing and declarations. "Interface", in this context, seems to describe what's declared. So, as you noted in the beginning of your post, an "interface" is considered as a declared type. Since SmallTalk claims to have no types at all (which is also the case with Python...), they claim not to have such thing as an "interface", so obviously they cannot inherit it... In fact, I don't see the point in this: as you noted, when a class inherits from another, it inherits everything, implementation and interface. So in practice, it's not really significant. As I understand it, the only practical consequence of this distinction *may* be in the following case: class A: def m(self, i): pass class B(A): def m(self, i, j): pass In Python or SmallTalk, the preceding code is completely valid, so one could say that the "interface" of class A was not inherited by class B, since its method m has a different signature than A's method m. Trying to do the same thing in interface-inheriting languages would not have the same effect at all: it would either be forbidden, or even have stranger consequences. In C++ or Java, it would declare a *second* method, also called m, that would be distinguished from the inherited one by its number of parameters or their type: public class A { public int m(int i) { ... } } public class B inherits A { public int m(int i, int j) { ... } } ... o = new B(); o.m(1) // Calls A.m o.m(1, 2) // Calls B.m So, as you see, you probably can live without knowing anything about all this and still be able to do great stuff with whatever language you like :-). However, if anybody knows a bit more than me about implementation/interface inheritance, I'd be glad to learn (I happen to teach OO sometimes and I'd like to be able to answer this question precisely if it ever gets answered to me ;-). -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com -- http://mail.python.org/mailman/listinfo/python-list From eppstein at ics.uci.edu Tue Jun 25 12:49:20 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Tue, 25 Jun 2002 09:49:20 -0700 Subject: Suggestions for good programming practices? References: <3D18868A.4050002@mxm.dk> Message-ID: In article , aahz at pythoncraft.com (Aahz) wrote: > At the very least, I think you ought to rewrite your example as > > d = MyData( > firstName = 'Max M', > lastName = 'Rasmussen > ) I think rewriting it without the syntax error would be even better... -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From mgilfix at eecs.tufts.edu Fri Jun 7 16:44:50 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Fri, 7 Jun 2002 16:44:50 -0400 Subject: Simple pychecker question Message-ID: <20020607164450.G24428@eecs.tufts.edu> Pychecker doesn't seem to like named arguments (such as def f(f='blah'), or sometimes, it's handy in __init__). Why is that? Are they considered bad style in some respects? How about use in __init__ functions? -- Mike -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From deathtospam43423 at altavista.com Sun Jun 9 03:15:05 2002 From: deathtospam43423 at altavista.com (netvegetable) Date: 9 Jun 2002 07:15:05 GMT Subject: Newby: Dictionaries as file objects? Message-ID: Hi. I want to be able to store a list on a file object, and I want each list item to be a dictionary, complete with its own set of keys and values. I know I can store a list in a file object, simply by writing each item to the file as a string , and making sure there's a "\n" character at the end of it. When I read the file object again, I merely need to open it as "open(object).readlines()" and hey presto, my list is back in order. So is there a way to conveniently store a dictionary in each item as well? Ta. -- netvegetable at excite.com From pyth at devel.trillke.net Sat Jun 1 13:34:02 2002 From: pyth at devel.trillke.net (holger krekel) Date: Sat, 1 Jun 2002 19:34:02 +0200 Subject: Generating unique numbers? In-Reply-To: ; from aahz@pythoncraft.com on Sat, Jun 01, 2002 at 01:09:36PM -0400 References: <3CF7EBC8.4080802@verio.net> <3CF8FC1C.7060903@lindbergs.org> Message-ID: <20020601193402.A30380@prim.han.de> Aahz wrote: > In article <3CF8FC1C.7060903 at lindbergs.org>, VanL wrote: > > > >The reason why I am wanting keys that are more likely to be globally > >unique is because I will be building in hooks to make this outliner > >network transparent (using ZEO), making it possible for multiple > >outliners to be used together as a real-time collaborative tool. I > >want to be able to be able to have people merge stuctures that people > >have made in the standalone instance into a shared instance without > >tromping on another nodes data. > > > >Based on what people have said, I was thinking of using some > >combination of DateTime.gmticks and the id of the obj, making it (I > >think) extremely unlikely that there would be a collision. > > id() is very, very bad for any kind of persistent ID; I still think it's > at least very bad even if you add in any kind of time. > > No, if you want to trade IDs across a network, you need GUIDs (DCE > UUIDs). There's just no way around that. It's not the most perfect > system in the world, but it's better than any other generally available > scheme. do you know of a good implementation of DCE UUIDs in python and/or C? holger From maxm at mxm.dk Sun Jun 23 05:36:22 2002 From: maxm at mxm.dk (Max M) Date: Sun, 23 Jun 2002 11:36:22 +0200 Subject: Web templating/db tool with best designer/coder separation? References: Message-ID: <3D159696.9010209@mxm.dk> Jon Ribbens wrote: > In article , Bengt Richter wrote: > > Take a look at http://jonpy.sourceforge.net/ . It almost completely > separates code and HTML so that the designer and the coder do not > interfere with each other. I do understand that argument, but I almost certainly don't agree that it is of much use. In smaller one-of systems it makes sense, but in an app-server like Zope where the idea is that different components can be joined together to create a bigger application, there has to be stronger rules for layout and design of the components so that they will automatically fit into the bigger whole. Page template languages is the wrong approach in this regards. The development of the Cmf and Plone are good examples of this wrongfull approach. They make it easy to create one single type of application, but makes it very hard to re-use their components to build other types of applications. And I believe that the reason is that they are using pagetemplate languages to bind it together, which leads to this kind of design. I my experience, tools which separates logic from view in the "pagetemplate" approach is doing it wrong. The layout may be separated, but reuse of code/componentes greatly suffers from this approach. regards Max M From SBrunning at trisystems.co.uk Tue Jun 25 09:31:48 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Tue, 25 Jun 2002 14:31:48 +0100 Subject: Suggestions for good programming practices? Message-ID: <31575A892FF6D1118F5800600846864DCBD432@intrepid> > From: Emile van Sebille [SMTP:emile at fenx.com] > Aahz > > In Python 2.1.2 or higher, fire up the interactive interpreter and > type > > "import this". > > Except ActiveState's > > F:\Python22as>python > Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import this > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named this It isn't in the 2.2 series until 2.2.1, IIRC. Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From BPettersen at NAREX.com Thu Jun 20 19:13:10 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Thu, 20 Jun 2002 17:13:10 -0600 Subject: Are generators in nested functions possible? Message-ID: <60FB8BB7F0EFC7409B75EEEC13E201922151A9@admin56.narex.com> I've got the following code to generate the indicies of all nearest neighbours (span levels) in a multi dimensional qube: def generateIndexes(length=5, span=1): spanvalues = range(-span, span+1) def genInd(res, length): if length == 1: for val in spanvalues: yield res + [val] else: for i in range(length): for val in spanvalues: genInd(res + [val], length-1) return genInd([], length) However, when I try to use it it doesn't seem to return anything: >>> for i in generateIndexes(3): ... print i ... >>> I tried getting the iterator (or is it generator?) directly and calling next() on it, and it seems like it raises a StopIteration exception immediately: >>> g = generateIndexes(3) >>> g.next() Traceback (most recent call last): File "", line 1, in ? StopIteration >>> Can anyone help me understand what is going on here? -- bjorn From tdelaney at avaya.com Wed Jun 12 00:51:07 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Wed, 12 Jun 2002 14:51:07 +1000 Subject: Sorting list (maybe stupid) Message-ID: > From: Tim Peters [mailto:tim.one at comcast.net] > > [Delaney, Timothy] > > ... > > Personally, I think the implementation should be documented to > > use a stable sort - presumably mergesort (stable, minimal number of > > comparisons which is very important in Python). > > Write a mergesort as fast and memory-efficient as the sort > we've got and we'll consider it. I wasn't able to ... > you'll find that mergesort doesn't have enough of an > advantage there to make up for the speed it loses due to greater data > movement. I'm not willing in the slightest to dispute this ... My preference for a stable sort as default is that it is the "least surprising" result. But I don't see it as a wart that the implementation is not stable. Tim Delaney From skip at pobox.com Thu Jun 13 03:31:49 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 13 Jun 2002 02:31:49 -0500 Subject: Extension objects in Python 1.5 and 2.2 In-Reply-To: <20020613071813.GA16764@strakt.com> References: <20020613071813.GA16764@strakt.com> Message-ID: <15624.19045.700125.215173@12-248-41-177.client.attbi.com> Martin> How do I write extension objects so that they work in both Martin> Python 1.5 and the 2.x series? Michael Hudson has been working on a new include file named pymemcompat.h. Since it's only used for backward compatibility it's in the Misc directory. You can grab it from CVS: http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Misc/pymemcompat.h The idea is that you should be able to include it and program to the 2.3 memory api in code that runs under 1.5.2 or newer versions of the interpreter. -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From usenet-jun02 at puzzling.org Sun Jun 9 23:37:16 2002 From: usenet-jun02 at puzzling.org (Mary Gardiner) Date: Mon, 10 Jun 2002 03:37:16 GMT Subject: Sydney Australia: Python Interest Group Message-ID: Hi, A Python Interest Group has just started in Sydney under the banner of the Sydney Linux Users Group (SLUG). It's not restricted to Python under Linux and it is not restricted to SLUG members or people involved in SLUG. It meets on the third Monday of every month. Our second meeting is on June 17th at 7:00pm at the University of Technology, Sydney, room 2.3.16. The announcement is at http://lists.slug.org.au/archives/announce/2002/06/msg00003.html We don't have a webpage or mailing list independent of SLUG at present, if you're interested in further announcements you should watch http://www.slug.org.au/ or subscribe to SLUG's low volume announce list at http://lists.slug.org.au/listinfo/announce -Mary. -- Mary Gardiner From garrett at bgb.cc Mon Jun 10 14:51:43 2002 From: garrett at bgb.cc (Don Garrett) Date: Mon, 10 Jun 2002 18:51:43 GMT Subject: Newbie question communicating between 2 progs References: <3D046BF0.DC36542C@raplounge.de> <3D04A938.627EE705@engcorp.com> <3D04E8ED.C0708C2B@raplounge.de> Message-ID: <3D04F4EF.9040800@bgb.cc> Ben Thursfield wrote: > > Peter Hansen schrieb: > > >>The question is ambiguous. When you say "frames", the only thing >>that comes to mind is that you are running Python on client-side >>Internet Explorer under Windows, as scripts in two different parts >>of a window (the frames) simultaneously. I think you must have >>meant something different however. >> >>Could you please describe more about your environment? The >>term "frame" can mean a number of things. > > > That's right. I am running 2 cgi-scripts in two different frames of the > browser, the one should only print an array into the frame and the other one > communicates with a server. I decided to split the programm up because i want > to refresh the printing frame every second. The main frame changes the array > the second frame prints it out. My host has Python installed, so the > #usr/bin/python method works fine. > So the question is how can the programm responsible for printing out the array > access the array defined in the other programm. This is a suprisingly hard problem. The two programs are only running while the frame they handle is being generated. They shutdown and start up on each refresh request. I'm assuming you aren't using some form of server push, which has it's own problems. They don't save any state at all between refreshes of the same page. This means you have to solve the problem of having a program communicate it's state to itself! The good news is that when the program can communicate to itself, you can use the same mechanism to communicate with the other frame. However, the best answer to your question is to use cookies. The contents should be visible to all pages on the local site (you can control this) so they will allow you scripts to communicate with themselves and each other. You can store a fair amount in one (I'm not sure what the size limit is), and it can be binary. A few warnings. Some people disable cookies. This can totally break your site. All cookies are always uploaded as part of every page request everywhere they are visible. This means that you shouldn't make them too large or you will slow your site. If they are big, try to restrict cookie visibility to just the pages that really need them. You can specify where the cookies are visible when you create them. You can even store the state info in a database and use the cookie as a key to retreive it. When it comes to security, you cannot trust the contents of the cookie. The contents need to be validated the same way the values from a form would be. A tricky black hat can force the cookie contents to be anything they want. Two last bits of advice from an old web developer (well as old as a web developer can be). Try to avoid frames. They cause a lot of problems for both you and for your users. For example, they often break cross-browser, they can break bookmarks, and they can break printing. Try to avoid refreshes, especially frequent ones. Someone with a poor link will spend more time looking at an empty page that hasn't loaded than they will looking at your content. > I hope i described the problem better now. > > Ben > -- Don Garrett http://www.bgb.cc/garrett/ BGB Consulting garrett at bgb.cc From robin at jessikat.fsnet.co.uk Sun Jun 30 18:38:15 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sun, 30 Jun 2002 23:38:15 +0100 Subject: yield equivalent in C/JavaScript? In-Reply-To: <20020630203856.GA59010@hishome.net> References: <20020630180139.GA38821@hishome.net> <20020630203856.GA59010@hishome.net> Message-ID: <08$soXAXh4H9EwQ2@jessikat.fsnet.co.uk> In message <20020630203856.GA59010 at hishome.net>, Oren Tirosh writes >On Sun, Jun 30, 2002 at 09:05:37PM +0100, Robin Becker wrote: >> In message <20020630180139.GA38821 at hishome.net>, Oren Tirosh > l at hishome.net> writes >> >> very smart! That Duff did it Fortran as I recall. > >I don't think there is switch with case fallthrough in fortran. Duff's >device is most definitely a unique abuse of the C language. > >http://www.lysator.liu.se/c/duffs-device.html > > Oren > I stand corrected, I thought this was Ian Duff who did marvellous things with sparse matrices in Fortran. -- Robin Becker From boud at valdyas.org Sat Jun 1 18:36:47 2002 From: boud at valdyas.org (Boudewijn Rempt) Date: Sun, 02 Jun 2002 00:36:47 +0200 Subject: wxPython performance References: <3CF8E382.3A44F0DA@engcorp.com> <83ptzavk14.fsf@panacea.canonical.org> <3CF9408E.6015D2A@engcorp.com> Message-ID: <3cf94ca7$0$31235$e4fe514c@dreader1.news.xs4all.nl> Peter Hansen wrote: > > Other options might include making sure modules are not loaded > until they are needed, or loading them on a separate thread just > after the main program starts. > Convincing your users that they need to preload the libs might work too -- for instance by creating a 'server' component that should be started when the machine is booted that loads the lib. > None of which seems to help the OP. I'm curious why the Linux > implementation is so much slower than the Win32. My own machine > is _not_ fast! (It's only a 233 MHz Pentium MMX.) > wxPython has to load gtk, probably, and the bindings. The underlying gui library is already present in memory on a windows machine, leaving only the bindings to be loaded. I've also noticed that Python loads its own bytecode files rather more slowly than other files. So any pixmaps shouldn't be put in the code, but loaded separately. That can make quite a difference. -- Boudewijn Rempt | http://www.valdyas.org From hesterloli at hotmail.com Wed Jun 19 04:17:13 2002 From: hesterloli at hotmail.com (George Hester) Date: Wed, 19 Jun 2002 08:17:13 GMT Subject: python version? References: Message-ID: You don't even have the balls to include a valid email address when you write to me. -- George Hester _________________________________ "Gerhard H?ring" wrote in message news:slrnagvdp4.1sg.gerhard at lilith.my-fqdn.de... > George Hester wrote in comp.lang.python: > > I just cannot believe what I ran into in this newsgroup. [...] > > > .:\:/:. > +-------------------+ .:\:\:/:/:. > | PLEASE DO NOT | :.:\:\:/:/:.: > | FEED THE TROLLS | :=.' - - '.=: > | | '=(\ 9 9 /)=' > | Thank you, | ( (_) ) > | Management | /`-vvv-'\ > +-------------------+ / \ > | | @@@ / /|,,,,,|\ \ > | | @@@ /_// /^\ \\_\ > @x@@x@ | | |/ WW( ( ) )WW > \||||/ | | \| __\,,\ /,,/__ > \||/ | | | jgs (______Y______) > /\/\/\/\/\/\/\/\//\/\\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ > -- > mail: gerhard bigfoot de registered Linux user #64239 > web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 > public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 > reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From cbrown at metservice.com Tue Jun 4 21:47:08 2002 From: cbrown at metservice.com (Colin Brown) Date: Wed, 5 Jun 2002 13:47:08 +1200 Subject: manipulating child processes under Windows References: Message-ID: <3cfd6d6d$1@news.nz.asiaonline.net> "Douglas Alan" wrote in message news:lcptz7zw0m.fsf at gaffa.mit.edu... > > (2) What's the best way for me to solve the problem. I.e., what's the > best way to get my Python script to wait for the real program to > terminate? > > |>oug To locate a grandchild process and get its pid and handle on Win2000 you could examine the output of the freeware program "pslist -t" (www.sysinternals.com). After that use win32 routines as usual. Colin Brown PyNZ From chris_mk at hotmail.com Tue Jun 4 20:31:36 2002 From: chris_mk at hotmail.com (Christopher) Date: 4 Jun 2002 17:31:36 -0700 Subject: Problem with urllib.urlopen() References: Message-ID: Okay okay, here are links that 1) are short, 2) should work, and 3) show my problem. link 1: http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=PureSearch&db=PubMed&details_term=%28%22glucagon%22%5BMeSH%20Terms%5D%20OR%20glucagon%5BText%20Word%5D%29 link2: http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=Display&db=PubMed&details_term=%28%22glucagon%22%5BMeSH%20Terms%5D%20OR%20glucagon%5BText%20Word%5D%29&dopt=XML&query_key=1 Look at link2 in your browser, then look at what urllib.urlopen or .urlretrieve get. Thanks. Chris From vvainio at tp.spt.fi Thu Jun 13 08:38:32 2002 From: vvainio at tp.spt.fi (Ville Vainio) Date: 13 Jun 2002 05:38:32 -0700 Subject: Wanted: Potential Python Authors References: Message-ID: Ian Bicking wrote in message news:... > want to learn to program). An expert programmer has already created an > effective internal model and metaphor for programming, which is not > shared by technical writers who are not experienced programmers (or > experienced in the appropriate domain). This reminds me of many of the C++ books, where the author 1) Learned C 2) Looked up the class syntax and iostreams 3) Wrote a C++ book From loewis at informatik.hu-berlin.de Thu Jun 6 04:35:21 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 06 Jun 2002 10:35:21 +0200 Subject: Detecting OS and Window Manager References: Message-ID: "Andrew Wilkinson" writes: > Basically I want to have a program that hides itself in the taskbar > of whatever the user is running. Unfortunately there isn't (or at > least I don't know of) a portable way of doing this. I guess I'll > just have to mess around with looking for the environment variables > and then code it up for KDE/Gnome/whatever. So you really don't care that much if the user is running KDE or Gnome, but whether the gnome-panel is running or . This is different from "running Gnome", since you can combine the components of either package with each other, or, say, run gnome without running a panel. Regards, Martin From tim.one at comcast.net Tue Jun 11 21:22:57 2002 From: tim.one at comcast.net (Tim Peters) Date: Tue, 11 Jun 2002 21:22:57 -0400 Subject: lists and sequences In-Reply-To: <200206120026.g5C0QiD24559@localhost.localdomain> Message-ID: [Collin Monahan] >>> E.g. when does n^2 time happen using it? [Tim] >> alist.insert(0, newthing) physically moves len(alist) elements. Ditto [Dave Reed] > Just to be clear, these are order n, not order n^2. "in a loop of appropriate duration" was left to the reader's imagination, assuming they had one . The obvious intent of Collin's question was to discover which elementary operations required worse than O(1) time. His "e.g." was for the benefit of those who couldn't decipher his immediately preceding "What type of situations should be avoided when using it?". Knowing that an individual insertion or deletion "at the wrong end" can be expensive is responsive to what he really wanted to know. modern-bots-don't-take-human-words-at-face-value-ly y'rs - tim From sketerpot at chase3000.com Tue Jun 11 11:54:55 2002 From: sketerpot at chase3000.com (Peter Scott) Date: 11 Jun 2002 08:54:55 -0700 Subject: Cross platform spawning Message-ID: <659f82ff.0206110754.775490d9@posting.google.com> I am trying to make a script spawn a seperate process, like you would do like this on unix: os.system('python myscript.py myargument &') But the & at the end (to make a separate process) doesn't work on Windows. I want the script to run on both Linux (*BSD, whatever) and Windows. I didn't want to have to find out the path to the python interpreter, so os.spawnlp (with no blocking) sounded perfect until I saw that it wasn't available on Windows. Does anyone out there know what I can do in this situation? From metaliu at yahoo.com Fri Jun 7 20:08:14 2002 From: metaliu at yahoo.com (Bill) Date: Fri, 7 Jun 2002 17:08:14 -0700 Subject: Stretching Images Message-ID: I'm currently using Tkinter for GUI development. I have a Tkinter label which is showing an image. Is there a way for me to stretch the image to a specific size? I tried creating a Frame and specifying its width and height. The I tried putting the label in the Frame and packing it using expand=YES and fill=BOTH, but the Frame gets resized regardless. I also ran the method .grid_propagate(0) on the Frame to make the Frame keep its size attributes, but it keeps resizing regardless. Also, when I resize the Frame manually with the mouse afterwards, the label with the image just centers itself in the Frame. It doesn't stretch the image to fill the Frame like I want. Any suggestions on how I can get the proper effect I'm looking for? Thanks ahead of time, Bill From BPettersen at NAREX.com Thu Jun 20 19:51:14 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Thu, 20 Jun 2002 17:51:14 -0600 Subject: Are generators in nested functions possible? Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192158EEE@admin56.narex.com> > From: David Eppstein [mailto:eppstein at ics.uci.edu] > > In article , > "Bjorn Pettersen" wrote: > > > def generateIndexes(length=5, span=1): > > spanvalues = range(-span, span+1) > > > > def genInd(res, length): > > if length == 1: > > for val in spanvalues: > > yield res + [val] > > else: > > for i in range(length): > > for val in spanvalues: > > genInd(res + [val], length-1) > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ > This is a no-op. Did you mean > for x in genInd(res+[val],length-1): return x ? Thanks! I knew it had to be something simple (got your other post about using yield instead of return). -- bjorn From Chris.Barker at noaa.gov Wed Jun 26 13:08:39 2002 From: Chris.Barker at noaa.gov (Chris Barker) Date: Wed, 26 Jun 2002 10:08:39 -0700 Subject: Reference Count Confusion References: Message-ID: <3D19F517.290A9CDE@noaa.gov> Jeff Smith wrote: > import Numeric > import foo > > a = Numeric.zeros(1000000).astype('f') > b = Numeric.ones(1000000).astype('f') A little nit unrelated to your question: use: a = Numeric.zeros(1000000,'f') instead. The result is the same, but it creates the Float array directly, rather than creating an integer array, and then making a float array from that. > return Py_BuildValue("O", c); You might want to try: return Py_BuildValue("N", c); I'm a little fuzzy on al this too, but that works for me in a similar situation. From Extending and Embedding the Python Interpreter: "N" (object) [PyObject *] Same as "O", except it doesn't increment the reference count on the object. Useful when the object is created by a call to an object constructor in the argument list. Good luck, -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From tatebll at aol.com Fri Jun 7 09:14:34 2002 From: tatebll at aol.com (Bill Tate) Date: 7 Jun 2002 06:14:34 -0700 Subject: Creating Dynamic Web Pages (ZOPE) References: <46ca81a0.0206062016.789d3af6@posting.google.com> Message-ID: hwcowan at hotmail.com (Hugh Cowan) wrote in message news:<46ca81a0.0206062016.789d3af6 at posting.google.com>... [snip] > My scenario is typical where I need to put together a company Intranet > with a few front end Web-Pages where users can select information, > various links, and enter search criteria. The information is then > retrieved from the MS-SQL Server and the results are sent back to the > user. It's nothing fancy, no shopping carts, or remembering sessions > states, etc.. just really a simple front-end interface for > non-technical people to easily retrieve information. > > I don't know if ZOPE would fit my situation or not. I know that it is > / can be used to create complex E-commerce sites, but I am wondering > if it is overkill for what I need done. Would I be better off trying > to find some sort of RAD Web Tool instead (anyone have any good > suggestions) ? I think its safe to say that there are any number of tools that could fit the bill here including Zope. There are aspects of zope that can make your life much easier (e.g., zsql methods) but it does take some time to get used to it and everything it offers. Several recent books on the subject I think would be very helpful to you in this regard. If you go to zope.org, there is some information on using WYSIWYG tools such as Dreamweaver with zope that may also be of interest to you as well. I think zope works bests for you over the long haul where it is important to keep things well organized and well structured. The ability to collaborate amongst individuals is also a great strength. If these issues are important to you, then I would say that Zope would be an excellent choice. Good luck!!! From h.baumgartl at chello.NOSPAM.nl Thu Jun 20 19:50:49 2002 From: h.baumgartl at chello.NOSPAM.nl (Henry Baumgartl) Date: Thu, 20 Jun 2002 23:50:49 GMT Subject: application development - separating content from function References: Message-ID: "Chris Liechti" schreef in bericht news:Xns9233ED737D952cliechtigmxnet at 62.2.16.82... > tkinter or wxWindows come to mind, they should run right out of he box > without special efforts of your side on those platforms, they're portable. tkinter is not quite enough, tkinter + Tix would be an option, but I'm not too sure about Tix on a Mac wxWindows - same problem as far as wxPython on a Mac is concerned. Although I understand that a port is in the making. The question is then; Go for certain on tkinter and invest quite a lot of effort in the future to deal with the application complexity? Go for wxPython,which is very much 'under construction', accepting other dependencies (i.e. mxDateTime) that are not really needed, and more or less join the (fascinating) wx* effort? The same goes, more or less, for design aspects of manipulating generated data, and conversion of this data to information and knowledge for users. Pickling flat files is flexible and fun, but in terms of quantitive capacity, the ceiling is soon reached. XML is still far from mature and, the way things look, may well become an unwielding giant, generating far too much overhead to become really useful for complex applications. SQL - how much longer do we have to suffer this non-OO solution (if only it didn't work so well ;-)) > the standard module ConfigParser provides .ini style configuaration. this > is easy to save window positions, user settings in general and much more. Will certainly be very useful and used to its limit. Can't do it all though... > if you need real plugin with dynamic loaded functions and classes: > import+reload, module imp or execfile() can be used to load plugins (.py > files) at runtime. > > in that case you migh define a simple interface like making it mandatory > for an object to inherit from a special base class and or the file must > provide an init() function to register itself in the main app. Maybe it's unnecessary, but I have set myself the goal to minimize the use of variables. Considering the enormous flexibility Python allows each variable, and the extended functionality associated with the same, one can only assume that too many variables do not exactly equal optimised use of resources. Even considered writing scripts that will generate the personalised modules and use these in the actual user application. Does that make sense, or am I going a little over the top there? > > 3. And, last but not least ;-) the application needs to be > > multi-lingual. Following the advice of earlier respondents to my post (reduce complexity to manageable proportions), and your suggestions, I feel that this issue may wait until a later stage. Regards, Henry Baumgartl Dynamic Knowledge Network *Please remove .NOSPAM from my e-mail address when abswering me directly.* From twister at raplounge.de Mon Jun 10 05:05:52 2002 From: twister at raplounge.de (Ben Thursfield) Date: Mon, 10 Jun 2002 11:05:52 +0200 Subject: Newbie question communicating between 2 progs Message-ID: <3D046BF0.DC36542C@raplounge.de> Hi! I am running two python scripts in 2 different frames simultanously, and one of the programm needs to access a list defined in the other programm. How do i manage to access that list? I am thankful for any help. Ben From phr-n2002b at NOSPAMnightsong.com Sun Jun 30 06:18:03 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 30 Jun 2002 03:18:03 -0700 Subject: yield equivalent in C/JavaScript? References: <7xy9cxhlvx.fsf@ruckus.brouhaha.com> <7xit41i7i9.fsf@ruckus.brouhaha.com> <14ms5VAygsH9Eww2@jessikat.fsnet.co.uk> Message-ID: <7xelepnk84.fsf@ruckus.brouhaha.com> Robin Becker writes: > However the content.gz data has to be exactly compatible with gzip. My > experiments with Python-2.1/zlib on freeBSD give me a compressed string > that's slightly too long for some reason. As an example gzip --> 14099 > bytes while zlib.compress-->15008 bytes. > > Anyone know what I need to do to make zlib work properly in this > context? Or should I really be using the gzip module? You're probably better off using mod_gzip (an apache module that compresses the output automatically) rather than trying to compress from Python. Note that gzip encoding doesn't work so well in some IE versions. From emile at fenx.com Tue Jun 11 23:17:21 2002 From: emile at fenx.com (Emile van Sebille) Date: Wed, 12 Jun 2002 03:17:21 GMT Subject: Filling a space... References: Message-ID: <53zN8.164672$cQ3.4444@sccrnsc01> "Thor" wrote in message news:ae4v9h$3qg34$9 at ID-108351.news.dfncis.de... > Having this tupe: (2,3,4), which one would be the msot efficient way to get > this (parentheses ommited): > > 0,0,0 0,0,1 0,0,2 0,0,3 > 0,1,0 0,1,1 0,1,2 0,1,3 > 0,2,0 0,2,1 0,2,2 0,2,3 > 1,0,0 1,0,1 1,0,2 1,0,3.... > >>> t = (2,3,4) >>> [(a,b,c) for a in range(t[0]) for b in range(t[1]) for c in range(t[2])] I think I needed this once for a variable length tuple and parameterized it further... -- Emile van Sebille emile at fenx.com --------- From pyth at devel.trillke.net Mon Jun 10 21:41:34 2002 From: pyth at devel.trillke.net (holger krekel) Date: Tue, 11 Jun 2002 03:41:34 +0200 Subject: Why does Python mix OO concepts and non OO concepts for operation s on basic types? In-Reply-To: <3D054A98.3090708@bgb.cc>; from garrett@bgb.cc on Tue, Jun 11, 2002 at 12:57:11AM +0000 References: <3CEC1506.B0DA1787@earthlink.net> <3D054A98.3090708@bgb.cc> Message-ID: <20020611034134.O6609@prim.han.de> Don Garrett wrote: > Hans Nowak wrote: > > Besides, while Python is object-oriented, that isn't the only > > paradigm in the language. People coming from a functional > > background may find the len() function more natural than a > > method. > > > > YMMV, > > > > That's one thing I don't get. Why wasn't len() added as a member to the > various types during the recent rework that added so many other members to the > native types? maybe duplicating '__len__' as 'len' is too much, well, duplication? holger From pereira at cis.upenn.edu Mon Jun 3 21:28:58 2002 From: pereira at cis.upenn.edu (Fernando Pereira) Date: Mon, 03 Jun 2002 21:28:58 -0400 Subject: Graph distances, how can I speed it up? References: <33803989.0206030235.4134d33e@posting.google.com> Message-ID: On 6/3/02 1:12 PM, in article eppstein-347A24.10122403062002 at news.service.uci.edu, "David Eppstein" wrote: > In article , > Fernando Pereira wrote: > >> Dijkstra's algorithm is not a good choice here, because distances from all >> sources appear to be needed, not from a single source. > > Dijkstra is not a bad choice for all pairs shortest paths -- just repeat > it for each source in the graph. Think about the redundant traversal of some sub-graphs compared with Floyd-Warshall. Worst-case bounds are not so interesting here, as we are dealing with very particular graphs (WordNet). There's a huge literature on all-pairs shortest-distance algorithms that may be worth looking at, for instance . -- F From chris_mk at hotmail.com Fri Jun 14 17:00:26 2002 From: chris_mk at hotmail.com (Christopher) Date: 14 Jun 2002 14:00:26 -0700 Subject: PythonWin Problem! References: <1a52c7f1.0206131455.6df50cf8@posting.google.com> <3D0973C5.60407@skippinet.com.au> Message-ID: Ethan, >From the sound of it, I think Mark's analysis may be correct. I ran into the EXACT same problem a while back (which I was able to fix using 'Move'). Incidently, I'm not sure what exactly happened to cause my problem, all I can say is that the program was maximized when I ran a script with a typo (it used a try..except: loop when I meant try...except IndexError: and it locked up big-time). When I started it again, same as you, appeared in taskbar and tray but not on screen. I, however, was able to right-click, Maximize and that's how I figured it was off the screen. Good luck. Chris Mark Hammond wrote in message news:<3D0973C5.60407 at skippinet.com.au>... > Ethan wrote: > > I have been using ActiveState's port of Python for a while. PythonWin > > has been very helpful. Since a couple of days PythonWin developed a > > problem. When I start it, it appears in the taskbar and tray but does > > not appear on the screen. > > > > My Win98 did recently develop a problem which prevents me from getting > > the right click menu on the taskbar entries. This was secondary to > > some registry cleaning I did. I am not sure if this is related to > > Pythonwin problem but all others apps are working fine. I do get the > > menu for the tray icon and the "Close Program" window does not say > > "not responding" > > > > I uninstalled Python - deleted the Python21 folder and reinstalled. It > > did not help. Any suggestions? I really prefer PythonWin over IDLE. > > Pythonwin has probably somehow remembered it's screen location as off > the screen. > > Try deleting the "HKLM\Software\Python 2.1\Python for Win32" key from > the registry, and it should come back. > > Alternatively, from the task-bar select "Move", then use the arrow keys > to try and bring it back on screen (presumably with the "Left" and "Up" > keys) > > Mark. From leonw at gmx.net Mon Jun 17 12:54:50 2002 From: leonw at gmx.net (Leon Widdershoven) Date: Mon, 17 Jun 2002 18:54:50 +0200 Subject: Numeric and PIL: 1D array from 2D-tuple References: <3D0479FA.CEFFFAC2@ipm.fhg.de> Message-ID: <3D0E145A.1D21E730@gmx.net> Hi, you probably wish to use something like: text = Image.tostring() arr = Numeric.fromstring( text ) with a possible Numeric.reshape() if you wish to operate on something else than a 1D array. Regards, Leon Markus von Ehr wrote: > > Hi, > > I have a 2D tuple (an Image) and want to display it using ImageTk > in PIL. > Numeric.choose throws me an error: > > Traceback (innermost last): > File "", line 1, in ? > res = Numeric.choose(MyImage, mask) > ValueError: invalid entry in choice array > > Anybody knows how to get a 1D-array to construct the > ImageTk.PhotoImage? > > Thanks for any comments, > > Markus > > code: > > MyImage = self.cam.Image # MyImage is a 2D-tuple > > mask = [1 for i in MyImage] > > MyImage = Numeric.choose(MyImage, mask) > > new_image = MyImage.tostring() > self.im.fromstring(new_image, "raw", "RGBX", 0, -1) > > self.photoimage = ImageTk.PhotoImage(self.im) From rkr1410 at poczta.onet.pl Mon Jun 24 04:05:29 2002 From: rkr1410 at poczta.onet.pl (hellboy) Date: Mon, 24 Jun 2002 10:05:29 +0200 Subject: Newbie question (anyone programming with curses?) References: Message-ID: Thanks everyone, you helped me much. cheers From boud at valdyas.org Tue Jun 4 06:26:54 2002 From: boud at valdyas.org (Boudewijn Rempt) Date: Tue, 04 Jun 2002 12:26:54 +0200 Subject: Looking for a list subclassing example... References: Message-ID: <3cfc994e$0$3851$e4fe514c@dreader4.news.xs4all.nl> Shagshag13 wrote: > Hello, > > I'm looking for a list subclassing example, and i can't find it... > > Do you have one to show ? > I subclass lists in drift: http://www.valdyas.org/python/drift.html. -- Boudewijn Rempt | http://www.valdyas.org From martin at v.loewis.de Fri Jun 14 14:51:18 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 14 Jun 2002 20:51:18 +0200 Subject: a possibly foolish question about slices References: Message-ID: eddie at holyrood.ed.ac.uk (Eddie Corns) writes: > It frequently bugs me that you can't supply any number for b in [a:b] > to indicate spanning to the end of the string. [...] > So if the designers could fix this for version 2.3 I think we'll all be happy > :) Let me introduce Guido's time machine: you can always use sys.maxint as the value of b. Regards, Martin From giannivolontosky at TOGLIyahoo.it Fri Jun 14 16:13:40 2002 From: giannivolontosky at TOGLIyahoo.it (LoGan) Date: Fri, 14 Jun 2002 22:13:40 +0200 Subject: socket raw Message-ID: hi, id like to make a python script that use socket raw, i found the btk module but it cant handle received packets, it's really a good module but useful only to send, anyone could help me ? bye From cmathur at cis.poly.edu Mon Jun 17 14:34:08 2002 From: cmathur at cis.poly.edu (chandan mathur) Date: Mon, 17 Jun 2002 14:34:08 -0400 Subject: Cookie based authentication Message-ID: <3d0e2b38@news.poly.edu> I am still stuck on how to use client cookie (http://wwwsearch.sourceforge.net/ClientCookie/). I am trying to write a script that automatically logs in to http://www.fool.com/login.asp (SSL encryption) and downloads pages that i need. This is what i have tried so far: I logged in using internet explorer and opened the cookie file from windows explorer. Using set_cookie method in Cookies, i tried to set the cookie as best as i could.. (i probably did something wrong here). import ClientCookie import urllib2 import urllib request = urllib2.Request("http://www.fool.com/Login.asp") result = urllib2.urlopen(request) c = ClientCookie.Cookies() c.extract_cookies(result, request) # let's say this next request requires a cookie that was set in result request2 = urllib2.Request("http://my.fool.com/index.htm") c.add_cookie_header(request2) c.set_cookie(None,"Wookie=Ref=","FoolV=5&Uid=123146592&LastVisit=6%2F17%2F20 02+1%3A24%3A20+PM&FirstVisit=6%2F17%2F2002+12%3A27%3A22+PM&Username=westlab" ,"/","fool.com/",None,None,None,None,None,None) result2 = urllib2.urlopen(request2) print result2.geturl() print result2.info() # headers print result2.read() it gets the wrong page Thanx for your time Chandan From deathtospam43423 at altavista.com Tue Jun 11 13:47:37 2002 From: deathtospam43423 at altavista.com (netvegetable) Date: 11 Jun 2002 17:47:37 GMT Subject: Newby: Dictionaries as file objects? References: <7396d2b2.0206101224.61005b7f@posting.google.com> Message-ID: d_blade8 at hotmail.com (Lemniscate) wrote in news:7396d2b2.0206101224.61005b7f at posting.google.com: > I agree with David. However, depending on exactly you want to be > doing (and be able to do), you may want to look into the dbm modules > (such as dbm, dbhash, etc.). These are, surprise, database modules > but they allow for the storage of dictionary items..... Damn! dbm doesn't appear to be available for windows. And dhash, doesn't seem to allow me to store a dictionary as a value. Any other suggestions? > ......Now, pickle, > shelve, and the like are perhaps the best things for storing Python > objects (let's say a user-created object that contains mixed types) > but the dbm modules have their uses too, based on EXACTLY what you > want to do. Anyway, have fun. > > Lem > -- netvegetable at excite.com From cliechti at gmx.net Tue Jun 4 14:44:12 2002 From: cliechti at gmx.net (Chris Liechti) Date: 4 Jun 2002 20:44:12 +0200 Subject: directory References: <3cfcfd4a_1@news.iprimus.com.au> Message-ID: Gold Fish wrote in news:3cfcfd4a_1 at news.iprimus.com.au: > How to read the subdirectories in the directory > Support i have the directory /home/ which have some subdirectories > /home/sub1 > /home/sub2 > /home/sub3 > I am using os.listdir('/home/') to read in the list so it will be > ['sub1','sub2','sub3'] now i want to read inside the sub directory > sub2 once again i using os.listdir(os.listdir('/home/')[1]) but it > came out with an errors: not a file or directory. Can anyone tell me > what did i wrong. Anh how to fix it. (probably because os.listdir returns only file-/diectorynames and not paths) look at os.path.walk(), it's there to solve your problem ;-) chris -- Chris From syver-en+usenet at online.no Fri Jun 21 12:02:14 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Fri, 21 Jun 2002 16:02:14 GMT Subject: python mode for emacs Message-ID: I've downloaded the latest version from the python cvs tree, and it works fine. But... I am not too happy with the default face for the py-pseudo-keywords face (None, self....), and tried to change it by customizing the face, which worked fine until I restarted emacs and the face got it's ugly default. I looked at the font-lock hook and it seems that the face is overwritten each time python-mode is loaded with the keyword face. Is there a straight forward way of deciding how the py-pseudo-keyword-face should look? -- Vennlig hilsen Syver Enstad From peter at engcorp.com Sat Jun 29 08:30:39 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 29 Jun 2002 08:30:39 -0400 Subject: I'm an idiot References: Message-ID: <3D1DA86F.17869A93@engcorp.com> Matt Gerrans wrote: > > Oops, silly me, it was posted, but I think there was a typo in it: > > > for line in open('c:/temp/temp.txt'): > > is missing the ".readlines()" part. Under newer Pythons (2.2?) it's valid because the file object will be treated as an iterator and do the equivalent of xreadlines() (I think) automatically. Not the most readable, perhaps, as written, but valid. -Peter From jj at void.si Fri Jun 7 18:35:56 2002 From: jj at void.si (jj) Date: Sat, 8 Jun 2002 00:35:56 +0200 Subject: win32com map attributes to methods References: Message-ID: <3d0135be$1@news.perftech.si> > Have you tried using property() in py2.2? Yes, and its working, but i have to support older versions (at least py2.1). My second attempt is done by the Mark's book using _dynamic_ and DynamicPolicy, and its working for attributes. Ofcouse there is a BUT, but its not working with methods. Example o.Flush method is CALLED # correct syntax causes proper method call too + exception: o.Flush() TypeError: 'NoneType' object is not callable, metod call invokes correct method and because # ----------- code ----------- mport sys, string import pythoncom import win32com.server.util import win32com.client #import win32com.server.policy class ResponseIStream: '''Istream for response''' _public_methods_ = ['Write', 'Flush'] _public_attrs_= ['ContentType', 'Expires'] _com_interfaces_ = [pythoncom.IID_IStream, pythoncom.IID_IDispatch] def __init__(self): pass def set_Expires(self, value): print 'set_expires', value self.x = value def get_Expires(self): print 'get_expires' return self.x def write(self, x): print 'write:', x def Write(self, s): self.write(s) return len(s) def Flush(self): print 'Iresponse.Flush' def _dynamic_(self, name, lcid, wFlags, args): if wFlags & pythoncom.DISPATCH_METHOD: print 'method call', name item= getattr(self, name) return apply(item, args) elif wFlags & pythoncom.DISPATCH_PROPERTYGET: print 'propget' mname = 'get_'+name if hasattr(self, mname): return apply(getattr(self, mname), args) item = getattr(self, name) if callable(item): return #return apply(item, args) return item elif wFlags & pythoncom.DISPATCH_PROPERTYPUT: print 'propset' mname = 'set_'+name if hasattr(self, mname): return apply(getattr(self, mname), args) item = getattr(self, name) if callable(item): apply(item, args) return setattr(self, name, args) if __name__=="__main__": o = win32com.server.util.wrap(ResponseIStream(), usePolicy = win32com.server.policy.DynamicPolicy) o = win32com.client.Dispatch(o) o.Flush print 'second flush !!!! is not working' o.Flush() o.Write('test') print 'set' o.Expires = 'test value' print 'get' print o.Expires xml = win32com.client.Dispatch("Msxml2.DOMDocument") xml.loadXML('streaming') xml.save(o) r = ResponseIStream() r.Expires = 9 print r.Expires From fperez528 at yahoo.com Thu Jun 27 14:44:23 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Thu, 27 Jun 2002 12:44:23 -0600 Subject: connecting embedded Python audio samples with NumPy? References: <3D1B2603.26EA9A9C@fxtech.com> Message-ID: Paul Miller wrote: > I have a C app that reads audio data, and I'd like to pass this audio > data in array format to Python functions so I can use it with NumPy. > > I have this working right now - generating a float array from the sample > stream. But I want to put this array into a form usable by the FFT > functions. I've read over this paper: > > http://www.onlamp.com/pub/a/python/2001/01/31/numerically.html > > Which indicates I need to put my 1D sample stream into a 2D array. Can > anyone elaborate more on this? I'm wondering if I should provide the > array pre-made for FFTs from my C code, or I should build the 2D array > from the 1D array I have in Python. I don't see why you need to convert the data stream to a 2d array. In fact, since you know your data is real, you can use FFT.real_fft() and FFT.inverse_real_fft() for the conversions, which guarantees that after processing you get real data back (without coefficients with small imaginary parts). That is, of course, as long as in your processing you don't break the symmetry assumptions on the fft data for a real signal :) FFT comes with Numeric, so with a properly installed numeric it imports straight out. Here's a quick example: In [1]: x = frange(0,2*pi,npts=8) In [2]: y = sin(x) + sin(4*x) In [3]: import FFT In [4]: yhat = FFT.real_fft(y) In [5]: yhat Out[5]: array([ -6.66133815e-16+0.j , 1.32978452e+00-3.21038382j, -8.67767478e-01+0.86776748j, -2.41187287e+00+0.99903045j, 3.89971165e+00+0.j ]) In [6]: y2 = FFT.inverse_real_fft(yhat) In [7]: y2 Out[7]: array([ -5.55111512e-17, 3.47947743e-01, 1.75675939e+00, -5.41044173e-01, 5.41044173e-01, -1.75675939e+00, -3.47947743e-01, -1.27675648e-15]) In [8]: y2 - y Out[8]: array([ -5.55111512e-17, -5.55111512e-17, 2.22044605e-16, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, -5.55111512e-17, -5.21501245e-17]) So within the accuracy of a C double, it all works as expected. Cheers, f From bh at intevation.de Sat Jun 22 13:05:21 2002 From: bh at intevation.de (Bernhard Herzog) Date: 22 Jun 2002 19:05:21 +0200 Subject: shallow copy vs. deep copy References: Message-ID: <6qofe35jn2.fsf@abnoba.intevation.de> Chris Liechti writes: > > on the other side i could also: > > > > new.__dict__ = old.__dict__.copy() > > that's what i would call a swallow copy. A european or an african swallow? SCNR ;-) Bernhard -- Intevation GmbH http://intevation.de/ Sketch http://sketch.sourceforge.net/ MapIt! http://www.mapit.de/ From gusraan at terra.com.br Sun Jun 16 17:38:00 2002 From: gusraan at terra.com.br (Raphael Ribeiro) Date: 16 Jun 2002 14:38:00 -0700 Subject: Visual Python Message-ID: <337619fa.0206161337.546a958f@posting.google.com> When i go to tools/debug and the ms-dos prompt start appears , an error message appears , anyone knows why? From peter at engcorp.com Sat Jun 1 17:45:50 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 01 Jun 2002 17:45:50 -0400 Subject: wxPython performance References: <3CF8E382.3A44F0DA@engcorp.com> <83ptzavk14.fsf@panacea.canonical.org> Message-ID: <3CF9408E.6015D2A@engcorp.com> Kragen Sitaker wrote: > > Peter Hansen writes: > > How fast do you need it to be? (That's a serious question. > > Are you planning to open and close the application so frequently > > that six seconds is unacceptable?) > > From a human interface perspective, having to wait six seconds for a > response to a command (including "start program") is annoying; this is > the reason for "splash screens". You don't want people to be annoyed > every time they start your program. I realize that. That's why I was directing the discussion towards alternatives, such as splash screens... :-) Other options might include making sure modules are not loaded until they are needed, or loading them on a separate thread just after the main program starts. None of which seems to help the OP. I'm curious why the Linux implementation is so much slower than the Win32. My own machine is _not_ fast! (It's only a 233 MHz Pentium MMX.) -Peter From mhammond at skippinet.com.au Sun Jun 16 18:57:14 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sun, 16 Jun 2002 22:57:14 GMT Subject: MS Word -- finding text References: Message-ID: <3D0D1862.5050708@skippinet.com.au> Mike Brenner wrote: > The COM objects (like Project, Word, Excel, etc.) sometimes return > stuff in Unicode format. When they do, the python str() function dies > when converting non-ASCII unicode characters. > > To avoid this problem, I use the following conversion routine. After > making the necessary check for None, it attempts a quick conversion > str() first. When necessary, it slowly goes through each character, > handling the exceptions that are raised. > > The default is a prime because that is the most common character that > hits me in Word and Excel documents. Instead of coding it as an ASCII > single-quote characters, these applications code it as a more > "beautiful" character, so it kills the python str() function. Note that you should be able to convert a Unicode object obtained from a COM object simply by saying: s = u_ob.encode("mbcs") And should never (OK OK - rarely :) fail. If it _does_ fail, then it means that the string can not be described in the mbcs code page, and you will need to determine the appropriate code page youself. Mark. From mcfletch at rogers.com Mon Jun 3 12:38:41 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 03 Jun 2002 12:38:41 -0400 Subject: List References: <20020602205610.31575.qmail@linuxmail.org> <009b01c20a7e$12a5ad80$0101010a@local> <3cfb07cf_1@news.iprimus.com.au> Message-ID: <3CFB9B91.2010002@rogers.com> Okay, this is pretty basic stuff, I'll just go over it quickly and refer you to http://www.python.org/doc/Newbies.html which has introductory documentation for Python. You'll particularly want to work on understanding the list as a data type and the manipulations you can use when working with it. Imagine you have a list of elements returned by the function "into" (from the previous message): pageData = [['p1','p2','p3'],['p4','p5','p6'],['p7','p8','p9'],['p10']] You generate this list when the user requests the page, and look at the query value in the CGI environment to determine which page of results the user wants to retrieve: requestedPage = '2' Now, you want requestedPage to show up as an integer index into your list of pageData, that is, it tells you what element in the compound list pageData should be used for generating the page. requestedPage = int(requestedPage) (You'd want to do some error-checking there, making sure it really is an integer, catching a ValueError will work). Now, to get the values for the particular page, you index into the pageData list using your new index: pageData[ requestedPage ] Again, you want to do error checking catching an IndexError works there. If you want to know the total number of pages, it's: len( pageData ) You then go about generating your page, being sure to enable/disable the forward (requestedPage-1)/backward (requestedPage+1) links depending on whether the user is on the first/last page (BTW: you can offer links to "first" and "last" on every page just by using 0 (first) and -1 (last) as the link indices). Note: if there are no results at all, even 0 won't work as an index, you'll need to catch that condition and generate a "no results" page. Hope this helps, Mike Gold Fish wrote: ... > Sorry for the very stupid question but i still don't get my goal, that's is > using Mike C. Fletcher method i will generate the list of elements again > and don't know what size it is. For example : > [['p1','p2','p3'],['p4','p5','p6'],['p7','p8','p9'],['p10']] > I want to seperate this list again in order to using them later .It look > like you go to the realestate agent website and find the list of property > then you just want to display 3 properties per pages. And you can go to > other pages which also contain 3 properties as well until the last pages > which has only 1 items. For example: > Page 1: ['p1','p2','p3'] > Page 2: ['p4','p5','p6'] > Page 3: ['p7','p8','p9'] > Page 4: ['p10'] > I didn't sleep well due to this problem Can any help me. > _______________________________________ Mike C. Fletcher http://members.rogers.com/mcfletch/ From peter at engcorp.com Mon Jun 24 21:08:58 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 24 Jun 2002 21:08:58 -0400 Subject: Suggestions for good programming practices? References: Message-ID: <3D17C2AA.F694F74@engcorp.com> Dianne van Dulken wrote: > > if anyone has a list of things that they consider as good programming > practice in Python (I thought this might be an interesting topic for > discussion, anyway) I'll amend my previous claim to point to testing as a very useful part of Python development. I don't mean running your code manually after the fact, either. I mean proper unit testing, which exercises as much of the code in small pieces as you possibly can. Unlike with statically typed languages, Python cannot check that you are not, for example, trying to pass an integer into a routine that can only accept a string until you actually execute the code. You don't get the error on compilation as with C for example. It can become frustrating if you have to run the code manually each time you make a change and possibly go through a large sequence of steps before you get to the part you want to test. Therefore, learn to make your code testable. Write it in small modular pieces and have good tests for each. When you make a change, run the tests again and they will tell you whether you've screwed up anything. If something slips through and you find a bug, go back and write another test that fails on the same problem, then fix the code (making the test pass). No, not many people actually do this. I've found it highly effective, however, and it more than makes up for any limitations that might exist because of the dynamic nature of Python compared to statically typed languages. This all comes from Extreme Programming, of course, but you can easily benefit from proper unit testing even without other changes to your development process. And most of this advice actually applies to any language, but I think Python can take advantage of it even more than most. -Peter From phd at phd.pp.ru Wed Jun 5 10:09:40 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Wed, 5 Jun 2002 18:09:40 +0400 Subject: new SmallEiffel elj-win32 release (-0.74) In-Reply-To: <8cd6cc47.0206050602.1d69a237@posting.google.com>; from geoff@elj.com on Wed, Jun 05, 2002 at 07:03:00AM -0700 References: <8cd6cc47.0206050602.1d69a237@posting.google.com> Message-ID: <20020605180940.C26674@phd.pp.ru> On Wed, Jun 05, 2002 at 07:03:00AM -0700, Geoff Eldridge wrote: > A new version of elj-win32 has been prepared and is now available from .. What does it have with Python? Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From bit_bucket5 at hotmail.com Thu Jun 6 15:06:34 2002 From: bit_bucket5 at hotmail.com (Chris) Date: 6 Jun 2002 12:06:34 -0700 Subject: Using AT on XP to run python script - MARK HAMMOND PLEASE READ References: Message-ID: Interesting findings. I know mine didn't work bcs the script I want AT to execute sends me an email. The script sends an email, then I want it to run another AT command to set itself up to run again at a later time. But I can't get it to work. If I run the script manually, it runs, sends email and executes the proper AT command. But when AT fires off the task the script set up, nothing happens and no more AT commands are set up. "David LeBlanc" wrote in message news:... > This is most curious, but I believe the commands _are_ getting executed! > > I tried the following (assume time is 16:30) "at 16:32 pythonw > j:\python22\tools\idle\idle.py" (without the qoutes of course). At the > appointed time, there was disk activity, but no idle window popped up (idle > was chosen just to get something to pop up!). However, there _was_ a pythonw > process running in the task manager! I think there might be a way to attach > a console or get access to the GUI, but i'm not sure - maybe Mark Hammond > might have a clue (he being the Python Win guru :) ). > > I tried the following: > #at_test.py > import sys > import time > > tst = open("testfile.txt", 'a+') > > tst.write(time.asctime() + "\n") > > tst.close() > > put into an 'at' job as: at xx:xx python j:\python22\at_test.py > > I expected the output from this to be in j:\python22, but to my surprise, it > was in c:\winnt\system32 where cmd.exe resides! testfile.txt contained the > exact time the 'at' job was set to run at too! > > I suspect your last example that produced no visible output did in fact work > :) > > In any case, it works - now if one could just get visible output! > > David LeBlanc > Seattle, WA USA > > > -----Original Message----- > > From: python-list-admin at python.org > > [mailto:python-list-admin at python.org]On Behalf Of Chris Stromberger > > Sent: Tuesday, June 04, 2002 17:35 > > To: python-list at python.org > > Subject: Using AT on XP to run python script > > > > > > I'm having trouble getting AT on XP to run a python script for me. > > Have tried: > > > > at xx:xx "c:\python21\python.exe c:\scripts\script.py" > > at xx:xx "start c:\scripts\script.py" > > at xx:xx "c:\scripts\script.py" > > > > and get "the system cannot find the file specified" for the first two. > > The last version does nothing apparently--no error indication or > > anything. > > > > I imagine it is related to user accounts and such. Anyone have any > > pointers? > > -- > > http://mail.python.org/mailman/listinfo/python-list From nico at tekNico.net Sat Jun 8 03:19:56 2002 From: nico at tekNico.net (Nicola Larosa) Date: Sat, 08 Jun 2002 09:19:56 +0200 Subject: Medium to Large Scale Python Deployments References: <38C31EBA-79A4-11D6-9A7D-003065B33450@intersight.com> <3D003EC7.C72D27BE@engcorp.com> <3D006320.5040805@web.de> <3D00A209.EC24F671@engcorp.com> <3D0140BF.A239E39E@engcorp.com> Message-ID: <3D01B01C.3000303@tekNico.net> > (we rarely use doc strings, having avoided that aspect of > Python when writing on an embedded system where all the .pyc > files were stored in our limited 1MB of flash along with the > interpreter...). python -OO ? -- "Too much cleverness in the parser can turn against you." Guido Van Rossum Nicola Larosa - nico at tekNico.net From gerhard at bigfoot.de Tue Jun 18 01:35:31 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 18 Jun 2002 05:35:31 GMT Subject: unicode strings and strings mix References: Message-ID: Roman Suzi wrote in comp.lang.python: > Is there any way to define "default" encoding Yes. > so the following error will not happen? > >>>> unichr(0x3345) + "?????" > Traceback (most recent call last): > File "", line 1, in ? > UnicodeError: ASCII decoding error: ordinal not in range(128) 'x' and 'A' are in the ASCII range, so this shouldn't produce an exception. I also cannot reproduce it with sys.getdefaultencoding() == "ascii". Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From rhymes at myself.com Sat Jun 29 14:54:43 2002 From: rhymes at myself.com (Rhymes) Date: Sat, 29 Jun 2002 20:54:43 +0200 Subject: private References: <7x8z4y9eex.fsf@ruckus.brouhaha.com> Message-ID: Thanks for the reply, you all -- Rhymes rhymes at myself.com " ride or die " From spokra at home.com Mon Jun 10 22:20:44 2002 From: spokra at home.com (Steven Pokrandt) Date: 10 Jun 2002 19:20:44 -0700 Subject: python and shared libaray Message-ID: I have a vendor supplied .so file, header file and docs. I would like to use this .so file in python but don't have the src. Is it possible to link this library ie: import filename.so when I try the python complains about no init function.. can I add this to the .so without having the src? can someone point me to a howto? please send message to the following address.. spokra (AT) attbi (dot) com you get the meaning of the email address, and hopefully the spammers don't From j.bodemann at gmx.de Sat Jun 1 11:17:07 2002 From: j.bodemann at gmx.de (Joern Bodemann) Date: Sat, 1 Jun 2002 15:17:07 +0000 (UTC) Subject: Jython: Getopt does not throw exception - 1 attachments Message-ID: Hello all, does anybody know why the following code does not throw an excetion if the script is started without parameter? jython question.py begin 644 question.py M:6UP;W)T(&=E=&]P=`T*:6UP;W)T('-Y7,N97AI="@P*0T* M"0T*=')Y. at T*"6]P=',L(&%R9W,@/2!G971O<'0N9V5T;W!T*'-Y > Hmmm... the meta- in "metaclass" or "metaphysics" really has > no relation to the original Greek, which means "with", or > "among" (as in "metatarsus" - the bones in the foot which > lie next to the tarsus). So whatever antonym you come up > with can't have anything to do with the original etymology > of the prefix... Erm... How about mundane? Or actual? > Intrinsic? Essential? Or even "per se"....? In ancient Greek, it also meant "over", like Latin "trans"... e.g. "over the river". I think the "meta" in "metaclass", "metadata" etc is related to this meaning. Cheers, -- Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) # decode for email address ;-) The Pythonic Quarter:: http://www.awaretek.com/nowak/ From boud at valdyas.org Sat Jun 15 05:18:09 2002 From: boud at valdyas.org (Boudewijn Rempt) Date: Sat, 15 Jun 2002 11:18:09 +0200 Subject: IDE recommendations?? References: Message-ID: <3d0b06bd$0$52043$e4fe514c@dreader3.news.xs4all.nl> Detlev Offenbach wrote: > Hi all, > > I have googled this list for IDE recommendations, but have found none > that satisfied me. I am looking for an IDE that allows development of > Qt/KDE applications using Python. So far I have found BlackAdder. > However, it looks as if development has stalled. I could use individual > applications (e.g. qt-designer for gui, scite as an editor, pyuic, ...), > but this lacks some comfort. I would appreciate any recommendation for a > suitable IDE > I've tried to use most IDE's out there -- from Pythonwin to Pythonworks. None was really comfortable, except for Wing IDE, which is really powerful. It doesn't include integration of a GUI designer, though, which makes it little more than a glorified editor/debugger (but _very_ glorified). At one point there was a version of KDevelop that supported Python development, but that has disappeared, it seems. I use bash & XEmacs & Designer nowadays, and that gives me a fair productivity. -- Boudewijn Rempt | http://www.valdyas.org From gerhard at bigfoot.de Sun Jun 9 08:47:11 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 9 Jun 2002 12:47:11 GMT Subject: Logic programing with python? References: <3D0343EA.4070100@gmx.de> Message-ID: Ingo Linkweiler wrote in comp.lang.python: > Hello, > > is it possible to use Python as "logic lanuage" ? > I have found the project "formula", a logical language coded with > python, and Chris Meyers "Prolog interpreter". > I have heard from "holmes", but can not find any information about it. > > Do you know other sources? http://www.logilab.org/python-logic/ Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From pyth at devel.trillke.net Mon Jun 17 11:37:31 2002 From: pyth at devel.trillke.net (holger krekel) Date: Mon, 17 Jun 2002 17:37:31 +0200 Subject: what *is* a class? In-Reply-To: <20020617143525.GB8814@unpythonic.net>; from jepler@unpythonic.net on Mon, Jun 17, 2002 at 09:35:26AM -0500 References: <3D0DBC87.B1BDEB2D@ifib.uni-karlsruhe.de> <20020617143525.GB8814@unpythonic.net> Message-ID: <20020617173731.Q15079@prim.han.de> Jeff Epler wrote: > This is not the Pythonic style. Even when it would sometimes be > convenient, methods do not tend to return "self". That's why these > don't work: > > # Iterate the sorted list > for item in l.sort(): ... > > # Create and pack a widget > x = Label(text="Wibble").pack() > > # Dump two objects to a pickle > p = pickle.Pickler() > p.dump(obj1).dump(obj2) > > One motivation for this is that if list.sort returns None, nobody > will write > for item in l.sort(): > thinking that a copy of l is sorted. It'll immediately blow up. I agree that this is a good thing. But it wouldn't hurt to have reverse, sort, extend as standalone functions somewhere in the stdlib. They would return a copy, so that you can write: # iterate over a sorted copy of a list for item in sort(l): ... reverse could probabally be made an iterator so that it gets really cheap to write: for item in reverse(l): ... And i think these functions should work with tuples and strings also. cheers, holger From jepler at unpythonic.net Tue Jun 4 12:31:47 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 4 Jun 2002 11:31:47 -0500 Subject: self In-Reply-To: References: Message-ID: <20020604113147.C24006@unpythonic.net> On Tue, Jun 04, 2002 at 12:15:22PM -0400, Vojin Jovanovic wrote: > Would it not be more logical > to just use the name of the variable like it is for example in C++? Nope. (Hint: http://www.python.org/cgi-bin/faqw.py?req=show&file=faq06.007.htp) Jeff PS we love it this way. You will too. From peter at engcorp.com Tue Jun 25 23:38:16 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 25 Jun 2002 23:38:16 -0400 Subject: Reminder of a python Project. References: <2218.941T781T12224051threeseas@earthlink.net> Message-ID: <3D193728.663CA774@engcorp.com> Timothy Rue wrote: > > First off, it's ok that I got such a high level of resistance to my > initial posting here about this project. Obviously the level was not high enough. Sorry, we'll try harder. > $81 Billion = 31% of software development gets cancelled before complete > $59 Billion = 53% of software development has cost over-runs of 189% > 16% success - project success and failure ratio [...] > My 1997 estimate of software failures all around (total of industry and > consumer level development and use): Low estimate of 300 Billion. Your information is out of date. Agile software development processes developed since 1997 have improved the success rate of software development projects to the point where this is no longer an issue. It is now possible to deliver software with a 96% success rate, for less cost than previous methods, with greater sustainability for the development teams, and at a much higher quality level than appeared possible in the past. I'm afraid there is no longer any need for an autocoder. -Peter From a.schmolck at gmx.net Mon Jun 17 17:41:31 2002 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 17 Jun 2002 22:41:31 +0100 Subject: "Fatal Python error: GC object already in linked list" Message-ID: Just got the following in an interactive session: >>> reload(awmstools) Exception exceptions.RuntimeError: 'maximum recursion depth exceeded' in ignored Fatal Python error: GC object already in linked list Process Python aborted Any ideas as to what might be the cause? alex From graham at effectif.com Wed Jun 5 19:44:32 2002 From: graham at effectif.com (Graham Ashton) Date: Thu, 06 Jun 2002 00:44:32 +0100 Subject: Compiling Python References: Message-ID: On Wed, 05 Jun 2002 11:31:19 +0100, TuxTrax wrote: > My question is this; I realize that Python compiles to bytecode > automatically as part of the interpreters tokenization run, but is there > a way to permanently compile python code outputting to an executable > binary? Not exactly, in general. Have a look for py2exe, psyco, and pyrex for info on some of the things that you can currently do. GvR alludes to compilation being of interest in the future in a recent interview: http://www.onlamp.com/pub/a/python/2002/06/04/guido.html -- Graham Ashton From debl2Nonospawhammy at bellatlantic.net Sat Jun 15 22:27:25 2002 From: debl2Nonospawhammy at bellatlantic.net (David Lees) Date: Sun, 16 Jun 2002 02:27:25 GMT Subject: Minor install annoyance on Activestate Python 2.2.1 build 222 Message-ID: <3D0BF7B4.21096694@bellatlantic.net> I just downloaded and installed the latest ActiveState build of Python 2.2.1 off their site and could not get it to install on my win98SE box even though I had previously run the windows installer. The problem turns on to be that the name of the file you download is ActivePython-2.2.1-222.msi.exe Simply remove the '.exe' extension so the name is: ActivePython-2.2.1-222.msi and the installation goes just fine. David Lees From skip at pobox.com Mon Jun 10 11:28:54 2002 From: skip at pobox.com (Skip Montanaro) Date: Mon, 10 Jun 2002 10:28:54 -0500 Subject: Source formatting for long expressions. In-Reply-To: <87hekdxypd.fsf@twistedmatrix.com> References: <87hekdxypd.fsf@twistedmatrix.com> Message-ID: <15620.50614.922005.965796@12-248-41-177.client.attbi.com> Chris> Does anyone know of a tool that will beak up a very, very long Chris> expression like this into multiple lines with sane indentation? How about the pprint module? -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) Boycott Netflix - they spam - http://www.musi-cal.com/~skip/netflix.html From peter at engcorp.com Tue Jun 11 01:34:00 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 11 Jun 2002 01:34:00 -0400 Subject: Correct code/unit testing (was Re: Efficient python programming...) References: Message-ID: <3D058BC8.1C4C3DFA@engcorp.com> "Delaney, Timothy" wrote: > > > From: Peter Hansen [mailto:peter at engcorp.com] > > I have to confess I have never seen a successful code review, nor > > an environment in which they were used regularly and which had a > > high level of code quality. Clearly as a result I'm fairly biased > > against them -- I should keep a more open mind on the issue perhaps. > > I presume you mean a full, formal review by a group for a large piece of > code? In that paragraph, yes, I meant that. > I'm certain that with your experience with XP, you have seen and taken part > in *many* successful reviews (where success means the code is improved as a > result). I think I tried to say that later in the message. If pair programming is considered the same as "review", then I agree. Of course, pair programming is _much_ more than review-as-you-code, but that's another topic. -Peter From uwe at rocksport.de Mon Jun 3 12:10:40 2002 From: uwe at rocksport.de (Uwe Schmitt) Date: 3 Jun 2002 16:10:40 GMT Subject: different gui-toolkits pros/cons... References: <_rLK8.12$fd2.979@news.ecrc.de> Message-ID: Markus Jais wrote: | with pyQT there might be problems with the license | if you want to make your programm freely available | (but I am not a lawyer, so I might be wrong) That's a very important point: what do I have to pay if I used pyQt for development ??? I did not find any explicit prices at the trolltec-page... Greetings, Uwe. -- Dr. rer. nat. Uwe Schmitt ICQ# 159647634 Uwe.Schmitt at num.uni-sb.de Universitaet des Saarlandes Angewandte Mathematik Building 36.1 Room 4.17 PO-Box 151150 D-66041 Saarbruecken Mobile:0177/6806587 Fax:+49(0)681/302-4435 Office:+49(0)681/302-2468 From jimmy at retzlaff.com Tue Jun 25 18:12:47 2002 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Tue, 25 Jun 2002 15:12:47 -0700 Subject: SOLVED (Re: Python hits the spot) Message-ID: Bengt Richter wrote: >>> Well, lucky guess on the heat. That _probably_ accounts for laptop >>> going to 87% and then shutting down, but how about the other huge >>> slowdowns in your big loop of 8? Did you get that diagnosed too? >>> Just curious ;-) >> >>On my stationary machine definitely not. The 8 steps remain constant. I > >Still curious ;-) I believe that newer mobile CPUs will throttle back their clock speed in response to heat. This could explain the slow down. Apparently the lowest clock speed wasn't low enough to keep the CPU happy... Jimmy From dfackrell at DELETETHIS.linuxmail.org Thu Jun 20 14:09:12 2002 From: dfackrell at DELETETHIS.linuxmail.org (Daniel Fackrell) Date: Thu, 20 Jun 2002 12:09:12 -0600 Subject: Proper number alignment References: Message-ID: <3d121a47$1_3@hpb10302.boi.hp.com> I would avoid tabs altogether and figure out how many spaces I needed to get there (tab stops can be set differently for every terminal). Basically, subtract the total length of the two strings from the total width you want to fill, and use (' '*numberOfSpaces) as your filler. -- Daniel Fackrell (dfackrell at linuxmail.org) When we attempt the impossible, we can experience true growth. "mdk" wrote in message news:aet5hu$9leln$1 at ID-98166.news.dfncis.de... > I am using \t\t (tabs) to align these numbers (disregard the math): > > Total RAM 2,141,056 > Available RAM 12,934,032 > Used RAM 1,024 > > But they are left justified and I need them right justified. > > Any ideas? > > Thanks. From anoop79 at myrealbox.com Thu Jun 13 04:06:05 2002 From: anoop79 at myrealbox.com (Anoop P B) Date: Thu, 13 Jun 2002 13:36:05 +0530 Subject: Threading tutorial wanted. References: <20020613073828.GD1792@matijek.plusseven.com> Message-ID: <3D08526D.9050203@myrealbox.com> check this: http://starship.python.net/crew/aahz/OSCON2000/TOC.HTM it may help also, wxpython has threading support. but i dont know how good it is. see the wxpython demo for more info. i too am in need of answers to ur other questions on when to use, how safe, memory consumption, how to get rich ;), etc. ~anoop Alex Polite wrote: > Okidoki. My little webspider has reached the point where further > optimization won't pay off. But my DSL pipe is not saturated by > far. So I guess it's time for me to start looking into threads. > > I few minutes of googling on python + threads doesn't yield a > lot. Maybe someone here can point me to a good primer. Maybe someone > here can write a good primer. > > When is threading good, when is it bad? How much memory do they > consume? Is it safe to let multiple threads use the same db > connection? How safe is safe? How can I get rich? > > Stuff like that. > > From a.schmolck at gmx.net Mon Jun 10 09:34:18 2002 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 10 Jun 2002 14:34:18 +0100 Subject: Could someone submit this to the sf-bug tracker, please?(Was: Re: __imul__ broken for 'objects' in 2.2.1) References: Message-ID: Michael Hudson writes: > Hmm. You should file a bug on sf so this doesn't get forgotten > (unless it's already been reported, but I don't think so). Well yes, but then I *can't* which is why I've posted the previous message. Could someone else please submit this bug to the sourceforge bug-tracker? I tried again today, but logging in from the submission form has no effect, I'm back to the same form that tells me to "please log-in" *after* I have completed the log-in step (if I submit the wrong password, however I do get an error message). I've tried 3 different browsers (mozilla .94, konqueror and netscape 4.7) -- to no avail. Now helpfuly, just giving my email address instead of logging in doesn't work either, because anonymous bug reports aren't permitted. If my problems don't reflect the weirdness of the proxy I'm forced to use, I'd really suggest that either the decision not to allow anonymous bug reports should be reviewed again. alex > Alexander Schmolck writes: > > > OK, after unsuccessfully trying for about half an hour to submit this to the > > sf bug tracker, I gave up: > > > > class Breaky(object): > > def __imul__(self, other): > > print "imuling" > > return self > > sq = Breaky() > > sq *=1. > > > > gives: > > > > Traceback (most recent call last):[...] line 10, in ? > > sq *=1. > > TypeError: can't multiply sequence to non-int > > > > Unless I'm overlooking something, this is a fairly serious bug and I > > can't see a way to work around it (getattribute would presumably > > work, but slow everything down unacceptably, so the only 'solution' > > seems to be to have no inplace-multiplication). > > > > I had the same behavior on two different machines (running Mandrake 8.2 and > > Suse 7.3). > > Hmm. You should file a bug on sf so this doesn't get forgotten > (unless it's already been reported, but I don't think so). > > Cheers, > M. -- Alexander Schmolck Postgraduate Research Student Department of Computer Science University of Exeter A.Schmolck at gmx.net http://www.dcs.ex.ac.uk/people/aschmolc/ From walter at livinglogic.de Wed Jun 19 07:03:48 2002 From: walter at livinglogic.de (=?ISO-8859-15?Q?Walter_D=F6rwald?=) Date: Wed, 19 Jun 2002 13:03:48 +0200 Subject: PEP 293, Codec Error Handling Callbacks Message-ID: <3D106514.5030203@livinglogic.de> There is a new PEP available (online at http://www.python.org/peps/pep-0293.html) Please comment! Bye, Walter D?rwald --------------------------------------------------------------------- PEP: 293 Title: Codec Error Handling Callbacks Version: $Revision: 1.1 $ Last-Modified: $Date: 2002/06/19 03:22:11 $ Author: Walter D?rwald Status: Draft Type: Standards Track Created: 18-Jun-2002 Python-Version: 2.3 Post-History: Abstract This PEP aims at extending Python's fixed codec error handling schemes with a more flexible callback based approach. Python currently uses a fixed error handling for codec error handlers. This PEP describes a mechanism which allows Python to use function callbacks as error handlers. With these more flexible error handlers it is possible to add new functionality to existing codecs by e.g. providing fallback solutions or different encodings for cases where the standard codec mapping does not apply. Specification Currently the set of codec error handling algorithms is fixed to either "strict", "replace" or "ignore" and the semantics of these algorithms is implemented separately for each codec. The proposed patch will make the set of error handling algorithms extensible through a codec error handler registry which maps handler names to handler functions. This registry consists of the following two C functions: int PyCodec_RegisterError(const char *name, PyObject *error) PyObject *PyCodec_LookupError(const char *name) and their Python counterparts codecs.register_error(name, error) codecs.lookup_error(name) PyCodec_LookupError raises a LookupError if no callback function has been registered under this name. Similar to the encoding name registry there is no way of unregistering callback functions or iterating through the available functions. The callback functions will be used in the following way by the codecs: when the codec encounters an encoding/decoding error, the callback function is looked up by name, the information about the error is stored in an exception object and the callback is called with this object. The callback returns information about how to proceed (or raises an exception). For encoding, the exception object will look like this: class UnicodeEncodeError(UnicodeError): def __init__(self, encoding, object, start, end, reason): UnicodeError.__init__(self, "encoding '%s' can't encode characters " + "in positions %d-%d: %s" % (encoding, start, end-1, reason)) self.encoding = encoding self.object = object self.start = start self.end = end self.reason = reason This type will be implemented in C with the appropriate setter and getter methods for the attributes, which have the following meaning: * encoding: The name of the encoding; * object: The original unicode object for which encode() has been called; * start: The position of the first unencodable character; * end: (The position of the last unencodable character)+1 (or the length of object, if all characters from start to the end of object are unencodable); * reason: The reason why object[start:end] couldn't be encoded. If object has consecutive unencodable characters, the encoder should collect those characters for one call to the callback if those characters can't be encoded for the same reason. The encoder is not required to implement this behaviour but may call the callback for every single character, but it is strongly suggested that the collecting method is implemented. The callback must not modify the exception object. If the callback does not raise an exception (either the one passed in, or a different one), it must return a tuple: (replacement, newpos) replacement is a unicode object that the encoder will encode and emit instead of the unencodable object[start:end] part, newpos specifies a new position within object, where (after encoding the replacement) the encoder will continue encoding. If the replacement string itself contains an unencodable character the encoder raises the exception object (but may set a different reason string before raising). Should further encoding errors occur, the encoder is allowed to reuse the exception object for the next call to the callback. Furthermore the encoder is allowed to cache the result of codecs.lookup_error. If the callback does not know how to handle the exception, it must raise a TypeError. Decoding works similar to encoding with the following differences: The exception class is named UnicodeDecodeError and the attribute object is the original 8bit string that the decoder is currently decoding. The decoder will call the callback with those bytes that constitute one undecodable sequence, even if there is more than one undecodable sequence that is undecodable for the same reason directly after the first one. E.g. for the "unicode-escape" encoding, when decoding the illegal string "\\u00\\u01x", the callback will be called twice (once for "\\u00" and once for "\\u01"). This is done to be able to generate the correct number of replacement characters. The replacement returned from the callback is a unicode object that will be emitted by the decoder as-is without further processing instead of the undecodable object[start:end] part. There is a third API that uses the old strict/ignore/replace error handling scheme: PyUnicode_TranslateCharmap/unicode.translate The proposed patch will enhance PyUnicode_TranslateCharmap, so that it also supports the callback registry. This has the additional side effect that PyUnicode_TranslateCharmap will support multi-character replacement strings (see SF feature request #403100 [1]). For PyUnicode_TranslateCharmap the exception class will be named UnicodeTranslateError. PyUnicode_TranslateCharmap will collect all consecutive untranslatable characters (i.e. those that map to None) and call the callback with them. The replacement returned from the callback is a unicode object that will be put in the translated result as-is, without further processing. All encoders and decoders are allowed to implement the callback functionality themselves, if they recognize the callback name (i.e. if it is a system callback like "strict", "replace" and "ignore"). The proposed patch will add two additional system callback names: "backslashreplace" and "xmlcharrefreplace", which can be used for encoding and translating and which will also be implemented in-place for all encoders and PyUnicode_TranslateCharmap. The Python equivalent of these five callbacks will look like this: def strict(exc): raise exc def ignore(exc): if isinstance(exc, UnicodeError): return (u"", exc.end) else: raise TypeError("can't handle %s" % exc.__name__) def replace(exc): if isinstance(exc, UnicodeEncodeError): return ((exc.end-exc.start)*u"?", exc.end) elif isinstance(exc, UnicodeDecodeError): return (u"\\ufffd", exc.end) elif isinstance(exc, UnicodeTranslateError): return ((exc.end-exc.start)*u"\\ufffd", exc.end) else: raise TypeError("can't handle %s" % exc.__name__) def backslashreplace(exc): if isinstance(exc, (UnicodeEncodeError, UnicodeTranslateError)): s = u"" for c in exc.object[exc.start:exc.end]: if ord(c)<=0xff: s += u"\\x%02x" % ord(c) elif ord(c)<=0xffff: s += u"\\u%04x" % ord(c) else: s += u"\\U%08x" % ord(c) return (s, exc.end) else: raise TypeError("can't handle %s" % exc.__name__) def xmlcharrefreplace(exc): if isinstance(exc, (UnicodeEncodeError, UnicodeTranslateError)): s = u"" for c in exc.object[exc.start:exc.end]: s += u"&#%d;" % ord(c) return (s, exc.end) else: raise TypeError("can't handle %s" % exc.__name__) These five callback handlers will also be accessible to Python as codecs.strict_error, codecs.ignore_error, codecs.replace_error, codecs.backslashreplace_error and codecs.xmlcharrefreplace_error. Rationale Most legacy encoding do not support the full range of Unicode characters. For these cases many high level protocols support a way of escaping a Unicode character (e.g. Python itself supports the \x, \u and \U convention, XML supports character references via &#xxx; etc.). When implementing such an encoding algorithm, a problem with the current implementation of the encode method of Unicode objects becomes apparent: For determining which characters are unencodable by a certain encoding, every single character has to be tried, because encode does not provide any information about the location of the error(s), so # (1) us = u"xxx" s = us.encode(encoding) has to be replaced by # (2) us = u"xxx" v = [] for c in us: try: v.append(c.encode(encoding)) except UnicodeError: v.append("&#%d;" % ord(c)) s = "".join(v) This slows down encoding dramatically as now the loop through the string is done in Python code and no longer in C code. Furthermore this solution poses problems with stateful encodings. For example UTF-16 uses a Byte Order Mark at the start of the encoded byte string to specify the byte order. Using (2) with UTF-16, results in an 8 bit string with a BOM between every character. To work around this problem, a stream writer - which keeps state between calls to the encoding function - has to be used: # (3) us = u"xxx" import codecs, cStringIO as StringIO writer = codecs.getwriter(encoding) v = StringIO.StringIO() uv = writer(v) for c in us: try: uv.write(c) except UnicodeError: uv.write(u"&#%d;" % ord(c)) s = v.getvalue() To compare the speed of (1) and (3) the following test script has been used: # (4) import time us = u"?a"*1000000 encoding = "ascii" import codecs, cStringIO as StringIO t1 = time.time() s1 = us.encode(encoding, "replace") t2 = time.time() writer = codecs.getwriter(encoding) v = StringIO.StringIO() uv = writer(v) for c in us: try: uv.write(c) except UnicodeError: uv.write(u"?") s2 = v.getvalue() t3 = time.time() assert(s1==s2) print "1:", t2-t1 print "2:", t3-t2 print "factor:", (t3-t2)/(t2-t1) On Linux this gives the following output (with Python 2.3a0): 1: 0.274321913719 2: 51.1284689903 factor: 186.381278466 i.e. (3) is 180 times slower than (1). Codecs must be stateless, because as soon as a callback is registered it is available globally and can be called by multiple encode() calls. To be able to use stateful callbacks, the errors parameter for encode/decode/translate would have to be changed from char * to PyObject *, so that the callback could be used directly, without the need to register the callback globally. As this requires changes to lots of C prototypes, this approach was rejected. Currently all encoding/decoding functions have arguments const Py_UNICODE *p, int size or const char *p, int size to specify the unicode characters/8bit characters to be encoded/decoded. So in case of an error the codec has to create a new unicode or str object from these parameters and store it in the exception object. The callers of these encoding/decoding functions extract these parameters from str/unicode objects themselves most of the time, so it could speed up error handling if these object were passed directly. As this again requires changes to many C functions, this approach has been rejected. Implementation Notes A sample implementation is available as SourceForge patch #432401 [2]. The current version of this patch differs from the specification in the following way: * The error information is passed from the codec to the callback not as an exception object, but as a tuple, which has an additional entry state, which can be used for additional information the codec might want to pass to the callback. * There are two separate registries (one for encoding/translating and one for decoding) The class codecs.StreamReaderWriter uses the errors parameter for both reading and writing. To be more flexible this should probably be changed to two separate parameters for reading and writing. The errors parameter of PyUnicode_TranslateCharmap is not availably to Python, which makes testing of the new functionality of PyUnicode_TranslateCharmap impossible with Python scripts. The patch should add an optional argument errors to unicode.translate to expose the functionality and make testing possible. Codecs that do something different than encoding/decoding from/to unicode and want to use the new machinery can define their own exception classes and the strict handlers will automatically work with it. The other predefined error handlers are unicode specific and expect to get a Unicode(Encode|Decode|Translate)Error exception object so they won't work. Backwards Compatibility The semantics of unicode.encode with errors="replace" has changed: The old version always stored a ? character in the output string even if no character was mapped to ? in the mapping. With the proposed patch, the replacement string from the callback callback will again be looked up in the mapping dictionary. But as all supported encodings are ASCII based, and thus map ? to ?, this should not be a problem in practice. References [1] SF feature request #403100 "Multicharacter replacements in PyUnicode_TranslateCharmap" http://www.python.org/sf/403100 [2] SF patch #432401 "unicode encoding error callbacks" http://www.python.org/sf/432401 Copyright This document has been placed in the public domain. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: From UG at LY Fri Jun 14 12:35:01 2002 From: UG at LY (Unconditional Grace) Date: Fri, 14 Jun 2002 12:35:01 -0400 Subject: NEWbie asks "is Python a good tool for automated file/folder generation?" Message-ID: <6k6kgukhuk8pfgos97a38h0d4r5jr0u3sr@4ax.com> Hi all, I'm so new that "newbie" doesn't even do me justice, and I'm writing humbly for advice. I have a series of scientific image files numbering, say, 1000, which are really 100 groups, each group with its own identical string, but appended with a different number from _01 to _10, or possibly some other string. The end enumeration is ALWAYS differentiated from the constant string by a final underscore, but the strongs themselves contain underscores too. i.e., stringa_01.jpg ... stringa_10.jpg stringb_01.jpg ... stringb_10.jpg ... What I would like to do is largely string-based file and folder manipulation: 1. Create a folder for each group of 10, where the folder name is the shared string for that group (no numbers). This list of string names could come directly from the directory, or I could perhaps port the directory listing to a text file and parse that. 2. Move each image into its appropriate folder. 3. Within each folder, create one HTML page consisting of a table with a link to each image, preferably with a thumbnail (can be original image resized by HTML since this is all local = no bandwidth issues). 4. Create a top level HTML page that links to all 100 image HTML pages created in step 3. Can be text only. 5. Optional: in step 3, make each image part of an HTML page with "previous image" and "next image" links, rather than just being called by the browser as a jpg image. --- I've never used Python, and I'm wondering if you, collectively, think that Python is a good language to do this. While it seems like Python is an incredibly useful tool, I'm not sure I have time right now to invest in learning it if it can't do this. It seems I frequently want to do repetitive Windows file/folder chores like this, so I want to get smart-like. If so, could someone please give me some pointers? If not, other tool recommendations? PHP? I'm not asking anyone to write such code for me, heh heh, but I'd love it if someone could give me some advice (here or URLs) on folder and file name operators, "for every item in list" type syntax, and/or general string operators (to truncate the numbers from the file names, e.g.). Anyhoo, in addition to any news group response, please cc: me on email (H_J_Fong at hotmail.com) since my server is spotty and I'd hate to miss your response(s). Thanks for reading this far, it is a lot to ask, Homer From cpgray at library.uwaterloo.ca Mon Jun 24 14:24:18 2002 From: cpgray at library.uwaterloo.ca (Chris Gray) Date: Mon, 24 Jun 2002 14:24:18 -0400 Subject: Handling HTTP Request Bodies (CGIHTTPServer) Message-ID: The http server modules in the standard python library have one severe limitation: They don't handle request bodies. CGIHTTPServer handles POST requests but doesn't process form values submitted by the POST, only values submitted in the query string. Where would I find examples (preferably built on SocketServer or BaseHTTPServer) of what's necessary to handle request bodies properly? Chris From stefan1werner at hotmail.com Tue Jun 11 16:52:51 2002 From: stefan1werner at hotmail.com (Stefan Werner) Date: Tue, 11 Jun 2002 22:52:51 +0200 Subject: Embedding Python 2.2 in non-reentrant application References: Message-ID: Hi, "Martin v. Loewis" schrieb: > No, you don't have to do anything. Inside a C function, you hold the > GIL, and any other Python thread will block while your C function is > running. So, I can write Python modules in C just as I did for 1.5? What a relief...keeping an eye on ownership and reference counting is enough work already :) Excuse my ignorance, but what does GIL mean? Thanks so far, Stefan From jones at jones.jones Wed Jun 19 00:19:06 2002 From: jones at jones.jones (Jones) Date: Wed, 19 Jun 2002 04:19:06 GMT Subject: Writing a simple linux daemon type thing... References: Message-ID: <_CTP8.4345$Fv1.455767@newsread2.prod.itd.earthlink.net> I would have to guess Hungarian.... but I could guess by looking at the words.. just the email addresses :-) Thank you all for you suggestions. It looks to me like the Python community is very strong and helpful! I'm glad I stumbled across it ;) > > Searching google on "python daemon os.setsid" if find the following: > > http://mlf.linux.rulez.org/Archivum/l-code-l-199911/msg00060.html > > Which contains some text in a language that I don't recognize > (Swedish?, Slavic?, who knows) and some code in Python: > From bokr at oz.net Thu Jun 27 14:35:35 2002 From: bokr at oz.net (Bengt Richter) Date: 27 Jun 2002 18:35:35 GMT Subject: Web templating/db tool with best designer/coder separation? References: Message-ID: On 24 Jun 2002 22:41:51 -0500, Ian Bicking wrote: >On Mon, 2002-06-24 at 19:36, Bengt Richter wrote: >> On 22 Jun 2002 18:43:50 GMT, bokr at oz.net (Bengt Richter) wrote: >> and from the description, this would seem to have a real advantage over all of >> the above, in that it uses attributes of html tags as opposed to special tags >> that browsers or design tools won't generally understand and render usefully. > [...] >You might be interested to look at XMLC (http://xmlc.enhydra.org/) -- >similar to ZPT, but with greater WYSIWYG support, and with considerably >less transparency (no actual code is contained in the template). It's >kind of the extreme of that direction -- like accessing a DOM where the >markup is annotated and the API is much more friendly. It's not in >Python, though maybe someone has created a clone (which shouldn't be >hard). I'd seen it in a list somewhere, but skipped it as I wasn't interested in a Java tool, but I do like the minimal intrusion into the designer-mockup HTML world, using "compilation" etc. Thanks for the pointer. Regards, Bengt Richter From gerhard at bigfoot.de Tue Jun 18 21:49:11 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Wed, 19 Jun 2002 03:49:11 +0200 Subject: calling wxPython from the shell In-Reply-To: <3D0FD764.4937BDB4@mitre.org> References: <3D0FD764.4937BDB4@mitre.org> Message-ID: <20020619014911.GA2739@lilith.my-fqdn.de> * Angel Asencio [2002-06-18 20:59 -0400]: > I have been requested to write a function that will take a list, open > a selection window, and then when the window is closed the function > would return a list with the selected items. > Looks like wxPython is quite favored, and I decided to use the Boa > Constructor, finished the tutorial. Everything fine and dandy, until I > wanted to create the function that you can call from the shell. > > The scenario that I have tried is for the function to call the MainApp > (that has the MainLoop) with the Frame that will do the selection. I > understand about the events, but what ever I do with the event, > 'myModule.myFunction( [ "a","collection","to","select"])' return > nothing on the combinations I have tried. Post source, or else nobody can help you with this particular problem. Preferrable on the wxPython mailing list, as that's where the knowledgeable folks hang around (I'm just a beginner). > Bottom line is that I want a function call that I can call in the > shell, like as part of a print, that I do the selection, and when I If you want to spoil the fun of finding it out yourself, here's a quick solution, hacked together with wxMultipleChoiceDialog and wxPySimpleApp. Replace exec with print to see the source code. Or just execute it to try it out ;-) import zlib,base64 exec(zlib.decompress(base64.decodestring(""" eNptkE9LxDAQxe/5FEO9JLIWvS5UWFwQcVcXil5DbKftYP7RZmn99iapHlycQyDvZX4vM93oDMzL 6SsMzpbzAmS8GwNcs+6Po+mjbElp10+/T+bleNaBvMaHwVGD+2wz1mIHRpHlYssglvIeqkyqY6fG nfdcsGxdwQ40TQFcB02GTFnXUaoixPMpjBsYle2R390Kkd18tLrP1P/+wF/eDocNFCdqPmFyBouL S+SvKOqAR1JZD24+ulZpLqBK2Ke9fH3+GSCVH8kGKGrU2ARydhspqfERw7vSZ+QiRsDNPVzodYiN fZo3RklplUEpU0QhZVqSlMUasm6MsW8XN3sP """))) Btw. I've learnt everything I know from studying the various parts of the demo application, there are some very nice goodies hidden there. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 22.2 ?C Wind: 0.9 m/s From michael at damaru.com Mon Jun 10 23:19:10 2002 From: michael at damaru.com (Michael Davis) Date: Mon, 10 Jun 2002 23:19:10 -0400 Subject: newbie question - python blocking on int()? References: <4LaN8.2488$Vr2.586019@news20.bellglobal.com> Message-ID: Wladimir wrote: > On Tue, 11 Jun 2002 01:59:33 +0200, Chris Liechti wrote: > >> also note that split() might not be safe for every case. e.g when the >> user name contains a space (if possible) and surely when the filename >> has a space in it. > > Parsing the output of ftp.dir in any way is never comphrehensively safe > because it it platform dependent according to the FTP RFC. Spaces in > usernames are not possible though AFAIK, and most servers use a unix ls > like semantic for dirs so it's *pretty safe*. (although I've seen ugly DOS > like listings as well) I know! I just want to make it work with two servers I use. I want to be able to detect when a file has changed, by a combination of modification time and file size. Unfortunately the ftp size() function is buggy, it always adds 1 whenever there is a \n in the file, (assumes, I guess, that you want the file size as though it were a unix text file that was going to be converted to dos)... Thanks for replying! -- Michael Davis Damaru Custom Programming - Web Development - Database Design http://www.damaru.com 416-540-1284 From aahz at pythoncraft.com Sat Jun 15 09:47:01 2002 From: aahz at pythoncraft.com (Aahz) Date: 15 Jun 2002 09:47:01 -0400 Subject: Pronouncing '__init__' References: <20020615132519.A14452@hishome.net> Message-ID: In article , holger krekel wrote: >Oren Tirosh wrote: >> >> There has been a thread about this issue in the past. Below are some of the >> proposals people made. I'd like to have an informal vote - how do *you* >> say Python's magic names when talking with other Pythoneers? > >for oral language: > > init constructor > >and if the context allows > > init > >for written languange __init__ > >Isn't it obvious? :-) Yup. Except that you're wrong: __init__ isn't a constructor, it's an initializer. __new__ is a constructor. ;-) So I just refer to the "init method" so nobody gets the wrong idea. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From gb at cs.unc.edu Sat Jun 1 07:32:35 2002 From: gb at cs.unc.edu (gb at cs.unc.edu) Date: 01 Jun 2002 07:32:35 -0400 Subject: Code Folding with Emacs References: Message-ID: Thomas Sicheritz-Ponten writes: > > Have you looked at folding.el? > (fold-add-to-marks-list 'python-mode "# {{{ " "# }}}" nil t) > (load "folding.el" 'nomessage 'noerror) Yes, I looked at it but I didn't want to have to mark up my files. Outline.el works really nicely with Python though I think outline has a minor bug with respect to handling empty lines.... gb From itamarst at yahoo.com Mon Jun 10 18:45:40 2002 From: itamarst at yahoo.com (Itamar Shtull-Trauring) Date: 10 Jun 2002 15:45:40 -0700 Subject: Python MTA References: Message-ID: <637b94bc.0206101445.4d5b8315@posting.google.com> "David LeBlanc" wrote in message news:... > Has anyone developed a simple/stupid Mail Transfer Agent using Python that > does't rely on any external mail agents (and thus would be platform > independent)? > > What I have in mind is an app that sits between my mail client (outlook > (dev/null=flames)) and, at most, a few mail hosts. It would act like a > client to those mail hosts and as a host to outlook. The idea is to be able > to insert a spam filter like ASK (or something better?). Twisted comes with a SMTP server that can act as a smarthost - forwarding requests on to other mailhosts. It can also act as an incoming server, delivering mail to mailboxes which you can then read with POP3 (also in Twisted), but this functionality is less developed. Here's a quick guide to getting started - download and install Twisted: http://www.twistedmatrix.com Debian unstable users: apt-get install python2.1-twisted Then: $ mktap mail --help $ mktap --xml mail .... # with appropriate options Now you have a mail.tax file you can run: $ twistd -n -x mail.tax mail.tax is a XML pickle, so you can edit it with a text file to change the configuration. From derek at wedgetail.com Thu Jun 20 05:24:16 2002 From: derek at wedgetail.com (Derek Thomson) Date: Thu, 20 Jun 2002 09:24:16 GMT Subject: 'else' clause in 'for' and 'while' References: Message-ID: <3D119F3F.5070600@wedgetail.com> Ville Vainio wrote: > How do you people use the else clause in for and while constructs? Are > they used widely for some specific applications? Do they offer > elegant, idiomatic solutions to some problems? > > I haven't found any use for them yet myself, but knowing that they > exist and still not using them troubles me, core python being quite > 'small' after all. It's good for searching, and saves mucking about with flags to achieve the same effect. For example: for item in list: if item == match: # Item found, take some action item_found(item) break else: # Item not found, take some other action item_not_found() Regards, Derek. From ethanw at rediffmail.com Thu Jun 6 18:07:24 2002 From: ethanw at rediffmail.com (Ethan) Date: 6 Jun 2002 15:07:24 -0700 Subject: GUI Toolkit! References: <1a52c7f1.0206011720.7c3ac7ea@posting.google.com> Message-ID: <1a52c7f1.0206061407.4d5d4225@posting.google.com> Thanks. I am downloading it now. > If you need to make something very quickly, try pythoncard at > pythoncard.sourceforge.net. It is a layer above wxWindows and comes with > tons of samples - including an interface builder written in itself. From peter at engcorp.com Fri Jun 7 01:04:07 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 07 Jun 2002 01:04:07 -0400 Subject: Medium to Large Scale Python Deployments References: <38C31EBA-79A4-11D6-9A7D-003065B33450@intersight.com> Message-ID: <3D003EC7.C72D27BE@engcorp.com> Christopher Armstrong wrote: > > > I'm also curious about large amounts of Python, period. Who knows of ~50K > > Python lines-of-code (LOC) systems? 100K LOC? More? > > chris at radii:~/Projects/Twisted$ find -name '*.py' | xargs wc -l > ... > 56051 total How big is that when run through pycount? (I.e. comments and blank lines don't count!) -Peter From observer at NOSPAM.space.pl Wed Jun 19 07:42:08 2002 From: observer at NOSPAM.space.pl (Johann) Date: Wed, 19 Jun 2002 13:42:08 +0200 Subject: PythonWorks Pro problem! References: <3lwP8.112157$pw3.6716@sccrnsc03> <8nrtgusniqrs9r3fs7l4nt8qka5fm7imi3@4ax.com> Message-ID: On 18 Jun 2002 22:39:43 -0700, brian_l at yahoo.com (Brian Lenihan) wrote: >Open the "project settings" in the SYSTEM project. You still have to >right click on project and "reload actions" before the edit prefs >change. Yes. I is working now. I thought it may help me with another, greater problem. PWpro has bugs dealing with non latin1 characters. I got a response that it will be fixed in future. There is no way for writing non-English characters for now. :( -- Johann From jan_hermanns at gmx.de Wed Jun 5 15:20:05 2002 From: jan_hermanns at gmx.de (Jan Hermanns) Date: 5 Jun 2002 12:20:05 -0700 Subject: problems compiling Python2.2.1 on OpenBSD3.0 Message-ID: I tried to compile Python 2.2.1 on OpenBSD3.0 (MacPPC Version), but it does not work. After running the configure script. I tried make. But make seems to run in an infinte loop! Can anybody help me? thank you Jan Hermanns From eric.brunel at pragmadev.com Tue Jun 4 14:38:22 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Tue, 4 Jun 2002 18:38:22 +0000 Subject: self References: Message-ID: Vojin Jovanovic wrote: > I have been working on a project trying to implement some advanced > functionality. Now, one thing that has been a constraint for me is the > concept of self. Why is it that within a class one has to use self. (or > "any word". ) to refer to instance variables? Would it not be more logical > to just use the name of the variable like it is for example in C++? This is *not* a variable, this is an attribute. Hence the "self.". I always found the C++/Java convention particularly disturbing. With this convention, there's no obvious means to tell a local variable from an object's attribute: public class C { public int a; public void m() { int b; a = 0; // What's the difference b = 0; // between these 2 lines? } } The notation is exactly the same for two quite different things: - "a = 0;" means "set the value of attribute a of method's receiver to 0", setting that will still exist after the method's end - "b = 0" means "set the value of the variable b, local to method m, to the value 0", setting that will be discarded after the method's end Not using any prefix in front of attribute names in methods is IMHO a dangerous shortcut, and a confusing one... I really prefer Python's notation, which is indeed a bit "heavier", but far less confusing. You'll certainly find your code far more readable in a few months than it would be in C++ or Java. -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From bokr at oz.net Sun Jun 23 13:17:41 2002 From: bokr at oz.net (Bengt Richter) Date: 23 Jun 2002 17:17:41 GMT Subject: Python hits the spot References: <3D1482AE.8FA299D8@kfunigraz.ac.at> <3D14CF95.4030501@kfunigraz.ac.at> <3D158F3E.1010907@kfunigraz.ac.at> Message-ID: On Sun, 23 Jun 2002 11:05:02 +0200, Siegfried Gonzi wrote: >Bengt Richter wrote: > >> Unless you are doing a lot of i/o from the program, sounds like maybe that >> 13% (100-87) may be waiting for swapping to get more virtual space? Or it could be >> coincidental background stuff? (Do you trigger any other processes at some point?) > >To cut it here: I tested the Mie code again and it works! The images >what I get are exactly the same as the one in a specific peer reviewed >paper. After that calculation I wait 20 minutes in order to watch ^^^^^ Not sure what you mean: Do you mean that the program completes, and then you wait a further 20 minutes after that, expecting a possible "freeze?" Is that something you have observed before? I.e., "freezing" _after_ successfully completing calculations, with something else working before the "freeze"? BTW, what will Suse with your configuration do if you press Alt-F2 etc? Will it give you a console login screen? Can you boot without X and keep two logged-in sessions, with maybe one as root to see if you can Alt-Fn to that when things "freeze" running your app from the other? BTW2: you're not running your app as root, right? Does your app need X for display or could you run it from a plain terminal console? The latter would have a lot less baggage when trying to switch between sessions. BTW. I heard there was one problematic version of SuSe in the past. You don't happen to have that version I hope. Would someone set that FUD straight? >whether the system will freeze or not: it freezes not. THE calculation >does not use any swap! I have got 256MB RAM but the calculation consumes >about 20 MB on Linux; there is no need for swapping (side note: my swap >is 756MB). Hm, ok. 20MB and not growing. I missed that point. BTW, are you getting your 87% number from top? If you toggle with "i" (no-idle) what else is left? Anything besides top? I wonder how/whether the percentage calculated is affected by power management that slows down the CPU clock to keep it cool? Wonder if that could be happening. I've never looked into power management stuff. I guess there is a temperature where it just shuts down too, to protect itself? > >In turn I tried the following combinations: > >1. The complete calculations without the Mie code (note: the Mie code >works) and dummy values instead. >Result: The first 10 minutes the system consumes 99.8% of the processor >(memory consumption is up to 5%) but after 10 minutes it sucks down to >87% and after 15 minutes the system freezes (I mean there is only the >power off option then!). How is your system configured to respond to Ctl-Alt-Del? Does it respond to that? If so, it's not _absolutely_ "frozen." Likewise, if you run without a GUI with plain virtual consoles, you can often switch to another even if if a current one appears "frozen." If you are on a local network and can log into another machine, you could also try to telnet in to the "frozen" machine, depending on how it's configured. You could enable telnet just for a local test. Plain old Ctrl-C or Ctrl-Break don't do anything when it's "frozen," right? > >2. I did the same without the Mie and Fortran code. Same situation as in >point 1. > >3. I did the same without Fortran/C/Satellite binary reading -> same >situation as in point 1 or 2. Well, seems like it must be something about your Python code? > >4. I turned off every power management for my laptop, but that won't >cure the situation. I don't know how that works, but I would think a system shouldn't shut itself down if it has work to do, unless it's an emergency like running out of battery power or overheating. So I don't understand this shutdown. > > >Summarize: The system frezzes after 15 minutes and sucks down to 87% ^^^^^^^ ^^^ In that order? How can you get a display of "87%" on a "frozen" system?? >system performance, without any notice why (I cannot see why under "top" >; sometimes I notice that many "kdeinits" appear right after the python >process)? Exactly the same situation appears on Windows: system goes >down from 99% to 87% after some time, but on Windows I do not get a >frozen system. I guess I need a clearer definition of "frozen" ;-) > >I then wrote a small Python script in order to test the swap. The Python >script does constantly claim memory and my swap memory consumption goes >up to 500MB (system perfromance is only some 5%). After 30 minutes the >calculation is completed and I can work on without any problems. > Ok. Sounds normal. > >That means, if I have got a calculation of the form: processor >consumption 99% and memory consumption 5% the system fails; if I have What exactly do you see or try that makes you conclude the system has "failed?" >got a calculation in the reverse order: 90% memory and 5% processor the >system remains stable. Does your program accumulate a lot of state to keep referring to as it progresses? E.g., if information were saved in lists that grew and had to be traversed a lot, you'd expect one kind of behavior. If you were simulating some population of things with behavior that was either easy or hard to calculate, and the progress of simulation forced changes to a more complex mode of calculation (e.g., adaptive adjustments to the resolution of a grid etc.), then you could expect increasingly bogged down behavior, which might be proper. But if there's a bug so that new iterations decide to shift gears using leftover parameters, you could get degraded performance (e.g., because of unneeded high resolution calculations), yet finally come out with valid numbers (and a false impression that Python sucked ;-) I have no idea what your app is doing, so I am just speculating, in the hope that something useful will trigger a helpful thought. > > >Maybe this all can be explained that the ActivePython version has a bug >or something like that. Or that the combination Linux/Python/laptop is >not optimal. But I am not willing to install the normal Python version >again (I did it until I noticed that idle was not installed; I invested >2 days in order to install idle but was not successfull; ActiveState was >my isle in the following). Why not run from a plain text mode virtual terminal? > >The offer remains valid: if someone is interested in my source code he >can get it. Ok. > >I am not any longer willing to try the calculation on my Linux box and >Python 2.2 (20 Linux power off shut downs are enough in a day; should I Do you know why it's shutting down? What are the manufacturer's criteria for shutting down? Or can some user software be calling for shutdown for some reason? Is a screen saver involved? It must be maddening ;-) >destroy my laptop?). In the afternoon I will decide whether I will wait >6 hours for the calculation on Windows or not. And I will also decide Are there parameters you can input to the problem to control how accurately you want things to be calculated? Can you make a low accuracy/resolution/whatever run in a short time? It might let you do debug experiments more quickly. Or maybe there's a bug in how that is controlled? Especially if it is adaptive. Maybe config parameters are getting modified so all 8 (IIRC) major loops don't see the same values? Have you any profiling information at all to know where all the time is being spent, and how the proportions change as things bog down? >whether it will be a good idea to rewrite it in Fortran 90. Python can >then be used in combination with DISLIN for the plots. > Still no real diagnosis, though ;-/ Regards, Bengt Richter From ianb at colorstudy.com Mon Jun 3 02:32:35 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 03 Jun 2002 01:32:35 -0500 Subject: Extracting data from HTML In-Reply-To: <837klhrpv3.fsf@panacea.canonical.org> References: <82096df4.0205311152.5891a17b@posting.google.com> <1022883953.6150.5802.camel@localhost> <837klhrpv3.fsf@panacea.canonical.org> Message-ID: <1023085956.8048.87.camel@localhost> On Sun, 2002-06-02 at 22:41, Kragen Sitaker wrote: > Geoff Gerrietts writes: > > Both techniques are worth knowing -- but better than either would be > > finding a way to get the information you're after via XML-RPC or some > > other protocol that's designed to carry data rather than rendering > > instructions. > > You seem to imply that XML-RPC is better suited to carrying data > rather than rendering instructions than HTTP is. I disagree with this > implication, and I adduce the following evidence: > - the thousands of RSS feeds (see www.syndic8.com) using HTTP > - people downloading Python via HTTP > - the fact that XML-RPC runs over HTTP I think you are misinterpreting Geoff's response, and you seem to have a chip on your shoulder about it. He did not compare XML-RPC to HTTP, but to HTML (at least, that's clearly implicit because this thread was talking about HTML parsing). HTML is clearly a poor way to exchange machine-readable information, there are too many layout-related tags that are usually only appreciated by humans. An alternative interface meant for programmatic parsing is clearly easier and more robust to deal with fetching data, be that with XML-RPC, or plain HTTP with normal GET/POST variables and XML response -- even a CSV response, or newline-delimited list, or what have you would be easier than nearly any HTML you'll find out there. Ian From buzzard at urubu.freeserve.co.uk Sun Jun 23 20:19:11 2002 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Mon, 24 Jun 2002 01:19:11 +0100 Subject: ? and %s placeholders, help? Message-ID: Can anyone please explain the following. Basically I need to know the difference between the ? placeholder and the %s placeholder. I have only been able to find examples of the use of '?' in situations where it clearly works (integers?). But I have no good idea why I cannot use it as below. Or am I stuck with having the statement parsed each time I execute it? Currently my INSERTs seem to be slow. In fact it's 15 times quicker to write my data to a text file and then dump it to a MySQL table, so I'm guessing I should be able to speed this up somehow? Cheers. TIA. Duncan >>> import MySQLdb >>> conn = MySQLdb.connect(db='mytests') >>> curs = conn.cursor() >>> query = "INSERT INTO %s (%s) VALUES %s" >>> tbl = 'AA_temp' >>> vars = 'var1, var2, var3, var4, var5, var6, var7' >>> vals = '("level1", "level1", "level1", "level1", "level1", "level1", "level1")' >>> curs.execute(query % (tbl, vars, vals)) 1L >>> query = "INSERT INTO ? (?) VALUES ?" >>> curs.execute(query, (tbl, vars, vals)) Traceback (most recent call last): File "", line 1, in ? File "C:\Python22\Lib\site-packages\MySQLdb\cursors.py", line 70, in execute raise ProgrammingError, m.args[0] ProgrammingError: not all arguments converted >>> From jdhunter at nitace.bsd.uchicago.edu Fri Jun 28 12:08:24 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Fri, 28 Jun 2002 11:08:24 -0500 Subject: Python objects References: Message-ID: >>>>> "Teja" == Teja Sastry writes: Teja> Could anybody share their experience on how to call the C++ Teja> variable to python, I'm not quite familiar with python . I Teja> see there is a way to declare that as a python object in C++ Teja> program and export it to python. I would really appreciate Teja> if anybody can clarify me on how do this prgramming. This is called 'Extending Python' and there is a helpful manual written by Guido van Rossum and Fred Drake: http://www.python.org/doc/current/ext/ext.html. There are tools to automate this process. The boost python library is probably the best; it's template based C++ library which has extensive support for wrapping C++ classes in python http://www.boost.org/libs/python/doc/. You may also want to look at SWIG http://www.swig.org, which will generate python extensions for C/C++ code but has limited support for some C++ features. There are more .... Have fun, John Hunter From Bart.Bartels at vu.edu.au Thu Jun 20 02:04:00 2002 From: Bart.Bartels at vu.edu.au (Bart Bartels) Date: Thu, 20 Jun 2002 16:04:00 +1000 Subject: Win32com Python script/MS-Access Please help!! References: Message-ID: <3D117050.E39766A1@vu.edu.au> Sprung !!!!! However, I would like to know as well. I live in Aust and find it hard (and expensive) going to school/uni in other parts of the world :-) Bart Robert Oelschlaeger wrote: > > Dave: > > You've done a good job of re-posting (my) code from > http://aspn.activestate.com/ASPN/Mail/Message/1225515 as > your own work. Yes, you changed two "int"s to "float"s and > added a "c:/" to the "open" call, and removed the "def main():", > but that's about it. > > Good luck with your homework. Let's see, that would be "OPIM > 101: Introduction to Computers as Analysis Tools" at the Wharton > School, University of Pennsylvania. See also > http://opim-web.wharton.upenn.edu/home/coursedes.html#OPIM101 > > Next time, you might just ask for help at opim-help at wharton.upenn.edu > > One of the stated aims of that course is "Build student skill and > comfort using the computer to solve problems"; I don't > think that they mean for you to use the computer to find > others to do your work for you. > > Bob > > "Dave" wrote in message > news:aeo6h1$itf$1 at netnews.upenn.edu... > > Hey all, > > I'm having trouble writing a Python script relating to Microsoft > > Access. If > > anyone could help me I would greatly appreciate it. Here's the > > problem : > > > > I built an MS-Access table with 5 columns(fields) : OrderID, OrderDate, > > PlantID, ProductID, OrderQty, with OrderID as the primary key. All > > fields > > are numeric, except for OrderDate(which is a date field). > > > > Now I want to populate this table with data from a web page > > (http://opim.wharton.upenn.edu/~opim101/spring02/Plant1.html). please > > check > > the site. > > > > My object is to read the the data and insert it record by record into my > > Access table. > > > > Here's what I have so far : > > > > import urllib, string > > Plant1 = > > urllib.urlopen > > ('http://opim.wharton.upenn.edu/~opim101/spring02/Plant1.html' > > ) > > lines1 = Plant1.readlines() > > import win32com.client > > engine = win32com.client.Dispatch("DAO.DBEngine.35") > > db=engine.OpenDatabase(r'd:\Plants.mdb') > > > > I have several problems : > > Firstly, when I read the lines, I notice that not all of them are > > relevant. > > I need to ignore , , etc. at the beginning of the file, as > > well > > as the column headers, so that the action really begins from line 4 of > > the > > file and ends with > > Also, I need to eliminate

from every line in the file in order to > > get to > > the five comma-delimited fields that follow, and then split the rest of > > the > > string to get to each field. Here's what I think part of the code > > should > > look like : > > > > for line in lines1.readlines(): > > line=line.rstrip() > > inOrderID,inOrderDate,inRegionID,inProductID,inOrderQty = > > line.split(",") > > > > Something like that, I'm not sure... > > Lastly, now that I've read all the fields, I need to insert them each > > as a > > single record into my table of my access database using Python DAO > > using the > > Insert statement. Also, the OrderDate field that I read in, looks like > > a > > text type to Access, so I need to pad it with the # sign on either side > > before inserting it into the Access database, so that Access interprets > > it > > as a Date/Time type. > > > > Finally, I need to get the same information from 2 other plants and tag > > them > > onto the same table...from the web page > > http://opim.wharton.upenn.edu/~opim101/spring02/PlantPortal.html > > where plant1's data shows up first, plant2's data shows up below it, and > > plant3's data shows up last...so all plants' data in the same table. > > > > I would like > > to use more standard commands. I can use SQL, and I know Python - > > Access > > commands like OpenRecordSet(), TableDefs.count(), Execute(), while not > > rs.EOF, Fields()..... > > Is there any other way to write the program without SGML? To give you > > more > > of an idea of the way I'd like the program, I wrote another program for > > doing a similar thing in Excel, not Access, for a file named sales.txt > > and > > the same 5 columns, but put from a file into 5 columns on excel, and > > certain > > parameters to enter at the beginning... : > > > > ProductID = float(raw_input("Please enter the ProductID: ")) > > OrderQty = float(raw_input("Please enter the cutoff order quantity: ")) > > CSV = open('c:/sales.txt','r') > > import win32com.client > > x1=win32com.client.Dispatch('Excel.Application') > > x1.visible=1 > > x1.Workbooks.Add() > > x1.Range("A1").Select() > > x1.Range("A1:B1").Value = ("ProductID:",ProductID) > > x1.Range("A2:B2").Value = ("OrderQty:",OrderQty) > > x1.ActiveCell.Offset(4).Activate() > > x1.ActiveCell.Range("A1:E1").Value= > > ("OrderID","OrderDate","RegionID","Produc > > tID","OrderQty") > > x1.ActiveCell.Offset(2).Activate() > > for line in CSV.readlines(): > > line=line.rstrip() > > inOrderID,inOrderDate,inRegionID,inProductID,inOrderQty = line.split > > (",") > > if float(inProductID) == ProductID: > > if float(inOrderQty) >= OrderQty: > > xl.ActiveCell.Range("A1:E1").Value = > > (inOrderID,inOrderDate,inRegionID,inProductID,inOrderQty) > > xl.ActiveCell.Offset(2).Activate() > > > > I just don't know how to adjust this type of thing for Access... > > > > If anyone could help me by writing the script I would greatly appreciate > > it... > > Thank you so much. > > Sincerely, > > Dave > > > > > > > > > > > > From pyth at devel.trillke.net Tue Jun 11 18:04:25 2002 From: pyth at devel.trillke.net (holger krekel) Date: Wed, 12 Jun 2002 00:04:25 +0200 Subject: RfD: Automagically making a class instance 'synchronized' (draft impl.) In-Reply-To: <20020611205423.GA28113@lilith.my-fqdn.de>; from gh_pythonlist@gmx.de on Tue, Jun 11, 2002 at 10:54:23PM +0200 References: <20020611205423.GA28113@lilith.my-fqdn.de> Message-ID: <20020612000425.U6609@prim.han.de> Gerhard H?ring wrote: > For one of my projects, I'll need something not quite unlike the > following code. It's not tested, yet, but it looks ok and complete to > me. I thought that it could be useful to other developers who need to > use multithreading, so I'm posting it here. Maybe something like this > would even be a useful addition to the Standard Library? note that Ian Kjos some weeks ago send a nice module 'morethreading.py' to the dev-list. IIRC, it still waits for beeing reviewed and extended with other ideas (like synchronized methods). > from threading import RLock > ... > def __call__(self, *args, **kwargs): > self.proxy.__dict__["rlock"].acquire(1) > ... I think for inclusion into the standard lib it *might* be worth to reduce overhead (doubly-indirect function calls + lookups). A quick google search showed there has already been some discussion on this issue and there seems to be a 'synchronizing' metaclass. anyway, another comment: > try: > self.obj(*args, **kwargs) > except: > self.proxy.__dict__["rlock"].release() > raise > return > self.proxy.__dict__["rlock"].release() this can be safely substituted and then even returns the correct value with try: return self.obj(*args, **kwargs) finally: self.proxy.__dict__["rlock"].release() the finally statement is executed in all cases and doesn't hinder an exception to be raised eventually. I think it was designed for use cases exactly like this :-) regards, holger From NineOfSix at gmx.de Wed Jun 19 02:55:46 2002 From: NineOfSix at gmx.de (Axel Grune) Date: Wed, 19 Jun 2002 08:55:46 +0200 Subject: python cgi + IIS References: <3D0F1813.3010304@gmx.de> Message-ID: <3D102AF2.5010204@gmx.de> Steve Holden schrieb: > http://www.e-coli.net/pyiis.html Thats what i read and did ;-( Thanks, Axel From peter at engcorp.com Tue Jun 25 09:47:09 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 25 Jun 2002 09:47:09 -0400 Subject: Thread Memory Leak References: Message-ID: <3D18745D.554A7C44@engcorp.com> Skip Montanaro wrote: > > Marco> while 1: > Marco> listThread = [] > > Marco> for i in range(50): > Marco> listThread.append( threading.Thread( None, runthread ) ) > Marco> for i in listThread: > Marco> i.start() > Marco> for i in listThread: > Marco> i.join() > > Marco> pid = os.getpid() > Marco> print "===================================" > Marco> os.system( "ps -o vsize,rss %d" % pid ) > > You never remove any thread objects from your listThread list. It fills up > with completed threads. Actually, the list is rebound to a new empty list each pass through the while loop... I can't duplicate the symptoms on my machine (RedHat 7.1, Python 2.0). -Peter From stagnoNOSPAM at prosa.it Mon Jun 24 16:38:21 2002 From: stagnoNOSPAM at prosa.it (Marco Stagno) Date: Mon, 24 Jun 2002 20:38:21 GMT Subject: [ANN] my_gui: a gui module for MySQL . First public release (0.24) Message-ID: This is the first public release for "my_gui". my_gui.py is a simple Grafic User Interface for MySql It can be used as Python module to create your own MySQL interface. Sorry, no documentation yet GPL licence download it at http://www.prosa.it/projects/projects MAS! From whisper at oz.net Wed Jun 19 20:46:05 2002 From: whisper at oz.net (David LeBlanc) Date: Wed, 19 Jun 2002 17:46:05 -0700 Subject: Flame fests (was Re: python version?) In-Reply-To: Message-ID: Darn Aahz - I was hoping to see a report that you had passed flame testing ;-) David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Aahz > Sent: Wednesday, June 19, 2002 16:46 > To: python-list at python.org > Subject: Flame fests (was Re: python version?) > > > Everybody have fun playing "kick the newbie"? Maybe it's time to quit? > > (Yes, yes, I've read the thread -- I still think it's time to revert > c.l.py to its usual habits.) > -- > Aahz (aahz at pythoncraft.com) <*> > http://www.pythoncraft.com/ > > Project Vote Smart: http://www.vote-smart.org/ > -- > http://mail.python.org/mailman/listinfo/python-list From spam at fisher.forestry.uga.edu Sat Jun 1 10:20:32 2002 From: spam at fisher.forestry.uga.edu (Chris Fonnesbeck) Date: 1 Jun 2002 07:20:32 -0700 Subject: passing large arrays from C to Python as arguments Message-ID: I am looking for a way of passing relatively large arrays to python as an argument to a method call, without hard-coding the length of the array using Py_BuildValue. Is there an obvious solution to this, like passing it in a dictionary, or something? At any rate, it is very awkward to have to pass each element of each array into the argument individually. Thanks, cjf From jbublitzNO at SPAMnwinternet.com Sat Jun 29 04:42:56 2002 From: jbublitzNO at SPAMnwinternet.com (Jim) Date: Sat, 29 Jun 2002 08:42:56 GMT Subject: I'm an idiot References: <3D1D5C5E.3A5EB81D@earthlink.net> Message-ID: <3D1D72E1.8060000@SPAMnwinternet.com> Joseph A Knapka wrote: > "Beej J?rgensen" wrote: >>Close--but I don't believe readline() throws an exception on EOF; >>instead it just returns "". > Now, personally, I'd like to have any read after EOF throw > an exception. That's a nice way to break out of a loop, and > it removes the confusion that newbies and occasionally > oldbies (cough) sometimes experience: "If it returns '' at > EOF, what the heck does it return for empty lines???". > But I'm sure there are Very Good Reasons not to do this, > and that some wise person will presently educate me :-) It's the readline() method, meaning it reads/returns lines, which are everything up to and including a newline. In a text file (where this is meant to be used), an 'empty' line contains at least a newline, which is what readline() will return (not ''). The only place an 'empty line' can exist is after the final newline or after the last character after the final newline for an unterminated last line. By definition, that's EOF. That's not a good explanation of why it doesn't throw an exception - just an explanation of how readline() works and why the exception isn't necessary. Generally, reading past EOF isn't considered an error in C/C++ either. Look at read() or readline() in C for example. If you want readline() to throw an exception, you can define your own comparable function that does that. Jim From kosh at aesaeion.com Fri Jun 21 03:40:15 2002 From: kosh at aesaeion.com (kosh at aesaeion.com) Date: Fri, 21 Jun 2002 01:40:15 -0600 (MDT) Subject: compile python witout tkinter In-Reply-To: <20020621074746.GA765@lilith.my-fqdn.de> Message-ID: On Fri, 21 Jun 2002, Gerhard [iso-8859-15] H?ring wrote: > * kosh at aesaeion.com [2002-06-21 01:26 -0600]: > > On a machine I need to build python on I need to build it without tkinter. > > Why? Even if Tkinter gets compiled, it doesn't change anything for the > rest. You could even delete the tkinter modules afterwards, if you're > short on disk (quota). Because the libraries it depends on are not installed on that machine and there is no point installing them since they are not needed. From david.abrahams at rcn.com Thu Jun 6 18:38:13 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Thu, 6 Jun 2002 18:38:13 -0400 Subject: numeric limits? References: <200206061327.46814.gherron@islandtraining.com> Message-ID: <1e8501c20dab$7e717a50$6601a8c0@boostconsulting.com> Thanks, that's a big help. -Dave ----- Original Message ----- From: "Gary Herron" To: "David Abrahams" ; Sent: Thursday, June 06, 2002 4:27 PM Subject: Re: numeric limits? > On Thursday 06 June 2002 01:15 pm, David Abrahams wrote: > > Is there some straightforward way to find out the range of a Python Int (in > > code)? > > Use sys.maxint : > > >>> import sys > >>> sys.maxint > 2147483647 > > Gary Herron > > From mike.christie at athensgroup.com Fri Jun 21 14:20:39 2002 From: mike.christie at athensgroup.com (Mike Christie) Date: Fri, 21 Jun 2002 18:20:39 GMT Subject: [newbie] Overwriting class definitions References: <3D13563D.AB80D324@athensgroup.com> <3d135729$1_2@hpb10302.boi.hp.com> Message-ID: <3D136E77.2F6197E4@athensgroup.com> Daniel Fackrell wrote: > You'll need to reload(circle), as import will simply reuse a version that > has already been loaded. Thanks! Much appreciated. Mike From ypoi at spray.se Tue Jun 11 04:52:56 2002 From: ypoi at spray.se (DR) Date: 11 Jun 2002 01:52:56 -0700 Subject: Getting Tkinter to accept cyrillic text Message-ID: <83034362.0206110052.351cb526@posting.google.com> I need Tkinter entry and label widgets to support cyrillic letters (koi8-r). I read in some post that you should change sys.setdefaultencoding(), but that method doesn't exist in my Python (I use version 2.2.1) -Has this feature been changed or is my installation bad? Also there is this locale.setlocale() thing. What effect does changing it have? I really would appreciate some kind of checklist, like: Do this, then change that, then evereything works! Or a patch or something (Win95) Is there any comprahensive recource for this type of problem? I've only found some scattered posts so far. Please help me out, i'm stuck! regards, DR From david at dataovation.com Thu Jun 27 23:35:09 2002 From: david at dataovation.com (David McInnis) Date: Thu, 27 Jun 2002 20:35:09 -0700 Subject: Dialing out on MODEM Message-ID: <000601c21e54$cdd6ae80$221d7041@bigdaddy> I need to write a small script that opens com3 and writes an ATDT to dial out, answer the line and send a numeric message. Basically, I paging utility. I am using pyserial and cannot seem to get my modem to dial with Modem.write("ATDT5555555") David McInnis From FooWeissBarMike at hotmail.com Mon Jun 17 10:37:46 2002 From: FooWeissBarMike at hotmail.com (Michael Weiss) Date: Mon, 17 Jun 2002 10:37:46 -0400 Subject: System Configuration References: Message-ID: <3d0df505$1@news.mhogaming.com> I'd suggest getting the win32all extensions for Python and using the Windows API do to all of this. http://msdn.microsoft.com/library/default.asp provides an extensive docs for everything MS development related. http://starship.python.net/crew/skippy/ is the site for all win32-python goodness. "Rajat Chopra" wrote in message news:Pine.LNX.4.44.0206170010400.15076-100000 at calypso.cs.brandeis.edu... > I am looking to create a utility program that will query various aspects > of my system, such as the hardware configuration and the software programs > installed. > > I have looked into the Python module list but could not find much to do > with system analysis. At the moment, I would like my program to function > only on Windows 2000 systems. What modules can I use to determine such > things as: > > -How much memory is installed in the system? > -How much disk space is available on the system? > -What is the processor speed of the system? > -What is the bus speed? > -Is Micrsoft Office installed on the system? > -What version of Internet Explorer is on the system? > -Certain registry actions, such as inserting a key, querying a key, etc. > > Thank you in advance for your help. > > Rajat > From david.abrahams at rcn.com Tue Jun 4 08:01:56 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Tue, 4 Jun 2002 08:01:56 -0400 Subject: Behavior of += (was Re: [Python-Dev] Customization docs) References: <06da01c208f4$d69003c0$6601a8c0@boostconsulting.com> <200206010121.g511LxX19223@pcp742651pcs.reston01.va.comcast.net> <073501c20960$23f367e0$6601a8c0@boostconsulting.com> <200206011334.g51DY1D21669@pcp742651pcs.reston01.va.comcast.net> <07d801c20970$cdebe050$6601a8c0@boostconsulting.com> <3CFC50BD.CB9CB70C@replyto.address.invalid> Message-ID: Funny that this topic should come up over here, since: http://aspn.activestate.com/ASPN/Mail/Message/python-dev/1222411 minds-think-alike-ly y'rs, dave "Greg Ewing" wrote in message news:3CFC50BD.CB9CB70C at replyto.address.invalid... > Jeff Epler wrote: > > > > Maybe the bytecode for inplace operations like > > f[i] += v > > should implement the > > pseudocode > > _temp = f[i] > > _new = inplace_add(_temp, v) > > if _new is not _temp: > > f[i] = _new > > del _temp, _new > > That's a nice idea... > > > However, this would probably double the bytecode size of the sequence, > > and hurt performance similarly.... > > It needn't, if: > > (1) the INPLACE_xxx bytecodes leave the first operand > on the stack > > (2) there are new STORE_xxx_IF_UNCHANGED bytecodes that > compare the value to be stored with the previous one. > > The total number of bytecodes should then be the same, > and all the new work would be done in C code, which > ought to be pretty fast (a pointer comparison and > a few extra inc/decrefs). > > -- > Greg Ewing, Computer Science Dept, > University of Canterbury, > Christchurch, New Zealand > http://www.cosc.canterbury.ac.nz/~greg From vjovanov at stevens-tech.edu Tue Jun 4 15:49:06 2002 From: vjovanov at stevens-tech.edu (Vojin Jovanovic) Date: Tue, 4 Jun 2002 15:49:06 -0400 Subject: self References: Message-ID: I don't see how that is going to work. In fact I tried things like that before without success. Just sticking the dictionary into eval/exec is missing the point. Every time parsing is done flow needs to go through __getattr__ special method to evaluate nested equations. Without self. you can't achieve that effect. Try the approach you suggested and you'll get '#U'. Vin "Vojin Jovanovic" wrote in message news:TL7L8.79$4p7.4100181 at newnews.cc.stevens-tech.edu... > > Which of i, j and k are instance variables? Which are locals? Which are > > globals? For all its virtues, Python isn't telepathic . > > Well, now that you pointed it out, I think that Python should be telepathic. > Those i,j and k variables should have been found in class C, otherwise they > should have been searched outside of the class. I read the FAQ page that > somebody sent me and I really think that the main reason for self is ... > "When classes were added to Python, this was (again) the simplest way of > implementing methods without too many changes to the interpreter. " which is > the main and really lousy argument. All, other arguments are debatable. > > Now let me give you the problem with self which is making my life > complicated. Consider this class. > > class Foo: > def __init__(self): > self.__dict__['Equations']={ > 'a':str(5), > 'b':'self.a+5', > 'c':'self.b*self.a'} > > def __getattr__(self,arg): > if self.Equations.has_key(arg) == 0: > raise AttributeError, "Foo instance has no attribute '" + arg + "'" > try: > try: #first check if this is a simple expression > return eval(self.Equations[arg]) > except: #if not try to execute it > exec self.Equations[arg] > except: #if even that didn't work then just return undefined > return '#U' > > def __setattr__(self,arg,val): > self.__dict__['Equations'][arg]=str(val) > > def __delattr__(self,arg): > del self.__dict__['Equations'][arg] > > This class implements a kind of symbolic behavior with the ability to add > new equations on the fly. For example... > > > >>> import foo > >>> A=foo.Foo() > >>> A.Equations > {'b': 'self.a+5', 'c': 'self.b*self.a', 'a': '5'} > >>> A.f='self.b*self.c' > >>> A.f > 500 > >>> A.Equations > {'f': 'self.b*self.c', 'b': 'self.a+5', 'c': 'self.b*self.a', 'a': '5'} > > > As you can see, equations get added on the fly and the parsing gets done as > the attribute is being called. Now, notice that ugly self. thing in the > equations. Instead of just typing >>>A.f='a*c' I have to add self in front > a and c to achieve the desired effect. I could not find any other way to > implement the class in order to avoid typing self. which of course it > doesn't mean that there isn't any. If anybody has an idea how to do this > please let me know. Otherwise, here is the situation where the self > concept is bad and having such a dynamic language like Python I think there > has to be a way out of this problem. > > Why is this all relevant? Well, I am working on embedding an interpreted > language in a large engineering application and Python is one of few > candidates. So I have been looking for its pros and cons. So far it passed > all the tests except the above. Because, imagine if we required from the > user of our system that he needs to type self. or even s. in front of every > new variable that he has in his equation, it would be a big turn off. > > Vin > > > From peter at engcorp.com Thu Jun 20 21:04:09 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 20 Jun 2002 21:04:09 -0400 Subject: RE strings (was: Variable Interpolation - status of PEP 215) References: <4PfQ8.44245$n4.10307683@newsc.telia.net> <29e28c51.0206201156.7e61a7f5@posting.google.com> Message-ID: <3D127B89.EE1C17F4@engcorp.com> Cimarron Taylor wrote: > > I like it! > > To me > > m = re'^EMP:([^,]*),([^,]*),([^,]*),([^,]*)$'.match(line) > if m: > ... > > is much clearer and more maintainable than > > import re > emp_re = re.compile(r'^EMP:([^,]*),([^,]*),([^,]*),([^,]*)$') > m = re.match(emp_re, line) > if m: > ... But is it really much clearer and more maintainable than import re m = re.match(r'^EMP:([^,]*),([^,]*),([^,]*),([^,]*)$', line) if m: ... Given that the only real difference is you skip an import, and at the cost of modifying the language definition in an unusual manner, is there any point to this at all? -Peter From milos.prudek at tiscali.cz Sat Jun 8 08:03:17 2002 From: milos.prudek at tiscali.cz (Milos Prudek) Date: Sat, 08 Jun 2002 14:03:17 +0200 Subject: htmllib and parsing data sourrounded by HTML tags Message-ID: <3D01F285.5010103@tiscali.cz> I studied htmllib hard and I was able to subclass it and do some processing of HTML tags. I managed to extend it to process , for instance. But what about the text that is surrounded by HTML tags? Can sgmllib, htmllib and formatter be leveraged to find data sourrounded by HTML tags and process them? An example HTML:
First Name:Peter Last Name:Smith
The task is to locate second row in this table, and pull string from second column of this row, i.e. "Smith". Naturally this can be done without htmllib, but for the sake of systematic approach I'm interested whether it can be done with htmllib. It seems that htmllib walks on tags but leaves everything that is not a HTML tag unprocessed and writes it out "as is", and there are not hooks to attach to. Also it seems that there would have to be a "row counter" and "column counter" attributes in sgmllib, but I do not feel smart enough to understand sgmllib enough to subclass it... Should I forget about htmllib because it is unsuitable for this? -- Milos Prudek From dryose at juno.com Mon Jun 3 16:02:39 2002 From: dryose at juno.com (yose) Date: 3 Jun 2002 13:02:39 -0700 Subject: mySQL on Solaris .8 References: <79d1869.0206030646.512af52c@posting.google.com> Message-ID: <79d1869.0206031202.228c4387@posting.google.com> dryose at juno.com (yose) wrote in message news:<79d1869.0206030646.512af52c at posting.google.com>... > I am trying to install a mySQL database in solaris 2.8. I have a copy > of the distro for mySQL-python-0.9.1. When I try to run setup.py, I am > told that I am missing distutils.core > > Where do I get this? What package is it part of? > > Thanks! Let me follow-up to my original message: I need to get a mySQL database working in Solaris, and I need to access it via the Python API. I would appreciate any help that you can offer!! Joe From derek at wedgetail.com Mon Jun 24 22:30:15 2002 From: derek at wedgetail.com (Derek Thomson) Date: Tue, 25 Jun 2002 02:30:15 GMT Subject: I'd give up Perl tomorrow if only... References: <3D12F6FC.3000608@wedgetail.com> Message-ID: <3D17D5B6.1090203@wedgetail.com> Michael P. Soulier wrote: > On Fri, 21 Jun 2002 09:50:54 GMT, Derek Thomson wrote: > >>Among other things, it's one of the reasons I'm tinkering with a Perl ORB. > > > There's also XMLRPC, and SOAP, something already supported by both > languages. These are no good for reasons I've described elsewhere on this thread. To summarize, the major problem is this - "How do you represent object references?". It's the difference between a marshalling scheme (which is what XMLRPC, SOAP, and CORBA-IIOP are) and a scalable architecture for distributed systems, which is what CORBA is (distributed as opposed to merely "client-server"). The simple answer for those who have large bandwidth, and like to waste it, and therefore want to use SOAP and/or XMLRPC as an on-the-wire protocol, is to add a CORBA-like infrastructure on top of, say XMLRPC, which I have in fact done with Fnorb in the xmlrpc branch on SourceForge. Regards, Derek. From tebeka at cs.bgu.ac.il Mon Jun 17 08:54:06 2002 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 17 Jun 2002 05:54:06 -0700 Subject: Help: win32gui and threads, process won't shut down Message-ID: <33803989.0206170454.4609ebab@posting.google.com> Hello All, Sorry if this is the 2'nd time I'm sending this. My browser hang up sending the 1'st one. I've wrote a simple logger daemon which has UI through Window's taskbar. (See code below) However when I close it from the taskbar the windows shuts down but the pythonw process still lives and I have to kill it explicitly. Any ideas how to make is shutdown properly? TIA Miki -------------- #!/usr/bin/env python '''Logger daemon Opens socket server and write messages to log file ''' __author__ = 'Miki Tebeka ' __version__ = '$Revision: 1.3 $' # $Source: /home/miki/.cvsroot/logging/logd.py,v $ import SocketServer import socket import Queue import threading import time import re from win32api import * from win32gui import * import win32con import sys import os, os.path MESSAGE_QUEUE = Queue.Queue(0) # Thread safe message queue with no limit # These two are not protected by mutex since only the main thread write there and # the worker thread reads them WRITE = 1 # Write flag NEW_LOG = 0 # Create new file def error(msg): '''Error function''' MessageBox(win32con.MB_OK, msg) class SocketListener(SocketServer.BaseRequestHandler): '''Socket listener. Reads line from socket and place it in message queue''' def __init__(self, request, client_address, server): '''Constructor''' SocketServer.BaseRequestHandler.__init__(self, request, client_address, server) def handle(self): '''Handler function. Reads line from socket and writes to queue''' msg = '' while 1: try: c = self.request.recv(1) if not c: return if (c == '\n'): MESSAGE_QUEUE.put(msg) msg = '' else: msg += c except socket.error, e: error('Error: %s' % e) return class LoggerDaemon(SocketServer.ThreadingTCPServer, threading.Thread): '''Logger Daemon. Listens on given port and threads listeners upon requests''' def __init__(self, port): self.port = port self.addr = ('', self.port) threading.Thread.__init__(self) SocketServer.ThreadingTCPServer.__init__(self, self.addr, SocketListener) def run(self): self.serve_forever() class LogWriter(threading.Thread): '''Log writer. Get messages from queue and write to file''' def __init__(self, log_dir): self.log_dir = log_dir if not os.path.isdir(self.log_dir): try: os.makedirs(self.log_dir) except OSError, ose: error("Can't create log directory %s (error was: %s)" % (self.log_dir, ose)) sys.exit(1) self.new_log() threading.Thread.__init__(self) def run(self): '''Thread function''' global NEW_LOG, WRITE while 1: msg = MESSAGE_QUEUE.get() if NEW_LOG: self.new_log() NEW_LOG = 0 # This is a sync NO-NO but we can live with that if WRITE: print >> self.fp, msg.strip() self.fp.flush() def new_log(self): '''New log file''' logname = '%s/%s' % (self.log_dir, re.sub('(\s+)|:', '_', time.ctime())) self.log_file = logname self.fp = open(self.log_file, 'a') class MainWindow: '''Main window for handling taskbar notifications''' def __init__(self): '''Constructor''' self.ID_TBAR = win32con.WM_USER + 20 self.icon_file = './logd.ico' self.title = 'BeeLogger Daemon' self.IDM_TOGGLE, self.IDM_NEWLOG, self.IDM_QUIT = 1023, 1024, 1025 self.resume_pause_msg = ('Resume', 'Pause') message_map = { win32con.WM_DESTROY: self.OnDestroy, win32con.WM_COMMAND: self.OnCommand, self.ID_TBAR : self.OnTaskbarNotify, } # Register the Window class. wc = WNDCLASS() hinst = wc.hInstance = GetModuleHandle(None) wc.lpszClassName = "BeeLoggerDaemon" wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW; wc.hCursor = LoadCursor( 0, win32con.IDC_ARROW ) wc.hbrBackground = win32con.COLOR_WINDOW wc.lpfnWndProc = message_map # could also specify a wndproc. classAtom = RegisterClass(wc) # Create the Window. style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU self.hwnd = CreateWindow( classAtom, self.title, style, \ 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, \ 0, 0, hinst, None) UpdateWindow(self.hwnd) # Try and find a custom icon if not os.path.isfile(self.icon_file): icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE self.hicon = LoadIcon(0, win32con.IDI_APPLICATION) else: self.hicon = LoadImage(hinst, self.icon_file, win32con.IMAGE_ICON, 0, 0, icon_flags) flags = NIF_ICON | NIF_MESSAGE | NIF_TIP nid = (self.hwnd, 0, flags, self.ID_TBAR, self.hicon, self.title) Shell_NotifyIcon(NIM_ADD, nid) def OnDestroy(self, hwnd, msg, wparam, lparam): nid = (self.hwnd, 0) Shell_NotifyIcon(NIM_DELETE, nid) PostQuitMessage(0) # Terminate the app. def OnTaskbarNotify(self, hwnd, msg, wparam, lparam): global WRITE if lparam==win32con.WM_LBUTTONUP or lparam==win32con.WM_LBUTTONDBLCLK or lparam==win32con.WM_RBUTTONUP: menu = CreatePopupMenu() AppendMenu(menu, win32con.MF_STRING, self.IDM_TOGGLE, self.resume_pause_msg[WRITE]) AppendMenu(menu, win32con.MF_STRING, self.IDM_NEWLOG, 'New Log') AppendMenu(menu, win32con.MF_STRING, self.IDM_QUIT, 'Quit') pos = GetCursorPos() TrackPopupMenu(menu, win32con.TPM_LEFTALIGN, pos[0], pos[1], 0, self.hwnd, None) return 1 def OnCommand(self, hwnd, msg, wparam, lparam): global WRITE, NEW_LOG id = LOWORD(wparam) if id == self.IDM_TOGGLE: WRITE = 1 - WRITE elif id == self.IDM_NEWLOG: NEW_LOG = 1 elif id == self.IDM_QUIT: DestroyWindow(self.hwnd) else: raise ValueError('Unknown command: %s' % id) # MAIN if __name__ == '__main__': if len(sys.argv) != 3: print >> sys.stderr, 'usage: logd LOG_DIR PORT' sys.exit(1) # Start writer writer = LogWriter(sys.argv[1]) writer.start() # Start TCP server logd = LoggerDaemon(int(sys.argv[2])) logd.start() # Start UI w=MainWindow() PumpMessages() -------------- From martin at strakt.com Tue Jun 4 03:24:37 2002 From: martin at strakt.com (Martin =?iso-8859-1?Q?Sj=F6gren?=) Date: Tue, 4 Jun 2002 09:24:37 +0200 Subject: 'for every' and 'for any' In-Reply-To: <7934d084.0206031636.5c29b31f@posting.google.com> References: <20020526135944.A32690@hishome.net> <20020526091742.A987@unpythonic.net> <7934d084.0206031636.5c29b31f@posting.google.com> Message-ID: <20020604072437.GA21777@strakt.com> On Mon, Jun 03, 2002 at 05:36:46PM -0700, Andrae Muys wrote: > > Now I just don't understand how this position can possibly make sense? > C dosn't have any 32-bit int types standardised, so what do _you_ use > when you need one? Please don't tell me you don't use int, or I'll > have to hunt you down and put you out of your misery ;). I personally > have absolutely no problem with any of the 3 examples you gave above: Doesn't C99 specify ? With int8_t, int16_t, ..., uint8_t, uint16_t, ... Martin -- Martin Sj?gren martin at strakt.com ICQ : 41245059 Phone: +46 (0)31 7710870 Cell: +46 (0)739 169191 GPG key: http://www.strakt.com/~martin/gpg.html From dougz at cs.washington.edu Mon Jun 24 18:57:06 2002 From: dougz at cs.washington.edu (Douglas Zongker) Date: Mon, 24 Jun 2002 22:57:06 GMT Subject: adding attributes to builtin functions Message-ID: I know that when you def a function in Python you can add arbitrary attributes to it: def foo(): return 4 foo.special = 6 Is it possible to do this with a function that comes from a C extension module? import mymodule print mymodule.myfunction mymodule.myfunction.special = 6 gives me: Traceback (most recent call last): File "", line 1, in ? TypeError: 'builtin_function_or_method' object has only read-only attributes (assign to .special) Is there a way to define a builtin function whose attributes aren't read-only? thanks, dz From bobx at linuxmail.org Thu Jun 13 17:35:03 2002 From: bobx at linuxmail.org (Bob X) Date: Thu, 13 Jun 2002 21:35:03 GMT Subject: Python 2.2.1 References: Message-ID: <3D09100A.4040201@linuxmail.org> If you go to www.activestate.com and get the ActivePython setup it will do it all for you. : ) Dave wrote: > Hi, I am 12 years old and would like to begin learning Python over > the summer. I have Windows 98 SE. I have python 2.2.1 and all of its > utilities on my computer. I am taking a tutorial > from http://softwaredev.earthweb.com/sdopen/article/0,,12382_626311,00.html > If you go to it and scroll down to the paragraph entitled *Getting > Started* there is a paragraph that says, *"You will need to cause the > directory containing the file named python.exe to be listed in your > system environment variable named path. If you already know how to set > the path, go ahead and do it. If you don't already know how, you may > need to get some help." * > ** > > How do I set the path and what should the name of the path be? All > help and information would be appreciated. Thanks.:) From altis at semi-retired.com Fri Jun 14 12:11:13 2002 From: altis at semi-retired.com (Kevin Altis) Date: Fri, 14 Jun 2002 09:11:13 -0700 Subject: ANN: PythonCard 0.6.7 Message-ID: PythonCard is a GUI construction kit for building cross-platform desktop applications on Windows, Mac OS X, and Linux. Release 0.6.7 includes over 30 sample applications, new additions include chat, webserver, pictureViewer, slideshow, and webgrabber. Four of the samples have been promoted to tools status: codeEditor, findfiles, resourceEditor, and textEditor. This release supports the new wxPython 2.3.3 preview for Mac OS X. All the information you need about PythonCard can be found on the project web page at: http://pythoncard.sourceforge.net/ The installation instructions and walkthroughs are available on the main documentation page: http://pythoncard.sourceforge.net/documentation.html You can download the latest release at: http://sourceforge.net/project/showfiles.php?group_id=19015 For a list of some of the samples that have been built with PythonCard and screenshots of them in action go to: http://pythoncard.sourceforge.net/samples.html A description of each sample is included in the readme.txt file in each sample directory. The kind people at SourceForge host the project: http://sourceforge.net/projects/pythoncard/ If you want to get involved the main contact point is the Mailing list: http://lists.sourceforge.net/lists/listinfo/pythoncard-users PythonCard requires Python 2.1.x or later and wxPython 2.3.2.1 or later. wxPython can be downloaded at http://www.wxpython.org/ ka --- Kevin Altis altis at semi-retired.com From jiri at baum.com.au Sun Jun 2 04:17:38 2002 From: jiri at baum.com.au (Jiri Baum) Date: Sun, 2 Jun 2002 18:17:38 +1000 Subject: How to call functions inside a cgi script from the html interface? References: Message-ID: <2bkcda.c25.ln@10.0.0.1> Ken: > How to call functions inside a cgi script from the html interface? > Eg. If there is a link on the html display call "Search", how do I get it > to call the function call "def search( )" inside the cgi script? You need to get yourself a CGI programming reference, or even a good HTML book, and refer to them before you post questions on the (wrong) newsgroup. Also read the docs for the python cgi module (eg at www.python.org). HTTP doesn't have any facilities for doing this directly. Every time a user selects a link, a request is made to the server for that page. This can either be a completely different cgi script, or it can be the same script with different parameters. Either way, it's a separate connection, so don't expect variables to stay. Jiri -- Jiri Baum http://www.csse.monash.edu.au/~jirib MAT LinuxPLC project --- http://mat.sf.net --- Machine Automation Tools From pyth at devel.trillke.net Tue Jun 18 13:07:09 2002 From: pyth at devel.trillke.net (holger krekel) Date: Tue, 18 Jun 2002 19:07:09 +0200 Subject: why len(list) instead of list.len() ? In-Reply-To: ; from emile@fenx.com on Tue, Jun 18, 2002 at 02:03:52PM +0000 References: Message-ID: <20020618190709.D15079@prim.han.de> Emile van Sebille wrote: > "Markus Jais" wrote in message > news:EhBP8.1$Qn1.1124 at news.ecrc.de... > > hello > > > > I way wondering why one has to write > > > > list = [2, 3, 5] > > print len(list) > > > > instead of list.len() > > > > in Ruby I can write > > > > array = [2, 3, 4] > > puts array.length() > > > > > > Because a two-line wrapper goes a long way? > > Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> class myList(list): > ... len = list.__len__ > ... > >>> l = myList([1,2,3,4]) > >>> l > [1, 2, 3, 4] > >>> l.len() > 4 > >>> l.extend([5,6,7]) > >>> l.len() > 7 this 'hands-on fix' has come up before, too. It bears the problem that you would have to wrap every list that you work with. Otherwise you get nasty inconsistencies. Actually i think that there might a solution for the 'why does len not work as expected'- problem. Once the builtin types cannot not only be extended by inheritance but also by directly binding names in the types attribute space. Something like: list.len=list.__len__ could then really fix this problem. Of course there would still be major combats over the question whether it should be included by default :-) holger From dfackrell at DELETETHIS.linuxmail.org Mon Jun 24 10:47:14 2002 From: dfackrell at DELETETHIS.linuxmail.org (Daniel Fackrell) Date: Mon, 24 Jun 2002 08:47:14 -0600 Subject: GOTO w/ Python? References: <3d10ed95@xpl-sdf1-sec1.> <3D11A21D.9010809@mxm.dk> <3D11DA9B.163A7BD0@info.unicaen.fr> <3D12EEAA.9C3A3D29@info.unicaen.fr> <6v30fa.sm1.ln@grey.aerojockey.localdomain> Message-ID: <3d1730f2$1_1@hpb10302.boi.hp.com> After skimming the linked page to get a feel for the CAME FROM statement, is it conceptually different from short procedures? Does the only difference lie in the fact that for compiled languages one of the instances will be inline? I do understand that it would have some effect on variable scoping, but this can be easily handled in other ways. So what's the benefit that might outweigh the opacity of the code created? -- Daniel Fackrell (dfackrell at linuxmail.org) When we attempt the impossible, we can experience true growth. "Carl Banks" wrote in message news:6v30fa.sm1.ln at grey.aerojockey.localdomain... > Jerzy Karczmarczuk wrote: > > (Oh, I adored that wonderful piece of programming madness, an "article" > > where somebody proposed a new super-Fortran where GO TO was replaced by > > CAME FROM statement, and the language had an inspiring non-deterministic > > conditional: If <> THEN WHAT?. > > Any references, anybody?) > > > http://www.fortran.com/fortran/come_from.html > > > -- > CARL BANKS http://www.aerojockey.com > "Nullum mihi placet tamquam provocatio magna. Hoc ex eis non est." From observer at NOSPAM.space.pl Thu Jun 13 04:57:21 2002 From: observer at NOSPAM.space.pl (Johann) Date: Thu, 13 Jun 2002 10:57:21 +0200 Subject: How to check version of Python under CGI References: <873cvrin1q.fsf@tux.ntw23.fr> Message-ID: On 13 Jun 2002 10:46:09 +0200, Sylvain Thenault wrote: >> I would like to write a simple CGI script to get as much info about >> installed Python as possible. But I even don't know how to check >> version of Python. :( From shell command it is easy, but how to do it >> from CGI script? Eg. > >print "Python version: %s" % sys.version Thanx. Do you know how to check what modules are installed? E.g. I would like to check if PYANA or other xml modules are installed. -- Johann From aurelienviolet at noos.fr Sat Jun 1 22:30:41 2002 From: aurelienviolet at noos.fr (aurel-le-gnou) Date: Sun, 02 Jun 2002 04:30:41 +0200 Subject: Help for Tkinter and python's programming Message-ID: <3CF98351.95763821@noos.fr> Hi, I'm french and just beginning in Python's programming. I'm doing a really simple GUI with the module "Tkinter" for the implementation of a meta search engine based on Google and altavista. This Gui is quite finished but i've a problem. I'm sure it's really stupid but I really not understand the reasons of this pb. If someone can Help me, it would be really fine. Here is my problem: I create a GUI with some buttons and entry, textbox, radiobuttons... Then there is a mainloop wainting for events. When the button 1 is pressed on a button, i want to get each content of these entries... and the state of the radiobuttons... Then launch a program with the differents values and contents found just before. I don't success in associating the event and the function to execute with the different arguments All my tkinter widgets are created in a simple main by calling some functions (no object implementation, this interface is really simple). Particularly these two functions define naturally before the main: def make_button(frame, text, color, side, padx, pady): button = Button(frame, text=text, fg=color, bg='white') button.pack(side=side,padx=padx, pady=pady) return button def make_call(frame_left, frame_right, list_one, list_two, button_number, button_search, button_language, button_rank, button_engine): .... .... return button_language_content, button_number_content, button_search_content, list_one, list_two, button_rank_content, button_engine_content The goal of the function make_call is: - to get the differents arguments in the diferents Entry and the state of different radiobuttons - then call an other program program with these arguments. In my main: ... button_go = make_button(bottom,'GO','black',LEFT, '5m',0) ... ... button_go.bind("", make_call(frame_left, frame_right, list_one, list_two, button_number, button_search, button_language, button_rank, button_engine)) # the arguments of make_call() are visible and defined in the main when I do this "bind". .... root.mainloop() So, I just want to execute the fonction make_call with some arguments (which corresponds to the different entries and radiobuttons to check their content) when the button1 is pressed on my button_go. (this arguments are visible in my main) But the problem is that even if the user doesn't click on the button the associate function is executed. I've also problem in giving arguments to make_call() (the number of arguments is sometimes wrong ... Is there a default argument "event" given to the function with some informations ?) Thanks a lot for your help and your criticm about what i've done wrong. Aur?lien Violet aurelienviolet at noos.fr From mgilfix at eecs.tufts.edu Mon Jun 10 08:49:17 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Mon, 10 Jun 2002 08:49:17 -0400 Subject: Does Python need a '>>>' operator? In-Reply-To: ; from cben@tx.technion.ac.il on Mon, Jun 10, 2002 at 08:57:15AM +0300 References: Message-ID: <20020610084917.C23641@eecs.tufts.edu> On Mon, Jun 10 @ 08:57, Beni Cherniavksy wrote: > I just got another idea: use 0x1234 for 0-filled numbers and 1xABCD for > 1-filled ones. That way you impose no restrictions on what follows the > prefix and keep backward compatibility. 0xFFFFFFFF stays a 2^n-1 > _positive_ number, as it should be. The look of 1x is weird at first but > it is very logical... Just a vote of confidence. I like this solution a lot. Seems the best of both worlds, since it leaves the current scheme alone and it doesn't mean fiddling with expected sizes. -- Mike -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From robin at jessikat.fsnet.co.uk Sun Jun 30 07:53:27 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sun, 30 Jun 2002 12:53:27 +0100 Subject: yield equivalent in C/JavaScript? References: <7xy9cxhlvx.fsf@ruckus.brouhaha.com> <7xit41i7i9.fsf@ruckus.brouhaha.com> <14ms5VAygsH9Eww2@jessikat.fsnet.co.uk> <7xelepnk84.fsf@ruckus.brouhaha.com> Message-ID: In article <7xelepnk84.fsf at ruckus.brouhaha.com>, Paul Rubin writes >Robin Becker writes: >> However the content.gz data has to be exactly compatible with gzip. My >> experiments with Python-2.1/zlib on freeBSD give me a compressed string >> that's slightly too long for some reason. As an example gzip --> 14099 >> bytes while zlib.compress-->15008 bytes. >> >> Anyone know what I need to do to make zlib work properly in this >> context? Or should I really be using the gzip module? > >You're probably better off using mod_gzip (an apache module that >compresses the output automatically) rather than trying to compress >from Python. Note that gzip encoding doesn't work so well in some IE >versions. Unfortunately I don't think the server uses apache, but maybe it can be persuaded to do it automatically. The IE stuff seems to rely too much on the URL extension so provided it thinks it's htm or html IE 5.x seems OK. -- Robin Becker From morningstar at yubc.net Sun Jun 23 13:35:35 2002 From: morningstar at yubc.net (Ivan J.) Date: 23 Jun 2002 10:35:35 -0700 Subject: printing on the browser Message-ID: Hi! This is actually cgi quesion, but ... Is there a way to print both HTML and IMAGE parts using: >>>print "Conent-type: ...", statement, if not is there any other way to create web page with text and images without savingimages onto disk? Thank you! From "aglyportat\" at n-o.spa__mmm.yahoo dott com> Sat Jun 15 22:40:43 2002 From: "aglyportat\" at n-o.spa__mmm.yahoo dott com> (Anton Graph) Date: Sat, 15 Jun 2002 19:40:43 -0700 Subject: RH7.2 2.4.X off_t: long or long long? References: Message-ID: Anton Graph wrote: > I have an odd problem trying to link my app: > > glog.o(.text+0x100a): undefined reference to `loadfile(char const *, > long long *)' > collect2: ld returned 1 exit status > > > in loadfile.C: > > char * > loadfile(const char *path, off_t *length) > { > ... > > and the declaration in the header is: > > char *loadfile(const char *path, off_t *size=0); > > nm -C libgen.a |grep loadfil > U loadfile(char const *, long *) > loadfile.o: > 00000000 T loadfile(char const *, long *) > U loadfile(char const *, long long *) > > Why are there two references differing in the last arg? Is off_t > supposed to be long or long long? > > Thank you! > Nevermind, this had something to do with Python.h that I've included. Removed the inclusion of Python.h and everything works fine. For some odd reason /* The number of bytes in an off_t. */ #define SIZEOF_OFF_T 8 is defined in pyconfig.h which is used by Python.h but oddly there is no redefinition of off_t anywhere in Python files. Kinda puzzling. From ehab_teima at hotmail.com Wed Jun 5 19:14:14 2002 From: ehab_teima at hotmail.com (Ehab Teima) Date: 5 Jun 2002 16:14:14 -0700 Subject: minidom and encoding problem Message-ID: <17aafe08.0206051514.4af054d2@posting.google.com> Hi, I'm using Python 2.1. I wrote classes to create xml document from scratch. The code worked fine until I hit an encoding problem. The classes can read text and insert it as is to xml document using creatTextNode. This text had characters > 127, and I got this error. self._doc=xml.dom.minidom.parse(self._xml_filename) File "D:\Python21\lib\xml\dom\minidom.py", line 910, in parse return _doparse(pulldom.parse, args, kwargs) File "D:\Python21\lib\xml\dom\minidom.py", line 902, in _doparse toktype, rootNode = events.getEvent() File "D:\Python21\lib\xml\dom\pulldom.py", line 234, in getEvent self.parser.feed(buf) File "D:\Python21\lib\xml\sax\expatreader.py", line 92, in feed self._err_handler.fatalError(exc) File "D:\Python21\lib\xml\sax\handler.py", line 38, in fatalError raise exception xml.sax._exceptions.SAXParseException: :75:1: not well-formed I know it's not possible to add an enconding attribute using writexml, so the generated document only has . Is there any way to get around this problem. I'd like to be able at least to parse the document while reading using the proper encoding, such as, encoding="ISO-8859-1". I'm only using minidom, any ideas how? Another question: Does any body know how to get the rootnode of a document? If I know the root node, I can add the proper header and then write the root node using writexml. Thanks, Ehab From wurmy at earthlink.net Fri Jun 28 11:33:01 2002 From: wurmy at earthlink.net (Hans Nowak) Date: Fri, 28 Jun 2002 15:33:01 GMT Subject: Be the first on your block to register your computer. References: <3D1B6E69.1090204@earthlink.net> Message-ID: <3D1C8169.2040800@earthlink.net> Neil Hodgson wrote: > I suspect that a Python interpreter could be built out of a set of > Outlook message processing rules although I wouldn't be the one to volunteer > to do it whereas I will volunteer to do the Excel port if it should ever be > needed. Cool! OutlookPython! I can see the ads now... "Virus developers! Are you tired of having to use a shoddy language like VB for your products? Then upgrade now to OutlookPython! Combining all the prized features of Outlook(TM) with a real programming language, including: - improved standard library makes reading mailboxes a breeze! - attach any file with just one function call! - reuse code to build your own virus library! - excellent introspection features allow for self-modifying code! - as an additional bonus, network features even allow for DoS attacks! Register now!" -- Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) # decode for email address ;-) The Pythonic Quarter:: http://www.awaretek.com/nowak/ From logiplexsoftware at earthlink.net Tue Jun 18 17:14:30 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Tue, 18 Jun 2002 14:14:30 -0700 Subject: python version? In-Reply-To: References: <3tingu8psfmefoab93pl8gips8hg7sgpvp@4ax.com> <9YBP8.44418$GY.13865843@twister.nyroc.rr.com> Message-ID: <20020618141430.76aa68ec.logiplexsoftware@earthlink.net> On Tue, 18 Jun 2002 20:48:14 GMT George Hester wrote: > Bah humbug. Ah, the Christmas spirit, all year round ;) -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From chris.lyon at tgm.co.uk Tue Jun 25 06:46:28 2002 From: chris.lyon at tgm.co.uk (Chris Lyon) Date: 25 Jun 2002 03:46:28 -0700 Subject: My .py CGI script works in IE but not Netscape References: <79b54d28.0205311837.731002aa@posting.google.com> Message-ID: <7652d5e7.0206250246.4b6e72ec@posting.google.com> Netscape is much less forgiving than IE, Check table tags and complete html,head and body tags alway's help. Content type will make a difference, and do include a 'proper DOCtype' above the head. It all helps From gerhard.haering at gmx.de Fri Jun 21 14:46:43 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Fri, 21 Jun 2002 20:46:43 +0200 Subject: ssl on windows In-Reply-To: References: Message-ID: <20020621184643.GB13964@lilith.my-fqdn.de> * Scott Hathaway [2002-06-21 13:09 -0500]: > I would like to use ssl on Windows with Python 2.2. Is this available yet? > If so, how can I go about getting it installed? When I try to get an https > address with urllib, it tells me that https is an unknown protocol. I've once built the socket module for Python 2.2 with SSL support. I don't think I've updated it for Python 2.2.1, yet. But you can still use it for 2.2.1, as these versions are binary compatible. I'll update it to 2.2.1 during the next day(s). Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From a.schmolck at gmx.net Fri Jun 7 13:17:45 2002 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 07 Jun 2002 18:17:45 +0100 Subject: __imul__ broken for 'objects' in 2.2.1 Message-ID: OK, after unsuccessfully trying for about half an hour to submit this to the sf bug tracker, I gave up: class Breaky(object): def __imul__(self, other): print "imuling" return self sq = Breaky() sq *=1. gives: Traceback (most recent call last):[...] line 10, in ? sq *=1. TypeError: can't multiply sequence to non-int Unless I'm overlooking something, this is a fairly serious bug and I can't see a way to work around it (getattribute would presumably work, but slow everything down unacceptably, so the only 'solution' seems to be to have no inplace-multiplication). I had the same behavior on two different machines (running Mandrake 8.2 and Suse 7.3). alex From calves at coelce.com.br Thu Jun 20 08:19:36 2002 From: calves at coelce.com.br (Alves, Carlos Alberto - Coelce) Date: Thu, 20 Jun 2002 09:19:36 -0300 Subject: RES: module string.py Message-ID: <29A97D00F387D411AC7900902770E148058F93C4@lcoeexc01.coelce.net> See answer below: > -----Mensagem original----- > De: r_proietti at yahoo.com [mailto:r_proietti at yahoo.com] > Enviada em: quinta-feira, 20 de junho de 2002 08:39 > Para: python-list at python.org > Assunto: module string.py > > > Hi, I'm a Python newbye so I'm sorry if my questions will be a little > stupid... > > I have two trouble: > > 1) looking at the module "string.py" I have seen that are described > some functions like "lower", "rjust", etc. Ther problem is that it > seems not to describe exactly how this functions are made, but there > is only a comment about their properties. So in which file are these > functions described? Try to see the documentation that comes with python distribuition at Doc/lib/module-string.html subdirectory of python directory. Or see Python Lybrary Reference that comes with python too. > > 2) I tried to cancel the file "string.py". After that, the Python > Interpreter doesn't work anymore (it can't even start working). Why? > > Thank you very much, Nop. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From m2 at plusseven.com Thu Jun 13 03:38:28 2002 From: m2 at plusseven.com (Alex Polite) Date: Thu, 13 Jun 2002 09:38:28 +0200 Subject: Threading tutorial wanted. Message-ID: <20020613073828.GD1792@matijek.plusseven.com> Okidoki. My little webspider has reached the point where further optimization won't pay off. But my DSL pipe is not saturated by far. So I guess it's time for me to start looking into threads. I few minutes of googling on python + threads doesn't yield a lot. Maybe someone here can point me to a good primer. Maybe someone here can write a good primer. When is threading good, when is it bad? How much memory do they consume? Is it safe to let multiple threads use the same db connection? How safe is safe? How can I get rich? Stuff like that. -- Alex Polite http://plusseven.com/gpg/ From siegfried.gonzi at kfunigraz.ac.at Wed Jun 26 03:08:44 2002 From: siegfried.gonzi at kfunigraz.ac.at (Siegfried Gonzi) Date: Wed, 26 Jun 2002 09:08:44 +0200 Subject: SOLVED (Re: Python hits the spot) References: <3D1482AE.8FA299D8@kfunigraz.ac.at> <3D14CF95.4030501@kfunigraz.ac.at> <3D158F3E.1010907@kfunigraz.ac.at> <3D16DD5C.1050708@kfunigraz.ac.at> <3D171291.2060905@kfunigraz.ac.at> <3D181BA2.3090009@kfunigraz.ac.at> Message-ID: <3D19687C.8040708@kfunigraz.ac.at> Bengt Richter wrote: > That can be read two ways ;-) > 1) Definitely no diagnosis, and 8 steps remain different as they were > 2) Definitely no slowdowns, and 8 steps now execute with ~constant timing. > > Still curious ;-) Hi, point 2) is appropiate. > I think the laptop manufacturer should buy it for you (unless you were > running it outside specs for ambient temperature and ventilation). > Good luck. They made me the offer to collect my laptop and look inside. Their stance actually ist that the cooler itself does wobbling and that is the reson for the strange beahvior. If my paper is over I will see to give them my laptop. I will then report any changes. Regards, S. Gonzi From peter at engcorp.com Sun Jun 23 21:45:35 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 23 Jun 2002 21:45:35 -0400 Subject: HTTP authentication References: <3D166ED4.FBE9E2C8@alcyone.com> Message-ID: <3D1679BF.7F2D3A1@engcorp.com> Erik Max Francis wrote: > > Preston Tamkin wrote: > > > hello all. I've just recently jumped on the python bandwagon, and I > > need > > some help! > > Derive from the urllib.FancyURLopener class, and override the > proper_use_password method to return the (user, password) 2-tuple you > want: > > http://www.python.org/doc/current/lib/urlopener-objs.html I think another solution is just to specify the username and password in the URL like so: ref = urllib.urlopen("http://username:password at host.domain/path/file") -Peter From mcfletch at rogers.com Thu Jun 20 23:24:19 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Thu, 20 Jun 2002 23:24:19 -0400 Subject: newbie string question References: Message-ID: <3D129C63.40109@rogers.com> Think of the indices as pointing between the characters. 0 is before the first character, len(sequence) is just after the last character, like so. [ a, b, c, d, e, f, g ] 0 1 2 3 4 5 6 7 -7 -6 -5 -4 -3 -2 -1 Asking for a single index gives you the index after the pointer, as if you were saying "move to pointer position 5, then read a single item (moving forward)". Asking for a negative index just sets that index = len(sequence)+index and does the same thing as normal. Asking for everything between two pointers/indices (slicing) starts from one pointer, and reads all the items up to the end pointer (which is sitting just before the character you'd get by asking for pystr[end]). If your end-pointer is before or equal to the beginning pointer, it's not going to read anything (there's nothing between the pointers moving in the forward direction). So, in the example above, 0:2 -> a,b 0:0 -> 2:3 -> c 4:-1 -> e,f 4:-3 -> 4:-4 -> HTH, Mike PS: Apologies to Tim Peters for mangling his explanation, it's been a long time since I've read it. Don Low wrote: > There's probably a very simple explanation, but I can't see it for now, so > bear with me. > > >>>>pystr = 'Python' >>>>pystr = [5] >>> > 'n' > >>>>pystr [2:5] >>> > 'tho' > > The question is, why isn't pystr [2:5] 'thon' instead of 'tho'. Could > somebody explain? > -- _______________________________________ Mike C. Fletcher http://members.rogers.com/mcfletch/ From merkosh at hadiko.de Wed Jun 12 13:45:24 2002 From: merkosh at hadiko.de (Uwe Mayer) Date: Wed, 12 Jun 2002 19:45:24 +0200 Subject: socket.inet_aton - bug? Message-ID: Hi, socket.inet_ntoa() accepts the string '\xff\xff\xff\xff' which is excactly the same i'd expect socket.inet_aton('255.255.255.255') to produce if it accepted the string '255.255.255.255' as an IP adress. socket.inet_aton() dies with socket.error "illegal IP adress". i know this is no valid ip adress, but it is a valid netmask. the purpose of converting the netmask to a binary format was that i wanted to isolate the subnet of an ip adress. i wanted to use test_ip & netmask == ip_range to allow subnets to access a tcp server. is there another way of controlling this or why does socket.inet_aton() behave like that? Ciao Uwe From mbell at cs.pitt.edu Thu Jun 13 11:51:31 2002 From: mbell at cs.pitt.edu (Matthew Bell) Date: 13 Jun 2002 08:51:31 -0700 Subject: email forwarding program Message-ID: Hi, I have a question regarding the email handling libraries in Python. I'm trying to write a program that, based on some information it extracts from an email, forwards it to another person. I've about figured out imaplib, but don't see how I can use it to forward on emails. One possibility I've considered is to write out the email to a temp file, then make a call to the operating system to use the UNIX program mail -- but would like to avoid doing that if at all possible. Any advice? Thanks, Matt From imbosol at vt.edu Tue Jun 25 18:13:41 2002 From: imbosol at vt.edu (Carl Banks) Date: Tue, 25 Jun 2002 18:13:41 -0400 Subject: Suggestions for good programming practices? References: Message-ID: brueckd at tbye.com wrote: > On Tue, 25 Jun 2002, Carl Banks wrote: >> You seem to have this idea, based on this last paragraph, that a good >> way to keep newbies from misusing eval and exec is to keep them in >> ignorance. I think that's absurd. I don't know if you're just >> grasping for arguments, because you previously seemed to think it's >> best to explain WHY, as opposed to simply saying, "Don't do it." > > Um, what's absurd is how you reached that conclusion from the paragraph I > wrote. <0.4 wink> I said that people WON'T get hurt if they are NOT > ignorant - I'm advocating an explanation of risk in place of the > categorical "stay away!". What's really absurd is how you reached the conclusion that I reached a conclusion when I only said, "you seem to." So why did you ask what kind of teacher calls a newbie's attention to eval? You seemed (not to be confused with "I have concluded") to have been advocating ignorance. Are you merely saying it's better to say nothing than to say, "don't do this?" Because I would disagree with that, too. -- CARL BANKS http://www.aerojockey.com "Nullum mihi placet tamquam provocatio magna. Hoc ex eis non est." From matt at mondoinfo.com Thu Jun 27 22:28:55 2002 From: matt at mondoinfo.com (Matthew Dixon Cowles) Date: Fri, 28 Jun 2002 02:28:55 GMT Subject: Is Python growing? References: <3D1B92FB.59B590A0@pop.ntlworld.com> Message-ID: On Thu, 27 Jun 2002 23:34:36 +0100, a.clarke11 wrote: > My question is, I use 2.1 and by the time I need to update, probably > the version number will have reached Python 3.xx. Will that version > have the inherent simplicity that makes 2.1 so usable? Or will it > become more complex, and lose some of its original ease of use? By > more complex, I mean will it have a steeper learning curve for > newbies, will it be slower, will the download take longer, and will > the featurelist be significantly longer? Other things develop until > they lose their function, eg flowers, saplings, clouds: can Python > avoid increasing complexity, is that the present trend in > development? Dear Tony, Entire flamewars have been written on the subject but here's my opinion: I suspect that you'll be OK. Indeed, I'm placing my own bets that way. Here's why I think that: It's not just complexity that's good to avoid, it's certain kinds of complexity. Python will surely get new features, but Python doesn't have to be much harder to learn and can be easier to use if (only) the right features are included. Python is wonderfully easy to get started with. But someone who's new to programming doesn't need to learn everything about Python in order for it to be useful and fun. (That sounds obvious but it's less true in many other languages.) So if Guido adds a feature here and there, that doesn't necessarily make the learning curve much worse. I've been using Python for some years now and there are corners of the standard library that I haven't explored because I haven't needed to. Indeed, there are aspects of the core language that I haven't found out much about because I haven't needed them. On the other hand, some features make Python much easier to use and read. A while ago, I replaced: def lengthOfLongestStr(list): l=len(list[0]) for count in range(1,len(list)): if len(list[count])>l: l=len(list[count]) return l with def lengthOfLongestStr(myList): return max([len(s) for s in myList]) To my eye, the second one is much easier to read. Similarly, writing something like: countWidgetsFound=countWidgetsFound+1 as countWidgetsFound+=1 makes the intention clearer and avoids the chance of making a typo. I'm happy to trust Guido to add the right features. Regards, Matt From debl2noohnospammyyy at bellatlantic.net Sun Jun 9 02:37:06 2002 From: debl2noohnospammyyy at bellatlantic.net (David Lees) Date: Sun, 09 Jun 2002 06:37:06 GMT Subject: Determination of screen resolution? References: <3D02F4C8.C2DF2EE0@bellatlantic.net> Message-ID: <3D02F7A4.89CE4537@bellatlantic.net> OK, I should have done a little more digging. I just found the answer to my question in the documentation which is simply: v = canvas.winfo_vrootheight() h = canvas.winfo_vrootwidth() David Lees wrote: > > I would like to use tkinter and have the canvas object automatically > scaled fit the screen. Is it possible to read the screen resolution > (800x600, 1024,768...) from somewhere. > > David Lees From peter at engcorp.com Mon Jun 24 21:03:04 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 24 Jun 2002 21:03:04 -0400 Subject: Suggestions for good programming practices? References: Message-ID: <3D17C148.6CC8B3D2@engcorp.com> David LeBlanc wrote: > > The one that always gets me is "lat,lon,timezone = getLocation("seattle")". > I.E. the ability to return multiple distinct values as opposed to returning > multiple values in the form of a struct as in C or C++. You _are_ returning them "in a struct". It's spelled "tuple" but other than that what's the difference? -Peter From gmcm at hypernet.com Thu Jun 6 08:37:07 2002 From: gmcm at hypernet.com (Gordon McMillan) Date: 06 Jun 2002 12:37:07 GMT Subject: Installer vs py2exe: Windows DLLs References: Message-ID: Paul Moore wrote: [Installer's dependency on win32api / pywintypes] > OK, I analyzed this a bit further. This is all for Python 2.2 on > Windows 2000. > > The win32api dependency (and hence the PyWinTypes22 dependency) comes > from iu.py, in the RegistryImportDirector. Two questions come to mind > - first is whether it is appropriate for Installer-built > applications to look in the registry for Python entries in any case, as > the whole point is to run independently of any installed copy of > Python. I imagine that something later in the process disables picking > up registry entries, but that leaves the RegistryImportDirector code as > dead code (which isn't worth worrying about, except for the spurious > dependency). Well iu.py is a drop-in import replacement. I guess I'll have to think about refactoring it so Installer can use it without drawing in the registry code. > The second question is whether RegistryImportDirector she > translation is pretty much automatic - I attach a patch. This gives a > dependency on _winreg.pyd (pity - I'd assumed _winreg would be built > in on Windows :-() but that is *much* smaller than win32api + > PyWinTypes22. Minimal testing shows no problems, but a better test > would be worth doing... _winreg.pyd didn't exist as of Py 1.5, but your patch looks good. > The dependency on _sre comes from posixpath (in expandvars()), which > is imported conditionally by os. And os is imported by archive.py, to > get at os.path.basename, and os.path.splitext. Would it not be > possible here to directly use {dos,mac,nt,posix}path? Sure. In fact, iu is already doing that, so archive could probably get at them that way (although it currently doesn't know about iu). But archive only imports os when *building* an archive, so if that's the only import of os, you're free to exclude it. > I know that in the grand scheme of things, removing dependencies like > this is fairly pointless for any "real" application, but it appeals to > my sense of minimalism. You can get a cross-reference of dependencies from mf.py for this exact reason (deciding what can be safely excluded). -- Gordon http://www.mcmillan-inc.com/ From missive at frontiernet.net Fri Jun 21 19:15:05 2002 From: missive at frontiernet.net (Lee Harr) Date: Fri, 21 Jun 2002 23:15:05 -0000 Subject: Newbie-Question: Oberserving an directory References: <3d1352a7@news.piro.net> Message-ID: In article <3d1352a7 at news.piro.net>, Marcus Klein wrote: > Hi there, > > I want to observe an directory to check if a new file has been put in, if > that happens I want to start an event. > > Does anyone have a good idea how to start, I've tried it with signal, but > either I am too stupid or it is the complete wrong way :-/ > You do not say which OS you are using. If FreeBSD, you might look at PyKQueue. The first hit from google with pykqueue will take you there. From tim.one at comcast.net Mon Jun 10 08:34:10 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 10 Jun 2002 08:34:10 -0400 Subject: Where is Berkeley DB on your system? Can you live without DB 1.85? In-Reply-To: Message-ID: [David LeBlanc] > ... > Hmmm... I have Python 2.2.1 binary installed from Sourceforge - > what is that bsddb.pyd file dated 4/9/2002 in the dlls directory? It's compiled from Sam Rushing's Win32 port of Berkeley's DB library, version 1.85, from http://www.nightmare.com/software.html under the "bsd db" link (*not* the "bsddb" link). It's a bug pit, through no fault of Sam's. The only reason we ship it is that we've always shipped it, and nobody has volunteered the work to package something better. > ... > could Guido be so heartless as to imperil people's data by > allowing the inclusion bsddb in the standard Python distro?!? Yes . It wasn't known to be badly damaged at the time it was first shipped, and now it's supplied for backward compatibility. A better alternative would be most welcome, but PythonLabs has no bandwidth to work on it. From peter at engcorp.com Tue Jun 18 20:51:30 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 18 Jun 2002 20:51:30 -0400 Subject: python version? References: <3D0E8AC8.6C5C96EE@engcorp.com> Message-ID: <3D0FD592.93BFBCDB@engcorp.com> George Hester wrote: > > Listen you aren't my daddy. If you do not want to help constructively then > please get off my boat. I thought I was being constructive in two distinct ways, although perhaps I was more blunt than you were able to handle. If so, my apologies for appearing to patronize you. That was not my intention. I did point out two helpful things (I thought). One was to show you by explicit example how you can't access sys.version until you've imported the sys module. You didn't seem to understand that was required from your response in another post, and I believe you might have missed the point again in reading my response. If you read the post again, you'll see that I got the same error you did until I did "import sys" and then the problem went away. As that would have solved your initial problem, I felt it would be fairly helpful. Secondly, and I believe I'm still correct here, I pointed out that you might have a lot of trouble trying to juggle two things at the same time: learning Python, and using it in an unforgiving environment as an ASP scripting language. I have been in your position many times in the past, and every time I have been burned by ignoring my own instincts. Never attempt to take on two difficult tasks at once when you can partition the problem and approach one task at a time. Learn Python first (without ASP involved), _then_ try to use it for ASP. You may choose to ignore my advice. It was, after all, given freely and, as always, is worth what it costs you... Cheers, -Peter From insyte-clp at emt-p.org Thu Jun 20 16:02:21 2002 From: insyte-clp at emt-p.org (Ben Beuchler) Date: 20 Jun 2002 20:02:21 GMT Subject: HTTPSHandler ??? missing? References: <3d121907$1@news.poly.edu> Message-ID: In article <3d121907$1 at news.poly.edu>, chandan mathur wrote: > I am trying to login to a ssl secure server using urllib2 and clientcookie > but can't find HTTPSHandler() in urllib2.py as mentioned in the manual! I believe that's only built if your 'socket' module supports SSL. And your socket module will only link against the SSL libraries if you already have them (OpenSSL) installed on your system. -Ben -- Ben Beuchler There is no spoon. insyte at emt-p.org -- The Matrix From occeanlinux at linuxmail.org Tue Jun 4 13:49:32 2002 From: occeanlinux at linuxmail.org (Gold Fish) Date: Tue, 04 Jun 2002 17:49:32 GMT Subject: directory Message-ID: <3cfcfd4a_1@news.iprimus.com.au> How to read the subdirectories in the directory Support i have the directory /home/ which have some subdirectories /home/sub1 /home/sub2 /home/sub3 I am using os.listdir('/home/') to read in the list so it will be ['sub1','sub2','sub3'] now i want to read inside the sub directory sub2 once again i using os.listdir(os.listdir('/home/')[1]) but it came out with an errors: not a file or directory. Can anyone tell me what did i wrong. Anh how to fix it. From amckay at merlintechnologies.com Mon Jun 10 14:11:50 2002 From: amckay at merlintechnologies.com (Andy McKay) Date: Mon, 10 Jun 2002 11:11:50 -0700 Subject: activating a webpage's click command from python In-Reply-To: <3D04EA96.B3518A37@engcorp.com> References: <3D04EA96.B3518A37@engcorp.com> Message-ID: <20020610181150.GB2547@mckay.merlintechnologies.com> > does the job for Nortel on the TSE (disclaimer: anyone even > thinking of buying Nortel should probably just keep thinking :-). Oh come on its a bargain, a fraction of what it was, good buying opportunity ;) not-putting-my-money-there'ly yours -- Andy McKay Merlin Technologies From igor.stroh at wohnheim.uni-ulm.de Wed Jun 12 15:15:06 2002 From: igor.stroh at wohnheim.uni-ulm.de (Igor Stroh) Date: Wed, 12 Jun 2002 21:15:06 +0200 Subject: methods to parse big foreign ascii-file? References: Message-ID: <3d079dbc$1@sol.wh-hms.uni-ulm.de> On Wed, 12 Jun 2002 18:05:51 +0200, "holger krekel" wrote: > - come up with a grammar and let a parser do > the hard work (which one?) if the file is structured in a certain form, that is you can describe the data structure with a EBNF, then have a look at 'simpleparse' (I've lost the link, but google will certainly have some for you :) )... HTH, Igor -- The idea behind optimistic concurrency control is surprisingly simple: just go ahead and do whatever you want to, without paying attention to what anybody else is doing. If there is a problem, worry about it later. Many politicians use this algorithm, too. (c) Andrew S. Tanenbaum From jadestar at idiom.com Sun Jun 16 18:37:06 2002 From: jadestar at idiom.com (James T. Dennis) Date: 16 Jun 2002 22:37:06 GMT Subject: newbie system() question References: <3d035180$0$7017$bc7fd3c@news.sonofon.dk> Message-ID: Dan Larsen

wrote: > Hi all :o) ... > ... Isn't there a function, where all output > from the command, is parsed to a variable? I think you're thinking of popen() There are several versions of popen() depending on whether you want the just one pipe (stdin or stdout) or a pair of pipes (one for input and another for output) a triplet of pipes (stdin,stdout, stderr) or a pair with stdout and stderr combined into one stream, etc. There is also a popen2 module which allows you to subclass your own popen class and then use the poll() or wait() methods to retrieve the error/return code from the terminated subprocess. > Thanx in advance :o) > Dan Larsen From dougz at cs.washington.edu Tue Jun 25 18:08:34 2002 From: dougz at cs.washington.edu (Douglas Zongker) Date: Tue, 25 Jun 2002 22:08:34 GMT Subject: Reference Count Confusion References: Message-ID: Jeff Smith wrote: : I'm a little puzzled about reference counts from Python objects created : in a C extension. [...] : : static PyObject *clean(PyObject *self, PyObject *args) : { : PyArrayObject *c; : : PyArg_ParseTuple(args, "O", &c); : : printf("clean: %d\n", c->ob_refcnt); : if (c->data != NULL) free(c->data); : if (c->dimensions != NULL) free(c->dimensions); : if (c->strides == NULL) free(c->strides); : Py_DECREF(c); : printf("clean: %d\n", c->ob_refcnt); : : return Py_BuildValue(""); : } You shouldn't decref c here. When you use the "O" specifier with PyArg_ParseTuple(), it gives you a borrowed reference to the object. You're losing references each time you call this function, and that's probably messing things up. dz From ftobin at neverending.org Sun Jun 30 16:02:12 2002 From: ftobin at neverending.org (Frank Tobin) Date: Sun, 30 Jun 2002 16:02:12 -0400 Subject: I'd give up Perl tomorrow if only... In-Reply-To: References: Message-ID: Christopher A. Craig, on 2002-06-21, wrote: > Given the hardware and bandwidth, it shouldn't be all that hard to > create a CPAN for Python. I suspect one of the main reasons it hasn't > been done is that Google works so well. I don't think you have a good grasp of what CPAN really is. It's much more than simply a big FTP site. The key thing about CPAN is not only the breadth of modules it has, but the strong testing system they employ, namely cpan-testers. I am the author of a module on CPAN, and it's great to be able to upload module, and have it tested on a diverse set of architecures. http://testers.cpan.org/ Note that in order to have something be as successful as cpan-testers, modules needs to have: 1) a standard extraction mechanism (Perl and Python do have) 2) a standard testing mechanism (Perl has ('make test'), Python doesn't) 3) a standard installation mechanism (Perl and Python do have) 4) a standard README system (Perl has, Python doesn't) What is most missing for Python is a standard testing suite system. And until it gets this, it's pretty much not possible to get anything close to the quality of CPAN with cpan-testers. Another great benefit of CPAN is that the modules on it are somewhat 'sanctioned'. Sure, it doesn't take much to get onto CPAN, but the difference between the 'something' it does take, and 'nothing', is enormous in speaking for the quality of the modules you'll find in contrast to searching Google and coming across Joe Schmoe's Python module. A similar scenario is comparing random RPM's you might find on Google to FreeBSD/Gentoo's ports trees; the centralization somewhat sanctions the software, and this is critical, IMO. Furthermore, I find the de-facto multi-tier naming system that Perl employs for modules to be a good thing; it encourages users dividing up their modules in the global namespace. This is critical for finding what you need. For example, I can go into the DBD branch on CPAN and find every database driver it has. Python doesn't have an equivalent (packages just aren't the same thing; they are owned by 'one' thing, most of the time). -- Frank Tobin http://www.neverending.org/~ftobin/ From whisper at oz.net Tue Jun 18 01:37:04 2002 From: whisper at oz.net (David LeBlanc) Date: Mon, 17 Jun 2002 22:37:04 -0700 Subject: Listing all available (not just loaded) modules In-Reply-To: Message-ID: Idle, PythonWin and Boa (at least) do this, with PythonWin being the most detailed - it shows classes and methods within the modules. The version of Pythonwin I have does not show the contents of the site-packages tree, but that would be easily fixable. HTH, David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Michael Steuer > Sent: Monday, June 17, 2002 20:35 > To: python-list at python.org > Subject: Listing all available (not just loaded) modules > > > I've been searching the newsgroup for information on this but so > far have been > unsuccessful: > > Is there a way to dynamically list all available modules (not > just those that > are already loaded) in python? By available I mean those modules, > which are > installed on the machine executing python (in the lib path(s)). > > Cheers, > > Mik.e > > > -- > http://mail.python.org/mailman/listinfo/python-list From chris.gonnerman at newcenturycomputers.net Tue Jun 18 08:08:03 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Tue, 18 Jun 2002 07:08:03 -0500 Subject: Newbie - Process Management References: <1024387201.371093@ernani.logica.co.uk> Message-ID: <002d01c216c0$d7a2d560$0101010a@local> ----- Original Message ----- From: "Dan Scholey" > Hi, > > I am hoping you can help me, I am fairly new to python (and Unix) but am > trying to solve the following problem... > > I want to be able to check if a parent process has died. > > At the moment I can check that a child process has died using... > > status = (os.waitpid(child, os.WNOHANG))[0] > if status!=0: > > I've looked at several manuals and can't find a similar function for parent > processes. > Obviously I know both the parent and child process id ( get_pid() / > get_ppid() ). Here is a partial screen-capture from my Linux system. If you are using any standard Unixoid OS this should work: << partial ps listing >> 15321 pts/1 S 0:00 -bash 15377 ? S 0:00 /usr/sbin/httpd -f /etc/httpd/httpd.conf 15521 pts/1 R 0:00 ps ax office:~ $ python Python 2.1.2 (#1, Jan 16 2002, 17:04:23) [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2 Type "copyright", "credits" or "license" for more information. >>> import os >>> os.kill(15321,0) >>> os.kill(15322,0) Traceback (most recent call last): File "", line 1, in ? OSError: [Errno 3] No such process >>> In other words, PID 15321 exists (I knew it did, it's my shell) but 15322 doesn't. So: def parentcheck(): try: os.kill(os.get_ppid(), 0) return 1 except OSError: return 0 > I have a workaround of.... > > ps_line=string.split(commands.getoutput("ps -lp %s"%my_pid),"\012") > if string.atoi(string.split(ps_line[1])[4])!=daddy: > > ... but I would rather not use ps. > > Any ideas? Hope this helps. > Cheers > Dan Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From whisper at oz.net Fri Jun 14 16:25:28 2002 From: whisper at oz.net (David LeBlanc) Date: Fri, 14 Jun 2002 13:25:28 -0700 Subject: Zip makes sense! was: Re: why not "'in' in 'in'"? In-Reply-To: Message-ID: Aaaah, a logger. Obviously the first on his block to be a logger. The joys of bravely loggin where no one has logged before! ;-> Perhaps if he was an english major, or english was his first language, he could tell that the common meaning of yield isn't produce. I have no idea what zip means beyond being a name for a compression utility or a verb meaning to exercise a zipper. If-you-want-to-make-a-beginner's-language-don't-fsck-it-up-with-obscure-mean ingsly-yours, David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Michael Hudson > Sent: Friday, June 14, 2002 2:38 > To: python-list at python.org > Subject: Re: Zip makes sense! was: Re: why not "'in' in 'in'"? > > > "David LeBlanc" writes: > > > Haskell - that's a mountain range in New York state? :p) > > No, it's the first name of a pioneering logician. > > Cheers, > M. > > -- > I really hope there's a catastrophic bug insome future e-mail > program where if you try and send an attachment it cancels your > ISP account, deletes your harddrive, and pisses in your coffee > -- Adam Rixey > -- > http://mail.python.org/mailman/listinfo/python-list From markus.vonehr at ipm.fhg.de Fri Jun 14 07:24:10 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Fri, 14 Jun 2002 13:24:10 +0200 Subject: PIL and miscolored images Message-ID: <3D09D25A.4C04E03@ipm.fhg.de> Hi everybody, I'd like to show a greylevel image as miscolored image, anyone has an idea how i can do it and maybe adjust the color scale? Thanks for any answer, Markus -------------- next part -------------- A non-text attachment was scrubbed... Name: markus.vonehr.vcf Type: text/x-vcard Size: 245 bytes Desc: Visitenkarte f?r Markus von Ehr URL: From krissepu at vip.fi Mon Jun 3 05:53:11 2002 From: krissepu at vip.fi (Pekka Niiranen) Date: Mon, 03 Jun 2002 12:53:11 +0300 Subject: Iterating through two list + moaning References: <3cee0ae6_1@news3.newsgroups.com> <3cee2338_2@news3.newsgroups.com> <1022297508.675568@yasure> <831ybrwl1v.fsf@panacea.canonical.org> <87sn44lusn.fsf@tleepslib.sk.tsukuba.ac.jp> Message-ID: <3CFB3C87.1F0E9EEB@vip.fi> Right, 1) now if somebody would: a) change lisp syntax to as clear as Python's is and b) wrap GUI library that supports grid with unicode (wxwindows) to it I would change to it immediately. 2) There has also been discussions to remove reduce(), map() and filter() from python, but as long as for -loops and list -comprehensions are as slow as presently, I am worried of it. 3) What I would like to see is: a) a bold move to fix python (to stackless for example) without any consideration of backwards compability b) Make distrubution smaller and consistent (no len() but a.len() ), since its standard library is resembling a bloatware allready. c) Development decisions made only on engineering bases. To me GvR and the rest of the developers are not owing anything to us "freeloaders". If they are into money/career, shit happens. With current development direction, I see no other result than Microsoft -syndrome, where you cannot fix code because of the wide userbase. -pekka- "Stephen J. Turnbull" wrote: > >>>>> "Kragen" == Kragen Sitaker writes: > > Kragen> "Donn Cave" writes: > > >> The function that carries data is cool enough. Lisp does it > >> easier than Python, and in fact does "functional programming" > >> better than Python by a long shot. > > Kragen> That's debatable. > > If you're going to take the Python side of that, I think you've found > yourself a real challenge. After all, Lisp was invented by writing an > automatic interpreter for a purely functional logic notation. > > While you can do functional programming in Python, the syntax and the > ubiquity of side effects makes it hard to emphasize that style. > > At least for me. > > Hm. Maybe I should take a look at M. Pinard's topy tool, and see if > maybe I shouldn't be writing my Python programs in Lisp (Scheme, to be > precise). > > -- > Institute of Policy and Planning Sciences http://turnbull.sk.tsukuba.ac.jp > University of Tsukuba Tennodai 1-1-1 Tsukuba 305-8573 JAPAN > My nostalgia for Icon makes me forget about any of the bad things. I don't > have much nostalgia for Perl, so its faults I remember. Scott Gilbert c.l.py From daniel.dittmar at sap.com Mon Jun 10 08:45:35 2002 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Mon, 10 Jun 2002 14:45:35 +0200 Subject: Program to an interface, not an implementation References: Message-ID: Egbert Bouwman wrote: > This I read as: > For Python interface_inheritance does not require class_inheritance. > > So you can inherit an interface without inheriting the class, > but interface_inheritance by way of class_inheritance is possible as > well. That means at least two things: > - python has interface inheritance (which some people deny), > - interface_inheritance without class_inheritance is a kind of > cultural (not genetical) inheritance: give it the same name and all > is well. But for me that is only polymorphism ! Perhaps it would be better to skip the term interface_inheritance altogether. In Javaspeak, you IMPLEMENT an interface, you promise that you conform to a specification. In Java, this can be checked at compile time. In Python, you could probably create interface objects which can check if a given object or class implements all the methods that are required. It is only polymorphism in the way the language runtime handles this. But it is a difference in the way you document your software. > I do all this hair splitting because the GoF say (still page 17) > that many patterns depend on the distinction between interface- and > implementation inheritance. How do you define in python the > interface inheritance the GoF talk about ? An example from the module pickle: dump(object, file[, bin]) ... file must have a write() method that accepts a single string argument. It can thus be a file object opened for writing, a StringIO object, or any other custom object that meets this interface. You specify the methods that will be called. Having a well known object with the required behaviour is always helpful. The important part about 'programming to an interface' is this: If you're implementing the 'dump' method, don't call arbitrary methods of a file object just because you happen to test it with a file object. Daniel From d_blade8 at hotmail.com Mon Jun 10 16:24:24 2002 From: d_blade8 at hotmail.com (Lemniscate) Date: 10 Jun 2002 13:24:24 -0700 Subject: Newby: Dictionaries as file objects? References: Message-ID: <7396d2b2.0206101224.61005b7f@posting.google.com> I agree with David. However, depending on exactly you want to be doing (and be able to do), you may want to look into the dbm modules (such as dbm, dbhash, etc.). These are, surprise, database modules but they allow for the storage of dictionary items. Now, pickle, shelve, and the like are perhaps the best things for storing Python objects (let's say a user-created object that contains mixed types) but the dbm modules have their uses too, based on EXACTLY what you want to do. Anyway, have fun. Lem netvegetable wrote in message news:... > Hi. > > I want to be able to store a list on a file object, and I want each list > item to be a dictionary, complete with its own set of keys and values. > > I know I can store a list in a file object, simply by writing each item to > the file as a string , and making sure there's a "\n" character at the end > of it. When I read the file object again, I merely need to open it as > "open(object).readlines()" and hey presto, my list is back in order. > > So is there a way to conveniently store a dictionary in each item as well? > > Ta. From ffjhenon at club-internet.fr Tue Jun 18 15:36:33 2002 From: ffjhenon at club-internet.fr (Fabien =?iso-8859-1?Q?H=E9non?=) Date: Tue, 18 Jun 2002 21:36:33 +0200 Subject: For those who are interested Message-ID: <3D0F8BC1.13E432FE@club-internet.fr> I have written an editor for POV-RAY ( the raytracer) using Tkinter that features syntax highlighting. It fires/stops up raytraces, save,.... It can be found at : http://pyvon.sourceforge.net Fabien From rowen at cesmail.net Wed Jun 26 16:02:02 2002 From: rowen at cesmail.net (Russell E. Owen) Date: Wed, 26 Jun 2002 13:02:02 -0700 Subject: Help with an algorithm wanted Message-ID: I'd like some help solving a problem in Python. The basic idea is I have an item of data that can be represented in any of four ways: A,B,C and D. I also have conversion functions between certain pairs of representations, such that there's always a path between any two data representations. In this case suppose I know A<->C, B<->C and C<->D, or graphically: A <--+ +--> C <---> D B <--+ I'd like to create objects that have one of these items (A,B,C,D) as a given, then be able to query any such object for any data representation. For instance, an object with A as the given would return D by solving A->C->D. What I'm trying to figure out is a simple and reasonably elegant way to code such objects. I am pretty sure recursion is the heart of the solution. An object with A as the given could have a method getD that returned D<-C and a method getC that returned C<-A. The real issue is creating such objects without hand coding each one (since in the real world I have more representations and the number of casese proliferates badly). I suspect I should use recursion to create the object, too, but it sounds like it'll need a lot of introspection. For instance to create an object with A as the given, one might: - start by defining method getA to return A - look through the set of conversion functions that output A; the only one is A<-C, so method getC returns C<-A. - repeat with all methods that return C and don't have methods already defined; this gives method getB returns B<-C and method getD returns D<-C. Alternatively, I can imagine making each object basically identical except for some kind of meta-data that tells each method which data item to query; the appropriate function can then be looked up as needed (e.g. via a dictionary that takes as a key the output and input representation). This would slow down the methods but avoid the introspection. Any suggestions? -- Russell From claird at starbase.neosoft.com Wed Jun 5 11:44:45 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 5 Jun 2002 10:44:45 -0500 Subject: writing a text in hyphenless justification References: Message-ID: In article , David LeBlanc wrote: >Justifying text, with or without hyphens, is SO not a trivial job to do >right. . . . ? There are a couple of senses of the original question which might make this easier than first appears. In any case, has a robust implementation of full-blown fixed-width justification. While it's written in Tcl, I don't think it'll present any problems for Pythoneers. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From kkto at csis.hku.hk Sun Jun 2 00:23:48 2002 From: kkto at csis.hku.hk (Isaac To) Date: 02 Jun 2002 12:23:48 +0800 Subject: Why no open(f, "w").write()? References: <20020531225504.248c92ce.larooy@xtar.co.nz> <20020601194350.6366b7be.larooy@xtar.co.nz> Message-ID: <7iu1omtijv.fsf@enark.csis.hku.hk> >>>>> "John" == John La Rooy writes: John> Good point. If I had infinite memory and was allowed an infinite John> number of open files, I'd never need to close or flush my file John> objects, because the optimisation between my writing to a file and John> the actual event taking place will have no effect on the behaviour John> of my code. But it DOES have an effect doesn't it? Buffering is an John> optimisation, isn't it? Is it remotely possible to make buffering to be transparent to the programmer? I don't think so: at least, when the language needs to define the concurrency semantics: when two programs open the same file, when is it guaranteed that the second program will correctly read the things written by the first program. It is not something that the programmer can say "okay, I'll let the system to figure that out"... or do you have some new ideas about it? Regards, Isaac. From mwh at python.net Mon Jun 10 09:25:45 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 10 Jun 2002 13:25:45 GMT Subject: PyCObject subtype PyObject References: <3D022727.2147C50E@doc.ic.ac.uk> <3D0483AF.5ACB350@doc.ic.ac.uk> Message-ID: Benjamin Tai writes: > Michael Hudson wrote: > > > > 2) For function "PyCObject_FromVoidPtr()", it takes in a "void*" as the > > > first argument. > > > For function "PyCObject_AsVoidPtr()", it returns a "void*". > > > When implementing Python extension, what is the potential danger of > > > casting pointers, of different size, to and from "void*"? > > > > Doesn't C guarantee that you can cast a pointer of type (T*) to > > (void*) and back again for all T? I was fairly sure it did. > > > > I am extending a C++ application with Python. Before attempting other > possibilities, like Boost, I just want to document the work I have done so > far. > > Simply speaking I am hiding a C++ pointer, as a PyCObject*, inside a Python > instance. > > The scheme works OK. The C++ class hierarchy is reflected by Python classes. > The pair of C++ and Python object is passed around between the two > languages. Oh, that makes sense. Hmm, you're probably going to be OK but I doubt you get a standard-backed guarantee any more. > > > 4) Apart from exporting function between modules, are there any > > > examples of using PyCObject? > > > > The example, in the Python/C API document, is talking about exporting > functions between Python modules. So I am wondering if my method is valid? I think so. Cheers, M. -- I'm a keen cyclist and I stop at red lights. Those who don't need hitting with a great big slapping machine. -- Colin Davidson, cam.misc From rodrigo.senra at ic.unicamp.br Wed Jun 19 12:55:43 2002 From: rodrigo.senra at ic.unicamp.br (Rodrigo Senra) Date: 19 Jun 2002 09:55:43 -0700 Subject: any users of ExtensionClass out there? References: Message-ID: <8b04704.0206190855.5696145b@posting.google.com> Jeremy Hylton wrote in message news:... > There has been little perceived interest in ExtensionClass releases > because Zope is moving away from ExtensionClass. I wonder, though, if > there are other users of ExtensionClass who would be interested in a > new release. Please let me know if you are. Even though I have no production code based in ExtensionClass, I'd used it sometimes to explore Python reflection capabilities over C extensions. Therefore, I'm interested in any changes you & your team may have come up with. best regards, Senra From erict at millfilm.co.uk Thu Jun 20 04:43:42 2002 From: erict at millfilm.co.uk (Eric Texier) Date: Thu, 20 Jun 2002 09:43:42 +0100 Subject: object object Message-ID: <3D1195BE.9B10EE00@millfilm.co.uk> I didn' t find a lot about class object. and I would like to know what I can inherit from it and what is the difference between, class foo(object): and class foo: Thanks From SteveC at nospam.innocent.com Wed Jun 19 17:48:36 2002 From: SteveC at nospam.innocent.com (Steven M. Castellotti) Date: Wed, 19 Jun 2002 21:48:36 GMT Subject: Dispatching a Win32 COM in the background? Message-ID: Hey all- I'm running a Python application under windows, and I want to make use of the Microsoft Speech API to sythesize Text-To-Speech output, without halting the execution of my program. I'm making my calls like this: (intialization) from win32com.client import constants import win32com.client self.speech = win32com.client.Dispatch("SAPI.SpVoice") (during execution) self.speech.Speak(text) I'm not very familiar with win32com calls, but I'm wondering if there's an easy to to either: 1) Make the call such that the process occurs in the background, and application execution continues to flow 2) Make the call inside a thread which produces the same effect. Can anyone please offer me some tips/sample code to achieve this? Thanks in advance. Cheers, Steve Castellotti SteveC (at) innocent.com http://cogengine.sourceforge.net/ From gh_pythonlist at gmx.de Tue Jun 18 18:20:11 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Wed, 19 Jun 2002 00:20:11 +0200 Subject: results of stat[ST_ATIME]??????? In-Reply-To: <3D0F9DAE0000034E@www.zipmail.com.br> References: <3D0F9DAE0000034E@www.zipmail.com.br> Message-ID: <20020618222010.GB1879@lilith.my-fqdn.de> * jubafre at zipmail.com.br [2002-06-18 18:58 -0300]: > when i use st[ST_ATIME] a int number is returned, how i can transform > this number to a "time number"??????? time.gmtime and time.localtime, depending on wether you want GMT or time in the local timezone. Check out the docs for the time module for details. If you want to have a readable string instead of the tuple gmtime/localtime give you, you need to format using strftime. Example: time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(os.stat("/tmp/a")[stat.ST_ATIME])) Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 25.0 ?C Wind: 1.1 m/s From Chris.Barker at noaa.gov Tue Jun 11 12:55:49 2002 From: Chris.Barker at noaa.gov (Chris Barker) Date: Tue, 11 Jun 2002 09:55:49 -0700 Subject: Sorting list (maybe stupid) References: Message-ID: <3D062B7C.FE6A4963@noaa.gov> Eric Brunel wrote: > l = [(102, 'foo'), (2, 'bar'), (1, 'baz')] > l.sort() > print l > > Apparently, the default sort function already sorts tuples according to > their first element... Note that this only works if the rest of the elements in the tuples are also sortable. In this case, they are strings, so they are. -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From whisper at oz.net Mon Jun 24 22:10:57 2002 From: whisper at oz.net (David LeBlanc) Date: Mon, 24 Jun 2002 19:10:57 -0700 Subject: Suggestions for good programming practices? In-Reply-To: <3D17CC8E.ABB72D14@engcorp.com> Message-ID: Somebody seems to be working overtime to miss the point here... BTW, struct is a module name :-> David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Peter Hansen > Sent: Monday, June 24, 2002 18:51 > To: python-list at python.org > Subject: Re: Suggestions for good programming practices? > > > Brian Quinlan wrote: > > > > Peter Hansen wrote: > > > You _are_ returning them "in a struct". It's spelled "tuple" > > > but other than that what's the difference? > > > > struct members are access by name while tuple elements are accessed > > positionally. > > Okay. So why is that a problem? > > Or to ask it from the other side, what's stopping you from > returning items in an object? > > class Struct: > pass > > def returnStruct(): > result = Struct() > > result.anInt = 5 > result.aString = 'foo bar baz' > result.spam = ('eggs', 'brian') > > return result > > -Peter > -- > http://mail.python.org/mailman/listinfo/python-list From dalke at dalkescientific.com Sun Jun 2 01:53:26 2002 From: dalke at dalkescientific.com (Andrew Dalke) Date: Sat, 1 Jun 2002 23:53:26 -0600 Subject: What does sys.exit(1) means? References: Message-ID: Ken: >What does sys.exit(1) means? It's the same as raise SystemExit(1) That is, it raises an exception. See the documentation for more information about what that means. If nothing else catches the exception (which may happen accidentally with a blanket 'excect:') then the top-level interpreter catches that exception, gets the exit value, quits the main loop, and returns that value (in this case, the integer '1') as the exit code for the program. Andrew dalke at dalkescientific.com From timr at probo.com Mon Jun 10 01:56:22 2002 From: timr at probo.com (Tim Roberts) Date: Sun, 09 Jun 2002 22:56:22 -0700 Subject: Removing ^M References: Message-ID: Michael Kelly wrote: >Michael Kelly wrote: > >> If you're on a unix flavor this works pretty well >> >> tr -d '\015' outfile > >Whoops! Should just be >tr -d '015' outfile > >No need for the backslash. There is if you want to remove carriage returns! Without the backslash, your command removes all occurrances of the digits '0', '1', and '5' from the file. Not entirely useless, but certainly much less useful than your FIRST example. In other words, you were right the first time... -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mis6 at pitt.edu Wed Jun 19 08:15:21 2002 From: mis6 at pitt.edu (Michele Simionato) Date: 19 Jun 2002 05:15:21 -0700 Subject: Tkinter and the Menu Widget Message-ID: <2259b0e2.0206190415.1f232447@posting.google.com> Hello everybody ! I just started playing with Tkinter. I have a problem with the Menu Widget. I want to create a menu like that File Help ----- ----- File1 Help1 File2 Help2 Actually this is a simplified version of what I need since for my application the number of items N has to be dynamic; here for sake of semplicity I took N=2. Notice that I want to store the labels for the various items in a dictionary like that: menuD={'File':['File1','File2'],'Help':['Help1','Help2']} This dictionary is created dynamically by another program and can have much more complicated items. When I invoke a specific menu a procedure has to be called which do something on a string of the form "invoked menu=invoked item" (for instance "Help=Help1" if I invoked the item Help1 of the menu Help). Suppose for sake of simplicity that dosomething(s) simply print the string s, even if in the real case dosomething() calls an external program which requires the string s as input. My attempt has been the following code: import Tkinter def dosomething(s): print s root=Tkinter.Tk() mn=Tkinter.Menu(root) #attach the menu mn to root menuD={'File':['File1','File2'],'Help':['Help1','Help2']} smn={} #dictionary keys->submenu-objects defined below for key in menuD.keys(): smn[key]=Tkinter.Menu(mn) #define a submenu of mn mn.add_cascade(label=key,menu=smn[key]) #attach smn[key] to mn for submenu in menuD[key]: smn[key].add_command(label=submenu,command=lambda : dosomething(key+'='+submenu)) root.config(menu=mn) #display the menu mn Tkinter.mainloop() I used the lambda statement since requires a callable object as argument; notice that this code only runs in Python2.2 (in Python2.1 with the statement from __future__ import nested_scopes). This code correctly creates the menu; however since at the end of the loop the value of key is 'Help' and the value of submenu is 'Help2', when I invoke any item of the menu with the mouse, dosomething always print the string 'Help=Help2'. Instead, I would like to print the string corresponding to the actually called menu ! The Tkinter documentation I have is not helpful, I need a way to pass to dosomething some identification of the called menu. Any suggestion ? -- Michele Simionato - Dept. of Physics and Astronomy 210 Allen Hall Pittsburgh PA 15260 U.S.A. Phone: 001-412-624-9041 Fax: 001-412-624-9163 Home-page: http://www.phyast.pitt.edu/~micheles/ From jh at web.de Fri Jun 7 03:39:12 2002 From: jh at web.de (=?ISO-8859-1?Q?J=FCrgen_Hermann?=) Date: Fri, 07 Jun 2002 09:39:12 +0200 Subject: Medium to Large Scale Python Deployments References: <38C31EBA-79A4-11D6-9A7D-003065B33450@intersight.com> <3D003EC7.C72D27BE@engcorp.com> Message-ID: <3D006320.5040805@web.de> Peter Hansen wrote: > Christopher Armstrong wrote: > >>>I'm also curious about large amounts of Python, period. Who knows of ~50K >>>Python lines-of-code (LOC) systems? 100K LOC? More? >> >>chris at radii:~/Projects/Twisted$ find -name '*.py' | xargs wc -l >>... >> 56051 total > > > How big is that when run through pycount? > > (I.e. comments and blank lines don't count!) > > -Peter Summary on "twisted" ==================== files 256 lines 51654 bytes 1728211 comments 5993 empty lines 10029 non-commentary lines 29910 From romberg at smaug.fsl.noaa.gov Wed Jun 12 12:31:45 2002 From: romberg at smaug.fsl.noaa.gov (Mike Romberg) Date: 12 Jun 2002 10:31:45 -0600 Subject: setup.py breaks Modules/Setup.local Message-ID: I am attempting to get Modules/Setup.local working to build python 2.2.1. But there seems to be a bad interaction with setup.py. I have a Modules/Setup.local which contains a definition for the _tkinter module. I would like to use a Tcl/Tk release from a location that setup.py does not find. It looks like this: # Edit this file for local setup changes *shared* _tkinter _tkinter.c tkappinit.c -DWITH_APPINIT \ -L/usr/local/tcltk-8.3.2/lib \ -I/usr/local/tcltk-8.3.2/include \ -I/usr/X11R6/include \ -ltk8.3 -ltcl8.3 \ -L/usr/X11R6/lib \ -lX11 # We don't want ssl sockets 'cause this opens # up a whole can of DLL heck (often missing on stock redhat setups). _socket socketmodule.c *static* Now when I build python I see this: 1. _tkinter.o is built with the -I switches I want (this is good) 2. _tkinter.so is linked with the -L switches I want (also good) 3. setup.py runs and relinks _tkinter.so with the incorrect -L switches. (not good) gcc -fPIC -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H -DWITH_APPINIT -I/usr/local/tcltk-8.3.2/include -I/usr/X11R6/include -c ./Modules/_tkinter.c -o Modules/_tkinter.o gcc -shared Modules/_tkinter.o Modules/tkappinit.o -L/usr/local/tcltk-8.3.2/lib -ltk8.3 -ltcl8.3 -L/usr/X11R6/lib -lX11 -o Modules/_tkinter.so case $MAKEFLAGS in \ *-s*) CC='gcc' LDSHARED='gcc -shared' OPT='-DNDEBUG -g -O3 -Wall -Wstrict-prototypes' ./python -E ./setup.py -q build;; \ *) CC='gcc' LDSHARED='gcc -shared' OPT='-DNDEBUG -g -O3 -Wall -Wstrict-prototypes' ./python -E ./setup.py build;; \ esac running build running build_ext [snip] building '_tkinter' extension skipping /scratch/Python-2.2.1/Modules/_tkinter.c (build/temp.linux-i686-2.2/_tkinter.o up-to-date) skipping /scratch/Python-2.2.1/Modules/tkappinit.c (build/temp.linux-i686-2.2/tkappinit.o up-to-date) gcc -shared build/temp.linux-i686-2.2/_tkinter.o build/temp.linux-i686-2.2/tkappinit.o -L/usr/X11R6/lib -L/usr/local/lib -ltk8.3 -ltcl8.3 -lX11 -o build/lib.linux-i686-2.2/_tkinter.so Is there some way to prevent this? Or is there something that I'm not doing correctly? Thanks, Mike Romberg (romberg at fsl.noaa.gov) From whisper at oz.net Mon Jun 17 16:29:17 2002 From: whisper at oz.net (David LeBlanc) Date: Mon, 17 Jun 2002 13:29:17 -0700 Subject: Long pathes on windows In-Reply-To: <7647A9F4B298E74DB6793865DA67285004AD86@exchange.adrembi.com> Message-ID: I'm not sure how you convert long paths containing spaces into the short mangled names that Windows 98 etc. used. I know they are on Windows 2000, since i've had a long filename "fold" itself for no reason I could figure out, but I don't know how to _make_ it happen. You actually don't have to get rid of the spaces (although it's inconvenient having them imo): all you need to do is quote the whole path as in: f = open("c:\\Documents and Settings\\Administrator\\Local Settings\\Temp\\conf.h", 'rw'). David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Roman Yakovenko > Sent: Monday, June 17, 2002 11:18 > To: python-list at python.org > Subject: Long pathes on windows > > > Good evening. I have big problem Windows 2000 and small one. > The small one is long pathes on windwos. How can I convert long > path with ' ' > into short path? > > Thanks for the help. Roman. > > > -- > http://mail.python.org/mailman/listinfo/python-list From beej at piratehaven.org Fri Jun 28 21:24:07 2002 From: beej at piratehaven.org (Beej Jørgensen) Date: 29 Jun 2002 01:24:07 GMT Subject: I'm an idiot References: Message-ID: In article , David wrote: >Any help would be appreciated. Ok, I'm no pro and don't have the manuals in front of me, so I hope I don't lead you too astray here: >f=open('c:\\temp\\temp.txt', 'r') >g=open('c:\\temp\\temp1.txt', 'w') >while 1: > try: > s=f.readline ^^^^^^^^ This is a method, so I think it should be "f.readline()" > g.write(s.split()) Er, did you mean strip()? And maybe you have to use String.strip(s), but I can't remember. > except IOError: > break Close--but I don't believe readline() throws an exception on EOF; instead it just returns "". >g.close >f.close So something like this: while 1: s = f.readline() if s == "": break g.write(String.strip(s)) # or s.strip(), if that doesn't work Sorry if I hosed something here, but maybe it'll be enough to get you going even if the info isn't entirely accurate. -Beej From mfranklin1 at gatwick.westerngeco.slb.com Wed Jun 5 09:37:00 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Wed, 5 Jun 2002 13:37:00 +0000 Subject: Fastest way to read / procsess / write text? In-Reply-To: <200206051234.g55CYsB06651@helios.gatwick.geco-prakla.slb.com> References: <3CFD5229.2060803@excite.com> <200206051234.g55CYsB06651@helios.gatwick.geco-prakla.slb.com> Message-ID: <200206051240.g55CeDB10732@helios.gatwick.geco-prakla.slb.com> On Wednesday 05 Jun 2002 1:31 pm, you wrote: > On Tuesday 04 Jun 2002 11:47 pm, you wrote: > > I'm somewhat new to python and programing in general and I trying to > > write a simple script that I can use to format large text files so that > > they are suitable for importing into MySQL. So far, I have came up with > > this: > > > > #!/usr/bin/python2 > > > > import sys, re > > > > infile = sys.stdin > > data = infile.read() > > infile.close() > > This was the standard idiom (untill xreadlines came along I guess) > > > while 1: > data=infile.readlines(100000) # hint to readlines for 100000 bytes.... > if not data: > break ## EOF reached > for line in data: > ## process data > > > data = re.sub('[.](?=\d\d\d\d\d\d)|[.](?=\w+[ ][<|>])|[.](?=\w+[:])|[ > > ](?!0x)', '\t', data) > > > > outfile = open("/mnt/storage/output.txt", "w") > > outfile.write(data) > > outfile.close() Havine re-read you original version this is how to do it;-) while 1: data=infile.read(100000) if not data: break ## EOF reached ## process data..... > > > > > > This works beautifully most of the time (it's super fast), except when I > > pipe large files (>50megs) to it and then it usually dies half way > > through complaining of memory errors because it ran out of ram. > > > > Short of buying more ram, is there a way I can make this more effecient > > without taking a big peformance hit? I tried the above where I used a > > "for line in data:" loop so it would only process one line at a time but > > this seemed to take forever! I'm imagining there's a way to process the > > data in something like 1 meg chunks, but I'm not too sure how to do that. > > > > I'm using python 2.2.1 on a RH linux 7.2 system with 256 ram and a > > Athlon XP1700 if it makes any diffrence. > > > > Any suggestions? > > > > TIA, > > Brent From chris.gonnerman at newcenturycomputers.net Tue Jun 18 08:24:13 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Tue, 18 Jun 2002 07:24:13 -0500 Subject: Newbie - Process Management References: <1024387201.371093@ernani.logica.co.uk> Message-ID: <006a01c216c3$0f8b0cc0$0101010a@local> As an addendum to my previous answer, I'd recommend you spend a little time studying the online manuals and info files. (Personally I HATE the GNU info system but hey, we're stuck with it. Perhaps if I was an EMACS user the insane key bindings would make sense to me.) Python's os module is, after all, an interface to the operating system, so more subtle or detailed information must come from the operating system documentation. To read the man page for the kill() system call: man 2 kill (at the shell prompt of course, not the Python prompt.) Access the info system with info but read the help right away because the key bindings are nasty. Current documentation for GNU command-line tools will be in the info system, but system calls are still in the man system. Note that the first parameter to man can be omitted if you are sure that the word you are looking for will be found in the right place (yeah, right). On my system, man kill does get you the right page, but some other keywords may turn up first in the TCL documentation for instance; that bites me regularly. The manual sections are based on the numbering of the old AT&T Unix manuals. Typing man man will tell you a bit about using the system, including this list of standard manual sections: 1 Executable programs or shell commands 2 System calls (functions provided by the kernel) 3 Library calls (functions within system libraries) 4 Special files (usually found in /dev) 5 File formats and conventions eg /etc/passwd 6 Games 7 Macro packages and conventions eg man(7), groff(7). 8 System administration commands (usually only for root) 9 Kernel routines [Non standard] There may be additional sections which are non-standard on your system. So, say you don't know where information on the kill() system call is: apropos kill gets this on my system: SDL_KillThread (3) - Gracelessly terminates the thread. pthread_kill (3thr) - handling of signals in threads pthread_kill_other_threads_np (3thr) - terminate all threads in program except calling thr ead kill (1) - terminate a process kill (2) - send signal to a process killall (1) - kill processes by name killall5 (8) - send a signal to all processes. killchar (3x) [curs_termattrs] - curses environment query routines killpg (2) - send signal to a process group killpg (3) - send signal to all members of a process group. killproc (8) - Send signals to processes by full path name rotatelogs (8) - rotate Apache logs without having to kill the server skill (1) - report process status yes (1) - output a string repeatedly until killed XKillClient (3x) - control clients xkill (1x) - kill a client by its X resource and it turns out that the kill in section 2 is the one we are looking for. <> Everyone has to have their own help system; KDE and GNOME each have built-in hypertext help which you will have to learn about to separately. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From gmcm at hypernet.com Sat Jun 1 11:39:29 2002 From: gmcm at hypernet.com (Gordon McMillan) Date: 01 Jun 2002 15:39:29 GMT Subject: Gordon McMillan's Installer - Data files in the archive References: Message-ID: David Bolen wrote: > Paul Moore writes: [a bunch of Installer questions that David answers as well as I could...] >> On a (semi-) related note, is it possible to make Installer *not* >> track dependencies back into the installed copy of Python, and so >> produce executables which assume the existence of an installed copy of >> Python on the target system? [snip] > I've also wanted to do this but haven't had a chance to run tests, so > this is just my thinking on how I would do it when I get time. [snip] I'll add another hint. TOC's support set operations (intersection, union and difference in particular). So if you had a TOC describing the std lib, you could do apppure = a.pure - stdlib appbinaries = a.binaries - stdbinaries Another hint: look at the .toc files in the buildxxx directory and note how easy it is to cut-and-paste. In some ways, wxPython is easier, since you can exclude it from the Analysis (in the latest Installer release). I believe David's right that you'll have to modify launch.c. On Windows, commenting out the sys.path manipulations should do it. On Linux / Unix you'd have to modify the make to use Python's getpath.c, not my hacked version. -- Gordon http://www.mcmillan-inc.com/ From brueckd at tbye.com Sun Jun 16 20:52:52 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Sun, 16 Jun 2002 17:52:52 -0700 (PDT) Subject: What If..... Strong Types In-Reply-To: <3D0C0F0D.4030900@bgb.cc> Message-ID: On Sun, 16 Jun 2002, Don Garrett wrote: > Primarily, what if classes always had rigidly defined interfaces. I > mean that public members had to be declared to exist, and that methods > couldn't be modified on an instance. Private members could exist but > would be really private. :( IMO this would add little value and we would lose a lot in the process. I wouldn't be bothered if some sort of optional interface support was built into the language itself, but I don't have the problem with the lack of it today (same with private members - it just doesn't cause me any problems the way it is). On the downside, some of the most Pythonic solutions to problems that'd be messy to solve in other languages are quite elegant in Python because of its "dynamicness". For example, it's sooo convenient to attach/detach members to objects as they pass through a program's workflow. Having to declare them all up front or whatever would be messy. > All types would be classes (including ints and such). I never understood all the hooplah over ints not being classes. I've only ever seen a handful of cases where it might be useful, and lots of cases where it'd get abused, but some people really seem to want it. > My belief is that almost all the convenience of Python would be > maintained, but that compilation, optimization, and automated code > analysis would be simpler. I'm _sort of_ in favor of some optional type annotation for optimization purposes, and sort of against it, the idea being that after your code is done you could go back and annotate (or even have a tool suggest annotation) variables with type information such that you are saying that a particular variable name will always refer to integers, for example. My fear, though, is that it would be used too often, i.e. people would provide type information in places where it wouldn't help at all in terms of execution speed. One of the beauties of Python is the clean syntax, the readable code. A good portion of that is the code is not encumbered with all sorts of variable and type declarations. I like the approach of Pyrex because it's close to Python but still separate enough to prevent people from using it too much - if you make it too easy to optimize the code then people will optimize it too often. Bleh. > I'm just wondering if the change would be good or bad. Would it really > break anything important in Python today? You might not consider it important, but it'd break a lot of _my_ code, so it'd be important to me! :) Python doesn't force you to use all its dynamic abilities, but I regard that as one of the tools of the Python toolbox, so yes, I'd be hurt by its removal. > Would it prevent any common errors? It'd be most useful for people who skimp on testing, but the added complexity might actually introduce errors, so who knows what the net effect would be - perhaps even buggier code than without it. > Would it help with automated code analysis (compilation and optimization > included) as much as I think it would? Dunno - how much do you think it would? ;-) A better question, is how often do we really need compilation and optmization at all anyway? If it's less than 10% (which I believe it is), then the payoff generally wouldn't be worth language-wide changes. A plain extension module (especially with the help of Boost, SWIG, PyInline, etc.) isn't too painful, and projects like Pyrex might have a permanent niche too, but in all cases they are one step removed from standard Python - which is exactly where they belong. -Dave From fperez528 at yahoo.com Wed Jun 19 16:21:42 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Wed, 19 Jun 2002 14:21:42 -0600 Subject: OS X debugger? References: Message-ID: Aahz wrote: > Anyone know a good visual debugger for OS X???I'd?originally?been > planning to just use shell windows for the demos of my OSCON tutorial, > but it occurs to me that a single-stepping debugger with watch variables > would be even better You can probably build ddd for OS X. I've used it for python in the past and it's quite nice (but I've only used it in Linux, so I don't know how tricky the osX build would be. It's Motif based). cheers, f From marklists at mceahern.com Thu Jun 27 09:00:12 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 27 Jun 2002 08:00:12 -0500 Subject: sys.argv[0] - Returns path and filename. In-Reply-To: Message-ID: > How do I get the current path of the script I am running, on the mac > osx and the linux box ? (Any work around would be great, I don't want > to have to hardcode the path into the script, or even give the path as > an argument,I want the script to know where it is.) import os print os.getcwd() // m - From derek at wedgetail.com Fri Jun 21 07:02:09 2002 From: derek at wedgetail.com (Derek Thomson) Date: Fri, 21 Jun 2002 11:02:09 GMT Subject: converting an array of chars to a string References: <3d12dda2_6@news.newsgroups.com> <3D12E228.6030501@wedgetail.com> Message-ID: <3D1307AF.3070308@wedgetail.com> Gerhard H?ring wrote: > > > Unless Python 1.5.2 compatibilty is a requirement, just use string > methods: > > lst = ['a', 'b', 'c', 'd'] > s = ''.join(lst) And they say you can't write obfuscated code in Python :) I would have expected "join" to be a method on the sequence, if anything. As in "s = lst.join('')". In fact, I looked for it, as I *knew* I'd seen it used before as a method, I just didn't expect it to be in the string class. I think I'll just stick with string.join for the time being. As it turns out, there's more than one way to do it, even in Python ;) < It's also not a good idea to replace the builtin list function, thus > I'm using 'lst' here. You're right, of course. Regards, Derek. From cliechti at gmx.net Fri Jun 28 17:04:17 2002 From: cliechti at gmx.net (Chris Liechti) Date: 28 Jun 2002 23:04:17 +0200 Subject: joining 2 lists together - an elegant way? References: Message-ID: Rajarshi Guha wrote in news:pan.2002.06.28.15.06.32.33132.1787 at presidency.com: > On Fri, 28 Jun 2002 15:03:29 -0400, Rajarshi Guha wrote: > >> Hi, >> is there a more elegant way to join to lists together? >> >> Right now I do: >> >> newlist = [] >> for i in l1: >> newlist.append(i) >> for i in l2: >> newlist.append(i) >> >> It does the job - but a one liner (if possible) would be nice :) TIA, > > Sorry :( Found it! Fine! now if you would post it also you would 1) get feedback, 2) help others/newbees when they search the news archive... just for the record: >>> l1, l2 = [1,2,3], [4,5,6,7] >>> l1 + l2 #oneliner [1, 2, 3, 4, 5, 6, 7] >>> n = l1[:] #copy and >>> n.extend(l2) #extend [1, 2, 3, 4, 5, 6, 7] chris -- Chris From emile at fenx.com Wed Jun 19 06:58:50 2002 From: emile at fenx.com (Emile van Sebille) Date: Wed, 19 Jun 2002 10:58:50 GMT Subject: CPU Usage Windows References: Message-ID: Rad > I've noticed that when I run Python script on > Windows 2k Pro > Dual Intel Xeon (2.2GHz) > CPU Usage for pythonw.exe is only 50%?! > > Nothing else is running on the machine (apart form the OS). Some of > the python programs are running for hours (large data sets) and even > though python shell freeze's (doesn't refresh) CPU usage is still only > 50%. > > System Idle Process is about 40%-50% > > Any ideas why is this and can I do anything about it? > > Is it something to do with python not being able to use the power of > both processors? > IIRC, when I noticed something similar I found out both that task manager has some issues with dual processor systems and that the 50% meant 100% of one processor. -- Emile van Sebille emile at fenx.com --------- From dougz at cs.washington.edu Tue Jun 18 18:40:42 2002 From: dougz at cs.washington.edu (Douglas Zongker) Date: Tue, 18 Jun 2002 22:40:42 GMT Subject: results of stat[ST_ATIME]??????? References: Message-ID: jubafre at zipmail.com.br wrote: : when i use st[ST_ATIME] a int number is returned, how i can transform : this number to a "time number"??????? What do you mean by "time number"? The file times given by stat() are just like the values returned by time.time(), except that they're ints instead of floats. You can do all the same things with them: >>> import os, time >>> access = os.stat('/tmp/foo').st_atime >>> access 1024439265 >>> time.ctime(access) 'Tue Jun 18 15:27:45 2002' >>> time.localtime(access) (2002, 6, 18, 15, 27, 45, 1, 169, 1) dz From skip at pobox.com Mon Jun 24 21:54:06 2002 From: skip at pobox.com (Skip Montanaro) Date: Mon, 24 Jun 2002 20:54:06 -0500 Subject: How to stop a SocketServer? In-Reply-To: <3D17BF72.2E1CCF40@engcorp.com> References: <7xhejv9af2.fsf_-_@ruckus.brouhaha.com> <3d1744d4$1_1@hpb10302.boi.hp.com> <3D1757DF.776A428F@engcorp.com> <3d176a0c$1_3@hpb10302.boi.hp.com> <3D17BF72.2E1CCF40@engcorp.com> Message-ID: <15639.52542.299814.852145@12-248-8-148.client.attbi.com> Peter> By the way, look into "timeoutsocket.py" which is a plug-in Peter> replacement for the standard socket.py and which might do the Peter> trick for you. Note socket objects grow a settimeout() method in 2.3. If you get Python from CVS you can have it today: settimeout(value) Set a timeout on blocking socket operations. The value argument can be a nonnegative float expressing seconds, or None. If a float is given, subsequent socket operations will raise an error exception if the timeout period value has elapsed before the operation has completed. Setting a timeout of None disables timeouts on socket operations. s.settimeout(0.0) is equivalent to s.blocking(0); s.settimeout(None) is equivalent to s.setblocking(1). New in version 2.3. -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From cbbrowne at acm.org Sat Jun 8 12:42:36 2002 From: cbbrowne at acm.org (Christopher Browne) Date: 8 Jun 2002 16:42:36 GMT Subject: Where is Berkeley DB on your system? Can you live without DB 1.85? References: <15617.3834.292130.446065@12-248-41-177.client.attbi.com> Message-ID: The world rejoiced as Oleg Broytmann wrote: > On Fri, Jun 07, 2002 at 01:14:59PM -0700, David LeBlanc wrote: >> If Sleepycat will allow it, i'm all in favor of updating to the latest >> version! However, they want money for commercial use of versions > 1.85 >> AFAIK. > > They don't. You can freely incorporate BSDDB into an opensource project. > http://www.sleepycat.com/faq.html#A22 Ah, but that presumably _wouldn't_ mean that incorporating it into Python would allow it to be freely incorporated into a "non-OS-project" that uses Python. -- (reverse (concatenate 'string "gro.mca@" "enworbbc")) http://www3.sympatico.ca/cbbrowne/wp.html Mental health is overrated!! From anoop79 at myrealbox.com Tue Jun 18 15:41:51 2002 From: anoop79 at myrealbox.com (Anoop P B) Date: Wed, 19 Jun 2002 01:11:51 +0530 Subject: tray icon using tkinter References: <4a7fde99.0206180244.11eea205@posting.google.com> Message-ID: <3D0F8CFF.1000905@myrealbox.com> thanks a lot for your help. appreciate it. actually, i havent done much tkinter or mfc before. i have been playing with wxpython for a month. i didnt like the idea that i had so many widget-ID numbers floating about in wxpython that i had to keep track of. and i dont understand why the concept of widgetID numbers - why not just link the widget-name with the handler? anyways, so i decided to check out tkinter and see if i can write my current project in tkinter instead. it appears as though i need to learn mfc to do what i want (the tray icon). so, i am thinking i'd rather go back to using wxpython. the TrayIt thing suggested by John looks like a gr8 tool but wont serve my purpose here since i want to also learn how to integrate this feature into my python program. Besides, deployment on the client's machine will be a problem. secondly, tkinter3000 seems to be in pre-alpha and the tkinter3k docs that i could find on the net dont seem to have anything on howto do the tray icon thing. or have i missed something there? ~anoop Ryan wrote: > john at johnnypops.demon.co.uk (John Popplewell) wrote in message news: > >>Anoop P B wrote in message news: >> >>> is there a way that i can provide a tray icon ie. next to the clock (on >>>win32) for my program (using tkinter) ? i know that there is a way of >>>doing this in wxpython but i need to know whether its possible in tkinter. >>> >>>thanks, >>>anoop >> >> >>Have you had a look at "Tray It!" ? >> >>http://www.teamcti.com/trayit/index.html >> >>cheers, >>John. > > > also look at the win32 extensions, I remember going through all the > demo code that there is a way to do it (MFC I think but don't know for > sure). It is simple to do a try except block around the import and > logic to use it since it will only be for windows. It is used for the > windows IDE also. > Also check out TKinter3000 at > http://www.pythonware.com/products/tkinter/tkinter3000.htm, they may > have something (or you can ship the one from win32 extensions with > your app) From gcordova at hebmex.com Mon Jun 17 13:49:06 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Mon, 17 Jun 2002 12:49:06 -0500 Subject: Divorce property objects from attribute access dependency? Message-ID: > > >>> class C(object): > ... def __init__(self,v): > ... self._v = v > ... def get_v(self): return self._v > ... def set_v(self,v): self._v = v > ... v=property(get_v,set_v) > ... vlist = [v,v] > ... > >>> c=C('something') > >>> c.v > 'something' > >>> c.v='other' > >>> c.v > 'other' > >>> c.vlist > [, ] > >>> c.vlist[0] > > > Why not trigger get_v() in these accesses too, and have > single mechanism to suppress it instead of a single > mechanism to effect it? > You mean that you don't recognize the difference between evaluating "c.v" and "c.vlist"? Well, for one: "c.v" is evaluated at runtime, and it's recognized as an instance's access to a class' property attribute, so all the background magic happens (which is what you expected). Just a note: get_v and set_v are methods, which take "self", and all that. Ok. On the other hand, "vlist" is created at compile time, and it's a list, not a property attribute; it's only a list with two objects. When you're evaluating "c.vlist", the items in the list are not in the correct context to be evaluated as property attributes, so the background magic does not happen. For one, there is no "self" to pass to the methods get_v and set_v; another, they're "property attributes", not "magical list items". :-) > ISTM kind of a hack to rig access via instance attribute as a > mechanism for controlling referenced-object behavior (this is > my impression, I haven't checked code ;-). IMO default behavior > of an object in lhs or rhs context should not depend on how a > reference to it was acquired and dereferenced. > > (Obviously, if property objects always acted as they now do > through instance attribute access, "vlist=[v,v]" in this > example would have to have some kind of access override like > "vlist = [obj(v),obj(v)]", or else it would generate > ['something','something'] right there. Using obj(p) a property > object could be passed around without evaluation and the > potential side effects thereof). > A property object *can* be passed around without side effects, it's only when accesed as an attribute of an instance of a class which defines them, that the expected behaviour triggers. For example, try this: >>> class klass(object): pass ... >>> ob = klass() >>> ob._blah = 10 >>> def _get_blah(self): return self._blah >>> def _set_blah(self, b): self._blah = b >>> ob.blah = property(_get_blah, _set_blah) What behaviour do you expect from this? Give it a try. :-) > BTW, it would be nice to be able to define a property at > global module scope also, and perhaps this would tie in nicely. > > Just musing ;-) Thoughts? Am I missing a big gotcha? > One thing is that it will effectively make possible a ()-less > function call, which will upset some people ;-) You can do that without properties: >>> class Caller: ... def __init__(self, func, *args, **kw): ... self.func, self.args, self.kw = func, args, kw ... def __str__(self): return self.func(*args, **kw) ... __repr__ = __str__ ... >>> def PrintTen(): print 10 ... >>> ten = Caller(PrintTen) >>> ten 10 Another thing, you *can* create "magical list items" with this class; since __repr__ is also defined, then when the list which contains them is rendered, the __repr__ method of the items is called. Neat. :-) I Know, it's a simple-minded example, but you know what I mean. You can use this Caller class to execute a function when you type the name of the object that's related to the function. Good luck :-) -gustavo > > Regards, > Bengt Richter > From shalehperry at attbi.com Tue Jun 4 16:56:04 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Tue, 04 Jun 2002 13:56:04 -0700 (PDT) Subject: self In-Reply-To: Message-ID: On 04-Jun-2002 Vojin Jovanovic wrote: > I don't see how that is going to work. In fact I tried things like that > before without success. Just sticking the dictionary into eval/exec is > missing the point. Every time parsing is done flow needs to go through > __getattr__ special method to evaluate nested equations. Without self. you > can't achieve that effect. Try the approach you suggested and you'll get > '#U'. > calc.setEquation('f = a*c') calc.valueFor('f') sometimes you can just redesign. From emile at fenx.com Sun Jun 23 21:22:15 2002 From: emile at fenx.com (Emile van Sebille) Date: Mon, 24 Jun 2002 01:22:15 GMT Subject: mail-problem over t-online References: Message-ID: "Klaus Reinhardt" wrote in message news:mailman.1024866209.9154.python-list at python.org... > Am 23.06.02 22:57:06, schrieb Peter Hansen : > > >Klaus Reinhardt wrote: > >> host=smtplib.SMTP('mailszrz.zrz.tu-berlin.de') > >> host.sendmail(zwi_eck(From),zwi_eck(Tp),al) > >> host.quit > >> authentification required .. Providing my log and pass > >> produces errors, too. > > >Try connecting manually with TELNET first, to ensure you > >have a clear channel to that server and port. Many ISPs > >will block port 25 except to their own mail server, to > >prevent you using them to send spam through other systems > >and having them suffer the consequences... > > > >-Peter > --------------------------------------------------------------------- > Hi > Thanks for the hint (port 25); the telnet is working > and on anis.tu I have a python, so I can launch a > script; but this is the long way. My goal is to fiddle all > together to one script. For now I couldn't establish > a working telnet a.s.o. - But these are my python- > beginnings. -) > K at Rdt > --------------------------------------------------------------------- > The intent of the hint was to manually telnet into port 25 and send mail to see what was going on -- not as an alternative method of implementation. Did you do that and see that you can send mail? -- Emile van Sebille emile at fenx.com --------- From jepler at unpythonic.net Tue Jun 25 09:34:14 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 25 Jun 2002 08:34:14 -0500 Subject: Suggestions for good programming practices? In-Reply-To: References: Message-ID: <20020625133409.GA4435@unpythonic.net> On Tue, Jun 25, 2002 at 07:48:06AM -0400, Roy Smith wrote: > "David LeBlanc" wrote: > > Structs and tuples are different. They're both of the same general category > > of aggregate data, but they are different as Brian notes. > > I've come to really dislike using tuples for data structures, and > instead create small data classes. Even if the class is no more > complicated than: > > class myData: > def __init__ (self, foo, bar): > self.foo = foo > self.bar = bar > > you've added quite a bit of functionality. First, the code becomes a > little more self-documenting. "power = ckt.volts * ckt.amps" is a lot > easier to read and understand than "power = ckt[0] * ckt[1]". (the following applies most obviously to modern versions of python. I use subclassing of builtin objects, __slots__ and zip(). Even so, the myStruct class is useful in any version of Python back to at least 1.5, if you make myStruct a regular class, and include a definition of zip()) You can do even better (lower memory overhead) with class myData(object): __slots__ = ['foo', 'bar'] def __init__ (self, foo, bar): self.foo = foo self.bar = bar you could go a little farther and make a superclass that has a __init__ that works for any subclass: class myStruct(object): def __init__(self, *args): if len(args) != len(self.__slots__): raise TypeError, \ "__init__() takes exactly %d arguments (%d given)" \ % (len(self.__slots__)+1, len(args)+1) for name, arg in zip(self.__slots__, args): setattr(self, name, arg) class myData(myStruct): __slots__ = ['foo', 'bar'] Jeff From bokr at oz.net Mon Jun 24 15:00:21 2002 From: bokr at oz.net (Bengt Richter) Date: 24 Jun 2002 19:00:21 GMT Subject: converting an array of chars to a string References: <3d12dda2_6@news.newsgroups.com> <3d17038e_6@news.newsgroups.com> <3d1757c7_1@news.newsgroups.com> Message-ID: On Mon, 24 Jun 2002 19:40:17 +0200, JB wrote: >Bengt Richter wrote: >> No cause for desperation ;-) >> >> Are you saying that you want modulo 256 arithmetic on >> unsigned 8-bit data? No problem. But what does your data >> represent? And what does adding a number to such a data >> item mean in the real world? > >Of course you are right. I really needed only some 8-bit >shifting. The point is, that there is no need for the >overhead that is involved. If anybody uses the array module >which, you can argue, is a low level module, he should know >what he is doing. > It is hard to be very helpful without knowing the "big picture." You originally said: "How can I convert an array of chars to string? The problem is this: I should like to perform 8 bit calculations in a buffer. After this has been done, the buffer has to ba written to a binary file (and file.write takes strings instead of lists)." And I still have no idea why you want to do that, or what your data represents, or how much of it there is, or where it comes from, or how fast and/or often you have to process it. Who knows, there may be a whole application out there that does what you want, and more. But a narrow question about 8 bit calculations and buffers and binary files will not generally evoke the association, unless someone happens to be doing an implementation, and says, "Hey, that's just what I'm working on in my blarglefoo framework. Are you by any chance working on a similar app? It's for processing ..." I'm not intending to criticize, I'm just trying to point out a typical feature of newsgroup technical questions. They tend to say, "I need a fast square root" and leave out that they don't have floating point (ok, that'd be a probable inference), and they are checking distances between things against a threshold. Whereas if they'd revealed what they were trying to do, it could've been pointed out that they didn't need a square root at all (just compare with the threshold distance squared). Anyway, good luck with it ;-) Regards, Bengt Richter From marklists at mceahern.com Sat Jun 15 10:14:01 2002 From: marklists at mceahern.com (Mark McEahern) Date: Sat, 15 Jun 2002 09:14:01 -0500 Subject: Pronouncing '__init__' In-Reply-To: <20020615165915.A17174@hishome.net> Message-ID: > I used __init__ just as an example. I meant how do you pronounce names > with leading and trailing double underscore in general. The magic name > __init__ may be by far the one most commonly encountered in everyday > programming but __there__ __are__ __many__ __others__. As Aahz just kindly pointed out my (shared) mistake in thinking of __init__ as a constructor, I withdraw that vote. ;-) But I think saying, for example, the str method, in the context of a user class, is clear enough to indicate __str__. If you're talking about len(), you probably just say "len." If you're talking about __len__, you probably say, "the len method of x" or just "the len method." Or "the magic len method." Cheers, // mark - From andersjm at dancontrol.dk Mon Jun 17 07:14:06 2002 From: andersjm at dancontrol.dk (Anders J. Munch) Date: Mon, 17 Jun 2002 13:14:06 +0200 Subject: Type subclassing: bug or feature References: Message-ID: <3d0dc4dc$0$80428$edfadb0f@dspool01.news.tele.dk> "Aahz" wrote: > Consider the following code: > > class MyStr(str): > def contains(self, value): > return self.find(value) >= 0 > > s = MyStr("hello, world!") > s = s.capitalize() > if s.contains('Hello'): > print "Found it!" > > It fails with an AttributeError when it calls s.contains(), because > s.capitalize() returned a str instead of a MyStr. Anyone want to take a > whack at defending this as the correct behavior? Inheriting from a class/type with value semantics is usually bad design. Use containment or helper functions instead. it-so-happens-that-Python-has-support-for-creating-thusly-flawed-designs- but-that-doesn't-make-it-a-good-idea-ly y'rs, Anders From occeanlinux at linuxmail.org Sun Jun 2 15:56:58 2002 From: occeanlinux at linuxmail.org (Gold Fish) Date: Sun, 02 Jun 2002 19:56:58 GMT Subject: List References: <3cfa6ed8_1@news.iprimus.com.au> Message-ID: <3cfa7619_1@news.iprimus.com.au> Charl P. Botha wrote: > In article <3cfa6ed8_1 at news.iprimus.com.au>, Gold Fish wrote: >> Assume we got 2 list >> list 1 = ['ABC','CDG','DAV','FE','FECA','FEAFA','FEA'] >> list 2 = [] >> how can we copy element from list 1 to list 2 say i just want to copy the >> 3 element 'CDG','DAV','FE' to list2 only. > > list1 = ['ABC','CDG','DAV','FE','FECA','FEAFA','FEA'] > list2 = list1[1:4] > > Is that what you meant? > No i mean if i got from list1 i wanna take 3 elements in any position to list2 but i don't know how many item in that list. From SteveC at nospam.innocent.com Fri Jun 21 15:06:49 2002 From: SteveC at nospam.innocent.com (Steven M. Castellotti) Date: Fri, 21 Jun 2002 19:06:49 GMT Subject: Dispatching a Win32 COM in the background? References: <9OpQ8.90552$ks6.8015@nwrddc02.gnilink.net> <3D127FE0.74D47795@engcorp.com> Message-ID: On Thu, 20 Jun 2002 20:22:40 -0500, Peter Hansen wrote: > "Steven M. Castellotti" wrote: >> >> Thanks a lot guys, your suggestions have worked perfectly! >> >> Just for the record, here's what the full implementation looks >> like. > > Beautiful... thanks for the followup Steven. I especially like your use > of deferred imports to speed up initial program loading. Thank you for the compliment. Speeding up program loading by deferring imports is really only a side bonus though. The program is actually cross-platfrom, meant to be run under both Linux and Windows. Since I'm making calls to the Festival TTS program under linux, I have a seperate class object, depending on what gets returned by os.name. > [...] >> if not(self.text_queue.empty()): >> text = self.text_queue.get() >> speech.Speak(text) >> time.sleep(.001) > > Note that the time.sleep() as shown above is doing nothing useful for > you. I suspect you had it unindented but your posting probably used > tabs and spaces which makes it hard to see properly on some readers. > > The reason it does nothing useful is that Python will automatically > switch between different threads every so often anyway, so the concept > of giving up the CPU for what amounts to a tiny fraction of a second is > somewhat unnecessary. That makes sense to me, I think I'll remove the time.sleep() call. The reason I had it in there in the first place (and it was unindented) was because I have a similar call in a loop to Pygame (a wrapper to the SDL graphics library), which is not multithreaded. I needed the calls in the Pygame loop in order to prevent CPU usage from sitting at 100%, but if multithreading will happen properly without it, I won't use it. Cheers, Steve Castellotti SteveC (at) innocent.com http://cogengine.sourceforge.net/ From david_griswold1 at yahoo.com Fri Jun 28 23:51:16 2002 From: david_griswold1 at yahoo.com (David Griswold) Date: Sat, 29 Jun 2002 03:51:16 GMT Subject: I'm an idiot References: Message-ID: Thank you, everyone, that took the time to help a newbie. David From fredegar at haftmann-online.de Tue Jun 4 08:48:46 2002 From: fredegar at haftmann-online.de (Florian Fredegar Haftmann) Date: Tue, 04 Jun 2002 13:48:46 +0100 Subject: Creating explorer link on Win32 Message-ID: <3CFCB72E.4010405@haftmann-online.de> Hi! I'm searching for a possibility to create an explorer link (*.lnk) to a file on Win32. Has anyne heard of a python module able to do that in a simple way? Thanks, FFH From Uwe.Mayer at ifib.uni-karlsruhe.de Mon Jun 17 06:40:07 2002 From: Uwe.Mayer at ifib.uni-karlsruhe.de (Uwe Mayer) Date: Mon, 17 Jun 2002 12:40:07 +0200 Subject: what *is* a class? References: Message-ID: <3D0DBC87.B1BDEB2D@ifib.uni-karlsruhe.de> Douglas Zongker wrote: > "Group()" creates a new object which is an instance of the class > Group. It calls the object's initializer ("__init__" method), then > returns the newly created object. > > : i want to write a method which returns the instance, so that f.e. the > : following is possible: > : g = Group() > : g2 = g.foobar() > : g2 is g > : so that g2 is identical to g. > : any idea? > > class Group: > def __init__( self ): > print 'creating instance' > > def foo( self ): > print 'in the foo method' > return self > > >>> g = Group() > creating instance > >>> g2 = g.foo() > in the foo method > >>> g2 is g > 1 > >>> > > Note that there's usually no reason for a method (such as "foo") to > return the self object, because the caller should already have the > object to call the method in the first place. I could leave "return > self" out of the definition of "foo", and just write: > > g = Group() > g.foo() > g2 = g > > The result would be the same. I am very sorry. Of course I tried that, returning self, but perhaps I called: g2 = g.foo instead of g2 = g.foo() :-((( The reason why I wanted that was for lazyness. I am writing classes which should provide random access to arbitrary binary file formats with a special focus on RIFF. I wanted to create an object model of the file (without actually reading all of it - especially skipping the large data chunks). I had to distinguish between creating the object model and actually reading the file in. Thus I decided to use the constructor for creating the object model and provide a parse() method. I didn't like writing: f = file('dummy.avi','rb') avi = RIFF() avi.parse(f) instead I wanted to write: avi = RIFF().parse(f) but then of course parse() must return an instance object. On the one side all parse() methods must explicitly "return self" (which is not nice). On the other side from the semantics I thought it was ok for parse to return an instance object of RIFF. What do you think? Thanks for your help! Ciao Uwe From sholden at holdenweb.com Wed Jun 26 09:53:32 2002 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 26 Jun 2002 09:53:32 -0400 Subject: enlightenment (Re: python cgi + IIS) References: <3D0F1813.3010304@gmx.de> <3D102AF2.5010204@gmx.de> <3D13522E.6010703@gmx.de> Message-ID: "Axel Grune" wrote in message news:3D13522E.6010703 at gmx.de... > > for, and so forth) give an account of all the steps you have performed > > This steps: http://www.e-coli.net/pyiis.html > > This doc tells you to change the 'App Mapping' in the properties of > [IISAdmin] to enable the execution of python files for the entire server > but for any reason it doesn't work. > In the end our admin suggested to change the properties of 'Default Web > Site' (the node above [IISAdmin]) and then it works. > In fact the document we are referring to says "Right click on the place you want the associations to apply to", by which the author means "Right-click on the server or one of its real or virtual subdirectory icons". Anyway, glad you got to where you needed to be. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From timr at probo.com Sun Jun 2 22:50:26 2002 From: timr at probo.com (Tim Roberts) Date: Sun, 02 Jun 2002 19:50:26 -0700 Subject: HTML and python References: Message-ID: "John J. Lee" wrote: >On Sun, 2 Jun 2002, Steve Holden wrote: >> "Ken" wrote: >> >> > How do you call to a static HTML page from the script? >> > >> >
>> > This doesn't seem to be working..... Can someone help? >> >> It really makes no sense to use method POST to access a static page. Using >> method GET will probably owrk, though you will see the for contents in the >> URL. > >Why doesn't it make sense? > >(following from memory, may be wrong) > >from urllib2 import urlopen >from urllib import urlencode >result = urlopen(url, urlencode(data)) > >Sorry if this is no help -- I didn't see the original message. How could you not see it? It was part of your reply! See the section that starts "How do you call..."? That is the original message. What you posted is not a static HTML page. It is a Python CGI script. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From andrewm at object-craft.com.au Thu Jun 20 00:40:38 2002 From: andrewm at object-craft.com.au (Andrew McNamara) Date: Thu, 20 Jun 2002 14:40:38 +1000 Subject: Variable Interpolation - status of PEP 215 In-Reply-To: Your message of "Thu, 20 Jun 2002 00:09:46 -0400." <3D11558A.14451441@engcorp.com> Message-ID: <20020620044038.9416438F5A@coffee.object-craft.com.au> >> I am a relative newbie to Python. I have a reasonably good perl background >> (don't worry I am not about to start a language flame war :-), and one of >> the things I really miss is variable interpolation in strings. I searched >> the net and found PEP 215 (http://www.python.org/peps/pep-0215.html). This >> seems to be exactly what I need. The proposal seems to be quite old, so I'd >> like to know if it's still in consideration or has it been dropped >> completely? [...] >>>> foo = "trick" >>>> bar = 95.5 >>>> print "This %(foo)s is loved by %(bar)s%% of programmers." % locals() >This trick is loved by 95.5% of programmers. > >You can use any dictionary, but locals() or globals() can be handy >in many cases. It took me a while to come to love the % operator - it really is a neat idea. It means that you don't have to worry about escaping the interpolation characters unless you explicitly want interpolation. In perl, I seemed to be forever forgetting to escape them, producing obscure bugs as a result. And it doesn't require any special rules in the grammer - it's just another operator. And in C, the problem is even worse (although it's not a fair comparison) - you have to allocate the memory first, worry about bounds checking, call sprintf (really snprintf), then worry about releasing the memory. -- Andrew McNamara, Senior Developer, Object Craft http://www.object-craft.com.au/ From pixie888 at hotmail.com Wed Jun 19 09:23:15 2002 From: pixie888 at hotmail.com (pixie888 at hotmail.com) Date: Wed, 19 Jun 2002 13:23:15 GMT Subject: SafeArray problem References: <3d105710.83643750@news.skynet.be> <3d108014$1@news.mhogaming.com> Message-ID: <3d108545.95472593@news.skynet.be> On Wed, 19 Jun 2002 08:55:31 -0400, "Michael Weiss" wrote: >How is the safearray parameter defined in the IDL on this method? [in, out] >[in] [out, retval], etc...? I have not written an idl-file myself, I just used the classwizard in Visual Studio to write my method on the automation object (using MFC). What do you really want to know? (I looked for idl-files in my project but did not find any) > wrote in message >news:3d105710.83643750 at news.skynet.be... >> Hi all, >> >> I am using an Automation object which has a method which takes a >> SafeArray as an argument. In my Python module I call this method and >> give a list of longs as an argument. >> >> While debugging (using the VC++6 IDE) I notice that the type of the >> argument (upon entering my automation object) is VT_ERROR (argument >> not found, actually). Now, what is really odd is the following: I >> extended my method: it takes two arguments, the first being a >> SafeArray and the second a long (which will not be used). When I call >> this method again from my Python module (with a list of longs and a >> dummy long as arguments) then everything works fine. >> >> Beats me, really. >> >> Any idea where the problem lies? >> >> Thanks, >> >> Henk > > From prema at prema.co.nz Sat Jun 15 02:49:32 2002 From: prema at prema.co.nz (Prema) Date: 14 Jun 2002 23:49:32 -0700 Subject: MS Word -- finding text Message-ID: Hi All ! Just wondering if anyone has some sample code around how to open a document, find a string and return the paragraph(s) containing the string. I have got a good part of the way but running up against Unicode decoding Can post some snippets if needed Thanks very much in advance Kind regards Mike From missive at frontiernet.net Sun Jun 23 05:49:03 2002 From: missive at frontiernet.net (Lee Harr) Date: Sun, 23 Jun 2002 09:49:03 -0000 Subject: DerivVar instance has no attribute '__float__' Message-ID: I just installed the Scientific module and am trying it out: >>> from Scientific.Functions.Derivatives import DerivVar >>> from math import sin >>> print sin(DerivVar(2)) Traceback (most recent call last): File "", line 1, in ? AttributeError: DerivVar instance has no attribute '__float__' >>> I googled for DerivVar float and found a message from one person last year with the same problem, but no posted solution. I am using: Python 2.2 FreeBSD 4.5 py22-numeric-20.3 py22-scientific-2.2 Anyone have a hint? From peter at engcorp.com Sun Jun 23 16:53:36 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 23 Jun 2002 16:53:36 -0400 Subject: Redirecting StdOut References: <1024856420.145085@seux119> <1024860416.580309@seux119> Message-ID: <3D163550.E525D840@engcorp.com> "Ugo Garc?a" wrote: > > perfect. This is what I was looking for. Now I'd make a C module to handle > the messages written to stdout & stderr in order to show them in the screen. > Thanks a lot Why would you bother with C for a game that relies on simple print statements for its interface? Can't you implement the game entirely in Python? -Peter From mcherm at destiny.com Wed Jun 19 14:23:02 2002 From: mcherm at destiny.com (Michael Chermside) Date: Wed, 19 Jun 2002 14:23:02 -0400 Subject: Pop a list from beginning ? and memory saving... Message-ID: <3D10CC06.3010700@destiny.com> Holger Krekel wrote: >> [Tim Peters] >>> [James T. Dennis] >>>> ... >>>> So, the critical question is: >>>> Is the list's reverse() method done in place >>> Yes. >>>> and does it run in linear time >>> Yes. >>>> (or better? >>> No. It does len(list)/2 swaps. > O(n/2) is linear, but still slightly better than > O(n) > >> in another thread we had some discussion about a >> reverse-iterator. You could write >> for item in iters.reverse(list): >> # item iterates over list's items backwards >> # but the list itself stays unmodified. >> Do you agree that this would be a good idea? >> please-share-your-brain-ly y'rs, holger > James T Dennis wrote: > It might be better to have a hack to the implementation of the > list primitives --- so they defer the shift of remaining elements > until GC. The head of the list could point at the first none > deleted item. Then pop(0) could be implemented in O(1) time and > the garbage collector would eventually come along to do it's > job. I'm not sure that makes sense in Python. Most garbage is NOT collected by a separate GC thread (as in Jython and Java) or in bursts of GC activity. In cPython, nearly everything is garbage collected via reference counting... the object is GC'ed when the last reference to it is released. As for the original question (is it a good idea), I'd say YES, but with one caveat. I think that it is important that the "iterable" utilities operate on ANY iterator ... and that isn't possible with the intelligent implementation of reverse. So I think that if iterable.reverse() were to check the type of it's argument and use the clever approach (counting backwards) for types list and tuple, but fall back on creating a temp list and reversing it for other types, then that'd be quite useful. Optimize the common case, but don't lose the universality. -- Michael Chermside From sheershion at mailexpire.com Wed Jun 12 16:21:11 2002 From: sheershion at mailexpire.com (Robert Amesz) Date: 12 Jun 2002 20:21:11 GMT Subject: newbie question - python blocking on int()? References: <4LaN8.2488$Vr2.586019@news20.bellglobal.com> Message-ID: Michael Davis wrote: > I'm writing a specialized ftp client. I'm parsing the output of > ftp.dir, which gives me a string like this (call it str): There already is a Python extension module for parsing that type of data. I found it on: http://freshmeat.net/redir/ftpparsemodule/20709/url_tgz/ftpparsemodule-0.93.tar.gz I haven't used it yet, so I can't comment on it. Robert Amesz From FooWeissBarMike at hotmail.com Wed Jun 5 08:48:12 2002 From: FooWeissBarMike at hotmail.com (Michael Weiss) Date: Wed, 5 Jun 2002 08:48:12 -0400 Subject: Compiling Python References: Message-ID: <3cfe0a36@news.mhogaming.com> While not exactly compiled to a native exe, there are other options: Look at this: (Py2Exe) http://starship.python.net/crew/theller/py2exe/ I understand there are other options similar to py2exe that I've never tried... like "freeze" or the stuff over at http://www.mcmillan-inc.com/install1.html "TuxTrax" wrote in message news:slrnafrqit.lbm.TuxTrax at fortress.tuxnet... > Hello all > > I am new to this forum, and to Python, please excuse the newbie question. > > I have started reading the o'reilly book, "learning python" and find python > to be an amazing language so far. My first impression of it is a language that > is easier than basic to learn and use, and more powerful than many other > high level languages such as pascal. > > My question is this; I realize that Python compiles to bytecode automatically > as part of the interpreters tokenization run, but is there a way to permanently > compile python code outputting to an executable binary? > > Cheers, > > Mathew > > -- > TuxTrax (n.) An invincible, all terrain, Linux driven armored assault > vehicle that can take as much fire as it gives ;-) > > > ASSASINATION ANTHRAX PRESIDENT NUCLEAR TALIBAN AMMONIUM NITRATE > > > Yes, I am a Penguin cult high priest. Fin readings upon request. > ROT13 this email address to mail me: uvtuqrfregzna at lnubb.pbz > From maxm at mxm.dk Thu Jun 20 05:36:29 2002 From: maxm at mxm.dk (Max M) Date: Thu, 20 Jun 2002 11:36:29 +0200 Subject: GOTO w/ Python? References: <3d10ed95@xpl-sdf1-sec1.> Message-ID: <3D11A21D.9010809@mxm.dk> Michael Hudson wrote: > "John Roth" writes: > > >>There's no equivalent of a goto command in Python, for good reason, >>which I won't repeat here. Prof. Djikstra did it very well in 1974, >>in his letter "Goto Considered Harmful." > > > There are also technical difficulties implementing it (the > blockstack), or I'd have probably done goto functionality in > bytecodehacks :) What do you mean??? Goto's are simple ;-) def goto(lable): lable() def start(): print 'starting' goto(lable2) def lable1(): print 'at lable 1' goto(stop) def lable2(): print 'at lable 2' goto(lable1) def stop(): print 'stopping' goto(start) >>> starting >>> at lable 2 >>> at lable 1 >>> stopping From candiazoo at attbi.com Thu Jun 27 13:34:26 2002 From: candiazoo at attbi.com (candiazoo at attbi.com) Date: Thu, 27 Jun 2002 17:34:26 GMT Subject: Here is the result of my profile... References: <3d1a6993.248534625@netnews.attbi.com> Message-ID: <3d1b4c89.306637140@netnews.attbi.com> Completed at Thu Jun 27 10:50:13 2002 11623 function calls in 152.079 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.001 0.001 151.962 151.962 :1(?) 429 0.140 0.000 0.279 0.001 catalog_model.py:109(__init__) 429 0.148 0.000 0.148 0.000 catalog_model.py:114(set_base_fee) 429 0.014 0.000 0.014 0.000 catalog_model.py:118(set_page_fee) 429 0.015 0.000 0.015 0.000 catalog_model.py:121(to_string) 1703 0.104 0.000 0.104 0.000 catalog_model.py:509(fix_date_rang e) 848 0.157 0.000 0.157 0.000 catalog_model.py:57(__init__) 1 150.396 150.396 151.961 151.961 catalog_model.py:573(generate_cata log) 848 0.027 0.000 0.027 0.000 catalog_model.py:66(set_wrk_inst) 848 0.020 0.000 0.020 0.000 catalog_model.py:69(set_title) 848 0.017 0.000 0.017 0.000 catalog_model.py:72(set_pub_name) 848 0.017 0.000 0.017 0.000 catalog_model.py:75(set_std_num) 848 0.016 0.000 0.016 0.000 catalog_model.py:78(set_date_range ) 848 0.137 0.000 0.137 0.000 catalog_model.py:81(set_source_id) 33 0.000 0.000 0.000 0.000 catalog_model.py:820(test_refresh) 36 0.353 0.010 0.353 0.010 catalog_model.py:823(test_echo) 1 0.000 0.000 0.000 0.000 catalog_model.py:826(test_cancel) 419 0.015 0.000 0.033 0.000 catalog_model.py:89(__init__) 419 0.136 0.000 0.136 0.000 catalog_model.py:92(to_string) 1 0.000 0.000 0.000 0.000 connections.py:85(cursor) 1 0.011 0.011 0.189 0.189 cursors.py:108(__do_query) 1 0.022 0.022 0.022 0.022 cursors.py:135(_fetch_row) 1 0.000 0.000 0.000 0.000 cursors.py:145(_check_for_warnings ) 1 0.178 0.178 0.178 0.178 cursors.py:160(_get_result) 2 0.002 0.001 0.002 0.001 cursors.py:162(close) 1 0.000 0.000 0.212 0.212 cursors.py:167(_query) 671 0.027 0.000 0.036 0.000 cursors.py:174(fetchone) 1 0.000 0.000 0.000 0.000 cursors.py:21(__init__) 1 0.000 0.000 0.000 0.000 cursors.py:28(__del__) 2 0.000 0.000 0.000 0.000 cursors.py:31(close) 671 0.009 0.000 0.009 0.000 cursors.py:36(_check_executed) 2 0.000 0.000 0.000 0.000 cursors.py:46(_get_db) 1 0.000 0.000 0.212 0.212 cursors.py:51(execute) 0 0.000 0.000 profile:0(profiler) 1 0.117 0.117 152.079 152.079 profile:0(test.generate_catalog()) From mfranklin1 at gatwick.westerngeco.slb.com Tue Jun 25 10:24:19 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Tue, 25 Jun 2002 14:24:19 +0000 Subject: Embedding in Tkinter (reprise) In-Reply-To: <1907a5e4.0206250504.4b417e9a@posting.google.com> References: <1907a5e4.0206240803.6ca0a4c@posting.google.com> <1907a5e4.0206250504.4b417e9a@posting.google.com> Message-ID: <200206251327.g5PDRwM28367@helios.gatwick.geco-prakla.slb.com> On Tuesday 25 Jun 2002 1:04 pm, Pier Paolo Glave wrote: > I tried to follow the hint by Jeff, but it seems that the TkSteal > package hasn't been updated for a long time: the last available > version is for Tk 4.x. > > Anyway, I made some further investigation on Tcl/Tk, and I found out > that there exists an extension package to Tk 8.x, named BLT, which has > a "container" object that can fit for my needs. > Now, my problem is that I'm not an expert in Python/Tk integration, > and I don't know how to wrap this into a Python class. > > Does anyone have any suggestions? Pmw (Python Mega Widgets) has an interface to BLT but I havn't used it so I don't know for sure that you can use this..... try: http://pmw.sourceforge.net/ for more info. Martin From whisper at oz.net Fri Jun 14 04:33:30 2002 From: whisper at oz.net (David LeBlanc) Date: Fri, 14 Jun 2002 01:33:30 -0700 Subject: Zip makes sense! was: Re: why not "'in' in 'in'"? In-Reply-To: <332c7c11.0206132333.199ba913@posting.google.com> Message-ID: Haskell - that's a mountain range in New York state? :p) David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Benno > Sent: Friday, June 14, 2002 0:33 > To: python-list at python.org > Subject: Zip makes sense! was: Re: why not "'in' in 'in'"? > > > "David LeBlanc" wrote in message > news:... > > > -----Original Message----- > > > From: python-list-admin at python.org > > > [mailto:python-list-admin at python.org]On Behalf Of Tim Peters > > > Sent: Thursday, June 13, 2002 18:57 > > > To: python-list at python.org > > > Cc: Grant Griffin > > > Subject: RE: why not "'in' in 'in'"? > > > > > > > > Hmmm... How about calling it "contains" instead of "in"? "if > 'feefifofum' > > contains 'fi'" seems nicer then "if 'fi' in 'feefifofum'" maybe? > > > > Of course maybe this makes too much sense for a language where > zip has zip > > to do with compression and yield nothing to do with threads. > > > I'm guessing you are mentioning this fairly tounge in cheek, > however zip makes > a lot of sense to anyone coming from Haskell. If I was after the > zip compression > algorithm i would look in the hypothetical compression package. > > it-made-perfect-sense-to-me-ing-ly yours Benno > -- > http://mail.python.org/mailman/listinfo/python-list From emile at fenx.com Sun Jun 2 10:27:49 2002 From: emile at fenx.com (Emile van Sebille) Date: Sun, 02 Jun 2002 14:27:49 GMT Subject: How to delete file? References: Message-ID: "Ken" wrote in message news:add9ai$107clv$1 at ID-49758.news.dfncis.de... > How do you delete file? > import os os.unlink(path) os.remove(path) > If you write to file from beginning position of an existing file, do you > overwrite the existing data or insert from it? > --or-- to overwrite a file (or create if not already there) just open it: >>> print open.__doc__ open(filename[, mode[, buffering]]) -> file object Open a file. The mode can be 'r', 'w' or 'a' for reading (default), writing or appending. The file will be created if it doesn't exist when opened for writing or appending; it will be truncated when opened for writing. Add a 'b' to the mode for binary files. Add a '+' to the mode to allow simultaneous reading and writing. If the buffering argument is given, 0 means unbuffered, 1 means line buffered, and larger numbers specify the buffer size. HTH, -- Emile van Sebille emile at fenx.com --------- From paul at fxtech.com Thu Jun 27 10:49:38 2002 From: paul at fxtech.com (Paul Miller) Date: Thu, 27 Jun 2002 14:49:38 GMT Subject: connecting embedded Python audio samples with NumPy? Message-ID: <3D1B2603.26EA9A9C@fxtech.com> I have a C app that reads audio data, and I'd like to pass this audio data in array format to Python functions so I can use it with NumPy. I have this working right now - generating a float array from the sample stream. But I want to put this array into a form usable by the FFT functions. I've read over this paper: http://www.onlamp.com/pub/a/python/2001/01/31/numerically.html Which indicates I need to put my 1D sample stream into a 2D array. Can anyone elaborate more on this? I'm wondering if I should provide the array pre-made for FFTs from my C code, or I should build the 2D array from the 1D array I have in Python. From ponderor at lycos.com Fri Jun 14 03:20:30 2002 From: ponderor at lycos.com (Dean Goodmanson) Date: 14 Jun 2002 00:20:30 -0700 Subject: Python 2.2.1 References: Message-ID: > How do I set the path and what should the name of the path be? All > help and information would be appreciated. Thanks.:) > -- Windows 9X -> Millenium get increasingly harder to setup environment details. a. Autoexec.bat MAY work for you. b. Typign MSCONFIG from your RUN menu (Start~Run, or Windows key+R) will bring you to an environment configuratin screen. c. These don't necesarily apply to the "DOS Mode" settings, which may require you setting up another autoexec.bat. d. The suggestions for using PythonWin are most appropriate. After rebuilding (for me this is re-installing OS+Formatting, not simply reinstalling.) my PC and not installing it, I missed PythonWIN. (But for a personal perspective training reason I want to use the default tools, plus run PythonCard with fewer "environment" variables. (Did you see the plug for PythonCard? If not here's a few more: Python-Tutor mailing list. Useless Python web site. Google those.)) PythonWIN includes the doc's in Windows Style help. I find those a handy in ways but prefer local HTML help files. PyDoc is also handy( http://www.onlamp.com/pub/a/python/2001/04/18/pydoc.html ). How's that for vague cues? I have Windows ME on my home laptop. Too cheap to buy XP or take the time to install Linux and train myself and wife. Your question is most valid. I searched the Windows help, google, microsoft.com, and finally got the answer from a friend trying to find why my autoexec.bat changes didn't take affect, and the diamond in the rough: MSCONFIG. -Dean From peter at engcorp.com Tue Jun 25 00:02:24 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 25 Jun 2002 00:02:24 -0400 Subject: Suggestions for good programming practices? References: Message-ID: <3D17EB50.E5A6781D@engcorp.com> David LeBlanc wrote: > > Somebody seems to be working overtime to miss the point here... Don't be rude please. Your offline message pointed out that you _like_ this behaviour, and so do I, but your original message appeared to indicate you did not. I was trying to get at why you didn't like it, not to be pedantic or anything. David LeBlanc originally wrote: > The one that always gets me is "lat,lon,timezone = > getLocation("seattle")". I.E. the ability to return multiple > distinct values as opposed to returning > multiple values in the form of a struct as in C or C++. Sorry for the confusion... -Peter From talon34 at hotmail.com Wed Jun 26 23:36:08 2002 From: talon34 at hotmail.com (Talon) Date: Thu, 27 Jun 2002 03:36:08 GMT Subject: Installation problems DCOracle2 & W2000 References: Message-ID: In article , brueckd at tbye.com wrote: > On Wed, 26 Jun 2002, Talon wrote: > > > OK, here you go: > > > > Path = C:\Python21\; (I don't have a specific PYTHONPATH variable set. > > This is in the general PATH variable) > > > > The error I get is > > > > File "C:\Python21\myfiles\htsa_data_loader_v2.py", line 9, in ? > > import os,sys,re,string,DCOracle2 > > File "C:\Python21\DCOracle2\__init__.py", line 91, in ? > > import DA > > File "C:\Python21\DCOracle2\DA.py", line 90, in ? > > from db import DB > > File "C:\Python21\DCOracle2\db.py", line 89, in ? > > import DCOracle2, DateTime > > ImportError: No module named DateTime > > > > DateTime is located in C:\Program Files\ZopeDev\lib\python\DateTime > > Aha! Here's what I think the problem is: the DCOracle2 bundle off the Zope > site comes all wrapped up in the Zope database adapter (ZOracleDA), so > your above script is actually trying to import the DA and not the > DCOracle2 package itself (I can see why this is confusing - both > directories are named DCOracle2 but one is a subdirectory of the other!). > > So... if you look in c:\python21\DCOracle2 you should find a subdirectory > in there also called DCOracle2. This is the only one you should need for > doing standalone (none-Zope) work with Oracle. The easiest thing to do is > rename c:\python21\DCOracle2 to DCOracle2bak or something, and then move > its DCOracle2 subdirectory into c:\python21 and then try your script > again. > > Does this make sense? Please let me know if it doesn't or if it still > doesn't work after that. > > -Dave > > > Dave, That was dead on. I did as you said and now it works perfectly. I thought I had done this originally, but I guess I had moved the outer folder instead. Thank you very much. Thanks to Fazal also for his input. It is much appreciated. Mark From recmorg at charter.net Mon Jun 10 19:44:14 2002 From: recmorg at charter.net (TuxedoKamen) Date: Mon, 10 Jun 2002 23:44:14 -0000 Subject: Making an About Box... Message-ID: Hello. I'd like to make an About Box using Tkinter. I'm using a grid inside a Toplevel widget, but I don't really like this solution. I'd like a window that did not have the minimize and maximize buttons, like the tkMessageBox derived boxes showinfo, showwarning, etc. Is it possible to make a window that has this type of title bar and put my own widgets in it? From peter at engcorp.com Wed Jun 19 22:03:14 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 19 Jun 2002 22:03:14 -0400 Subject: Unicode hexadecimal characters References: <3eeda89d.0206191615.71b0629d@posting.google.com> <3D112C60.9C3D2F9F@engcorp.com> Message-ID: <3D1137E2.7CB8F814@engcorp.com> Thinkit wrote: > > "Peter Hansen" wrote in message > news:3D112C60.9C3D2F9F at engcorp.com... > > Thinkit wrote: > > > > > > It's a bit OT but does Unicode support the digits ten through fifteen > > > (for hexadecimal)? > > > > Do you mean "does Unicode have unique glyphs representing the > > hexadecimal digits ten through fifteen other than the standard > > A, B, C... ?" > > Yes, that's what I mean. I looked at the spec and saw a lot of different > numerals, including 1-20 for circled numbers. Will have to examine it > again. Ah, those are just for typographical use, as in for glossy brochures and such. Not intended to be used to represent digits in any mathematical or computer sense I believe. It's unlikely there is any aspect of Unicode which covers "pretty" representations of hexadecimal digits... -Peter From mwh at python.net Mon Jun 10 05:52:41 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 10 Jun 2002 09:52:41 GMT Subject: PyCObject subtype PyObject References: <3D022727.2147C50E@doc.ic.ac.uk> Message-ID: Benjamin Tai writes: > Hi, > > > Any comments to clarify my confusion would be appreciated. > > In Python/C API Reference Manual, section 7.5.9 CObjects, the document > mentions that: > > "PyCObject This subtype of PyObject represents an opaque value, ..." > > > > 1) What does it mean by "subtype"? As a C interface, is the document > talking about two structs which share some common fields? Yes. > 2) For function "PyCObject_FromVoidPtr()", it takes in a "void*" as the > first argument. > For function "PyCObject_AsVoidPtr()", it returns a "void*". > When implementing Python extension, what is the potential danger of > casting pointers, of different size, to and from "void*"? Doesn't C guarantee that you can cast a pointer of type (T*) to (void*) and back again for all T? I was fairly sure it did. Python is implemented in C not C++, you know... > 3) What if I can always determine the original type of the pointer? Huh? > 4) Apart from exporting function between modules, are there any > examples of using PyCObject? Not sure what you mean here either... Cheers, M. -- The PROPER way to handle HTML postings is to cancel the article, then hire a hitman to kill the poster, his wife and kids, and fuck his dog and smash his computer into little bits. Anything more is just extremism. -- Paul Tomblin, asr From donn at drizzle.com Wed Jun 5 02:04:34 2002 From: donn at drizzle.com (Donn Cave) Date: Wed, 05 Jun 2002 06:04:34 -0000 Subject: Behavior of += (was Re: [Python-Dev] Customization docs) References: <3CFCF3E7.AE891EBE@noaa.gov> Message-ID: <1023257072.657314@yasure> Quoth huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu): ... | That is one proposal. My proposal is to disallow += for immutables. | Another symbol would be used for rebinding operations. (Or maybe swap the | role of these symbols.) Thus for mutables both operations would be | available. That suits me, except the mutable/immutable distinction. That's how we have been describing the distinction, but it's worth noting that it isn't really what we mean. For a silly example, suppose that in 2.3, None supports +=, kind of like the UNIX /dev/null. This would not make it mutable in any reasonable sense of the word, but it's in the "in place" category. A class instance that implements __iadd__ to return something other than self, would not be, though it's certainly mutable. Donn Cave, donn at drizzle.com From eric.brunel at pragmadev.com Mon Jun 3 10:56:57 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Mon, 3 Jun 2002 14:56:57 +0000 Subject: Interrupting a continuous script References: <_6JK8.1535$376.74360@newsfep1-win.server.ntli.net> Message-ID: Julian Gollop wrote: > I have a few programs continually processing text files on a Linux > machine. Occasionally I need to stop them, but I don't want to use a > keyboard interrupt because it may cause the script to stop in the middle > of doing something. > Does anyone know a simple way to allow me to stop the process by pressing > a key on the keyboard - without stopping inside something crucial? I'd use an interrupt handler on the signal SIGINT, which is sent to your process when you press Ctrl-C. It may sound complicated, but is in fact quite straightforward (as often with Python :-): --------------------------- import sys, os, signal, time interrupted = 0 def ctrlCHandler(*whatever): global interrupted interrupted = 1 print "Interrupt caught. Please wait..." signal.signal(signal.SIGINT, ctrlCHandler) print "Something really important start" for i in range(50): time.sleep(0.1) print "Something really important end" if interrupted: sys.exit() print "Something really important start" for i in range(50): time.sleep(0.1) print "Something really important end" --------------------------- Try to run this script and press Ctrl-C while it runs. You'll see it stops only when the "important" things are over. You'll just have to put a few lines like: if interrupted: sys.exit() at strategic places in your code, i.e. between important things. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From egbert at bork.demon.nl Sat Jun 22 13:57:15 2002 From: egbert at bork.demon.nl (Egbert Bouwman) Date: Sat, 22 Jun 2002 19:57:15 +0200 Subject: Tkinter & Python: how to get the return of a call associated to an event on my gui In-Reply-To: <3D12A2E4.6A566789@noos.fr>; from aurelienviolet@noos.fr on Fri, Jun 21, 2002 at 05:52:04AM +0200 References: <3D12A2E4.6A566789@noos.fr> Message-ID: <20020622195714.A689@bork.demon.nl> A callback may do something, but it does not return anything, at least not something you may use. I suppose that you need 'global', ie an export of a name from within a function (the local namespace) to the surrounding global one: the namespace of the module in which the function is defined. I think the line 'global result' in your callback will help. As long as you stay within one class-instance, you can solve it in another way: let your callback produce a 'self.result', which is available in the whole class-instance. Things become interesting when you have two classes, A and B, and A needs the data that will be collected by a gui in B. I call it interesting because I am still struggling with it. A and B should agree on the layout of the data structure that goes from B to A, but how B collects these data, from which entries or canvases, is entirely his own business. In the same way: B knows nothing of the way A handles these data. First the solution, and then some explanations. class B: def __init__(self,callback=None): # build a gui ... bouton = Button( ....., command=callback) bouton.grid( ...) def retour(self): # collect the gui-data in retour_list[], # and probably close this b-gui. return retour_list class A: def __init__(self): b = B( ..., callback=self.sign) def sign(self,event=None): self.data_list = b.retour() process_data() def process_data(self) # do something usefull with self.data_list # exit (button) the application Within the usual Tkinter loop you start this with: a = A() A passes in an argument the name of a callback to B. This callback ('sign') is a method of A. The chain of activities is started by the button-push in B that activates the callback in A. The callback sends a message ('retour') to B to collect and return the data, and A processes them. How B collects the data is hidden in 'retour', and what A does with them is hidden in 'process_data'. Now I have two questions: am I making things much too complicated, or does some standard pattern solve this problem in a better way ? egbert -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From K.Rdt at TU-Berlin.DE Sun Jun 23 15:08:14 2002 From: K.Rdt at TU-Berlin.DE (Klaus Reinhardt) Date: Sun, 23 Jun 2002 21:08:14 +0200 Subject: mail-problem over t-online Message-ID: --------------------------------------------------------------------- Hi Testing python and email I adapted this script: host=smtplib.SMTP('mailszrz.zrz.tu-berlin.de') host.sendmail(zwi_eck(From),zwi_eck(Tp),al) host.quit This is working, when I'm directly connected to my old ISP TU-Berlin via ISDN. But the same is failing, when I'm connected at t-online via ADSL, with authentification required .. Providing my log and pass produces errors, too. Pop3 is working in both cases. Who can give me a hint? Tia K at Rdt --------------------------------------------------------------------- From cliechti at gmx.net Sat Jun 29 16:44:26 2002 From: cliechti at gmx.net (Chris Liechti) Date: 29 Jun 2002 22:44:26 +0200 Subject: can't import generators References: Message-ID: aahz at pythoncraft.com (Aahz) wrote in news:afl5je$4iu$1 at panix1.panix.com: > In article , > John Hunter wrote: >> >>I am having trouble working with generators. Anyone know what might >>cause this behavior: >> >>Python 2.2.1 (#1, Apr 22 2002, 21:20:54) [GCC 3.0.4] on linux2 >>Type "help", "copyright", "credits" or "license" for more information. >>>>> from __future__ import generators >>Traceback (most recent call last): >> File "", line 1, in ? >>ImportError: cannot import name generators > > Can't do this in interactive mode. Use a script. ?!?!? since when? $ python Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from __future__ import generators >>> def g(x): ... for p in x: yield p ... >>> [x for x in g(range(3))] [0, 1, 2] >>> definetly works.... chris -- Chris From sholden at holdenweb.com Tue Jun 4 08:47:04 2002 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 4 Jun 2002 08:47:04 -0400 Subject: Printing a text centered, it would be a newbie prob References: Message-ID: <2J2L8.225207$%u2.29779@atlpnn01.usenetserver.com> "Backflip" wrote in message news:c7bfc769.0206040012.20aa0a10 at posting.google.com... > Hello World (= > I?ve got a little problem, i want to put out an import string centert. For example: > for word in raw_input("bitte hier ihren text eingeben:").split(): > print word > > text=dies ist ein test > > now the output looks like this > > dies > ist > ein > test > > but i want that it looks like this one > > dies ist > ein test > > that both rows are simular to each other, could smb help me? >From your description, are we to assume that you only want two rows of output? Is the "similarity" referring to the number of words or the number of characters? Since the former is easier, would this answer your problem: >>> w = "this is an example".split() >>> wl = len(w) // 2 >>> l1 = w[:wl] >>> l2 = w[wl:] >>> print "%s\n%s" % (" ".join(l1), " ".join(l2)) this is an example >>> I suspect there will be more that you haven't yet told us, however: the specification was not rigorous. regards -- ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From neal at metaslash.com Thu Jun 6 16:50:28 2002 From: neal at metaslash.com (Neal Norwitz) Date: Thu, 06 Jun 2002 16:50:28 -0400 Subject: ANN: PyChecker v0.8.11 Message-ID: <3CFFCB14.22BB35E6@metaslash.com> A new version of PyChecker is available for your hacking pleasure. PyChecker is a tool for finding bugs in Python source code. It finds problems that are typically caught by a compiler for less dynamic languages, like C and C++. It is similar to lint. Comments, criticisms, new ideas, and other feedback is welcome. Changes from 0.8.10 to 0.8.11: * Improve error message for syntax errors from user files * Fix pychecker.bat so it should work now * Add a warning for using __coerce__ in new-style classes * Add --deprecated option for using deprecated modules or functions * Add a warning for using functions with security problems (os.t[e]mpnam) * Add a warning for comparing against True/False or defining True/False * Add --badexcept option to warn when using string exceptions or classes not derived from Exception to raise/catch exceptions * Fix spurious warnings from using (test and 'true' or 'false) Various other bugs were also fixed, including some problems using PyChecker in Python 2.2. PyChecker is available on Source Forge: Web page: http://pychecker.sourceforge.net/ Project page: http://sourceforge.net/projects/pychecker/ Mailling List: pychecker-list at lists.sourceforge.net Neal -- pychecker-list at lists.sourceforge.net From emile at fenx.com Sat Jun 15 10:22:09 2002 From: emile at fenx.com (Emile van Sebille) Date: Sat, 15 Jun 2002 14:22:09 GMT Subject: fileupload error! References: Message-ID: penguin > Hi I try to upload a picture with a python cgi script. Tried many versions of the code, this is the current. > Here's the code and error! > > The error: > > Traceback (most recent call last): File "C:\cgi-bin\upload.py", line 179, > in ? xmldokument = skjema['dok'].value File "C:\Python22\lib\cgi.py", line > 550, in __getitem__ raise KeyError, key KeyError: dok > I didn't read through your code, but the error you're getting means that 'doc' is not a key in cgi.FieldStorage(). skjema = cgi.FieldStorage() xmldokument = skjema['dok'].value There are many discussions and examples of cgi module usage at: http://groups.google.com/groups?as_q=cgi.FieldStorage&as_ugroup=comp.lan g.python HTH, -- Emile van Sebille emile at fenx.com --------- From jadestar at idiom.com Thu Jun 27 18:53:23 2002 From: jadestar at idiom.com (James T. Dennis) Date: 27 Jun 2002 22:53:23 GMT Subject: How to get rid the new line References: <3D1AD534.A74EC9F4@ipm.fhg.de> <3D1B1A76.563E5394@engcorp.com> Message-ID: SiverFish wrote: > On Thu, 27 Jun 2002 14:00:22 +0000, Peter Hansen wrote: >> Markus von Ehr wrote: >>> >>> f = open(filename, 'r') >>> lines = f.readlines() >>> line1 = lines[0] # exemplarily for first line line1 = >>> line1[0:len(line1)-1] >>> >>> or: >>> f = open(filename, 'r') >>> lines = f.readlines() >>> line1 = lines[0][0:len(line1)-1] # exemplarily for first line >> >> I believe this is unsafe. The final line may not be terminated with \n. >> >> -Peter > Any method like chomp in perl > I just one to cut read only the line that not empty into the list Could try this: def chomp(line): if line[-1]=='\n': line=line[:-1] return line (or variations thereon, to satisfy other semantic requirements). From peter at engcorp.com Sat Jun 29 00:23:16 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 29 Jun 2002 00:23:16 -0400 Subject: I'm an idiot References: Message-ID: <3D1D3634.C89FCF95@engcorp.com> David Griswold wrote: > > I had no idea it could be this compact. Thank you for your help! > > David > > Carel Fellinger wrote in > news:mailman.1025316799.2919.python-list at python.org: > > and write it like this: > > > > g = open('c:/temp/temp1.txt', 'w') > > for line in open('c:/temp/temp.txt'): > > g.write(line.strip()) It can't! At least, it's pretty ugly and not very Pythonic code (says yet another self-proclaimed expert :-). Also, it's going to write out all lines in the file as one big line because it removes the \n at the end of each but doesn't add any. Try some of the other, slightly more verbose, suggestions if you want your code to be readable. -Peter From calves at coelce.com.br Mon Jun 17 12:05:17 2002 From: calves at coelce.com.br (Alves, Carlos Alberto - Coelce) Date: Mon, 17 Jun 2002 13:05:17 -0300 Subject: tab size Message-ID: <29A97D00F387D411AC7900902770E14805853F72@lcoeexc01.coelce.net> Hi all, Consider the following code: >>> for i in range(10): print "%d\t"%i, 0 1 2 3 4 5 6 7 8 9 >>> How can I change the default size of tab in formating string \t?! Carlos Alberto COELCE/DPRON-Departamento de Projetos e Obras Norte Fone: 677- 2228 e-mail: calves at coelce.com.br \|||/ (o o) --ooo0-(_)-0ooo-- -------------- next part -------------- An HTML attachment was scrubbed... URL: From baf at texas.net Sun Jun 30 11:49:16 2002 From: baf at texas.net (Ben Fairbank) Date: Sun, 30 Jun 2002 15:49:16 GMT Subject: [Newbie] Is the text delimiter changeable? Message-ID: <3d1f26a4.5915886@news.texas.net> I have to process large amounts of text and the text includes numerous apostrophes and quotation marks. It would be very handy if I could temporarily assign a substitute for Python's use of the caracters " and ' to delimit text strings. If I could use, for example, the @ character or the # character, neither of which appears in the text I have to work with, and if I could disable the " and ' delimiters, then my task would be greatly simplified. I realize I can backslash escape these characters in some circumstances, but I do not think that will work when a user's input is a word such as "can't" or "don't." Anyway, short of doing something truly drastic, such as recompiling the system (which I have no intention of doing), is there a workaround that will permit this? Thank you, BAF From peter at engcorp.com Wed Jun 19 21:18:56 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 19 Jun 2002 21:18:56 -0400 Subject: directory References: Message-ID: <3D112D80.830FAB33@engcorp.com> "James T. Dennis" wrote: > > os.path.walk() uses an awkward interface. I wrote and posted this a couple > of months ago: > > #!/usr/bin/env python2.2 > ## Change the shebang line to match your needs! > import os > def dirwalk(startdir=None): > if not startdir: > startdir="." .... I guess this needs the following line before the "import os" ? from __future__ import generators I'm using standard 2.2.1, I think, and although I vaguely thought generators were already enabled by default I guess they are not. Have you modified your site.py or something? -Peter From rajarshi at presidency.com Fri Jun 28 15:03:29 2002 From: rajarshi at presidency.com (Rajarshi Guha) Date: Fri, 28 Jun 2002 15:03:29 -0400 Subject: joining 2 lists together - an elegant way? Message-ID: Hi, is there a more elegant way to join to lists together? Right now I do: newlist = [] for i in l1: newlist.append(i) for i in l2: newlist.append(i) It does the job - but a one liner (if possible) would be nice :) TIA, From rddlog at prodigy.net Sat Jun 22 13:01:47 2002 From: rddlog at prodigy.net (Russ Dilley) Date: Sat, 22 Jun 2002 17:01:47 GMT Subject: Numerical Methods in Python Message-ID: <%32R8.853$xv1.36390126@newssvr15.news.prodigy.com> I am interested in the numerical capability of Python as well as it's applicability to system administration tasks. I am a thermal analyst and deal rather extensive with numerical solutions to problems, such as finite-difference methods, interpolation, and numerical integration. I understand that there is a numerical package for Python called PyNum and was wondering if anyone can give me any insight into the capacities of this package. My dilemma is that I also have responsibilities in UNIX system administration and it seems to me that I might be able to "kill two birds with one stone" by learning the Python language. I currently use Perl and Shell scripts for system admin tasks and a mixture of FORTRAN, C, MathCAD, Matlab, and Excel for numerical work. As you might guess, it tends to get confusing constantly jumping from one to another. The syntax and application tends to blur and it is somewhat inefficient to "relearn" each to some extent whenever I have a new task to address. I would like to focus more attention to become proficient with a single language and, based on what I've seen, it seems that Python might be appropriate for use in system administration AND numerical programming. Does anyone have any insight to the applicability of Python to either, or both, of these tasks? From tjreedy at udel.edu Wed Jun 12 16:34:53 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 12 Jun 2002 20:34:53 GMT Subject: get a list of classes in this module References: Message-ID: "Mark McEahern" wrote in message news:mailman.1023907851.3426.python-list at python.org... > Suppose I have a list of classes: > > # validation.py > class CreditCardValidation: ... > and I want to make a helper method in the module to translate card type > strings into their appropriate class constructor. ... > I know I can use inspect.getmembers() to do this, but what if I want to put > the helper method in the same file as the classes (i.e., validation.py)? > How do I refer to *this* module? I believe the name of a modulue is the same inside as out. I do not know inspect or whether it can work on a module under construction. However, if the subclasses are too numerous to build the dict by hand, or the set so dynamic that you do not trust yourself to update it properly, I believe something like the following (untested) should work: def propersubclasstuple((classname,classobj)): return class_dict = dict(filter(propersubclasstuple, globals().items() )) > Should I use globals()? I mean, that would work--so I guess the question is > whether there's a more Pythonic approach? Correct and simple (in that order) *is* Pythonic ;<) Terry J. Reedy From DLNXPEGFQVEB at spammotel.com Mon Jun 10 08:47:00 2002 From: DLNXPEGFQVEB at spammotel.com (Christos Georgiou) Date: Mon, 10 Jun 2002 15:47:00 +0300 Subject: __imul__ broken for 'objects' in 2.2.1 References: Message-ID: <3n79guskvoaeqtr4srg11kaqse7jcqutt4@4ax.com> On 07 Jun 2002 18:17:45 +0100, rumours say that Alexander Schmolck might have written: >class Breaky(object): > def __imul__(self, other): > print "imuling" > return self >sq = Breaky() >sq *=1. > >gives: > >Traceback (most recent call last):[...] line 10, in ? > sq *=1. >TypeError: can't multiply sequence to non-int Just in case: it is indeed your intention to multiply the object with a float, right? PS It seems that a Breaky instance is not (incorrectly) considered a sequence in 2.3a0 (20020603). -- TZOTZIOY, I speak England very best, Real email address: 'dHpvdEBzaWwtdGVjLmdy\n'.decode('base64') From merkosh at hadiko.de Mon Jun 17 10:39:00 2002 From: merkosh at hadiko.de (Uwe Mayer) Date: Mon, 17 Jun 2002 16:39:00 +0200 Subject: what *is* a class? References: Message-ID: [This followup was posted to comp.lang.python and a copy was sent to the cited author.] In article , mgerrans at mindspring.com says... > It creates and returns an instance (or object, if you prefer) of the class > Group. g is referring to that instance, so you haven't lost it, unless you > assign g to something else. Since you have a reference to the object you > created (g), you don't need to "get ahold of it again" -- you still have a > hold of (on?) it. well, yes. and no. if you want to create an object structure, mapping f.e. a binary file you have to somehow 'create' the structure. for this you don't have to read the file in. the problem was how to code this. assuming i have classes for BYTE, WORD, DWORD, LONG, FLOAT, etc. i could pass the root node (here: f.e. AVI()) a list of classes describing the header information: AVI(BYTE, DWORD, BYTE, BYTE, BYTE, ...) If you then build compound classes they perhaps consist of a length DWORD followed by 'length' number of bytes. it would be natural to compose this new structure LIST of more basic types (at least for the length DWORD, certainly not for the chain of data): class LIST(...): def __init__(self, f): self.file = f self.length = BYTE().parse(f) ... the last line creates a byte structure and reads it from file. i *have* to use a separate method call here, because imagine the AVI example from above having a string of 17 characters as an argument: AVI(BYTE, DWORD, STR(len=17), ...) STR(len=17) already instanciates a STR object while BYTE and DWORD only refer to classes. In the above LIST declaration I could write: self.length = BYTE() self.length.parse(f) ... which looks a little humble to me. > But if you insist on having a method to do it, you could define it like so: > > class Group: > # ... other code. > def getRef(self): > return self > > Then, instead of "g2 = g", you could do this: > > g2 = g.getRef() I guess when I tried that I wrote: g2 = Group().getRef instead of g2 = Group().getRef() (ouch!) which of course returned an "unbound method object" (IIRC) > I can't think of any reason why you would want to do this though, unless you > just need the extra typing practice and want to confuse someone who might be > reading the code... lol. :) does the above explanation make sense now or is there a more common approach to what i'm doing? > Perhaps I misunderstand your question and what you want is a factory. That > would be a method that creates and returns objects. Of course, the > constructor does this, but you might want a factory if you will instantiate > different types of objects based on some runtime consideration. If this is > what you are after, then reply to that effect for more elaboration. Yes. That sounds good, too. Depending on how you can define and create them. I will be parsing arbitrary binary files. Up till now I'm just writing some base classes for later use. If you got some spare time I'd greatly appreciate it if you could either elaborate on factories or perhaps name a link with some related information to it. Thanks Ciao Uwe From eppstein at ics.uci.edu Thu Jun 20 19:38:22 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Thu, 20 Jun 2002 16:38:22 -0700 Subject: Are generators in nested functions possible? References: Message-ID: In article , "Bjorn Pettersen" wrote: > def generateIndexes(length=5, span=1): > spanvalues = range(-span, span+1) > > def genInd(res, length): > if length == 1: > for val in spanvalues: > yield res + [val] > else: > for i in range(length): > for val in spanvalues: > genInd(res + [val], length-1) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This is a no-op. Did you mean for x in genInd(res+[val],length-1): return x ? > return genInd([], length) -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From marklists at mceahern.com Sat Jun 15 09:49:54 2002 From: marklists at mceahern.com (Mark McEahern) Date: Sat, 15 Jun 2002 08:49:54 -0500 Subject: Pronouncing '__init__' In-Reply-To: <20020615132519.A14452@hishome.net> Message-ID: My vote(s): the constructor or init when it makes sense it context. // m - From stephen.boulet at motorola.com Wed Jun 5 10:59:46 2002 From: stephen.boulet at motorola.com (Stephen Boulet) Date: Wed, 05 Jun 2002 09:59:46 -0500 Subject: os.popen and place in file Message-ID: <3CFE2762.519E4344@motorola.com> I'm running windows NT. The command: f = os.popen('dir') returns a file object 'f'. I can't however use the seek command on it: for i in range(3): print f.readline() f.seek(0) # Should put me back at the top of the "file" for i in range(3): print f.readline() This should (I think) print the same three lines again, but it doesn't. Anyone know why? -- Stephen (By the way, f = os.popen('dir', 'rb') doesn't work either.) From pyth at devel.trillke.net Wed Jun 12 06:09:36 2002 From: pyth at devel.trillke.net (holger krekel) Date: Wed, 12 Jun 2002 12:09:36 +0200 Subject: JIT Complier for python? In-Reply-To: <8d3f4438.0206111905.7934664b@posting.google.com>; from d2002xx@myrealbox.com on Tue, Jun 11, 2002 at 08:05:09PM -0700 References: <8d3f4438.0206111905.7934664b@posting.google.com> Message-ID: <20020612120936.W6609@prim.han.de> d2002xx wrote: > Is there any JIT Compiler for Python? you might want to take a look at http://homepages.ulb.ac.be/~arigo/psyco/ --holger From gh_pythonlist at gmx.de Thu Jun 13 22:09:24 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Fri, 14 Jun 2002 04:09:24 +0200 Subject: Type subclassing: bug or feature In-Reply-To: References: Message-ID: <20020614020924.GC590@lilith.my-fqdn.de> * Aahz [2002-06-13 16:08 -0400]: > Consider the following code: > > class MyStr(str): > def contains(self, value): > return self.find(value) >= 0 > > s = MyStr("hello, world!") > s = s.capitalize() > if s.contains('Hello'): > print "Found it!" > > It fails with an AttributeError when it calls s.contains(), because > s.capitalize() returned a str instead of a MyStr. Anyone want to take a > whack at defending this as the correct behavior? I once had the same problem with subclassing the list type/class: you'd need to override every single method of the base class to make subclassing of builtin Python types really useful. I ended up just implementing the parts of the sequence protocol that I needed in the particular case. I'll look at the other answers if there is some clever soluiton using __getattr__ or a metaclass. One day I'll have to figure out that metaclass stuff, anyways. I still have no idea what it's all about. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 17.1 ?C Wind: 1.2 m/s From peter at engcorp.com Sat Jun 22 18:52:37 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 22 Jun 2002 18:52:37 -0400 Subject: The best GUI library in python References: <8d3f4438.0206220457.b820418@posting.google.com> <3D1481DE.C0331204@engcorp.com> <8d3f4438.0206221422.6f71287a@posting.google.com> Message-ID: <3D14FFB5.90808865@engcorp.com> d2002xx wrote: > > Peter Hansen wrote in message news:<3D1481DE.C0331204 at engcorp.com>... > > How fast do you need your GUI to be? Are you talking about > > an unacceptably slow loading time, or response time within > > the application? > > Response time within the application, "idle" is. I think it's not due > to python, because boa-constructor (using wxWindows) and some examples > of PyQT work much faster than idle and others based on Tkinter. > > Well, if you doubt what I said, try to use grail. Or write a listbox > containing 10,000 items, then wait...... So your application needs to work in a speedy fashion with listboxes containing 10,000 items? How fast? Is your test simply to scroll through the list, or is it to time the display the first time? Grail? I didn't think that was supported. I did try downloading it once, as I recall, a long time ago, but didn't get it to work. It was probably just me but I don't feel like trying again. Anyway, how fast do you need the GUI to be? The grass is always greener... -Peter From gerhard at bigfoot.de Tue Jun 18 18:41:40 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 18 Jun 2002 22:41:40 GMT Subject: python version? References: Message-ID: George Hester wrote in comp.lang.python: > I just cannot believe what I ran into in this newsgroup. [...] .:\:/:. +-------------------+ .:\:\:/:/:. | PLEASE DO NOT | :.:\:\:/:/:.: | FEED THE TROLLS | :=.' - - '.=: | | '=(\ 9 9 /)=' | Thank you, | ( (_) ) | Management | /`-vvv-'\ +-------------------+ / \ | | @@@ / /|,,,,,|\ \ | | @@@ /_// /^\ \\_\ @x@@x@ | | |/ WW( ( ) )WW \||||/ | | \| __\,,\ /,,/__ \||/ | | | jgs (______Y______) /\/\/\/\/\/\/\/\//\/\\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From eric.brunel at pragmadev.com Thu Jun 6 05:40:06 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Thu, 6 Jun 2002 09:40:06 +0000 Subject: Freeze questions References: Message-ID: Sung H. Kim wrote: > Can the Freeze tool be used with C libraries? i.e. extensions? > > Will it create a truly standalone app (on Windows)? > > Does it support tk/tkinter apps yet? > > Finally, is there a good how-to on the Windows platform? Does it have to be freeze? I used it quite a lot and to be honest, it's quite difficult to get Tkinter applications working after freezing if you do not have a shared tcl/tk installation... There are other solutions that are far more straightforward for this business. I personally use Gordon McMillan's installer ( http://mcmillan-inc.com/install1.html ) which is very simple to configure and use. And it natively supports Tkinter applications. There is another installer called py2exe (just google for it), but I never tried it, so I don't know if it suits your needs. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From paul at boddie.net Tue Jun 11 07:49:20 2002 From: paul at boddie.net (Paul Boddie) Date: 11 Jun 2002 04:49:20 -0700 Subject: Compiling python2.2.1 on redHat 6.1 - doesn't work References: <23891c90.0205220343.4aa581c8@posting.google.com> <23891c90.0205230743.7ea59255@posting.google.com> <23891c90.0206030901.26402dd0@posting.google.com> Message-ID: <23891c90.0206110349.15aa7861@posting.google.com> matthew.russell at securetrading.com (Matt Russell) wrote in message news:... > Thanks Paul, > am afraid being a "c" newbie, I have no idea on how to apply the > patch, would be great if you could provide an example. Well, the stated bug in question is supposed to be fixed, although the thread on SourceForge hardly seems to indicate complete satisfaction, and I'm not entirely convinced that fixing configure.in changes the underlying issue. Anyway, I think it's enough for you to do the following: 1. Copy posixmodule.c somewhere safe. You shouldn't need to do this but it makes me feel better! 2. In the Python-2.2.1 directory (the top level of the source tree) download the patch as Python-2.2.1-posixmodule. 3. Try something like this in that directory: patch -p0 < Python-2.2.1-posixmodule The program should work out which file is to be patched automatically. You should be able to complete the build from there on. In other words: make Remember that I haven't tested any of functionality affected by this patch, and I suppose that what I've done hasn't been rubber-stamped by the people who really maintain this code, so beware! Paul From phr-n2002b at NOSPAMnightsong.com Fri Jun 21 06:33:57 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 21 Jun 2002 03:33:57 -0700 Subject: I'd give up Perl tomorrow if only... References: <3D12F6FC.3000608@wedgetail.com> Message-ID: <7xd6ukex9m.fsf@ruckus.brouhaha.com> Derek Thomson writes: > Among other things, it's one of the reasons I'm tinkering with a Perl ORB. Wow, that sounds cool. > Yes, it's stop-gap, but when you already have a non-trivial Perl > module, either on CPAN or in-house, it can save a lot of > rewriting. What we *really* need to do is dynamically create CORBA > interfaces for Perl modules, but that might be impossible given that > Perl is like Python in that module and class interfaces aren't > pre-declared :( Why not some more dynamic remote object protocol instead of messing with Corba? From whisper at oz.net Fri Jun 14 17:28:58 2002 From: whisper at oz.net (David LeBlanc) Date: Fri, 14 Jun 2002 14:28:58 -0700 Subject: Associating a C++ class with a Python class In-Reply-To: <2cc96dc7.0206141212.5b6ca5df@posting.google.com> Message-ID: Try the Boost Python library that does all this and more - you can write python classes callable from C++ and vice versa. The author says the latest and greatest (version 2) is best obtained from CVS if you're starting a new project. www.boost.org HTH, David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of John Dunn > Sent: Friday, June 14, 2002 13:13 > To: python-list at python.org > Subject: Associating a C++ class with a Python class > > > I would like to add a new class type to my embedded python engine and > I would like this class to wrap an exisiting C++ class instance. All > of the examples I have found are more 'c implementation' than 'c > wrappers', meaning that the python instance is not associated with an > different c++ class. The methods of the python class will just be > straight calls through to the C++ class. > > These classes will only be created from C, so I am basically looking > for a way to stuff a pointer to my C++ class into the python object. I > guess I could have a map of PyObject->C++ class, but I was hoping > there was a cleaner way to accompish this task. Is there a standard > way to do this? Am I missing something obvious? > > Thanks- > > John > -- > John Dunn > Peak Audio, a division of Cirrus Logic, Inc. > http://www.peakaudio.com > -- > http://mail.python.org/mailman/listinfo/python-list From jubafre at zipmail.com.br Tue Jun 18 21:01:07 2002 From: jubafre at zipmail.com.br (jubafre at zipmail.com.br) Date: Tue, 18 Jun 2002 22:01:07 -0300 Subject: =?iso-8859-1?Q?I=20have=20=2Epy=2C=20I=20want=20=2Eexe=2C=20how=3F=3F?= Message-ID: <3D0F6623000012D8@www.zipmail.com.br> i have a file.py how i make e executable file .exe for run in windows??? Juliano Freitas www.gebrasil.hpg.com.br ------------------------------------------ Use o melhor sistema de busca da Internet Radar UOL - http://www.radaruol.com.br From jonathan at onegoodidea.com Wed Jun 26 14:39:54 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Wed, 26 Jun 2002 19:39:54 +0100 Subject: Python 2.2 __slots__ Bug? References: Message-ID: On 26/6/2002 17:57, in article afcrp8$c64$1 at panix1.panix.com, "Aahz" wrote: > Interesting. Using Python 2.2.1 on Mandrake 8.1, I get a segfault > without printing "I'm fine". Go ahead and file a bug. I finally got Sourceforge to talk to me long enough to submit a bug report for this: #574207 Chained __slots__ dealloc segfault Feel free to followup with any information I've missed. Jonathan From ponderor at lycos.com Sat Jun 15 20:45:42 2002 From: ponderor at lycos.com (Dean Goodmanson) Date: 15 Jun 2002 17:45:42 -0700 Subject: Newbie deluxe References: Message-ID: "Zach" wrote in message news:... > I've just started taking a look at Python (experienced in Delphi) and so far > it looks very clean and comprehensible. My question is, what are the > fundamental differences and similarities between it and Perl? I hear so > much about these two languages, especially in Linux circles and just > wondered what sets them apart. This is an interesting article: http://www.prescod.net/python/why.html > Can full fledged graphical applications be > built with Python or does it lean more towards scripting? If you do like WXPython & Rapid GUI (You /did/ mention Delphi), also check out the PythonCard project: http://pythoncard.sourceforge.net/ >> I'm aware that it > has OOP capabilities so I assume it reaches beyond just scripting but like I > said, I've no experience with it. I would like to broaden my coding skills > with the addition of another language so any general opinions with regards > to its usefulness are appreciated. Broadening my programming language perspective was one of the primary reasons I dug into Python. I realized how important this was studying Java (from a C/C++ background), and realized how wonderful this CAN BE studying Python. The shell/procedural perspective gives you a "try it while it's fresh in my head" opportunity, which quickly and easily allows you to wrap your procedural research in OO classes...OO purists require that you map all classes before implementation, but I don't find this to be the best case, especially when you're getting familier with the language/technology. I digress, yet that is where I find Python very useful, and wish other languages (C#) provided a shell epxerience. BTW, Jython is on my To-Do list, and where I'd consider starting if you're heading into a Java project. ( http://www.oreilly.com/catalog/jythoness/ , http://www.onjava.com/pub/a/onjava/2002/03/27/jython.html ... and since I'm here, O'Reilly's Safari is a fairly cheap way to get your hands on the book resources you're not sure you want to invest in. ) Python's "batteries included" and open source initiative takes you beyond learning the language to learning and experimenting with modern technologies, and if you're looking into deep comp. sci. studies I don't think you'll be disappointed with opportunities to find and experiment with classical algorithm implementation or specialized projects. I'm not sure what meant by "coding skills", but by shear speed of coding & it's consistency with many coder's common thinking ("How I Think") should support your endeavor. Python's OOP will give you all you want. Unless you're a purist...Python has multiple inheritance, and requires some extra syntax for interfaces, and other mostly minor nuances, nuances are familier to all "OO" languages....but if that's your style you'll probably grumble about indention and : usage and will get over it shortly after you've got a good grasp on the language. (Note the /after/ part, you'll probalby tune into Python quickly enough to start pondering fundamentals, instead of still memorizing syntactic features/stumbling blocks of other languages.) (For the c.l.py record, I haven't been following the recent "why doesn't ... OO" discussions, and I'm not qualified nor want to comment on Python as a functional language. But mention it in case that's what Zach may be looking for in expanding his coding skills.) When you get perplexed, the python mailing lists, especially the Tutor list, are friendly environments for your questions/befuddlements. My 2 cents flattened by a train of associations, -Dean From gerhard at bigfoot.de Thu Jun 20 09:10:34 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 20 Jun 2002 13:10:34 GMT Subject: RES: latex-tex-packages References: Message-ID: Alves, Carlos Alberto - Coelce wrote: > This message is in MIME format. Since your mail reader does not understand > this format, some or all of this message may not be legible. Please don't do that and configure your mail-/newsreader to send text-only. > Thanks, > Pardon me, but I forgot to say it's to install in my linux box at home. So I > appreciate packages for linux box based on debian distribuition (I use > kernel series 2.4). I'd let the Debian package management worry about the dependencies, and just $ apt-get install lyx which will install the tetex-bin, among others. Btw. my preferred frontend to the Debian package management system is aptitude. Or you can use the somewhat clumsy, but powerful dselect to select packages to install. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From gh_pythonlist at gmx.de Tue Jun 11 01:49:46 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Tue, 11 Jun 2002 07:49:46 +0200 Subject: wxPython performance In-Reply-To: <3D04CF8D.4050407@bgb.cc> References: <3D04CF8D.4050407@bgb.cc> Message-ID: <20020611054946.GA10730@lilith.my-fqdn.de> * Don Garrett [2002-06-10 16:12 +0000]: > RPM1 wrote: > >"Andrei Kulakov" wrote > >> "hello world" type program from wxPython tutorial takes 6 > >>seconds to start on my cel 366 128mb system (running Debian). Is > >>this typical? Why is it so slow? I'm looking for a graphic > >>toolkit that'd be fairly quick. I don't want to use Tk because of > >>the looks. > > This whole thread is somewhat strange.... one of the things I liked about > wxWindows was that it seemed like one of the snappier cross plateform > libraries I've worked with. [...] I agree. Some people are mistaking "hello world" with typical applications and startup time with performance ;-) Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 12.1 ?C Wind: 2.7 m/s From R.Barrett at ftel.co.uk Mon Jun 10 12:45:30 2002 From: R.Barrett at ftel.co.uk (Richard Barrett) Date: Mon, 10 Jun 2002 17:45:30 +0100 Subject: module name differences depending on how generated Message-ID: <5.1.0.14.2.20020610171311.037b8c98@pop.ftel.co.uk> Compiling Python 2.2.1 from source on Suse Linux 7.3. It appears that if the nis (Sun Yellow Pages support) module is generated by $build/setup.py, the resulting shared library is called nis.so (presumably per the Extension constructor in $build/setup.py). If, on the other hand, you enable the nis support module's production in the $build/Modules/Setup file the module gets called nismodule.so (after the source file name). I'll assume there is a good reason for this difference and would appreciate it if anyone could tell me what it is. It happens that I initially did make install (which installed nis.so). Later, while making other changes, I uncommented the nismodule line $build/Modules/Setup and ended up with both nis and nismodule installed. As I subsequently figured out, nis.so will be loaded in preference to nismodule.so when in response to an import nis statement. The problem I then had was that in patching nismodule.c to fix a documented problem in the nismdoule.c code running under Linux (see http://sourceforge.net/tracker/index.php?func=detail&aid=233084&group_id=5470&atid=105470) running make install to generate a revised nis support module produced and installed a new nismodule.so. But this had no effect as the originally generated nis.so was being picked up in preference. Of course nis.so was not being regenerated and installed (presumably because setup.py detected that nismodule.so was being produced) so that at first blush the patch appeared to be ineffective. Having wasted some time with this module naming problem, I thought I'd ask if it was for a good purpose. From claird at starbase.neosoft.com Fri Jun 14 15:34:23 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 14 Jun 2002 14:34:23 -0500 Subject: NEWbie asks "is Python a good tool for automated file/folder generation?" References: <6k6kgukhuk8pfgos97a38h0d4r5jr0u3sr@4ax.com> Message-ID: <91B0759CECFC4C3A.944B7AF3C2197D61.C612F005CF9D6D07@lp.airnews.net> In article <6k6kgukhuk8pfgos97a38h0d4r5jr0u3sr at 4ax.com>, Unconditional Grace wrote: . . . >I have a series of scientific image files numbering, say, 1000, which >are really 100 groups, each group with its own identical string, but >appended with a different number from _01 to _10, or possibly some >other string. The end enumeration is ALWAYS differentiated from the . . . >I've never used Python, and I'm wondering if you, collectively, think >that Python is a good language to do this. While it seems like Python Python's an absolutely fine language for this. No broadly-popular language will do the job much better, and it certainly would be consider- ably harder in several. . . . -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From chris.lyon at spritenote.co.uk Sun Jun 23 14:30:49 2002 From: chris.lyon at spritenote.co.uk (chris lyon) Date: Sun, 23 Jun 2002 19:30:49 +0100 Subject: Newbie to HTMLgen Message-ID: <3d16132a$0$27325$afc38c87@news.easynet.co.uk> I'm porting an app from Cold Fusion to Python, for various reasons. And am looking at the possibility of using HTMLgen I am trying to place the Submit button of a form into a table element using Tablelite since the Submit button is generated by the Form Class is there any way to put it into the table header tag, of a table that has rows of table data and inputs. I can't seem to find a way to place the submit button into a table header cell where the client likes it. What I'm trying to produce is :- General Input Form  

Add A New System

This produces entries in the octavia database
DSN:
Webroot valueC:\INETPUB\WWWROOT
Title:
Webroot:
Image (large):
Image (small):
Logo:
Bkgd Colour:
Text Colour:
From emile at fenx.com Fri Jun 7 09:17:51 2002 From: emile at fenx.com (Emile van Sebille) Date: Fri, 07 Jun 2002 13:17:51 GMT Subject: Efficient python programming... References: <3D00A456.4315EDA3@engcorp.com> <3D00ABB6.6FAFD567@engcorp.com> Message-ID: <3o2M8.10509$pw3.96@sccrnsc03> "Peter Hansen" wrote in message news:3D00ABB6.6FAFD567 at engcorp.com... > Emile van Sebille wrote: > > > > Peter Hansen > > > You forgot the even more important first thing for a beginner: > > > get it correct! The only good way to do this is to write unit > > > tests that prove it. If you don't have tests, you don't have > > > working code (or how can you prove it?). > > > > We always used absence of bug reports as a gauge... and always > > questioned if that indicated usage or correctness. ;-) > > For those who are serious when they say that, it's all well > and good if you can get your customer to test the code for > you.... ;-) > Even better, as most of the time they're not sure what they asked for in the first place, blurring the line separating implementation error and user specification error. ;-)) (we really did think like that then -- for some set of we that includes me anyway) -- Emile van Sebille emile at fenx.com --------- From fwang2 at yahoo.com Tue Jun 11 02:19:29 2002 From: fwang2 at yahoo.com (oliver) Date: 10 Jun 2002 23:19:29 -0700 Subject: python, shell, environment variable Message-ID: hi, folks, I am trying to get a set of python and bash scripts to work, and I constantly run into trouble with environment variables: First, my python script need to modify environment variable, say, PATH, and want to keep the modification even after the script is done. os.environ["PATH"]= ... doesn't seem to work, any idea? Second, it would be better if my python script can call bash shell and still keep the environment variable modification done by bash. I tried os.popen("source some_shell"), it doesn't work. ? Thanks for help. -oliver From jblazi at hotmail.com Mon Jun 24 07:40:51 2002 From: jblazi at hotmail.com (JB) Date: Mon, 24 Jun 2002 13:40:51 +0200 Subject: converting an array of chars to a string References: <3d12dda2_6@news.newsgroups.com> Message-ID: <3d17038e_6@news.newsgroups.com> Bengt Richter wrote: > Have a look at the array module. It can construct an array > of signed or unsigned character elements optionally > initialized with values from a list or string. [...] Thank you very much. In principle, this was exactly, for what I was looking. But most unforunately if I declare such an array a, then a[0]=210 a[0] += 46 produces an error instead of the correct result 0. Now I am a bit desperate. This is like many things in the Python library: they look good at first sight but when you take a closer look at them, you see, that... Thank you anyway! -- Janos Blazi -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From plugin at supercable.es Tue Jun 25 14:11:18 2002 From: plugin at supercable.es (Ugo García) Date: Tue, 25 Jun 2002 20:11:18 +0200 Subject: Threads on embedded Python References: <1024952585.111238@seux119> <1024957605.771843@seux119> Message-ID: <1025028733.290520@seux119> thanks Chris. The URL you give me is very interesting. Pufff, this is a big mess... Don't know exactly how to do it. Perhaps could be a good idea to have the main loop in Python... But, one question: you say that I don't have to have a main loop in order to have threads running using Py_BEGIN_ALLOW_THREADS, but don't known exactly how to use it. I explain: from the main loop in my C application I launch threads in python using PyRun_SimpleString. But these threads doesn't run unless I call Python to do something. How I have to use Py_BEGIN_ALLOW_THREADS in order not to call Python continuosly? Thanks again, --ugo "Chris Liechti" escribi? en el mensaje news:Xns9238944DA0FEcliechtigmxnet at 62.2.16.82... > "Ugo Garc?a" wrote in > news:1024957605.771843 at seux119: > > > Let see if I get something clear... I don't have any main loop in > > Python. I only have some functions that 'control' certains object in > > my operation. To be a little more clear, the task of the functions are > > for example, move an object in the world generated by a game with a > > little intelligence. For example: (a simple example) > > > > FUNCTION 1: > > - Wait until main character is in correct position > > - Play a sound > > - Move an enemy from pos X1,Y1 to X2,Y2 > > - Play an animation > > - .... > > - .... > > > > So, I don't have a main loop, only function like that (and other kind > > of functions) that a run as a thread to have all them running > > simultaneous. Is there other way to do that without having threads? > > sure, it's called polling ;-) > > and i think this one could be an iteresting read for you: > http://www-106.ibm.com/developerworks/library/l-pythrd.html > it's a good way to distribute CPU power to different 'microthreads' while > having them well separated. altough you will need polling as microthreads > don't support blocking IO. > > > why not hanging it up the other way round? i think if you have the main > loop in python the thing will get easier. you can then call back to your C > module to do the screen updates etc. > > > Do > > I have to have a main loop in order to have the threads running? > > when you're in a C module the Global Interpreter Lock stopps all python > activity util you enable it explicitly (Py_BEGIN_ALLOW_THREADS) or you > return to python. > the GIL makes writing extensions to python peanuts... > > > Perhaps running Python in a separate thread could be a good idea. > > yes someone has to spend the CPU cycles... > > > Thanks, > > --ugo > > "Chris Liechti" escribi? en el mensaje > > news:Xns9237EECAA9CC5cliechtigmxnet at 62.2.16.82... > >> "Ugo Garc?a" wrote in > >> news:1024952585.111238 at seux119: > >> > >> > Hi all. I have an applicattion who uses Python to control some > >> > processes. I've made a little script library to work with threads > >> > and each proccess is a Python thread. The main application make > >> > calls to Python in order to create these proccesses. The problem is > >> > that the proccess doesn't run unless I call Python to do something. > >> > Now in the main loop I have a line like this: > >> > PyRun_SimpleString("dummy=1"); > >> > > >> > This make Python the threads to run. The problem is that this is a > >> > little slow 'cause if I call Python from tha main application too > >> > many times the proccesses run well but not the main application, > >> > and if a make a big pause between calls the proccesses doesn't work > >> > at a good speed. Is posible to have some threads running in an > >> > embedded Python without making callings to it continuosly? It would > >> > be a better idea to have another thread who's only task is to call > >> > Python (a line that the one written before) in order to have the > >> > Python proccesses running? > >> > >> why not run python in a separate thread (created by your app) and > >> doing > > the > >> loop in python, like PyRun_SimpleString("while 1: mainloop()") or so? > >> you do have a main loop in python, don't you? otherwise you wouldn't > >> need python threads, right? :-) > >> > >> you could possibly also release the GIL, but don't forget to grab it > >> again when accessing the python interpreter. i'm not sure about this > >> one, so i would try the above. > >> > >> chris > >> > >> -- > >> Chris > >> > > > > > > > > > > -- > Chris > From erict at millfilm.co.uk Wed Jun 5 08:12:28 2002 From: erict at millfilm.co.uk (Eric Texier) Date: Wed, 05 Jun 2002 13:12:28 +0100 Subject: wxPython performance References: <3cfb2695$1_1@news.uni-bielefeld.de> Message-ID: <3CFE002C.73A706C8@millfilm.co.uk> What did you lose using pygtk instead of wxWindow ? Mario Wehbrink wrote: > Am Sat, 01 Jun 2002 14:38:46 GMT schrieb/wrote/ > Andrei Kulakov < ak at silmarill.org > in comp.lang.python : > > > Hello, > > > > "hello world" type program from wxPython tutorial takes 6 > > seconds to start on my cel 366 128mb system (running Debian). Is > > this typical? Why is it so slow? I'm looking for a graphic > > toolkit that'd be fairly quick. I don't want to use Tk because of > > Hi, > > try pygtk. I also switched to it, after i found wxPython too slow for my > PPro-200. > > http://www.daa.com.au/~james/pygtk/ > > Mario > > -- > http://www.porcupinetree.com From cmkim at shinbiro.com Fri Jun 28 02:11:16 2002 From: cmkim at shinbiro.com (Kim Chul Min) Date: Fri, 28 Jun 2002 15:11:16 +0900 Subject: [Q] How Can I call python function from C source? References: Message-ID: Thank you for the help, Dave. BTW, I make test1.c like what you said and when I compile it I got some compile errors. Plz help more. ************************************************************** $ gcc -o test1 test1.c Undefined first referenced symbol in file PyCallable_Check /var/tmp/ccob3Tkv.o PyLong_AsLong /var/tmp/ccob3Tkv.o PyObject_HasAttrString /var/tmp/ccob3Tkv.o PyObject_GetAttrString /var/tmp/ccob3Tkv.o Py_Exit /var/tmp/ccob3Tkv.o PyImport_ImportModule /var/tmp/ccob3Tkv.o PyObject_CallFunction /var/tmp/ccob3Tkv.o Py_Initialize /var/tmp/ccob3Tkv.o ld: fatal: Symbol referencing errors. No output written to main collect2: ld returned 1 exit status ************************************************************** Anything I mistake? Wait for Any Idea. Plz help me. Kim Chul Min "Dave Kuhlman" wrote in message news:affguf$e3cn5$1 at ID-139865.news.dfncis.de... > Kim Chul Min wrote: > > > Hello there, > > > > I want to call python function from c source. > > > > for example, > > > > in file "main.c" > > -------------------------------------------------------------- > > int main(void) > > { > > > > /** want to call python function add(a,b) that return a+b **/ > > > > } > > -------------------------------------------------------------- > > > > in the file "add.py" > > -------------------------------------------------------------- > > def add(a,b): > > return(a+b) > > -------------------------------------------------------------- > > > > Can I call any function that written by python from C source ? > > > > If possible, can anyone show me simple example like above?? > > > > Plz,,, Help me....Thankx in advance... > > > > Ciao, > > Farangan Xavio > > cmkim at shinbiro.com > > Here is a simple example. > > You will find the following especially helpful: > > http://www.python.org/doc/current/api/importing.html > http://www.python.org/doc/current/api/object.html > > /* =========================================== */ > > #include "Python.h" > > int main(int argc, char ** argv) > { > PyObject * module; > PyObject * function; > PyObject * result; > long cresult; > int arg1; > int arg2; > > if (argc != 3) > { > printf("Usage: test1 \n"); > exit(-1); > } /* if */ > > arg1 = atoi(argv[1]); > arg2 = atoi(argv[2]); > > Py_Initialize(); > module = PyImport_ImportModule("add"); > if (PyObject_HasAttrString(module, "add")) > { > function = PyObject_GetAttrString(module, "add"); > if (PyCallable_Check(function)) > { > result = PyObject_CallFunction(function, "ii", arg1, arg2); > cresult = PyLong_AsLong(result); > printf("arg1: %d arg2: %d result: %d\n", arg1, arg2, cresult); > } > else > { > printf("Error -- attribute is not a function/method\n"); > } /* if */ > } > else > { > printf("Error -- Module does not contain \"add\" function.\n"); > } /* if */ > Py_Exit(0); > } /* main */ > > /* =========================================== */ > > > > -- > Dave Kuhlman > dkuhlman at rexx.com > http://www.rexx.com/~dkuhlman > From loewis at informatik.hu-berlin.de Sat Jun 15 07:31:27 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 15 Jun 2002 13:31:27 +0200 Subject: Pronouncing '__init__' References: Message-ID: Oren Tirosh writes: > under under init under under [...] > Most of these pronounciations also have a shorter version with the > trailing part omitted. I use under under init Regards, Martin From rdacker at pacbell.net Mon Jun 10 22:35:07 2002 From: rdacker at pacbell.net (rdack) Date: 10 Jun 2002 19:35:07 -0700 Subject: urllib question Message-ID: <644f6688.0206101835.5dc793b1@posting.google.com> this works but i don't understand it. it retrieves data from my router. params = urllib.urlencode({'RC': '@D', 'ACCT' : "root", 'PSWD' : "71:29:26", 'URL': 'admin' }) ipurl = "http://" + iphost + "/cgi-bin/logi" urlfp = urllib.urlopen(ipurl, params) i was wondering exactly what those params mean. i have some other code that wants a user name and password and i don't know what to give it. is the username = 'root'? and what is the password? a string with 3 two digit numbers separated by colons? what is the 'URL' param mean? somewhere to find documentation? From BPettersen at NAREX.com Tue Jun 18 12:11:49 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Tue, 18 Jun 2002 10:11:49 -0600 Subject: Embedding Python - time module problem Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192158EDE@admin56.narex.com> > From: Richard Townsend [mailto:richardt at edshk.demon.co.uk] > > I have been having problems embedding Python in a small C > program which calls a Python script which, in turn, imports > the time module. > > This fails with the error: > > "ImportError: dynamic module does not define init function (inittime)" > > I have simplified this down to a minimal C program which just > tries to import the time module. This gives the same error. > > #include > #include > > int main(int argc, char **argv) > { > PyObject *module; > Py_Initialize(); > module = PyImport_ImportModule("time"); > if (module == NULL) > { > PyErr_Print(); > } > } > > If I substitute "os" or "sys" for "time" then no error > occurs. However "math" does give a similar error. > > If I run the interpreter on its own, I can import time and > math with no problems. > > I am using Python 2.2.1 on HP-UX 11i > > Is there something special I need to do to be able to import > time and math modules when using embedded Python? Your example works for me (WinXP). The time module should be compiled into the Python library, so I'm not sure why your installation is trying to import it as a dynamic module... but since it is, do you happen to have a shared library named time somewhere on your path? Sorry I couldn't be of more help, it's been a while since I saw an HP box. -- bjorn From markus.vonehr at ipm.fhg.de Thu Jun 27 05:04:52 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Thu, 27 Jun 2002 11:04:52 +0200 Subject: How to get rid the new line References: Message-ID: <3D1AD534.A74EC9F4@ipm.fhg.de> f = open(filename, 'r') lines = f.readlines() line1 = lines[0] # exemplarily for first line line1 = line1[0:len(line1)-1] or: f = open(filename, 'r') lines = f.readlines() line1 = lines[0][0:len(line1)-1] # exemplarily for first line Markus SiverFish schrieb: > Anyone tell me how to skip the empty line when you read through the file > and copy the information in to the list(no empty line ) From gumuz at looze.net Thu Jun 13 07:39:26 2002 From: gumuz at looze.net (Guyon Morée) Date: Thu, 13 Jun 2002 13:39:26 +0200 Subject: Bits and bytes? References: Message-ID: <3d08839a$0$226$4d4ebb8e@news.nl.uu.net> ok, really a lot of thanx for your help, this is awesome! :D but, let me explain what i am actually trying to do here and why i think both of your solutions won't work for me. i am trying to implement my own sort of huffman encoding/compression. converting asci-characters to a compressed bitstream requires me to write it at bit-level. Bill's solution might work in some way, but my sequence of bits aren't allways divideable by eight. a word like 'ape' (which is 3x8=24 bits) might become 1001101, which is 7 bits.... catch my drift? strings is no option as this would have no positive effect on the 'real size' ;there's no compression. i hope this makes it a bit clearer for you. anyway, thanx a lot. guyon "Scherer, Bill" wrote in message news:mailman.1023896057.21318.python-list at python.org... On Wed, 12 Jun 2002, Guyon Mor?e wrote: From storminDOTnorm at excite.com Wed Jun 12 08:59:59 2002 From: storminDOTnorm at excite.com (Stormin Norm) Date: Wed, 12 Jun 2002 08:59:59 -0400 Subject: filecmp.cmpfiles on directories References: <3D06491B.302@excite.com> Message-ID: <3D0745CF.7060203@excite.com> Thanks Gordon, The documentation does not mention the filecmp.dircmp function. Any documentation on filecmp.dircmp anywhere?? Do you know if there is any ability with filecmp to walk the tree structure. Otherwise I'll use os.path.walk and call filecmp.dircmp. -StorminNorm. Gordon McMillan wrote: >Stormin wrote: > >>I am trying to walk a directory structure and compare directories for >>duplicates. For some reason I get the filecmp to work on individual >>files, but not on directories. >> > >>example: >>DOES NOT WORK: >>dups=filecmp.cmpfiles("C:\comp1","c:\comp2",common) >>print dups,"||",common >>result: >>([],[],[])|| >> > >For each filename in common, cmpfiles will compare the files >with that basename in the two directories. What you want >is: > x = filecmp.dircmp("C:\\comp1","c:\\comp2") > print x.same_files > print x.diff_files > >which will figure out "common" and call cmpfiles for you. > >-- Gordon >http://www.mcmillan-inc.com/ > From merkosh at hadiko.de Sun Jun 30 22:22:15 2002 From: merkosh at hadiko.de (Uwe Mayer) Date: Sun, 30 Jun 2002 19:22:15 -0700 Subject: arguments to functions References: Message-ID: In article , cliechti at gmx.net says... > Uwe Mayer wrote in > news:MPG.178955a4fc8bfc1c989680 at news.rz.uni-karlsruhe.de: > > I wanted to pass one named and a collection of unnamed (an arbitrary > > number) to a function: > > def f(*args, **kwargs): > print "positional args:", args > print "keyword args:", kwargs > if kwargs.has_attr("expected"): > print "Expected was set to", kwargs["expected"] > > does that help somehow? :-) > > chris yes, thanks. I think I should rather think of "expected=None" as an initialisation value rather than a "named parameter". Ciao Uwe From jjl at pobox.com Sun Jun 9 17:29:25 2002 From: jjl at pobox.com (John J. Lee) Date: Sun, 9 Jun 2002 22:29:25 +0100 Subject: Efficient python programming... In-Reply-To: <3D02FCBF.EEA954C4@engcorp.com> References: <3D013FB1.3D7477EA@engcorp.com> <83y9dp43d0.fsf@panacea.canonical.org> <3D02FCBF.EEA954C4@engcorp.com> Message-ID: On Sun, 9 Jun 2002, Peter Hansen wrote: [...] > What tests do, however, is vastly increase your confidence in the > correctness of the code, and when written properly (in advance > of each small morsel of code that is written, and having been > shown to fail without that code) they are sufficient to deliver [...] This point -- that tests should fail before they pass -- is easy to forget about. Thanks for reminding me. John From phd at phd.pp.ru Tue Jun 18 04:42:05 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Tue, 18 Jun 2002 12:42:05 +0400 Subject: unicode strings and strings mix In-Reply-To: ; from rnd@onego.ru on Tue, Jun 18, 2002 at 08:51:11AM +0400 References: Message-ID: <20020618124205.E17532@phd.pp.ru> On Tue, Jun 18, 2002 at 08:51:11AM +0400, Roman Suzi wrote: > Is there any way to define "default" encoding so the following error > will not happen? > > UnicodeError: ASCII decoding error: ordinal not in range(128) http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.102.htp Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From Nixdisciplenews at hotmail.com Thu Jun 13 22:26:46 2002 From: Nixdisciplenews at hotmail.com (Felix) Date: Thu, 13 Jun 2002 22:26:46 -0400 Subject: Scripting with Python in Xchat Message-ID: <3D095466.4000908@hotmail.com> Dear Community, does anyone here have experience with scripting in Xchat (IRC client) with Python programming language? I really need some sort of help considering there isn't any real documentation for this project. Your help will be greatly appreciated From phlip_cpp at yahoo.com Sun Jun 2 22:24:11 2002 From: phlip_cpp at yahoo.com (Phlip) Date: 03 Jun 2002 02:24:11 GMT Subject: SNIP IT: inspectObject(thing) Message-ID: Hop Nyh: Because groups.google.com is the world's ultimate backup server, I'm parking this snippet here. Given most object references, it prints out an "instant man page" of the value of every member, the name of every local or inherited method, and every __doc__ string of every method. Some of it could be replaced by calls into the inspect.py module, and one could extend it using that module. Put another way I wrote this before I learned of inspect.py. def printDocString(thing): dok = None try: dok = thing.__doc__ except: pass # whatEver if dok == None: dok = '' print '"'+dok+'"' return def _showAllMethods(klassList): for klass in klassList: for z, funk in klass.__dict__.items(): print klass.__name__+"."+z, printDocString(funk) _showAllMethods(klass.__bases__) # # prints out the dir() for any object in a pretty format. # def inspectObject(obj): printDocString(obj) klass = obj.__class__ try: print "("+klass.__name__+")" except(AttributeError): pass printDocString(klass) # TODO: call inspectObject on each member? for z in dir(obj): print "."+z, repr(getattr(obj, z)) _showAllMethods([klass]) return -- Phlip http://www.greencheese.org/LucidScheming -- Just think: Four billion people in the world have never received Spam... -- From seeger at sitewaerts.de Wed Jun 12 06:30:44 2002 From: seeger at sitewaerts.de (Felix Seeger) Date: Wed, 12 Jun 2002 12:30:44 +0200 Subject: Reload an imported file References: <3D071FC6.5000309@mxm.dk> Message-ID: Max M wrote: > Felix Seeger wrote: > >> I have a config file. This is a normal python file. >> Can I reimport this file during runtime ? >> So changing the configuration will not need a restart of my program. > > > import myModule > reload(myModule) > > regards Max M Mhm, sorry I have another problem now ;) I do an "from configuration import Configu" configuration is not known and Configu is no module. What can I do ? thanks have fun Felix From erict at millfilm.co.uk Thu Jun 6 10:11:18 2002 From: erict at millfilm.co.uk (Eric Texier) Date: Thu, 06 Jun 2002 15:11:18 +0100 Subject: HttpServer help! References: <3CFF4C14.450850D8@millfilm.co.uk> <3CFF6568.7EE613CE@millfilm.co.uk> Message-ID: <3CFF6D86.57CF7F6D@millfilm.co.uk> req = HTTP("10.16.3.132:2112") works Thanks You Steve Holden wrote: > "Eric Texier" wrote in message > news:3CFF6568.7EE613CE at millfilm.co.uk... > > The server and the client run from the same directory. > > and the cgi file is in the same directory. > > > > all the following failled. > > req.putrequest("POST", "favquote.cgi") > > req.putrequest("POST", "/favquote.cgi") > > req.putrequest("POST", "./favquote.cgi") > > > > > > What is the meaning of *relative to the server root* > > > Well, I was kind of assuming that the server was written to run CGI scripts, > but I think on further examination I was wrong. The "server root" is the > directopry that the server looks in when you request a document like > http://server:port/index.html -- it's the top-level content directory of a > web server, which may have subdirectories, and so on. > > From your server code: > > # start the server on port 2112, requires browser URLs > # to be addressed as http://servername:2112/pathtofile > myServer = HTTPServer(('', 2112), myRequestHandler) > > This has one obvious implictaion you seem to have overlooked. Your call in > the client > > req = HTTP("10.16.3.132") > > is trying to connect to the default port, port 80. You may need to change > this to > > req = HTTP("10.16.3.132:2112") > > It looks, from the code of the server, as though *any* POST request will > result in the same output, so the path you request maybe isn't that > important. Although I haven't read Fred's book yet, I am guessing that the > .putrequest() method assumes you are already connected to the server, and > that the HTTP() object will allow you to put a port number after the IP > address. > > If this isn't the case, try writing an HTML page containing a form whose > action attribute is something like > > ACTION="10.16.3.132:2112/something" > > and see if submitting that displays a response in the browser. > > regards > ----------------------------------------------------------------------- > Steve Holden http://www.holdenweb.com/ > Python Web Programming http://pydish.holdenweb.com/pwp/ > ----------------------------------------------------------------------- From peter at engcorp.com Sun Jun 23 19:09:10 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 23 Jun 2002 19:09:10 -0400 Subject: Python hits the spot References: <3D1634ED.B9ACF9EC@engcorp.com> Message-ID: <3D165516.110FD94D@engcorp.com> Peter Hansen wrote: > > P?r Kurlberg wrote: > > > > > It's no wonder that 1000 lines of uncommented code behave like that, taking > > > into account that you were trying to integrate several (Tcl/Tk, Fortran, C, > > > Python) systems in a hurry, and, I presume, not knowing most of them. > > > > Funny you should mention this. On my laptop (IBM Thinkpad with 128 > > megs of ram) the following two-liner gets me a lockup (i.e. keyboard > > and mouse completely unresponsive, powertoggle needed): > > > > for i in range(50*1000*1000): > > pass > > > > (I am serious.) Happened some time ago, but I never got around to > > filing a bug report (this thread was a good reminder.) > > Given that you're asking it to allocate something like 800MB of > memory, and not all at once but in a list that grows steadily > in size and has to be copied over and over, I'm not at all > surprised it appears to lock up a machine with only 128MB. Judging by Tim's reply elsewhere, and giving this a moment more thought, I can see the comment about 'grows steadily' is false. Of course it knows how many elements need to be allocated ahead of time so it doesn't actually need to grow the list. Doesn't change anything else though... -Peter From jbublitzNO at SPAMnwinternet.com Tue Jun 11 18:20:25 2002 From: jbublitzNO at SPAMnwinternet.com (Jim) Date: Tue, 11 Jun 2002 22:20:25 GMT Subject: Installing PyQt on Mandrake 8.2 References: <3D06689A.9040807@nospam_xs4all.nl> Message-ID: <3D06777B.7060105@SPAMnwinternet.com> iwk wrote: > I need to install PyQt on Mandrake 8.2 but I've been running into some > trouble. PyQt doesn't seem be included in the PowerPack edition which I > bought so I downloaded the RPM from the contributions directory on a > mirrorsite but that one failed because it was linked to an older version > of SIP. Then I tried to install from source but ./configure failed > because it couldn find the Python SIP modules. Apparently these ones > aren 't included with Mdk8.2 either. > Has anyone been more succesfull? What should be the proper steps to get > PyQt installed on Mdk 8.2? Uninstall any rpm sip versions and download the latest sip from http://riverbankcomputing.co.uk. Install the new sip version, and then configure, make and install PyQt. The PyQt version (3.2.4 for example) and sip version (also 3.2.4) have to match. Also, the location of the sip libraries was changed in recent versions. Jim From zopestoller at thomas-guettler.de Tue Jun 25 10:49:38 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Tue, 25 Jun 2002 16:49:38 +0200 Subject: Switch from 2.1 to 2.2 References: Message-ID: <3D188302.1030109@thomas-guettler.de> Mathieu Belanger wrote: > Hi all! > > I was trying to switch my server from python 2.1 to python 2.2 when I > began to have some compatibility problems. > > I'm a newbie in python and the following code was not written by me, > I'm only try to make it works! > > docType = implementation.createDocumentType('','','') > doc = implementation.createDocument('',None,docType) > parentNode = doc.createElementNS(None,'ACTION') > parentNode.setAttribute("name", "RESULT") > parentNode.setAttribute("DCId", DCSystemId) > doc.appendChild(parentNode) > RegSection1(doc,parentNode) > FileSection1(doc,parentNode) > SrvSection1(doc,parentNode) > StationSection1(doc,parentNode) > strDoc = StringIO() > PrettyPrint(doc, strDoc) > > I got an error in the PrettyPrint call. This call worked well before!! > Whats wrong now?? > > Thanks for your help! Plese send the stracktrace, too thomas From geoff at galtar.co.uk Wed Jun 26 13:57:30 2002 From: geoff at galtar.co.uk (Geoff Tarrant) Date: Wed, 26 Jun 2002 18:57:30 +0100 Subject: printing (again!!) Message-ID: I want to use Python as the language in a Computing course that I teach. However, I can't find a way that is relatively straightforward to send data to a printer in a Windows environment. If I can't find a way around this, I will have to revert to Delphi or VB. Please help. I like the idea of sending 20 or so Python programmers to University each year. Geoff Tarrant From sholden at holdenweb.com Fri Jun 28 10:00:42 2002 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 28 Jun 2002 10:00:42 -0400 Subject: [NEWBIE]- Syntax error References: Message-ID: "Alistair Campbell" wrote in message news:a7YS8.727$yY2.23825 at ozemail.com.au... > Hi, > I imagine the answer to this post is very simple ... but I'm not proud. > > Using Python2.2 on Windows OS > > Anyway, when I try to run a script fom the command line in IDLE or Python > > >>>python name_of_script.py > > the interpreter complains that there is a syntax error and highlights the > "name_of _script" part. > > I imagine that I have not initialised some PATH variable or other. I guess > that i need to put something in the autoexec.bat. Can anyone suggest what? > When you see the ">>>" prompt, the program that's currently reading your input *is* the Python interpreter. You should use python nameofscript.py at your shell command line prompt. You *can* execute your Python code from the ">>>" prompt with import nameofscript but then I'd have to explain why this works only once, and why thereafter you'd need to use reload(nameofscript) regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From fredrik at pythonware.com Thu Jun 20 12:17:39 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 20 Jun 2002 16:17:39 GMT Subject: module string.py References: <3d11bd6a.11177520@news.polito.it> <3d11f18b.24524431@news.polito.it> Message-ID: "NOPollution" wrote: > Where could I find the source code of the functions implemented in > "string.py"? The functions implemented in string.py are implemented in string.py (obviously). However, where that implementation looks something like def lower(s): return s.lower() you need to look at the implementation of the "lower" method of whatever "s" you want to pass to that function. Assuming you're using strings, the implementations can be found in Objects/stringobject.c or Objects/unicodeobject.c depending on the string type. To implement "lower", the latter uses Objects/unicodectype.c which depends on data in Objects/unicodetype_db.h, which in turn is generated by tools/unicode/makeunicodedata.py from the Unicode database available from the Unicode Consortium. (are you sure it's not easier to just read the library reference, and be done with it?) Btw, the source code can be found here (make sure to get the tgz file, not the installers) http://www.python.org/2.2.1/ From pinard at iro.umontreal.ca Thu Jun 6 16:32:19 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 06 Jun 2002 16:32:19 -0400 Subject: Efficient python programming... In-Reply-To: References: Message-ID: [Shagshag13] > I'm looking for any state of art, optimizing techniques, tips, that a > python beginner couldn't know by itself, but should learn and would be > aware to write "efficient and good looking"python's code... There is a lot of Python code all around to look it, including all the Python which comes with the Python distribution itself. I guess you will quickly get used to grasp in a glimpse which code is worth looking and which looks less interesting. One feels when code smells written by people having good taste and experience. There is practical principle that people generally who do well in many aspect of their work, which seem good to you right now, are likely to do equally well in the aspects which are more new to you. Also, on the Python site, there are a few essays written by Guido van Rossum about how one writes and optimises, and on Python in general, and which I read soon after starting to learn Python. I found these to be well written, quite instructive, and very welcome at the time. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From mikeb at mitre.org Sat Jun 1 20:35:01 2002 From: mikeb at mitre.org (Mike Brenner) Date: Sat, 01 Jun 2002 20:35:01 -0400 Subject: File Iterator - Print - Double New Lines Message-ID: <3CF96835.14EB1C61@mitre.org> Hi Peter, That is not what happens, though. The first three outputs (from the first call to reader) do not get newlines. The second three outputs (from the second call to reader) get double newlines. The explanation that "the print statement adds newlines after every lines it prints" would explain the double newlines the second time, but it does not explain the lack of newlines the first time. Did you run it on a windows machine? Mike Peter wrote: Mike, the print statement adds newlines after every line it prints. If you want to see the real contents of the file, use sys.stdout.write(). Alternatively, you might want to strip the newlines from each line as you read them in. Depends what you are trying to do. MIKE's OUTPUT (CONTAINING HIS QUESTION): QUESTION: How to get SINGLE SPACING? Using Python 2.2.1, it does the same under win32all build 142 and running it from a DOS box without the windows extensions. trying it without the \n abc trying it with the \n a b c MIKE's PROGRAM: print "QUESTION: Why did it jump from NO LINE SPACING to DOUBLE SPACING?" print "QUESTION: How to get SINGLE SPACING?" print print "Using Python 2.2.1, it does the same under win32all build 142 and " print " running it from a DOS box without the windows extensions." def writer(list): f=open("tmp.tmp","w") for item in list: f.write(item) f.close() def reader(): f=open("tmp.tmp","r") for line in f: print line f.close() print "trying it without the \\n" writer(["a","b","c"]) reader() print "trying it with the \\n" writer(["a\n","b\n","c\n"]) reader()abc trying it with the \n a b c From akakakhel at attbi.com Sat Jun 29 20:19:29 2002 From: akakakhel at attbi.com (Ali K) Date: Sun, 30 Jun 2002 00:19:29 GMT Subject: geting python files for use on web References: Message-ID: how do i install the files? Do I have the people from which i am getting my free space install the files? Do I just upload them onto my freespace? From pan-newsreader at thomas-guettler.de Sun Jun 16 18:18:12 2002 From: pan-newsreader at thomas-guettler.de (Thomas Guettler) Date: Mon, 17 Jun 2002 00:18:12 +0200 Subject: GdkImLib: Image(filename) seems to cache Message-ID: Hi! I use GdkImLib.Image(filename) to load and display jpeg files: img=GdkImLib.Image(filename) #(1)... rotate filename with shell script calling image-magic img=GdkImLib.Image(filename) but the image seems to be cached. The second time I load it, it is not rotated. It even gets stranger: If I add img=None at (1) the image gets rotated if I rotate it 90 or 270 degrees. If it gets rotated 180 I still see the old picture. Does someone know why the images seems to be cached thomas From sameer_ at email.com Wed Jun 5 11:36:06 2002 From: sameer_ at email.com (sameer) Date: 5 Jun 2002 08:36:06 -0700 Subject: constructive critisism on pythonwin IDE Message-ID: <6bd9f01b.0206050736.f469082@posting.google.com> First of all, let me start of by saying that Pythonwin is a great IDE. Now for the constructive critisism. The thing I hate about PythonWin is, that despite the fact that it's a development environment, there is a lot of caching done of modules, and the cached copy is not checked against a potentialy modified copy. Whenever I change the contents of a file and try to run a module that depends on that file, I always end up with the old copy. I have to then import and then reload the changed module in the interactive window for it to refresh. It would greatly increase my productivity, if I can specify which modules can be cached. I understand that there is a speed and development time issue, but I would like a little more fine grained control on how caching works on PythonWin, as the way it's currently implemented now is not acceptable. From krissepu at vip.fi Thu Jun 20 13:33:04 2002 From: krissepu at vip.fi (Pekka Niiranen) Date: Thu, 20 Jun 2002 20:33:04 +0300 Subject: Brackets in brackets, braces in braces Message-ID: <3D1211CF.59CBDC1B@vip.fi> It is possible to use regular expressions to match nested brackets, if you FIX the amount of nesting: >>> pattern = re.compile("(\?[^?!]+(\?[^?!]+\!)*[^?!]+\!)") >>> Line = "?AA?BB!CC!?DD!ee?EE!ff?FF?GG!HH!" >>> print re.findall(pattern, Line) [('?AA?BB!CC!', '?BB!'), ('?DD!', ''), ('?EE!', ''), ('?FF?GG!HH!', '?GG!')] In above I am searching strings limited by ?- and ! -characters. Only one level of nesting is allowed. The only problem I find is that re.findall() returns empty matches too. Maybe in next version of SRE modified findall is introduced. ;) -pekka- PS. How about searching line = "??BB!CC!" ? ;) From shagshag13 at yahoo.fr Wed Jun 5 11:58:36 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Wed, 5 Jun 2002 17:58:36 +0200 Subject: List containing objects and subclassing... Message-ID: Hello, I need an advice, i have a python list containing only object "node", and i'm wondering if this is best to hold it in a python list (as by now) or if i should write a "nodes" object subclassing from list and implementing some other methods i need to process on node object (contained by this list) and that i do now from "outside", or if i should write my own container implementing __getitem__ (i also have done that in another version)... ... [hash_i] --> [node_j] -> [node_k]... ... Which way is better OO practice ? which is the efficient one ? What are the pros and cons (maybe best oo vs efficient ?) ? Thanks, s13. From dman at dman.ddts.net Thu Jun 27 13:55:20 2002 From: dman at dman.ddts.net (Derrick 'dman' Hudson) Date: Thu, 27 Jun 2002 12:55:20 -0500 Subject: How to find out DNS ? In-Reply-To: <3D1B6186.3142.295959@localhost> References: <3D1B6186.3142.295959@localhost> Message-ID: <20020627175520.GA3547@dman.ddts.net> On Thu, Jun 27, 2002 at 07:03:34PM +0200, A wrote: | Is there a way how to find out, from Python , what primary or | secondary DNS I use when connecting to internet? f = open( "/etc/resolv.conf" , "r" ) nameservers = [] for line in f.xreadlines() : line = line.strip() if line.startswith( "nameserver" ) : _ , ip = line.split() nameservers.append( ip ) f.close() for ns in nameserver : print "nameserver" , ns Of course, this only works on a UNIX-like system where /etc/resolv.conf is used to list the nameservers. A common setup (on unix systems) is for some entries to be in /etc/hosts which takes precedence over DNS lookups. Any given application can also do its own thing too, if it wants. For example, the 'host' command can be told to contact any arbitrary host and submit a DNS query to it. Some setups will have LDAP (or maybe NIS) also serving host information, in which case DNS isn't involved for those hosts. Why do you want to know what the nameserver(s) are? Usually it is better to not know that and just let the underlying libresolv handle name resolution for you. (program to the interface, not the implementation ...) -D -- Microsoft is to operating systems & security .... .... what McDonald's is to gourmet cooking http://dman.ddts.net/~dman/ -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 248 bytes Desc: not available URL: From fperez528 at yahoo.com Wed Jun 19 20:00:14 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Wed, 19 Jun 2002 18:00:14 -0600 Subject: GOTO w/ Python? References: <3d10ed95@xpl-sdf1-sec1.> Message-ID: Gerhard H?ring wrote: >> I've always been curious. Why isn't the standard tutorial linked to here? >> It seems like the obvious first link to have, no? > > Because it's not well suited for programming newbies? Mmmhh, I'd disagree with that. Considering that it introduces all the data types and control structures one by one, nicely and slowly, I'd imagine many programming newbies could actually pick it up fairly well. Granted, by the time I read it I had been programming for many years and python was like my 10th language, so I have a hard time judging it from a 'programming newbie' perspective. But I honestly think it's clear and slow-paced enough to be a good starting point for any newbie. It could perhaps be included there with a simple comment like 'This tutorial may be a bit difficult to follow if you have zero previous programming experience in other languages. But if you know the basic concepts of computer programming, it will get you up to speed in python in half an afternoon.' Cheers, f. From steve at ferg.org Sun Jun 23 14:03:47 2002 From: steve at ferg.org (Stephen Ferg) Date: 23 Jun 2002 11:03:47 -0700 Subject: a Tree data-structure class? References: Message-ID: Thanks! From candiazoo at attbi.com Thu Jun 13 21:18:42 2002 From: candiazoo at attbi.com (candiazoo at attbi.com) Date: Fri, 14 Jun 2002 01:18:42 GMT Subject: ADO Command object/Parameters problem... Message-ID: <3d09426d.313465031@netnews.attbi.com> I am still having problems using dynamic sql statements to perform lookups and inserts into a MS Access database and an Oracle database. I've looked up the error at Microsoft and the solution is to find the OLEDB provider and add "OLEDB_SERVICES" DWORD value to the registry entry... did this (actually, it already HAD it)... no go. I used MakePy... no go. The code I used works in a VB application. I used the errors collection from the connection object and it only gives me a more concise version of what you see below. Does anyone have any idea why I cannot create a command object with parameter objects?? I am using only adVarChar and adNumeric values... no dates, no blobs, nothing odd at all...!!! Has anyone else run into this (note: I have seen other entries for the same error, which is rather generic, but not for my specific reason). Thank you, in advance... Mike J. ----------------------------------------------------------------------------------------------------------------------------------------- begin updating recType[s] on Thu Jun 13 12:15:39 2002 Traceback (most recent call last): File "C:\Documents and Settings\mjessop\My Documents\Python Development\Catalo g\BuildCatalog.py", line 1300, in ? setRecordType() File "C:\Documents and Settings\mjessop\My Documents\Python Development\Catalo g\BuildCatalog.py", line 506, in setRecordType rstOracle, status = cmdOracle.Execute() File "C:\Python22\Lib\site-packages\win32com\gen_py\00000205-0000-0010-8000-00 AA006D2EA4x0x2x5.py", line 1698, in Execute return self._ApplyTypes_(0x5, 1, (9, 0), ((16396, 18), (16396, 17), (3, 49)) , 'Execute', '{00000556-0000-0010-8000-00AA006D2EA4}',RecordsAffected, Parameter s, Options) File "C:\Python22\Lib\site-packages\win32com\client\__init__.py", line 341, in _ApplyTypes_ return self._get_good_object_(apply(self._oleobj_.InvokeTypes, (dispid, 0, w Flags, retType, argTypes) + args), user, resultCLSID) pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft OLE DB Provider for ODBC Drivers', 'Multiple-step OLE DB operation generated errors. C heck each OLE DB status value, if available. No work was done.', None, 0, -21472 17887), None) HERE is an example of what I am doing... (note, I added the long() typecasting to make sure the value was coerced into a long integer)... sql = "select pty.orgname " + \ "from ccc_party pty, ccc_right_rightsholder rgh, ccc_right rgt " + \ "where pty.pty_inst = rgh.rgh_inst " + \ "and rgh.rgt_inst = rgt.rgt_inst " + \ "and rgt.rgt_inst = ?" cmdOracle.ActiveConnection = cnnOracle cmdOracle.CommandType = 1 cmdOracle.CommandText = sql trsInst = long(rstTempDB.Fields("trs_inst").Value) aasInst = long(rstTempDB.Fields("aas_inst").Value) anyInst = trsInst or aasInst cmdOracle.Parameters.Append(cmdOracle.CreateParameter("orgname", 200, 2, 80)) cmdOracle.Parameters.Append(cmdOracle.CreateParameter("rgt_inst", 3, 1, 4, long(anyInst))) rstOracle, status = cmdOracle.Execute() From bt98 at doc.ic.ac.uk Sun Jun 2 05:55:21 2002 From: bt98 at doc.ic.ac.uk (Benjamin Tai) Date: Sun, 02 Jun 2002 10:55:21 +0100 Subject: Pop a list from beginning ? and memory saving... References: Message-ID: <3CF9EB89.7CA7204B@doc.ic.ac.uk> Shagshag13 wrote: > and is there a way to pop from the beginning of the list ? (i think i could > use reverse but > i don't know if this memory consuming) > > >>> a = [1,2,3,4,5,6,7] > >>> while 1: > try: > f = a.pop() > except IndexError: > break > print f > > thanks, > > s13. You could try a.pop(0), which pop the first instance of the list, like a FIFO. Thanks Ben From Alexandre.Fayolle at logilab.fr Thu Jun 6 09:58:35 2002 From: Alexandre.Fayolle at logilab.fr (Alexandre) Date: Thu, 6 Jun 2002 15:58:35 +0200 Subject: [ANN] constraint-0.1 Message-ID: <20020606135835.GF26159@orion.logilab.fr> Hello, Logilab has released constraint-0.1. The constraint package is an extensible Constraint Satisfaction Problem (CSP) solver using constraint propagation algorithms written in 100% pure Python (tested with Python 2.1) You can download it from ftp://ftp.logilab.org/pub/constraint, or read a bit more about it on http://www.logilab.org/python-logic/constraint.html, and discuss it on the logic-sig mailing list (see http://lists.logilab.org/mailman/listinfo/python-logic to subscribe) The package is still young, but we find it useful enough right now, so I thought I might as well publish it. What can it do? * solve some finite-domain CSP * handle n-ary constraints How can you extend it: * by implementing new Domain classes * by implementing new constraint classes * by implementing new Distributor classes How well does it perform? * 8-queens problems solved in 15 seconds on my 1GHz PC * SEND+MORE=MONEY problem solved in 8 seconds on the same machine If you're interested by constraint propagation programming in python, please join the logic-sig mailing list. Alexandre Fayolle -- LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org Narval, the first software agent available as free software (GPL). From ifls at rz.tu-clausthal.de Mon Jun 3 08:19:32 2002 From: ifls at rz.tu-clausthal.de (Lutz Schroeer) Date: 3 Jun 2002 12:19:32 GMT Subject: pygoogle search restricted by date Message-ID: Hi Pythonistas, The Goolge API doc tells me that I can restrict my search to a specific date range using "daterange:-" where date1 and date2 are Julian Day Numbers. I put the term in the restrict part auf the doGoogleSearch function (-> code snippet). Nevertheless I'm getting the same results. Any hints? Lutz <--snip--> import google from mx.DateTime import * google.setLicense('') today = int(now().jdn) yesterday = today - 1 restrict_query = 'daterange:%d-%d' % (yesterday, today) data = google.doGoogleSearch('python', restrict = restrict_query) for x in data.results: print x.title, x.URL -- From maxm at mxm.dk Mon Jun 17 03:37:00 2002 From: maxm at mxm.dk (Max M) Date: Mon, 17 Jun 2002 09:37:00 +0200 Subject: I feel stoopid ... this code is to verbose References: <3D0A1791.3060307@mxm.dk> <871yb922el.fsf@bunty.ruud.org> Message-ID: <3D0D919C.1010101@mxm.dk> ruud de rooij wrote: > Max M writes: > import locale > locale.setlocale(locale.LC_NUMERIC, 'da_DK') > locale.format('%.2f', 42000000.00, 1) > > batteries-included-ly y'rs, Yes this was actually one of the first things I tried, but I got a bit confused by the documentation:: "setlocale() is not thread safe on most systems. Applications typically start with a call of:: import locale locale.setlocale(locale.LC_ALL, '') This sets the locale for all categories to the user's default setting (typically specified in the LANG environment variable). If the locale is not changed thereafter, using multithreading should not cause problems. " So I worried that it would wreck havock with my application as I am using IIS, and I worried that the locale would be out of sync on different pages. My misunderstanding was seeded by me reading the docs wrong. I though that if I set the locale to 'danish' that the built in functions str(), atof() etc. would change behind the scene to using different locales. But off course it is only if I do something like:: from locale import str locale.setlocale(locale.LC_NUMERIC, 'da_DK') str('%.2f', 42000000.00, 1) that locale is used on str(). If I just do the below, I get no problems:: import locale locale.setlocale(locale.LC_NUMERIC, 'da_DK') locale.str('%.2f', 42000000.00, 1) So I worried for no reason, and will use the batteries instead of my home cooked function. regards Max M From martin at strakt.com Mon Jun 17 09:56:02 2002 From: martin at strakt.com (Martin =?iso-8859-1?Q?Sj=F6gren?=) Date: Mon, 17 Jun 2002 15:56:02 +0200 Subject: non blocking socket.accept() In-Reply-To: References: Message-ID: <20020617135602.GA24002@strakt.com> On Mon, Jun 17, 2002 at 01:45:05PM +0000, Zsolt Marx wrote: > I far as I know socket.accept() waits for a client > to ask for a connection with the server. > > This command seems to be blocking, though I would > like to limit the wait time onto a predefined interval > and to throw an error, if there is no connection. > > How can I achieve this? You will probably be able to do this with the new timout sockets, but in the meantime, check out the select module: import select if select.select([serversock], [], [], timeout): client,addr = serversock.accept() Regards, Martin -- Martin Sj?gren martin at strakt.com ICQ : 41245059 Phone: +46 (0)31 7710870 Cell: +46 (0)739 169191 GPG key: http://www.strakt.com/~martin/gpg.html From hjwidmaier at web.de Fri Jun 21 04:10:08 2002 From: hjwidmaier at web.de (Hans-Joachim Widmaier) Date: 21 Jun 2002 01:10:08 -0700 Subject: Advice sought on ps module References: <6e990e29.0206200325.355f0413@posting.google.com> <3D11BE17.C6AE67A@ipm.fhg.de> Message-ID: <6e990e29.0206210010.26d2b887@posting.google.com> Markus von Ehr wrote in message news:<3D11BE17.C6AE67A at ipm.fhg.de>... > Hi, > > do you know the PSDraw Module in the PIL? > http://www.pythonware.com/library/pil/handbook/psdraw.htm > Maybe this is a solution for you. I've looked at it, of course. But it provides nothing I can't do today (granted, my ps module lacks most of PSDraw's functions -- drawing lines and rectangles is easily done directly; I was more concerned with the text and font side). Looks like I do have to write lots of wrappers and start second guessing. ;-( Hans-Joachim From kragen at pobox.com Sun Jun 2 23:54:09 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 02 Jun 2002 23:54:09 -0400 Subject: Generating unique numbers? References: <3CF7EBC8.4080802@verio.net> <3CF8FC1C.7060903@lindbergs.org> Message-ID: <834rglrp9a.fsf@panacea.canonical.org> aahz at pythoncraft.com (Aahz) writes: > No, if you want to trade IDs across a network, you need GUIDs (DCE > UUIDs). There's just no way around that. It's not the most perfect > system in the world, but it's better than any other generally available > scheme. URLs are an alternative to UUIDs that have some advantages. They tend to be shorter, more human-readable, more memorable, less privacy-invasive, and there's a decentralized scheme for attaching arbitrary data to URLs you own, specifically, the Web. Their disadvantage is that they are reusable, i.e. that the same URL may designate two different objects at different times. From max at alcyone.com Wed Jun 12 14:20:42 2002 From: max at alcyone.com (Erik Max Francis) Date: Wed, 12 Jun 2002 11:20:42 -0700 Subject: Reload an imported file References: Message-ID: <3D0790FA.B730A9BE@alcyone.com> Felix Seeger wrote: > I have a config file. This is a normal python file. > Can I reimport this file during runtime ? > So changing the configuration will not need a restart of my program. Try the reload builtin. Note, though, that this will not change the state of objects already created, and it won't help if you did from module import *. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Who'd ever think it / Such a squalid little ending \__/ The American and Florence, _Chess_ Church / http://www.alcyone.com/pyos/church/ A lambda calculus explorer in Python. From sholden at holdenweb.com Wed Jun 26 11:49:59 2002 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 26 Jun 2002 11:49:59 -0400 Subject: Blank results using mxODBC against References: Message-ID: <3olS8.46473$mF.2290@atlpnn01.usenetserver.com> "Sandeep Gupta" wrote ... > We are trying to connect to MS SQL Server from Linux, but we are only > receiving blank values in the query results. The number of rows and columns > in the result is correct, but each result cell is blank. > > As a test, we successfully used mxODBC against a local MySQL going through > unixODBC. > > We then tried: Python2.2 --> mxODBC --> unixODBC --> inline TDS 1.6 --> MS > SQL Server > When I use isql with unixODBC, I am able to view the results of a simple > select. That same select in mxODBC returns blank result values. > > The python code I'm using is: > import mx.ODBC.unixODBC > db = mx.ODBC.unixODBC.DriverConnect('DSN=MSSQL') > > c = db.cursor() > > c.execute('select * from dbo.Source;') > > mx.ODBC.print_resultset(c) > [other information] Try running the mxODBC test program on the data source you are expecting to use, ands see if it returns any errors. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From cliechti at gmx.net Thu Jun 20 16:54:58 2002 From: cliechti at gmx.net (Chris Liechti) Date: 20 Jun 2002 22:54:58 +0200 Subject: How to represent the infinite ? References: <3d11ee9b$1@news.swissonline.ch> <20020620193230.53d58f8f.christophe.delord@free.fr> <3D121A29.A733609F@noaa.gov> Message-ID: Chris Barker wrote in news:3D121A29.A733609F at noaa.gov: > Christophe Delord wrote: >> There is another simple solution. Just use a float that is bigger >> than any 64-bit float. For example 10^1000. This float has a special >> encoding meaning +oo ! > > this is part of the IEEE 754 standard for floating point computation > (http://cch.loria.fr/documentation/IEEE754/) It is not guaranteed to > be implimented by Python (someone please correct me if I'm wrong). > whether this works is a function of the machine, compiler and library > used to compile Python. I'm not sure how common it is, but if you want > your code portable, it may not be reliabel on all machines, which is > too bad, because IEEE 754 is pretty darn good standard. > > BTW: I'd love to see literals for Inf, -Inf and NaN in Python. do it yourself ;-) >>> Inf = struct.unpack('f', '\x00\x00\x80\x7f')[0] >>> Inf 1.#INF >>> -Inf -1.#INF >>> NaN = struct.unpack('f', '\x7f\xff\xff\x7f')[0] >>> NaN 1.#QNAN don't know if it works anywhere but it does on Py2.2 win32. BTW: >>> struct.unpack('>f', '\x00\x00\x00\x01') (1.4012984643248171e-045,) >>> struct.unpack('>> struct.unpack('@f', '\x00\x00\x00\x01') (2.350988701644575e-038,) so the format code '<' is same as '@', little endian which is correct on my intel P3 but: >>> struct.unpack('@f', '\x00\x00\x80\x7f') (1.#INF,) >>> struct.unpack(' From steve at lurking.demon.co.uk Tue Jun 4 18:52:41 2002 From: steve at lurking.demon.co.uk (Stephen Horne) Date: Tue, 04 Jun 2002 23:52:41 +0100 Subject: y=if x>High: 2 elif x <3CEC15F0.DF78A4F@earthlink.net> <3CEC1D26.AF0CE2FB@earthlink.net> Message-ID: On Wed, 22 May 2002 19:12:10 -0400, Steven Majewski wrote: >I prefer: > >>>> ( 2, 1, 0 )[ [ x > hi, x < low, 1 ].index(1)] > >as more readable, although the lambda functional version gets a bit >more baroque: > >>>> (lambda x: (2,1,0)[(lambda x: [x > hi, x < low, 1])(x).index(1)])(arg) Hmmm I occasionally use the following little trick... def IF(p_Condition, p_True, p_False=lambda: None) : """ Expects parameterless functions or lambdas for the p_True and p_False arguments """ if p_Condition : return p_True () return p_False () #... print IF(x != 0, lambda: 5 // x) This could easily be adapted... print IF(x>High, lambda:2, IF(xHigh, lambda: 2) ], lambda: 0 ) """ for l_Test,l_Value in p_Tests : if l_Test () : return l_Value () return p_Default () if p_Lo_Test () : return p_Lo_Result () if p_Hi_Test () : return p_Hi_Result () return p_Mid_Result () Actually, I prefer to use 'None' as the fail case in this pattern so that the test and result can be bound in one function. def FIRST (p_Functions) : """ p_Functions : a sequence of parameterless functions, each either returning a valid result or None. Example... FIRST( [(lambda: xHigh and 2 or None), (lambda: 0 ) ] ) """ for l_Function in p_Functions : l_Result = l_Function () if l_Result != None : return l_Result return None Personally, I think there should be an if 'function' built in which has similar semantics to the IF function above but without needing the lambdas. It would be nice if it also supported more than three parameters - each pair giving an 'if' or 'elif' condition plus result and the final odd parameter giving the 'else' result. This would allow something like... if (x < Low : 1, x > High : 2, 0) From bl at netgroup.dk Mon Jun 3 08:52:23 2002 From: bl at netgroup.dk (Bo Lorentsen) Date: 03 Jun 2002 14:52:23 +0200 Subject: Embedding and threads ? In-Reply-To: References: <1022771667.689.136.camel@netgroup> <1022830475.893.17.camel@netgroup> <1022839266.823.66.camel@netgroup> Message-ID: <1023108743.685.88.camel@netgroup> On Mon, 2002-06-03 at 14:19, Martin v. L?wis wrote: > > So under normal conditions, on a single processor, with enough > runnable Python threads: the processor will always be busy, and all > threads will make progress. You can hardly ever tell the difference to > free threading. Ok, I think my problem is that I try to model my code around a thread model (to keep things clear), and I got confussed about the way Python did things, as I somehow assumed it had a more strit forward thread model (ala : 1 thread = 1 interpreter state). I will use Python for this project as long as what I do only need a single thread model, and when I need more than that I'll se what to do about it :-) /BL From ethanw at rediffmail.com Sat Jun 1 21:20:12 2002 From: ethanw at rediffmail.com (Ethan) Date: 1 Jun 2002 18:20:12 -0700 Subject: GUI Toolkit! Message-ID: <1a52c7f1.0206011720.7c3ac7ea@posting.google.com> Hi, I need to do some GUI programming with Python. I found that there are quite a few options available for the toolkits . Apart from TkInter, I have seen bindings for Qt, wxWindows, FOX and FLTK. I want to pick one with the best open visual tools available. From what I have looked I am really impressed with the screen shots of Boa Constructor. Apparently it even generates the event procs. But I doubt that I have seen everything. Can anyone please tell me about any other options that I might have. I am developing on Windows. Thanks From kzaragoza at attbi.com Mon Jun 17 12:45:31 2002 From: kzaragoza at attbi.com (Kris J. Zaragoza) Date: 17 Jun 2002 11:45:31 -0500 Subject: Python and SQL Server 2000 References: <1bf96e7f.0206170345.515227c1@posting.google.com> Message-ID: In article <1bf96e7f.0206170345.515227c1 at posting.google.com>, Dave Moor wrote: > kzaragoza at attbi.com (Kris J. Zaragoza) wrote in message news:... >> So, let me add to the original poster's question: Has anyone ever >> tried running the Windows version of Python (either the main >> distribution or ActiveState's) under Wine to take advantage of the >> database drivers, etc.? > > Another solution is to write a simple pair of client/server socket > apps. The server is passed and executes sql on the windows using COM > or ODBC. Then pass the results using the struct module back to the > client. > > Dave I don't like using this kind of relay to expose a database. There are too many security issues to address. You end up having to roll your own authentication and authorization mechanisms, figure out whether masquerade database users or use the credentials given, and figure out how best to encrypt data if appropriate. Too much work, and far too error prone if alternatives are available. That's why I asked about the feasibility of using Wine with the Windows version of Python. Although it's a less than ideal solution, it could work in a pinch. Unfortunately, I haven't had the time to try it out myself. :-( Kris -- Kris J. Zaragoza | On the face of it, Microsoft complaining about kzaragoza at attbi.com | the source license used by Linux is like the | event horizon calling the kettle black. | -- Adam Barr, article on kuro5hin.org From theller at python.net Mon Jun 17 09:34:02 2002 From: theller at python.net (Thomas Heller) Date: Mon, 17 Jun 2002 15:34:02 +0200 Subject: pychecker + XEmacs References: <3d0de483$0$3881$e4fe514c@dreader4.news.xs4all.nl> Message-ID: "Boudewijn Rempt" wrote in message news:3d0de483$0$3881$e4fe514c at dreader4.news.xs4all.nl... > Has anyone succeeded in combining pychecker and XEmacs (or emacs)? I'm > checking a large project I began in 1999, and which is full of the most > atrocious errors, and I'd like to click on the line that mention the error > and be transported there, just like when you run a python program from > XEmacs and get a stacktrace. > > -- > Boudewijn Rempt | http://www.valdyas.org python-mode.el from CVS contains pychecker support. C-c C-w runs 'pychecker --stdlib ', and shows the results in a *compilation* window. Then you can M-x next-error or M-x previous-error to your hearts content. Thomas From garth at deadlybloodyserious.com Sun Jun 16 18:57:52 2002 From: garth at deadlybloodyserious.com (Garth T Kidd) Date: 16 Jun 2002 15:57:52 -0700 Subject: MS Word -- finding text References: Message-ID: <4c877253.0206161457.a2289c8@posting.google.com> > To avoid this problem, I use the following conversion routine. > After making the necessary check for None, it attempts a quick > conversion str() first. When necessary, it slowly goes through > each character, handling the exceptions that are raised. Great technique! Now, I don't suppose you could identify the characters str() isn't handling, so that someone can fix str()? :) Regards, Garth. From mcfletch at rogers.com Thu Jun 6 22:22:45 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Thu, 06 Jun 2002 22:22:45 -0400 Subject: Problem pickling class instance References: <3D000D77.7040008@erols.com> Message-ID: <3D0018F5.4000904@rogers.com> The name of the top-level script's module is __main__, so your instance is getting stored with the class name __main__.A . The __main__ module of your second script doesn't include an A class, so the pickler can't find the "A" class to use when it tries to load the instance. Put A in it's own module, and always import it explicitly. HTH, Mike Edward C. Jones wrote: > I think the following problem may be discussed in the Python Library > Reference, section 3.14.4 but I don't understand it. > > Here is the file mod.py: > > import pickle > > def Read(): > f = open('saved', 'r') > return pickle.load(f) > > class A: > def __init__(self): > pass > > if __name__ == '__main__': > a = A() > f = open('saved', 'w') > pickle.dump(a, f) > > and the file top.py: > > import mod, pickle > > a = mod.Read() > > First I run mod.py then top.py. The latter give the message: > > AttributeError: 'module' object has no attribute 'A' > > Please explain the problem to me. Is there a standard work-around? > > Thanks, > Ed Jones > -- _______________________________________ Mike C. Fletcher http://members.rogers.com/mcfletch/ From peter at engcorp.com Sun Jun 23 16:51:57 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 23 Jun 2002 16:51:57 -0400 Subject: Python hits the spot References: Message-ID: <3D1634ED.B9ACF9EC@engcorp.com> P?r Kurlberg wrote: > > > It's no wonder that 1000 lines of uncommented code behave like that, taking > > into account that you were trying to integrate several (Tcl/Tk, Fortran, C, > > Python) systems in a hurry, and, I presume, not knowing most of them. > > Funny you should mention this. On my laptop (IBM Thinkpad with 128 > megs of ram) the following two-liner gets me a lockup (i.e. keyboard > and mouse completely unresponsive, powertoggle needed): > > for i in range(50*1000*1000): > pass > > (I am serious.) Happened some time ago, but I never got around to > filing a bug report (this thread was a good reminder.) Given that you're asking it to allocate something like 800MB of memory, and not all at once but in a list that grows steadily in size and has to be copied over and over, I'm not at all surprised it appears to lock up a machine with only 128MB. You don't need the for loop for this to work either: just try "biglist = range(50000000)". It took several minutes for my 96MB Windows 98 machine to manage even 10 million items, let alone 50 million! -Peter From peter at engcorp.com Mon Jun 24 20:57:05 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 24 Jun 2002 20:57:05 -0400 Subject: SOLVED (Re: Python hits the spot) References: <3D1482AE.8FA299D8@kfunigraz.ac.at> <3D14CF95.4030501@kfunigraz.ac.at> <3D158F3E.1010907@kfunigraz.ac.at> <3D16DD5C.1050708@kfunigraz.ac.at> <3D171291.2060905@kfunigraz.ac.at> Message-ID: <3D17BFE1.B55C689F@engcorp.com> Chris Liechti wrote: > > Tim Churches wrote in > news:mailman.1024950033.16332.python-list at python.org: > > > Siegfried Gonzi wrote: > >> It was really the laptop processor. I tried the calculation on a > >> stationary machine (Pentium II 450 MHz and SuSE 8.0), and it works. > >> > >> Die Typen k?nnen jetzt was erleben. > > > > Could someone who understands idiomatic ?sterreichisches Deutsch > > confirm that the above means "And sorry for being such a prat."? > > it's more like a threat to the laptop manufacturer.... > > you have to admit that it was a nasty failure... is bad hardware your first > thought when your program fails? on the other side he realy had a bad start > with this thread. I think if we were right there, "try the program on another machine" would have come up pretty quickly. In all the noise I guess nobody thought of it. -Peter From tdelaney at avaya.com Wed Jun 5 19:41:37 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 6 Jun 2002 09:41:37 +1000 Subject: semi-concatenated strings Message-ID: > From: Steve Holden [mailto:sholden at holdenweb.com] > > # The next three lines are bogus > > > sql = string.split(sql) > > > sql = string.join(sql, ' ') > > > sql = string.strip(sql) > > > > > > rows = self.executesql(sql, (city,)) > > Not only that, but for any reasonable database the whole schemozzle is > completely unnecessary. SQL is a free-format language, and > newlines and > spaces embedded in statements make absolutely no difference. I agree entirely - if you can rely on the database to handle embedded newlines in queries (and most can) then there is no need to perform the preprocessing. I meant to include that those lines were only there to match the original, which did not have embedded newlines. The main point is the preference to use a triple-quoted string to lay out the query readably. If preprocessing is necessary, I would *still* prefer that, and add the required preprocessing. After all, SQL queries are often read in from files, with newlines in the queries ... Tim Delaney From rjones at ekit-inc.com Mon Jun 3 04:23:30 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Mon, 3 Jun 2002 18:23:30 +1000 Subject: How to suspend execution for at least x seconds in python ? (ie does "sleep" exist in Python ?) In-Reply-To: References: Message-ID: <200206031823.30498.rjones@ekit-inc.com> On Mon, 3 Jun 2002 18:03, Nicolas Torzec wrote: > Dear all, > I was wondering if an utility like "sleep x" exist in python ? > Under Unix-like operating systems, the sleep utility suspends execution for > at least x seconds under... Look up the time module, specifically time.sleep. Richard From sholden at holdenweb.com Wed Jun 5 11:47:26 2002 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 5 Jun 2002 11:47:26 -0400 Subject: self References: <0%hL8.22575$tK.5490038@news02.optonline.net> <_zpL8.81$pq2.4342892@newnews.cc.stevens-tech.edu> Message-ID: "Vojin Jovanovic" wrote ... [...] > > > Well, good luck with your project -- and don't spring any more > > requirements on us, it's getting harder each time to solve your problem. > > Sorry, but it is not that my problem is hard. It is that the concept of > having > to reference instance variables always through self. is making it hard and > inconvenient which was my point in my original post. > My opinion is that those points explained in FAQ are irrelevant. The only > one relevant is ..... > [...] Could you maybe use self.__dict__ as a namespace argument to the eval()? if-tim-didn't-solve-this-i-don't-fancy-my-chances-ly y'rs - steve -- ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From pyth at devel.trillke.net Thu Jun 6 08:19:28 2002 From: pyth at devel.trillke.net (holger krekel) Date: Thu, 6 Jun 2002 14:19:28 +0200 Subject: introspect c-functions? Message-ID: <20020606141928.A16359@prim.han.de> Hello, is there any way to introspect the *number of arguments* of a function implemented at c-level? the inspect module works only on python-functions, seemingly. >>> import inspect >>> inspect.getargspec(filter) ------------------------------------------------------------ Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.3/inspect.py", line 621, in getargspec if not isfunction(func): raise TypeError, 'arg is not a Python function' TypeError: arg is not a Python function >>> Any input and comments appreciated. holger From qual at epost.de Sun Jun 23 05:14:37 2002 From: qual at epost.de (Uwe Hoffmann) Date: Sun, 23 Jun 2002 11:14:37 +0200 Subject: DerivVar instance has no attribute '__float__' References: Message-ID: <3D15917D.8020908@epost.de> Lee Harr wrote: > I just installed the Scientific module and am trying it out: > > >>>>from Scientific.Functions.Derivatives import DerivVar >>>>from math import sin instead use: from Numeric import sin ... Uwe From shagshag13 at yahoo.fr Fri Jun 7 02:47:33 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Fri, 7 Jun 2002 08:47:33 +0200 Subject: Efficient python programming... References: <20020606215349.GA13474@node1.opengeometry.net> Message-ID: "gabor" a ?crit dans le message de news: mailman.1023401650.18434.python-list at python.org... > but if you want to know about specific python issues, then you have to > learn things like "dictionary are very well optimized etc.." That's what i'm asking : learning and understanding... but where should i go ??? I'm wondering if there is a place to go to find "why this solution is better in this appropriate case... ". For example, i was looking for the best pythoner's way to remove duplicate in a list, and after reading many posts, i find at the end of a cookbook recipe that it was : set = {} map(set.__setitem__, alist, []) alist = set.keys() But that's not trivial !!! And quite difficult to find... > those things doesn't make your code obfuscated.. I agree :) > [file.printsize() for file in directory] > > they're the same, and everyone would recommend you the last one.. Yes but i would have asked why this is the best... And i think that your answer would have helped me to become a better pythoner... I mean there should be a place to go where you could read generalities like "as dictionary are very well optimized, you can use it without trouble and for example it's best in : removing duplicates, ..." or "if you need to do an operation on a list use map because it's c-optimized", there are "object overhead if you...", and so on that's not in the books, that's not in 'dive in python', it's spreaded in Guido's essays, and posts over there... But i worry, you could miss it if you don't spend many time to search, and say "there should be a place for that"... > so to summarize this: what do you want to know/learn? What a beginner should learn to do it the pythoner way... s13. ps : and sorry for my poor english and typos... From not.this at seebelow.org Thu Jun 13 11:32:13 2002 From: not.this at seebelow.org (Grant Griffin) Date: 13 Jun 2002 08:32:13 -0700 Subject: why not "'in' in 'in'"? References: Message-ID: In article , "Mark says... > >I haven't followed this thread. Someone else has probably already suggested >this, but in case they haven't, it's fairly easy to define your own function >that does what you want: > >def is_in(search, search_for): > """Return bool indicating whether search_for is in search.""" > return search.find(search_for) >= 0 > >subject = "i like spam, i do." >x = "spam" >y = "ham" > >print is_in(subject, x) >print is_in(subject, y) > That's not a bad suggestion, Mark, but if I did that I guess I would be forever wondering if I was testing whether the first one was in the second or the second one was in the first. Again, it doesn't read nearly as well as: if x in subject: ... which leaves no doubt. Ironically, that's already perfectly legal--so long as x has no more than one character: >>> subject = "i like spam, i do." >>> x = "s" >>> y = "h" >>> if x in subject: ... print "x is in subject and x has no more than one character" ... x is in subject and x has no more than one character >>> if y in subject: ... print "same goes for y" ... else: ... print "can't say the same for y" ... can't say the same for y >>> reluctant-to-discard-my-hard-won-near-mastery-of-"find"-ly y'rs, =g2 _________________________________________________________________________ Grant R. Griffin g2 at dspguru.com Publisher of dspGuru http://www.dspguru.com Iowegian International Corporation http://www.iowegian.com From tim.one at comcast.net Fri Jun 21 01:19:50 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 21 Jun 2002 01:19:50 -0400 Subject: How to represent the infinite ? In-Reply-To: <20020620225355.7b8dd9db.christophe.delord@free.fr> Message-ID: [Christophe Delord] > ... > >>> 1e200**2 > Traceback (most recent call last): > File "", line 1, in ? > 1e200**2 > OverflowError: (34, 'Numerical result out of range') > >>> 1e400 > inf > > When the overflow occurs, the OverflowError exception is thrown. > inf can't be the result of a computation (without patch and > without catching exception). It can, but it's a x-platform crapshoot as to exactly how. For example, under current Windows CVS, this still "works": >>> 1e300 * 1e300 1.#INF >>> Here's a clumsier way : >>> 1.6e308 + 1.6e308 1.#INF >>> Both of those assume the user hasn't installed and enabled the fpectl module, whose purpose in life is to cause even this to complain. maybe-number-crunchers-will-agree-on-something-after-i'm-dead- but-i'm-not-holding-my-breath-ly y'rs - tim From garrett at bgb.cc Wed Jun 19 00:48:36 2002 From: garrett at bgb.cc (Don Garrett) Date: Wed, 19 Jun 2002 04:48:36 GMT Subject: What If..... Strong Types References: <3D0C0F0D.4030900@bgb.cc> Message-ID: <3D100C9A.10502@bgb.cc> Huaiyu Zhu wrote: > Don Garrett wrote: > >> I'm not suggesting any real changes to any, only proposing a thought >>experiment. >> >> What if Python had been built from the start with strong types? And I mean >>strong types, not strong typing. The distinction I am trying to draw is that >>variables would not be typed, but that all types would have rigid interfaces. >> >> Primarily, what if classes always had rigidly defined interfaces. I mean >>that public members had to be declared to exist, and that methods couldn't be >>modified on an instance. Private members could exist but would be really private. >> >> All types would be classes (including ints and such). Amoung other things, >>I would add the concepts of Interfaces, instanceof operators. >> >> Local variables would not require declaration, and would work just like >>today. Introspection would work, but be read-only. >> >> My belief is that almost all the convenience of Python would be maintained, >>but that compilation, optimization, and automated code analysis would be simpler. >> >> I'm just wondering if the change would be good or bad. Would it really >>break anything important in Python today? Would it prevent any common errors? >>Would it help with automated code analysis (compilation and optimization >>included) as much as I think it would? > Have you, by chance, ever used Sather? It was (I think development is stopped) an Eiffel inspired language that seperated interface and implementation inheritance (amoung several other cool ideas). Unfotunatly, I never got to use it for any large projects, so never felt that I learned it well. http://www.icsi.berkeley.edu/~sather/ -- Don Garrett http://www.bgb.cc/garrett/ BGB Consulting garrett at bgb.cc From jknapka at earthlink.net Wed Jun 26 17:25:26 2002 From: jknapka at earthlink.net (Joseph A Knapka) Date: Wed, 26 Jun 2002 21:25:26 GMT Subject: Python daemon References: Message-ID: <3D1A3119.5A57CF4B@earthlink.net> Steve Holden wrote: > > "Cameron Laird" wrote ... > > In article , > > Roman Suzi wrote: > > . > > . > > . > > >> 3. restarting of the program if it fails, or the watchdog doesn't > trigg= > > >er > > > > > >Run the program from the /etc/inittab - if it terminates,=20 > > >init will restart it for you. > > . > > . > > . > > This is one of the great FMMs under Unix--the under-utilization > > of init(1). From everything I know, Roman's exactly right, that > > /etc/inittab is the right way to set up a process that you truly > > want to keep running. However, many, MANY Unix hosts have all > > kinds of ugly home-brewed hacks to duplicate this functionality. > > I don't have an explanation, beyond the rather tautologous ob- > > servation that init(1) simply isn't as widely understood as it > > deserves to be. > > You're probably right. Don't forget you need to specify "respawn" to have > the process restarted when it terminates. > > Of course, this doesn't address the issue of if the controlled process stops > making progress but doesn't die. Normally I'd allow wiser heads to address such issues, but surprisingly none of them have directly answered this question thus far, so here goes: Just ensure that your daemon touches a file, say /var/run/.doggy, every N seconds. Another job run from cron attempts to delete /var/run/.doggy every 2*N seconds. If that fails, it does "kill `cat /var/run/.pid`" and then init restarts the daemon. -- Joe "They call them the Diamond Dogs." -- David Bowie, "Diamond Dogs" From fredrik at pythonware.com Sun Jun 23 18:10:05 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 23 Jun 2002 22:10:05 GMT Subject: PIL, Python and CGI References: <3D1626FD.DA934B09@infineon.net> Message-ID: <1HrR8.44835$n4.10519234@newsc.telia.net> Sascha Ferley wrote: > raise ImportError, "The _imaging C module is not installed" > ImportError: The _imaging C module is not installed > > Anyone have any ideas? when running your CGI script, the Python interpreter cannot find the _imaging extension. chances are that sys.path isn't what you think it is. From kalab at gmx.net Tue Jun 25 08:07:40 2002 From: kalab at gmx.net (Gerhard Kalab) Date: 25 Jun 2002 05:07:40 -0700 Subject: Python and Eclipse References: <3D17FAF4.35CC9F1B@earthlink.net> Message-ID: Joseph A Knapka wrote in message news:<3D17FAF4.35CC9F1B at earthlink.net>... > I am interested in having Python support in > Eclipse - interested Have a look at http://sourceforge.net/projects/rubyeclipse. I replaced all occurrences of "Ruby" with "Python" and it works quite well :) Unfortunately it's under the GPL and I'd like a python integration based on a different license (IBM Public License or Python License). So I started to play with the wizards in eclipse and I've got a working python editor (only with some sort of syntax hightlighting) for now. Gerhard From peter at engcorp.com Wed Jun 19 22:07:42 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 19 Jun 2002 22:07:42 -0400 Subject: python version? References: Message-ID: <3D1138EE.FDDCE5DF@engcorp.com> "Delaney, Timothy" wrote: > > > From: George Hester [mailto:hesterloli at hotmail.com] > > > > All fixed > > > [snip questionnaire] > > Now I'm confused. What does that mean??? I interpreted it as "I got the point, please leave it alone now." -Peter From peter at engcorp.com Sun Jun 9 09:29:02 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 09 Jun 2002 09:29:02 -0400 Subject: Socket error problem References: Message-ID: <3D03581E.FA5890EF@engcorp.com> David LeBlanc wrote: > > I have this problem on windows where socket.socket(...) keeps returning > 10022, 'Invalid argument'. It's actually dieing in the > poplib.POP3.__init__(...) method. I have verified that host is reasonable > (mymail.myisp.net or something like that ;)), and port is 110. > > If I use the test script in poplib.__main__(...) with the correct host, user > and password, all is well, but if I call it from this other program i'm > trying to get working I get the above error. > > I can't figure out what's wrong - any pointers? As usual, post a traceback, or code snippets... don't make us guess what you're doing. From johnroth at ameritech.net Wed Jun 19 16:58:25 2002 From: johnroth at ameritech.net (John Roth) Date: Wed, 19 Jun 2002 16:58:25 -0400 Subject: GOTO w/ Python? References: <3d10ed95@xpl-sdf1-sec1.> Message-ID: "Angela Williams" wrote in message news:3d10ed95 at xpl-sdf1-sec1.... > I'm looking for the equivalent of the GOTO command for Python 2.2.1 running > on Windows 98. I have programmed very little and am new to Python. I found > the following information on the FAQ page but it doesn't make any sense to > me. > > > 6.26. Why no goto? > Actually, you can use exceptions to provide a "structured goto" that even > works across function calls. Many feel that exceptions can conveniently > emulate all reasonable uses of the "go" or "goto" constructs of C, Fortran, > and other languages. For example: > > class label: pass # declare a label > try: > ... > if (condition): raise label() # goto label > ... > except label: # where to goto > pass > ... > > This doesn't allow you to jump into the middle of a loop, but that's usually > considered an abuse of goto anyway. Use sparingly. > > > > Any and all help would be greatly appreciated. > > Thanks, Angela There's no equivalent of a goto command in Python, for good reason, which I won't repeat here. Prof. Djikstra did it very well in 1974, in his letter "Goto Considered Harmful." If you'd like to post the problem you're trying to solve, someone will be sure to help you. The reason for mentioning exceptions in the FAQ is that, for a long while, exception handling was the sole programming task where people thought they still needed a goto. That was solved over a decade ago, with structured exception handling, and Python simply does it the same as everyone else, only (possibly) better. John Roth > > From saint at ghost.lt Thu Jun 20 13:03:08 2002 From: saint at ghost.lt (martynas sklizmantas) Date: 20 Jun 2002 19:03:08 +0200 Subject: Function to add commas in numbers? In-Reply-To: References: Message-ID: <1024592588.720.4.camel@naked> hello, On Thu, 2002-06-20 at 18:53, Sean 'Shaleh' Perry wrote: > and also takes up less room on your system. > > Edit /etc/locale.gen and follow the directions in the comments. > indeed, that was the problem. thank you very much. best regards, ms -- Alas, how love can trifle with itself! -- William Shakespeare, "The Two Gentlemen of Verona" From cliechti at gmx.net Wed Jun 26 22:23:18 2002 From: cliechti at gmx.net (Chris Liechti) Date: 27 Jun 2002 04:23:18 +0200 Subject: Accessing C++ variables from Python References: Message-ID: Teja Sastry wrote in news:mailman.1025138558.21469.python-list at python.org: > I have a c++ program storing a binary stream into a buffer, i want to > access that buffer from python. The buffer is actually a cPickled > binary stream from another program loaded in to c++ 'cuz we use a > routing layer called diffusion, and its API is in c++ so i have to put > the variable into C++ to transport it over the network, at the > receiving end i have another C++ diffusion API program holding the > variable, i have to transfer it as object back to python, i'm not > quite sure about how to do this could you please clarify i think passing around those buffers as python strings will be the easiest approach. binary or not does not matter for python-strings. (see below) > or is there any mailing list for python users you're already posting to it... > P.S: I know how to use SWIG and creating shared modules for python my experience with SWIG is that while it's powerful it doesn't do quite that waht I want... therefore i end up writing my extensions by hand. (when i tried it it generated wrapper objects en masse but i simple wanted to pass around strngs.) don't know about BOOST or CXX cause i don't use C++ in my projects, but those get usualy mentioned for Python extensions with C++. maybe one of those could be very helpful for you. http://www.boost.org/libs/python/doc/ http://cxx.sourceforge.net/ chris -- Chris From sholden at holdenweb.com Tue Jun 18 16:24:38 2002 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 18 Jun 2002 16:24:38 -0400 Subject: Python interface to ImageMagick References: Message-ID: "Achim Domma" wrote in message news:aec8qd$19p$05$1 at news.t-online.com... > Hi, > > I just uploaded a first alpha version of my python wrapper for ImageMagick. > Currently there is only a windows version, which is tested on Win2K with > ActiveState Python 2.2.1. Other version, more documentation and examples > will follow hopefully soon. Every feedback or bugreport is wellcome, because > I don't have different testing environments. > > If you want to try it, you can download it here: > http://www.procoders.net/imagemagick/ImageMagick-0.1a.win32.exe > > An working ImageMagick (www.imagemagick.org) Installation is required. The > wrapper is linked with ImageMagick 5.4.5-1. > You should certainly consider renaming the installer so it looks like a Python extension and not an ImageMagick installer. PyImageMagick...? regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From wurmy at earthlink.net Fri Jun 28 00:16:15 2002 From: wurmy at earthlink.net (Hans Nowak) Date: Fri, 28 Jun 2002 04:16:15 GMT Subject: Plugins in Python References: Message-ID: <3D1BE2DD.608@earthlink.net> Lars Yencken wrote: > Hello, > > I'm trying to do plugins for a program I'm writing in Python, and I'm not > sure how exactly to do it. Basically what I want it to be able to write a > module which loads every python file in a directory and stores an instance > of each one that loaded successfully. > > I tried using exec() and compile() to run each of the files in the > directory from my Plugins module, and had each of the files import my > Plugins module and store an instance of themselves there, but at the end of > it they weren't stored. > > Any ideas? One way to do this is making a subdirectory and using it as a package. For example, a structure like this: main.py plugins/ __init__.py foo.py bar.py If you want all the plugin modules imported, you can simply do this in __init__.py (import foo, import bar, etc). Then all you have to do from a program that uses the plugins, is import the package: import plugins plugins.bar.baz() # call baz() function in module bar in plugins directory HTH, -- Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) # decode for email address ;-) The Pythonic Quarter:: http://www.awaretek.com/nowak/ From max at alcyone.com Thu Jun 13 15:45:25 2002 From: max at alcyone.com (Erik Max Francis) Date: Thu, 13 Jun 2002 12:45:25 -0700 Subject: why not "'in' in 'in'"? References: <3D080482.7A7FD514@alcyone.com> <3D082A62.CF800C75@seebelow.org> <3D083298.470850D0@alcyone.com> <3D08A161.A9F3136F@seebelow.org> Message-ID: <3D08F655.27790070@alcyone.com> Grant Griffin wrote: > Again, it has to do with the fact that the illegal multi-character > "in" > is intuitive and reads better. Compare the following: > > if 'mortgage' in email_subject: > ... > > to: > > if email_subject.find('mortgage') >= 0: > ... > > I consider the former to be highly practical, if not highly pure. The problem here is that you're declaring it more intuitive because you've already decided a priori that you want it. To a true Python programming, the line if 'mortgage' in email_subject: is pretty suspicious; it makes it sound like email_subject is a sequence of keywords. > As to the latter, I frequently made this mistake at first: > > if email_subject.find('mortage'): > ... > > which is fairly intutitive, but doesn't work, of course, because > "find" > returns -1 (logical true) in the failure case! That is just the nature of string functions; it is documented well. Not every aspect of Python programming can be short _and_ do what you expect. Some learning is required. That learning is what tells you the `in' operator is for membership, not subsequence comparison. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Who'd ever think it / Such a squalid little ending \__/ The American and Florence, _Chess_ Church / http://www.alcyone.com/pyos/church/ A lambda calculus explorer in Python. From mdk at mdk.com Thu Jun 20 11:17:55 2002 From: mdk at mdk.com (mdk) Date: 20 Jun 2002 15:17:55 GMT Subject: Function to add commas in numbers? Message-ID: Hello, Is there a function that will take, for example, 1234567 and return 1,234,567? Thanks From andreas at kostyrka.priv.at Sat Jun 1 02:26:12 2002 From: andreas at kostyrka.priv.at (Andreas Kostyrka) Date: Sat, 1 Jun 2002 08:26:12 +0200 Subject: Why no open(f, "w").write()? In-Reply-To: References: Message-ID: <200206010826.12474.andreas@kostyrka.priv.at> Am Donnerstag, 30. Mai 2002 02:47 schrieb Delaney, Timothy: > I can come up with a perfectly good example where Well, replacing the semantics of a builtin operation is not a perfectly good example IMHO. ;) > > open(FILE, 'w').write(CONTENTS) > > will fail to close the file in CPython. > > There are no guarantees that the reference to the object returned is the > *only* reference to that object. Assume the following (perverse) > implementation of open: > > __files = [] > > def open (path, mode): > f = __open(path, mode) > __files.append(f) > return f > > or > > class file: > > __files = [] > > def __init__(self, path, mode): > __files.append(self) > > Whilst I know this is not the implementation, there is nothing that > prevents it from being like this. So you get back an object that has one > more reference count than expected. It never gets collected. Well, then the implementation is broken. If you allow the implementation to collect additional references at random places, you can prove quite easily that nothing is safe :) Your proof is a bit like the classical error from "full induction" (is this the english name?) proofs in math class. If you reason with faulty premises you can prove anything. > > You should never rely on automatic freeing of *any* resources unless it is > guaranteed. Always explicitly free resources when you have finished with > them. Well, then you should del all your names too. Oops wait, how can we be sure that del works? What if del also increments the refcount instead of decrementing? What if some operation before the del incremented the refcount? Basically what you have proven is, that if you have a faulty open() implementation, the open(f,t).write(d) idiom doesn't work. Guess what. I can prove that open(f,t).write(d) wouldn't work if write is implemented buggy. The exact proof is left as an exercise to the reader. :) In respect to CPython, refcounting behaviour, or more general retaining references in any gc regime, is a quite important part of the interface. Andreas -- Andreas Kostyrka +43 676 4091256 andreas at kostyrka.priv.at andreas at mtg.co.at From jhndnn at yahoo.com Fri Jun 14 12:02:04 2002 From: jhndnn at yahoo.com (John Dunn) Date: 14 Jun 2002 09:02:04 -0700 Subject: Standalone embedded Win32 Python Message-ID: <2cc96dc7.0206140801.7d43ff5e@posting.google.com> I have embedded Python in my C++ Win32 app. What is the recommended way of installation/distribuion? It seems the best would be to statically link to Python - this would also allow me to customized the Python environment that runs with my app. Unfortunately, Python doesn't appear to support static linking on Win32. I really don't want to run the whole Python installed when I install my app. If I can't statically link, is it acceptable to just ship my own local copy of the DLL? I assume I will have to edit some code so it doesn't look to the registry to find the path to Python. Is there any documentation on doing this? This seems to be important to any app that has Python embedded - you can't very well tell your customers to download the latest Python install just to run your program. Thanks for any help- John Dunn -- John Dunn Peak Audio, a division of Cirrus Logic, Inc. http://www.peakaudio.com From ponderor at lycos.com Mon Jun 24 20:27:39 2002 From: ponderor at lycos.com (Dean Goodmanson) Date: 24 Jun 2002 17:27:39 -0700 Subject: Windows versions of Python---pros and cons? References: <3D138293.85892240@noaa.gov> Message-ID: > Now I have to figure out how to change my PATHEXT environment variable, > which is pretty OT for this group... A clearer answer to my hasty response in Trent's direction: WinME: Start , Run , MSConfig . (Also works in Win98.) From aahz at pythoncraft.com Fri Jun 28 15:28:52 2002 From: aahz at pythoncraft.com (Aahz) Date: 28 Jun 2002 15:28:52 -0400 Subject: wxpython threads help needed References: <6bd9f01b.0206281055.2b01a2a6@posting.google.com> Message-ID: In article <6bd9f01b.0206281055.2b01a2a6 at posting.google.com>, sameer wrote: > >Does anyone have an example of wxpython threads in action? I am >trying to create an application with several (tabbed) panels, each of >which is being updated on its on thread. Basically, I don't want the >application to freeze up, or to have long startup times as all the >panels are being updated. I want the startup to happen as soon as the >main panel is built. I would appreciate it if someone can give an >example either from their own app or code, or a simple example cooked >up on the fly. Not wxPython, but if you go to my web page, you can see an example for TKinter that should be useful for you. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From frank.sonnenburg at biosolveit.de Thu Jun 27 12:30:19 2002 From: frank.sonnenburg at biosolveit.de (Frank Sonnenburg) Date: Thu, 27 Jun 2002 18:30:19 +0200 Subject: C API: PyXXX_SetItem Message-ID: <200206271630.SAA24525@post.webmailer.de> Hi all, am i right, that PyTuple_SetItem() and PyList_SetItem() only *transfer* references to objects, but don't increment reference counts? And, in contrast, PyDict_SetItem() *does* increment the object reference count? So, PyTuple_SetItem(tup,idx,PyInt_FromLong(123)); is perfect, but PyDict_SetItemString(dict,"key_name",PyInt_FromLong(123)); will lead to a memory leak. To avoid this: PyObject *py_int; py_int = PyInt_FromLong(123); PyDict_SetItemString(dict,"key_name",py_int); Py_DECREF(py_int); I would appreciate any suggestions/corrections to this point. Thanks in advance Frank Sonnenburg -- ____________________________________________________________________________ _________ / _________ Frank Sonnenburg Bio \ \ Software Developer ________/ / olve \________ BioSolveIT GmbH, An der Ziegelei 75 I N F O R M A T I O N - 53757 Sankt Augustin, Germany - - T E C H N O L O G Y Tel: +49 - 2241 - 973 66 81 Fax: +49 - 2241 - 973 66 88 www.biosolveit.de frank.sonnenburg at biosolveit.de ____________________________________________________________________________ From dom at edgereport.put_a_c_o_m_here Thu Jun 6 22:11:14 2002 From: dom at edgereport.put_a_c_o_m_here (Domenic R. Merenda) Date: Fri, 07 Jun 2002 02:11:14 GMT Subject: Medium to Large Scale Python Deployments References: <34b82fda.0206061639.67964684@posting.google.com> Message-ID: <6DUL8.21673$BJ6.2510024856@newssvr10.news.prodigy.com> Yes, thank you. I've been following this since 2000, and have looked at using some of the code, but wasn't able to open source our work, and so refrained for using theirs. :-) -- Domenic R. Merenda Editor, The Edge Report http://www.edgereport.com "Stuart Quimby" wrote in message news:34b82fda.0206061639.67964684 at posting.google.com... > You may be interested in the gnuenterprise project. They are > developing a multi-tier db independant ERP that is open-source. > Details can be found at http://www.gnuenterprise.org. > > Stuart Quimby From look at replyto.address.invalid Tue Jun 4 01:43:55 2002 From: look at replyto.address.invalid (Greg Ewing) Date: Tue, 04 Jun 2002 17:43:55 +1200 Subject: Python Turing machine References: Message-ID: <3CFC539B.BCBFC855@replyto.address.invalid> "Delaney, Timothy" wrote: > > Yeah - the dependence on an infinitely-long tape can be a real bugger ... well, any terminating computation only uses a finite amount of tape, so you just need to be prepared to buy more tape as needed. Of course, if the universe is closed, you could find yourself in a situation of having run out of matter to make new tape from. Hopefully this will have been fixed by the time Python 3000000000000000000000000000000 is released. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From fperez528 at yahoo.com Mon Jun 3 15:30:15 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Mon, 03 Jun 2002 19:30:15 +0000 Subject: using getopt References: Message-ID: David Bear wrote: > Found a couple of frustrating things with getopt. I am writing a filter > that will be called by lprng -- or other spool services. rather than > trying to code for every possible cmd line arg I may be given, in there a > way to use getopt to grab just a few options that I care about and through > the rest away? getopt sucks. Period. Take a look at DPyGetOpt, which implements the Getopt::Long perl facilities. It's very very nice. I've also heard good things about optik, but haven't used it myself. If you can't find DPyGetOpt (it's a bit hard to get) drop me a line. Cheers, f From SBrunning at trisystems.co.uk Thu Jun 20 04:49:55 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Thu, 20 Jun 2002 09:49:55 +0100 Subject: GOTO w/ Python? Message-ID: <31575A892FF6D1118F5800600846864DCBD3E8@intrepid> > From: John Roth [SMTP:johnroth at ameritech.net] > There's no equivalent of a goto command in Python, for good reason, > which I won't repeat here. Prof. Djikstra did it very well in 1974, > in his letter "Goto Considered Harmful." Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From whisper at oz.net Fri Jun 28 15:23:47 2002 From: whisper at oz.net (David LeBlanc) Date: Fri, 28 Jun 2002 12:23:47 -0700 Subject: metaclasses vs. inheritance In-Reply-To: Message-ID: > PS - what's the antonym of meta? Mundane I think. This might also shed some light (from dictionary.com): meta /me't*/ or /may't*/ or (Commonwealth) /mee't*/ A prefix meaning one level of description higher. If X is some concept then meta-X is data about, or processes operating on, X. For example, a metasyntax is syntax for specifying syntax, metalanguage is a language used to discuss language, meta-data is data about data, and meta-reasoning is reasoning about reasoning. Dave LeBlanc Seattle, WA USA From krissepu at vip.fi Mon Jun 3 16:07:04 2002 From: krissepu at vip.fi (Pekka Niiranen) Date: Mon, 03 Jun 2002 23:07:04 +0300 Subject: Guru advice needed for mxTextTools Message-ID: <3CFBCC68.D35A03D8@vip.fi> I am trying to optimize a function that searches nested strings from set of (allmost) flat files (about 2 MB each) . If I use regular expressions, I must fix the amount of nesting: ----- code example ---- def make_regular_expression(prefix, suffix): if prefix == suffix: pattern = "%s%s%s" % (re.escape(prefix), '.+?', re.escape(suffix)) else: repeat = "%s%s%s%s" % ('[^', prefix, suffix,']+') pattern = "%s%s%s%s%s%s%s%s%s%s%s" % ('(',re.escape(prefix),repeat, '(',re.escape(prefix),repeat, re.escape(suffix),')*', repeat,re.escape(suffix),')') return pattern ---- code example ends ---- In the code above support two nested strings. If prefix is "?" and suffix is "!" then it will evaluate into: >>> pattern = re.compile("(\?[^?!]+(\?[^?!]+\!)*[^?!]+\!)") >>> Line = "?AA?BB!CC!?DD!ee?EE!ff?FF?GG!HH!" >>> print re.findall(pattern, Line) [('?AA?BB!CC!', '?BB!'), ('?DD!', ''), ('?EE!', ''), ('?FF?GG!HH!', '?GG!')] So far so good, but: 1) Re -module returns also empty matches which I have to clean: pars = filter(operator.truth,reduce(operator.add,re.findall(pattern, Line))) 2) The file is not flat: I also need to check the contents of the previous line. If previous line does not contain correct value, I do not have to run the regular expression on the current line: for i in range(1,len(lines),2): test = lines[i-1].strip() if (test == 'x' or test == 'y'): matches = re.findall(pattern, lines[i].strip()) if matches: # Remove empty results with filters pars = filter(operator.truth,reduce(operator.add, matches)) 3) Amount of nesting may vary in the future I have managed to speed up the search about 10x by using map() instead of for -loop and the current bottleneck is the regular expression. I have thought of EBNF -notation that should be supported with Simpleparse + mxtexttools Questions are: 1) What is the mxtexttool tagtable for the regular expression above with additions of unlimited nesting. If suffix is the same as prefix, no nesting is assumed 2) Is it possible to parse the file without keeping the record of the current line number since values to be checked are allways on odd line numbers and regular expression is allways run on even line numbers. If I could read two lines at a time and parsing them both simultaneously (as a single line) with mxtexttools (with lookAhead or whatever ), I could gain some speed ? 3) Should I seek examples from XML -tools instead OR write my own parser with C + SWIG ? -pekka- From sholden at holdenweb.com Wed Jun 5 08:51:04 2002 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 5 Jun 2002 08:51:04 -0400 Subject: Problem with urllib.urlopen() References: Message-ID: "Christopher" wrote in message news:cc14131d.0206041631.157f11d1 at posting.google.com... > Okay okay, here are links that 1) are short, 2) should work, and 3) > show my problem. > > link 1: > http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=PureSearch&db=PubMed&detai ls_term=%28%22glucagon%22%5BMeSH%20Terms%5D%20OR%20glucagon%5BText%20Word%5D %29 > > link2: > > http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=Display&db=PubMed&details_ term=%28%22glucagon%22%5BMeSH%20Terms%5D%20OR%20glucagon%5BText%20Word%5D%29 &dopt=XML&query_key=1 > > Look at link2 in your browser, then look at what urllib.urlopen or > .urlretrieve get. Thanks. > Just to be sure, do you expect the second link (in a browser) to show "Error handling request: no current query"? This seems to work w/Python 2.2 under cygwin, at least. There was so much output I omitted quite a lot, replaced by ellipses below: >>> import urllib >>> f = urllib.urlopen("""http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=Display& db=PubMed&details_term=%28%22glucagon%22%5BMeSH%20Terms%5D%20OR%20glucagon%5 BText%20Word%5D%29&dopt=XML&query_key=1""") >>> ll = f.read() >>> ll '\n ...
Error handling request: no current query
... \n\n' >>> regards Steve -- ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From shagshag13 at yahoo.fr Sun Jun 2 05:01:09 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Sun, 2 Jun 2002 11:01:09 +0200 Subject: Which is fastest dict or list.index() ? References: Message-ID: Thanks !!! (i use some tricks i find in seqdict) > If you want a skiplist version, let me know and I'll send it. > Raymond Hettinger I'm sorry, but i don't understand what you mean by a "skiplist version" So here is how i do it now, i think i miss to explain that i must keep some kind of id (which i use as a key in another table, and i want to keep this other table indexed by integer instead of words to save mermory). <- thoug i don't know if this is a real saving... i'm huge newbie but i feel python really pleasant, great, etc... (even if i had lots of trouble with memory run out... on a solaris system with 1024mo...) i post for comments or advices as i'm not a skilled pythoner... thanks in advance for reading and helping class IKeys: def __init__(self): self._size = 0 self._term = {} # element -> int key - ex: {a : 0, b : 2, c : 1} self._iKeys = [] # contains elements, int key -> element - ex: [a, c, b] def __str__(self): s = 'iKey (' + "\n" s += str(self._term) + "\n" s += str(self._iKeys) + "\n" s += str(self._size) + " # size)\n" return s def __len__(self): return self._size def __getitem__(self, pos): return self._iKeys[pos] def index(self, element): return self._term[element] def add(self, element): if self._term.has_key(element): return self._term[element] self._iKeys.append(element) self._term[element] = self._size self._size += 1 return (self._size - 1) def keys(self): return self._iKeys def get_size(self): return self._size which i use like this : >>> toons = IKeys() >>> for t in ['Bugs', 'Mickey', 'Babs', 'Jerry', 'Tom', 'Babs']: toons.add(t) 0 1 2 3 4 2 # already in toons so we don't had it, we get id >>> print toons iKey ( {'Mickey': 1, 'Babs': 2, 'Tom': 4, 'Bugs': 0, 'Jerry': 3} ['Babs', 'Bugs', 'Jerry', 'Mickey', 'Tom'] 5 # size) >>> t[2] 'b' >>> toons[2] 'Babs' >>> toons.index('Jerry') 3 >>> tmp = toons.keys() >>> tmp.sort() >>> for t in tmp: # here it's sorted i = toons.index(t) print "Toons [%s] has id [%s]" % (t, i) Toons [Babs] has id [2] Toons [Bugs] has id [0] Toons [Jerry] has id [3] Toons [Mickey] has id [1] Toons [Tom] has id [4] From sarmstrong13 at mac.com Sat Jun 8 12:30:26 2002 From: sarmstrong13 at mac.com (SA) Date: Sat, 08 Jun 2002 11:30:26 -0500 Subject: Newbie OOP Question.(diff between function, module and class) Message-ID: Hi Everyone- I'm still trying to grasp this OOP concept in Python. Can someone tell me the difference between a function, a module, and a class? Since Python defines them all as objects, how do they differ outside of being called from inside the script or outside the script? Thanks. SA From loewis at informatik.hu-berlin.de Tue Jun 18 03:07:44 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 18 Jun 2002 09:07:44 +0200 Subject: unicode strings and strings mix References: Message-ID: Gerhard H?ring writes: > 'x' and 'A' are in the ASCII range, so this shouldn't produce an > exception. I also cannot reproduce it with sys.getdefaultencoding() == > "ascii". These where not 'x' and 'A', but '\xd7\xc1\xd7\xc1\xd7'. Since the article was posted in KOI8-R, Roman probably meant those bytes to denote CYRILLIC SMALL LETTER VE and CYRILLIC SMALL LETTER A, respectively. Of course, when Python add strings, it can't possibly know that this is how the byte string was meant to be interpreted, so you need to write unichr(0x3345) + unicode('\xd7\xc1\xd7\xc1\xd7', 'koi8-r') The result string cannot be represented in KOI8-R, though, since it contains SQUARE MAHHA. Regards, Martin From ljd at nospam.com Sat Jun 8 18:19:47 2002 From: ljd at nospam.com (LJD) Date: Sat, 08 Jun 2002 22:19:47 GMT Subject: Program mysteriously STOPS! References: Message-ID: <7qvM8.134377$352.6595@sccrnsc02> Just for more info... Running Linux 7.3 Python 1.52 Program autostarts, runs for a while, then stops! Larry From eric.brunel at pragmadev.com Fri Jun 28 09:57:27 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Fri, 28 Jun 2002 13:57:27 +0000 Subject: menue windowing help needed References: Message-ID: Klaus Reinhardt wrote: > --------------------------------------------------------------------- > Hi > > I tried the samples from wxPython and tkinter > without succes. Can you tell us what samples? And what happened? > I need some scripting help for: > A menue > each alternative can open > one window for print or .. Here is a simple example with Tkinter: ---------------------------------- from Tkinter import * def openWindow(): wdw = Toplevel() root = Tk() menuBar = Menu(root) root['menu'] = menuBar fileMenu = Menu(root) fileMenu.add_command(label='Open window', command=openWindow) fileMenu.add_separator() fileMenu.add_command(label='Quit', command=root.quit) menuBar.add_cascade(label='File', menu=fileMenu) root.mainloop() ---------------------------------- HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From phr-n2002b at NOSPAMnightsong.com Thu Jun 27 19:38:02 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 27 Jun 2002 16:38:02 -0700 Subject: How to get rid the new line References: <3D1AD534.A74EC9F4@ipm.fhg.de> <3D1B1A76.563E5394@engcorp.com> Message-ID: <7xlm90cmxx.fsf@ruckus.brouhaha.com> "James T. Dennis" writes: > Could try this: > > def chomp(line): > if line[-1]=='\n': > line=line[:-1] > return line > > (or variations thereon, to satisfy other semantic requirements). If you don't mind removing all trailing whitespace, there's also line = line.strip() or more portably import string line = string.strip(line) From alecg at inwave.com Mon Jun 10 23:32:19 2002 From: alecg at inwave.com (Alexander Garden) Date: Mon, 10 Jun 2002 22:32:19 -0500 Subject: Correct code/unit testing (was Re: Efficient python programming...) In-Reply-To: <83u1oaq0jt.fsf@panacea.canonical.org>; from kragen@pobox.com on Mon, Jun 10, 2002 at 05:35:50PM -0400 References: <3D00A456.4315EDA3@engcorp.com> <834rgd5isv.fsf@panacea.canonical.org> <3D02FB3B.CF75E925@engcorp.com> <83u1oaq0jt.fsf@panacea.canonical.org> Message-ID: <20020610223219.B1061@genesis.gnet> On Mon, Jun 10, 2002 at 05:35:50PM -0400, Kragen Sitaker wrote: > Yes, one of the beautiful things about programming is how it impresses > upon each of us how fallible we are. Amen! From gherron at islandtraining.com Mon Jun 17 12:56:55 2002 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 17 Jun 2002 09:56:55 -0700 Subject: tab size In-Reply-To: <29A97D00F387D411AC7900902770E14805853F72@lcoeexc01.coelce.net> References: <29A97D00F387D411AC7900902770E14805853F72@lcoeexc01.coelce.net> Message-ID: <200206170956.55939.gherron@islandtraining.com> On Monday 17 June 2002 09:05 am, Alves, Carlos Alberto - Coelce wrote: > Hi all, > > Consider the following code: > >>> for i in range(10): > > print "%d\t"%i, > > > 0 1 2 3 4 5 6 7 8 9 > > > > How can I change the default size of tab in formating string \t?! You can't. In fact the question does not even make sense in this context! A tab has no size. It is a single ascii character just like any other ascii character. However, when a string containing tabs is DISPLAYED, then the tabs are expaned into some definite amount of space on the screen or paper or wherever the display is occuring. So to answer your question, we'd need to know where you are running this: unix xterm? dos prompt? IDLE? emacs? ...? Once you get the display of tabs to work as you wish in your setting, you would still have the problem that running the program elsewhere would expand the tabs according to other settings. If you want FULL control of the output wherever the thing is run, don't use tabs. Dr. Gary Herron From marklists at mceahern.com Tue Jun 18 15:02:37 2002 From: marklists at mceahern.com (Mark McEahern) Date: Tue, 18 Jun 2002 14:02:37 -0500 Subject: Python to MS SQL Server In-Reply-To: <3D0F8099.8080106@matteicos.com> Message-ID: > I am interested in using Python in a MS SQL Server environment, but do > not see any database modules out there, especially for native versus > using ODBC. Is there such a module? This is a total guess, because I haven't done this myself: Have you tried using win32com to use ADO? // mark - From bjarne_christiansen at hotmail.com Wed Jun 26 06:48:59 2002 From: bjarne_christiansen at hotmail.com (Bjarne Christiansen) Date: Wed, 26 Jun 2002 10:48:59 +0000 Subject: Python file upload Message-ID: Thanks for your reply Richard! I have changed the script to the following: ... item = form["filename"] if item.file: data = item.file.read() f = open("file1.jpg","wb") f.write(data) ... But I still run into the same problem, any ideas? ~Bjarne >From: Richard Barrett >To: "Bjarne Christiansen" , >python-list at python.org >Subject: Re: Python file upload >Date: Wed, 26 Jun 2002 09:56:33 +0100 > >I think you will find that your calls to cgi.escape the incoming data are >the cause of your problem. > >You do not need to escape incoming multipart/form data. The documentation >for cgi.escape says: > > >Use this if you need to display text that might contain such characters in >HTML > > >which is clearly not your purpose in handling the incoming data, >particularly when it is binary data. > >At 08:08 26/06/2002 +0000, Bjarne Christiansen wrote: >>Hi, >>I have some problems uploading binary files though the web browser. It >>seems to work fine when uploading ASCII file but but binary files seems to >>be corrupted. The beginning of the binary file seems fine, but some data >>is missing.... >> >>Here is my file upload script: >> >>#!c:\Python\python -d >> >>import cgi >> >>print "content-type: text/html\n\n" >> >>form = cgi.FieldStorage() >>if not form: >> print """ >>
>enctype="multipart/form-data"> >> >> >>
>> """ >>elif form.has_key("filename"): >> item = form["filename"] >> if item.file: >> data = item.file.read() >> print cgi.escape(data) >> data1 = cgi.escape(data) >> f = open("file1.jpg","wb") >> f.write(data1) >> >>Any help will be greatly appriciated! >> >>Best Regards, >>Bjarne Christiansen >>bjarne_christiansen at hotmail.com >> >> >>_________________________________________________________________ >>MSN Photos is the easiest way to share and print your photos: >>http://photos.msn.com/support/worldwide.aspx >> >> >> >>-- >>http://mail.python.org/mailman/listinfo/python-list > > > >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ Send and receive Hotmail on your mobile device: http://mobile.msn.com From arlo.maillist at ozmaker.com Sun Jun 9 11:28:02 2002 From: arlo.maillist at ozmaker.com (Arlo) Date: Sun, 09 Jun 2002 23:28:02 +0800 Subject: Embed python in multi-thread environment Message-ID: <3D037402.1070301@ozmaker.com> hi, all i've tried to embed python in multi-thread application( written in c++) the flow is: 1.create socket,listen,accept. 2. create thread to handle different clients. 3. in thread func, use Python C API to import my python script, and use PyObject_CallObject(func,args); to call python function ( just passing socket descriptor which got from accept() to this function) but when it just one client, it works perfect, but when more than one client, it core dumped. it seems i can't call PyObject_CallObject twice at the same process? From pedro_rodriguez at club-internet.fr Sun Jun 30 17:12:13 2002 From: pedro_rodriguez at club-internet.fr (Pedro Rodriguez) Date: Sun, 30 Jun 2002 23:12:13 +0200 Subject: aspect-oriented demo using metaclasses References: Message-ID: [Mark] > The latest version I posted continues to punt on staticmethod and > classmethod. They're currently not aspected because my type comparison > to type(lambda x:x) will effectively filter out staticmethod and > classmethod. I would have to change the observer interface slightly > since staticmethods don't have have a self parameter and the first > parameter of classmethods is a reference to the class not the instance. > I don't see this being too hard--I plan to fix it in the next iteration. > >> Even if deprecation of the types module have been discussed on the >> devel list, I think it is preferable. > > Yeah, using type(lambda x:x) seems more portable or something. > Sorry, but I wasn't clear : I meant that using the types module should be better. But honnestly I am not that sure. [Mark] > Hmm, you're right, my approach will do NOTHING for methods that aren't > associated with a class. BTW, I thought a normal method associated with > a class whether new type or old was a bound method? I'm not too worried > about old style classes--although maybe I should be? I figure if a > requirement of using this is that it only works with new-style classes, > that's fine with me. Until I run into a problem, of course. ;-) > Just to be sure, let me clarify some points about functions and methods : - a def statement introduces a function - when a function is declare in a class we should talk of an unbound method - when we make a reference to a function from an instance we talk of a bounded method >>> def f(x): pass ... >>> class A: ... def f(self): pass ... >>> a = A() >>> >>> print f >>> print A.f >>> print a.f > >>> The difference between an unbound method and a bound method is that the latest won't need to be passed a 'self' argument because it is already bounded to an object. For class and static methods, I will need some time to learn how to identify them and catalog them in my 'bestiaire'. [Mark] > I often use methods that aren't associated with a class and I'd like to > aspect those as well, although, when I think about something like > Persistence, that does seem initimately bound up with classes. So maybe > it depends on the aspect? I see your points here. Could/Should an aspect be used for Persistence ? I don't know, but it is a good remark. I recall that I discovered AOP after having to add some notification in Models in an Model/View/Presenter framework and it seemed quite intrusive. With your remark I wonder if the saving of my models (call it Persistence/Serialization) should also be considered as a good candidate for being aspectified. By doing so that I could keep my model simple and externalize the way I want to implement save/load. > > I should say that my motivation for pursuing a metaclass implementation > is partly just to learn metaclasses, Understanding metaclasses is quite a challenge, putting them to good use is, IMO, even more challenging (Alex Martelli recommended the reading of the book mentionned in the 'descintro' document : Putting Metaclasses to Work: A New Dimension in Object-Oriented Programming, by Ira R. Forman and Scott H. Danforth) > ... but also partly because I want > something that requires no modification to the aspected class and > minimal effort, maximum flexibility for defining join points. What I > like about the metaclass approach is that I just wire up every single > class that's aspected for all events. It's then up to the observer to > hook into them. Of course, I need to try to use this for something real > and I'm sure that will expose its weaknesses/my conceptual gaps quickly. > I think you should clearly separate : 1. the place where you do your 'method call interception' 2. the way you stack (and call) advices Actually you do 1. at class definition level for all methods defined in the class by using a metaclass, and for 2. you use an observer-like object. For 1. I decided to it in a different way, closer to Java implementations (and I think that aop.py in Pythius already did it this way) : - I created a Joinpoint class - the constructor received an object called a callableSet and a string pattern - a callableSet was anything that could contain a 'function' I wanted to intercept. This could be a module, a class, an instance - I scaned the callableSet in search for attributes that were functions that matched the pattern - I intercepted the matching functions with what I defined for 2. [Pedro] >> Too intrusive. I don't believe that you can do it dynamically, at least >> not for classes defined at module level. They will be created with the >> metaclass defined at compilation time. [Mark] > > This is a good point. Here's the sort of dynamism I'm aiming for: > > The modules containing classes to be aspected have no reference to the > framework inside them. Not even a __metaclass__ statement. > > Oops, a little testing shows that may simply not work. Hmm. I don't > want to have to edit the modules that contain the classes to be > aspected, even to add a __metaclass__ declaration. Since I can't seem > to change that at runtime, this approach probably won't work. > This is what I feared with the usage of metaclasses (at least by solely using __metaclass__ in this way) [Pedro] >> Yes. Interception of raised exception is a good (and easy ;) feature. >> Just try to go a step further with 'around' methods. [Mark] > > I avoided adding around because it doesn't seem primitive to me. In > other words, isn't around just before + after notification? So I could > add support for around simply by making it so that observers wanting > around notification just got before and after notification? Not sure > what to do if the method raises an error--skip the after? > No 'around' is not that simple I fear. I think you could make some comparison with 'generators'. One of the purpose of generators is to simplify design by not having to keep a context between invocations. The same thing occurs with 'around' in a less trivial way. Consider this : you want to track some log information on a method : - when it started - how long it lasted So that you have a trace like : Method XXX called for object YYY at HH:MM for XX seconds Question : how will you track the start time so that you'll be able to compute the duration and produce your log line ? [Take into account that method XXX may be called recursively, or concurently in a multi-threaded environment] An 'around' advice will simplify your life as a user of aop (but not as the designer of the aspect framework ;) this is were I ended with an implementation that seemed quite complicate and that will need some rework - and also why I didn't dare posting its UML description ;) Bon courage, Pedro From gcordova at hebmex.com Thu Jun 27 18:44:42 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Thu, 27 Jun 2002 17:44:42 -0500 Subject: Pythoniac: Thoughts on a hardware Python processor Message-ID: > > Whoever asked if the Intel/AMD FP stack counted: nah - it's > not the primary mode of the CPU like it was on the HP 3000 > and the Forth chip. BTW, speaking of the Forth chip, I think > Forth, Inc. is still offering the IP for that if anyone wants > to burn a few hunderd k$ on new silicon. > If I recall correctly, Chuck Moore's still churning out forth processors, with on-chip fast memory and hardware stacks, really really cool stuff. I think there's more info in the ColorForth site, or at least it points you in the right direction. > While I think that creating a Python chip is a great and > wonderful idea, I doubt it will or should happen: > > [... snip ...] > > For all these reasons and more, I think a good compiler with > a retargetable backend is a better expenditure of time/effort > and would yield a result far faster then a silicon development effort. > > Dave LeBlanc > Seattle, WA USA > That's what I meant!! This compiler you talk about should generate Forth instead of the normal byte code. Hmmm... I think it's doable, but I've yet to learn more forth. Do you know any good resources? Online books? Good archives? Anything? :-) -gus From cunsan at lycos.com Wed Jun 19 06:19:14 2002 From: cunsan at lycos.com (cunsan) Date: 19 Jun 2002 03:19:14 -0700 Subject: posting message Message-ID: <54f48551.0206190219.25d6d269@posting.google.com> hi, sorry if this posting is not relevant to this mailing list. i want to post using groups.yahoo.com/group/python-list (on the web). but it always fails (the target email seems not exist anymore). can anyone tell me why? i mostly read the postings on the web. i sent this message on google. the problem is that it's not so convenient as yahoo :(. thx. From brueckd at tbye.com Wed Jun 19 18:12:25 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Wed, 19 Jun 2002 15:12:25 -0700 (PDT) Subject: What If..... Strong Types In-Reply-To: <3D10D17B.6070004@bgb.cc> Message-ID: On Wed, 19 Jun 2002, Don Garrett wrote: > > It's sometimes hard for me to model my objects this way because of having > > had to always do it the other (completely statically defined) way, but > > when this approach works the solutions are often quite elegant and > > straightforward (btw - I believe that a good portion of bugs and program > > cruftiness is related to forcing the programmer to clearly define, up > > front, what the complete type of the object is. In many cases this forces > > the programmer to make decisions without enough information, in others it > > is too constricting, and in others it's just too tedious to make the > > programmer worry about all those details, and in all cases general > > hackiness ensues). > > [snip] > Don't you find that you miss the advantages of a clear definition of > what a class is and/or does? That's more important with group > development, but even when it's just me.... I need memory aids. A clear definition... as in a completely specified data type? ;-) It's the same issue of not being required to supply any more information than you really have. I know what you mean though, but it's not like your objects are going to be completely devoid of form or description when you use the dynamic techniques. And like any other tool, when used in excess it doesn't really help (i.e. in reality many/most data members of most classes won't be dynamically added and removed so it's not too big of a deal). In the cases I've used dynamic data members + group development, 99% of the time the dynamic members were pretty private to my class, and the one or two that weren't were covered in the test cases, which is where people go to look to know how to use the class anyway. Have fun, -Dave From gerhard at bigfoot.de Tue Jun 4 07:55:17 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Tue, 4 Jun 2002 13:55:17 +0200 Subject: Creating explorer link on Win32 In-Reply-To: <3CFCB72E.4010405@haftmann-online.de> References: <3CFCB72E.4010405@haftmann-online.de> Message-ID: <20020604115516.GB704@lilith.my-fqdn.de> * Florian Fredegar Haftmann [2002-06-04 13:48 +0100]: > Hi! > > I'm searching for a possibility to create an explorer link (*.lnk) to a > file on Win32. Has anyne heard of a python module able to do that in a > simple way? Mark Hammond's win32 extensions. On my homepage, under VitaminP, there is a pure-C solution, which you can live with software explictely marked as 'experimental'. IOW, I'd go with the win32 extensions. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From sandeep182 at hotmail.com Mon Jun 24 17:27:30 2002 From: sandeep182 at hotmail.com (Sandeep Gupta) Date: 24 Jun 2002 14:27:30 -0700 Subject: Pychecker and /var/tmp/python2-2.2-root/usr/lib/python2.2/..... Message-ID: I'm using pychecker on my application, which uses BaseHTTPServer.py and unittest.py. Both those files have "No method" warnings that are displayed as: /var/tmp/python2-2.2-root/usr/lib/python2.2/BaseHTTPServer.py and /var/tmp/python2-2.2-root/usr/lib/python2.2/unittest.py I want to be able to ignore the "No method" warnings in those two files, but not in other files. I've tried both blacklist and ignoreStandardLibrary, but neither works: 1)before removing warnings for blacklisted modules, pychecker checks to see if the module listed in blacklist is valid. /var/tmp/python2-2.2-root/usr/lib/python2.2/BaseHTTPServer.py actually doesn't exist (I don't understand why pychecker thinks that is the fully qualified location of the module. I would expect the module name to be /usr/lib/python2.2/BaseHTTPServer.py ). Blacklisting /usr/lib/python2.2/BaseHTTPServer.py doesn't work either since it doesn't match /var/tmp...../BaseHTTPServer.py. 2)On my python installation, ignoreStandardLibrary only checks that the prefix of the module is /usr/lib/python2.2. Again, that doesn't match. Does anyone know why /var/tmp/python2-2.2-root gets prepended to the file name? How can I remove the warnings for these files? Thanks Sandeep Gupta From anton at vredegoor.doge.nl Sat Jun 22 15:06:03 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sat, 22 Jun 2002 21:06:03 +0200 Subject: [ANN] cdrom catalog scripts Message-ID: Name : Cdrom catalog scripts. Description : Some scripts to browse directories offline. Zip archives are treated as subdirectories. Dependencies: Python distribution with idle Tested : On windows 2000 and 98 SE with python 2.2 Audience : Hobby programmers with a low budget. For example I myself do a lot of archiving and backupping by packing files into a zip archive and later on I burn these files onto a cdrom. There's a nice little tool called catfish to inspect directory listings of cdroms but it doesn't look into zipfiles. That's why I wrote this utility. Of course now that its there there's no reason anymore for those applications that do exactly this to hide themselves for me. That's another reason why I wrote this. Warning : This is just a first trial so don't be surprised if something goes wrong. Use at your own risk, provide feedback to make it better. Usage : Just put a CD in the drive, run dirdict.py and point it to the CD or any other drive or directory structure that needs to be stored. Have patience, it may take a while. The program returns to ask for a place to store a file. Make sure the extension is ".zid". Then run ziptree.py to open the zidfile that was just created. The cdromcatalog scripts are: dirdict.py : A utility to store a directory structure in a file with extension ".zid", Zip archives are treated as subdirectories, but zipfiles inside zipfiles are not -yet- expanded. ziptree.py : A utility to view .zid files. It can be run without arguments it will then ask for a filename to open, this file should be produced first by using dirdict.py. Alternatively it could be used with a file type association. The commandline should then be something like this (adjust for the cdromcatalog directory): d:\python22\pythonw.exe f:\cdromcatalog\ziptree.py "%1" License : BSD style, use at your own risk. Contact : For questions and comments I can be reached at Author : Anton Vredegoor, july 2002 Download : http://home.hccnet.nl/a.vredegoor/cdromcatalog/cdromcatalog.zip From dfackrell at DELETETHIS.linuxmail.org Thu Jun 13 13:51:26 2002 From: dfackrell at DELETETHIS.linuxmail.org (Daniel Fackrell) Date: Thu, 13 Jun 2002 11:51:26 -0600 Subject: system command References: Message-ID: <3d08dba0_2@hpb10302.boi.hp.com> Assumption: You are referring to the "source" command as provided by the bash shell on some *nix. The man page for bash suggests that you probably want: print "source "+root+".in" os.system("bash "+root+".in") -- Daniel Fackrell (dfackrell at linuxmail.org) When we attempt the impossible, we can experience true growth. "Thor" wrote in message news:aeajuh$5b5eo$1 at ID-108351.news.dfncis.de... > Having this code > > print "source "+root+".in" > os.system("source "+root+".in") > > the script does not run the root+".in" file, but copying and pasting the > output form teh 1st line work.. what i'm doing wrong? Thanks in advance > -- > Thor -- Stockholm -- Sverige From m2 at plusseven.com Mon Jun 17 10:32:06 2002 From: m2 at plusseven.com (Alex Polite) Date: Mon, 17 Jun 2002 16:32:06 +0200 Subject: Python and SQL Server 2000 In-Reply-To: References: Message-ID: <20020617143206.GA29257@matijek.plusseven.com> On Sat, Jun 15, 2002 at 02:56:02PM -0500, Kris J. Zaragoza wrote: > My first instinct on seeing this reply was to point out that win32com > doesn't run on Red Hat Linux. :-) Then I got to thinking a bit more > about it and realized this may actually be possible. Guess your right. This was a long time ago. > So, let me add to the original poster's question: Has anyone ever > tried running the Windows version of Python (either the main > distribution or ActiveState's) under Wine to take advantage of the > database drivers, etc.? Wouldn't want to try it. The socket server idea that the other guy posted is probably the way the go. -- Alex Polite http://plusseven.com/gpg/ From sandeep182 at hotmail.com Wed Jun 19 10:50:30 2002 From: sandeep182 at hotmail.com (Sandeep Gupta) Date: Wed, 19 Jun 2002 14:50:30 GMT Subject: Blank results using mxODBC against Message-ID: We are trying to connect to MS SQL Server from Linux, but we are only receiving blank values in the query results. The number of rows and columns in the result is correct, but each result cell is blank. As a test, we successfully used mxODBC against a local MySQL going through unixODBC. We then tried: Python2.2 --> mxODBC --> unixODBC --> inline TDS 1.6 --> MS SQL Server When I use isql with unixODBC, I am able to view the results of a simple select. That same select in mxODBC returns blank result values. The python code I'm using is: import mx.ODBC.unixODBC db = mx.ODBC.unixODBC.DriverConnect('DSN=MSSQL') c = db.cursor() c.execute('select * from dbo.Source;') mx.ODBC.print_resultset(c) odbcinst.ini contains ================== [SQLServer] Description = SQL Server driver for Linux Driver = /usr/lib/odbc-i02.so FileUsage = 1 ================== odbc.ini contains ================== [MSSQL] Description = MSSQL Test DB Driver = SQLServer Server = Port = 1433 User = Pass = Database = majorver = 5 minorver = 0 Trace = On TraceFile = /tmp/DB.out ================== Thanks Sandeep From debl2nononospammywhammy at bellatlantic.net Sat Jun 1 18:24:28 2002 From: debl2nononospammywhammy at bellatlantic.net (David Lees) Date: Sat, 01 Jun 2002 22:24:28 GMT Subject: OverflowError: math range error ??? References: Message-ID: <3CF9499E.F5365921@bellatlantic.net> See: http://www.python.org/doc/current/lib/module-math.html david lees Shagshag13 wrote: > > What are "the known limits" of math modules ? > > Where can i find more infos on this ? > > Thanks, > > s13. From gleki at gol.ge Mon Jun 24 05:19:09 2002 From: gleki at gol.ge (Giorgi Lekishvili) Date: Mon, 24 Jun 2002 11:19:09 +0200 Subject: Synchrinized chat? Message-ID: <3D16E40D.500A5DD4@gol.ge> Hi all! Is somebody making a synchronized chat in Python? I don't need the script of the chat itself, rather a learning example of a real-world synchronized (multi)threading. Thank you in advance. Grtz, Giorgi From Johannes.Nix at mail.uni-oldenburg.de Tue Jun 4 04:57:49 2002 From: Johannes.Nix at mail.uni-oldenburg.de (Johannes Nix) Date: 04 Jun 2002 10:57:49 +0200 Subject: Kalman Filters, Particle Filters and SVM's Message-ID: <671ybne7zm.fsf@mail.uni-oldenburg.de> Are there any implementations of Kalman Filters, Particle Filters or Support Vector Machines in (Numerical) Python ? Especially the latter would be fine, I'm dreaming to implement a SVM based script with the capability to distinguish spam from personal mails.... but I'm way to lazy to write my own SVM. Johannes -- -------------------------------------------------- Johannes Nix jnix at medi.physik.uni-oldenburg.de AG Medizinische Physik Fax +441 798-3902 Universit?t Oldenburg Tel +441 798-3270 26111 Oldenburg -------------------------------------------------- From tjreedy at udel.edu Mon Jun 10 12:20:25 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 10 Jun 2002 16:20:25 GMT Subject: [ANN] constraint-0.2 References: Message-ID: To paraphrase Magnus Lie Hetland, the general constraint-propagation system constraint-0.2 takes 100 times as long to do the 8-queens problem as the specific backtracking queens.py found in the standard Python distribution: 15 versus .1 sec on comparable machines. The is about the same comparison, for some computations, as between generic/dynamic Python and type-specific C. In both cases, there are two more questions of practical interest: which platform/method is faster for the *programmer*? and, is the slow method fast enough? So, what is the relative programming speed of the general constraint propagation system versus specific backtracking? I suspect that some people could whip up something like queens.py as fast or faster that they could the (unpublished?) constraint input for the same problem. However, I also suspect the reverse would be true for the more realistic and useful scheduling example that Fayolle used to illustrate and motivate constraint-0.2. http://www.logilab.org/python-logic/documentation.html Real world problems may have no solution as given. On the other hand, constraints may not be absolute. In the scheduling example, two workshops *can* be scheduled simultaneously, if necessary, even though many people want to take both. So a stepwise procedure may be needed. (Given multiple solutions, one might also want to add 'wishes' as pseudoconstraints to help select just one.) So, is it equally easy, with the two approaches, to add or drop constraints and rerun? This would be fairly simple with c-0.2 input but probably harder for backtracking code unless planned for from the beginning. Is it equally easy to give constraints priorities and have the system automatically either add them in order from the highest or drop them from lowest? Constraint-0.2 evaluates constraints in the order listed, but I do not know if it properly backtracks from failure to report the most satisfying solutions. Terry J. Reedy From troels at 2-10.org Tue Jun 18 04:38:49 2002 From: troels at 2-10.org (Troels Therkelsen) Date: Tue, 18 Jun 2002 10:38:49 +0200 Subject: python version? In-Reply-To: Message-ID: > I remember once I tried to explain to my students the theory > behind the limit in > calculus. To 35 students. Maybe 3 understood it in such a way > that they could > present a solution back to me. But most just didn't want to > know. I was wrong. > I was not teaching Mathematicians but Buisness students that just > needed the > credit. Now I am not someone who necessarily wants to code using > Python in ASP. > I just want some code to find my version of Python using ASP. > I'm sorry if I > have not lived up to your expectations. > > -- > George Hester The document on this URL might help explain why you feel you have not gotten the answer to the question you thought you asked :-) http://www.tuxedo.org/~esr/faqs/smart-questions.html Regards, Troels Therkelsen From peter at engcorp.com Sun Jun 30 12:12:53 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 30 Jun 2002 12:12:53 -0400 Subject: [Newbie] Is the text delimiter changeable? References: <3d1f26a4.5915886@news.texas.net> Message-ID: <3D1F2E05.93926893@engcorp.com> Ben Fairbank wrote: > > I have to process large amounts of text and the text includes numerous > apostrophes and quotation marks. It would be very handy if I could > temporarily assign a substitute for Python's use of the caracters " > and ' to delimit text strings. If I could use, for example, the @ > character or the # character, neither of which appears in the text I > have to work with, and if I could disable the " and ' delimiters, then > my task would be greatly simplified. I realize I can backslash escape > these characters in some circumstances, but I do not think that will > work when a user's input is a word such as "can't" or "don't." > Anyway, short of doing something truly drastic, such as recompiling > the system (which I have no intention of doing), is there a workaround > that will permit this? Do you know about Python's triple-quoted strings? >>> a = """This isn't much of a "string" now, is it?""" >>> b = '''This can't have "triple-quotes" inside, of course, but that's okay.''' -Peter From debl2Nonospammywhammy at bellatlantic.net Sun Jun 9 02:24:54 2002 From: debl2Nonospammywhammy at bellatlantic.net (David Lees) Date: Sun, 09 Jun 2002 06:24:54 GMT Subject: Determination of screen resolution? Message-ID: <3D02F4C8.C2DF2EE0@bellatlantic.net> I would like to use tkinter and have the canvas object automatically scaled fit the screen. Is it possible to read the screen resolution (800x600, 1024,768...) from somewhere. David Lees From cliechti at gmx.net Mon Jun 10 19:40:35 2002 From: cliechti at gmx.net (Chris Liechti) Date: 11 Jun 2002 01:40:35 +0200 Subject: Iterators vs. Generators References: Message-ID: aahz at pythoncraft.com (Aahz) wrote in news:ae3a6f$9d9$1 at panix1.panix.com: > So when would one actually write an iterator instead of a generator? > I've been trying to think of an example and failing. don't know, maybe when you don't like the additional loop in the generator (see example below) maybe the iterator has advantages when the data in the object changes or has to be chaged as the object q (from below) _is_ the iteraror but it's _not_ the generator (but this does not matter in the example below ...). if you pass "i = iter(q)" somewhere then with the iterator (and forget about q) you can still modify the original object as "i is q" (at least in my example), but this is not even possible with a generator. iterators can be generated implicit by __iter__ in a "for", but a generator needs a factory function (of course that can be named __iter__ ...) seems to be a matter of taste... chris PS: why is Queue not iterable by default? here's a Queue for fun : ---- #!/usr/bin/env python from __future__ import generators import Queue, threading, time class Q(Queue.Queue): def __iter__(self): return self def next(self): x = self.get(1) if x is None: raise StopIteration return x class Q2(Queue.Queue): def __iter__(self): while 1: x = self.get(1) if x is None: return yield x class Producer(threading.Thread): def __init__(self, queue): threading.Thread.__init__(self) self.q = queue def run(self): for n in range(10): time.sleep(0.2) self.q.put(n) self.q.put(None) if __name__ == '__main__': #iterator q = Q() print ":", q is iter(q), type(iter(q)) Producer(q).start() for x in q: print x #generator q = Q2() print ":", q is iter(q), type(iter(q)) Producer(q).start() for x in q: print x -- Chris From stephen at theboulets.net Fri Jun 7 22:31:38 2002 From: stephen at theboulets.net (Stephen Boulet) Date: Fri, 07 Jun 2002 21:31:38 -0500 Subject: Confidence intervals, stats modules? Message-ID: Are there any stats modules to calculate things like confidence intervals, mean, standard deviation? Thanks. -- Stephen From radix at twistedmatrix.com Mon Jun 3 08:47:21 2002 From: radix at twistedmatrix.com (Christopher Armstrong) Date: 03 Jun 2002 08:47:21 -0400 Subject: Interrupting a continuous script In-Reply-To: <_6JK8.1535$376.74360@newsfep1-win.server.ntli.net> References: <_6JK8.1535$376.74360@newsfep1-win.server.ntli.net> Message-ID: <87u1okmsva.fsf@twistedmatrix.com> >>>>> "Julian" == Julian Gollop writes: Julian> I have a few programs continually processing text files on a Linux Julian> machine. Occasionally I need to stop them, but I don't want to use Julian> a keyboard interrupt because it may cause the script to stop in the Julian> middle of doing something. Does anyone know a simple way to allow Julian> me to stop the process by pressing a key on the keyboard - without Julian> stopping inside something crucial? Julian> Julian. >>> import signal >>> def handleBreak(sig, frame): ... print "I caught a break!" ... >>> signal.signal(signal.SIGINT, handleBreak) >>> while 1: pass ... I caught a break! I caught a break! I caught a break! (I pressed C-c 3 times) Your handleBreak method should set a flag somewhere so your processing code knows it should stop and clean up whenever it gets the chance. In case you're considering just catching KeyboardInterrupt exception: don't. It's not the same as using a signal handler, bacause it will still interrupt execution and jump to your 'except' block. (with signals, after running thi handler, it goes back to the code it was running last) -- Chris Armstrong << radix at twistedmatrix.com >> http://twistedmatrix.com/users/carmstro.twistd/ From phawkins at connact.com Thu Jun 20 13:14:39 2002 From: phawkins at connact.com (Patricia J. Hawkins) Date: 20 Jun 2002 13:14:39 -0400 Subject: GUI (PyQt) & thread problem References: <8b5d764c.0202240451.1c4bda3b@posting.google.com> <8b5d764c.0202250020.268f4a81@posting.google.com> Message-ID: >>>>> "KN" == Kristian Nylund writes: KN> Thank you for your reply. Do you have any pointers on how to implement KN> this kind of functionality, i.e. when something happens in the worker KN> thread (not GUI related), the GUI needs to be updated. Is it at all KN> possible? Boudewijn Rempt has added a QT modification to an Activestate recipe for using Tkinter and threads -- scroll down to see his version. Note that his version changes the GUI based on thread results, though the original Tkinter example doesn't: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965 -- Patricia J. Hawkins Hawkins Internet Applications, LLC From kragen at pobox.com Thu Jun 6 14:15:55 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 06 Jun 2002 14:15:55 -0400 Subject: self References: Message-ID: <83g000e0is.fsf@panacea.canonical.org> "Sean 'Shaleh' Perry" writes: > it sees 'a*c' and asks it own dict 'do we know a?' if so it access dict['a'] > and returns its value. Looking at your example you seem to be implementing a > symbolic calculator. Most implementations I have seen involve writing a small > language with interpreter. It's a shame that this is necessary, since we already have a perfectly good language with an interpreter already present. From jubafre at zipmail.com.br Wed Jun 19 00:38:45 2002 From: jubafre at zipmail.com.br (jubafre at zipmail.com.br) Date: Wed, 19 Jun 2002 01:38:45 -0300 Subject: =?iso-8859-1?Q?how=20i=20use=20=27=E3=27=20in=20python=3F=3F=3F?= Message-ID: <3D0F6623000017AA@www.zipmail.com.br> i?m brazilian, and in my laguage(Portguese) there are many other caracters how ?, ?, ? and a string in python doesn?t support this how i can use??? have a import module for this??? BRASILEIROS DA LISTA COMO VCS CONSEGUEM USAR ACENTO NO PYTHON?? for exmple: s='?' doesn?t work?why?? Juliano Freitas www.gebrasil.hpg.com.br ------------------------------------------ Use o melhor sistema de busca da Internet Radar UOL - http://www.radaruol.com.br From ballabio at mac.com Thu Jun 27 15:38:03 2002 From: ballabio at mac.com (Luigi Ballabio) Date: Thu, 27 Jun 2002 21:38:03 +0200 Subject: squared functions--most Pythonic way? Message-ID: Hi all, suppose we want to define a function which, given f(x), returns its square. There are a number of ways which come to mind, such as: object-oriented programming: def fsquare: def __init__(self,f): self.f = f def __call__(self,x): return self.f(x)**2 functional programming: # with an internal named function def fsquare(f): def f2(x): return f(x)**2 return f2 # with lambda def fsquare(f): return lambda x: f(x)**2 and I'm sure people can come out with others that I didn't figure but are obvious to any Dutchmen. My question: is any of the above considered more Pythonic? Thanks, Luigi From eric at enthought.com Tue Jun 4 22:51:02 2002 From: eric at enthought.com (eric jones) Date: Wed, 05 Jun 2002 02:51:02 GMT Subject: weave.accelerate? References: Message-ID: The CVS version has accelerate in it. You can get a nightly snapshot here: http://www.scipy.org/site_content/download_list Take note that accelerate is still minimally capable. It is unlikely to be useful for real work. eric "Chris Fonnesbeck" wrote in message news:c3835e5f.0206040624.7054ff3c at posting.google.com... > I'm trying to locate a version of weave that includes the accelerate() > function; the version posted on scipy.org doesnt seem to have it. Can > anyone point me in the right direction. > > Thanks, > cjf From peter at engcorp.com Sun Jun 9 13:02:17 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 09 Jun 2002 13:02:17 -0400 Subject: libftp.size function gives wrong results! References: Message-ID: <3D038A19.D991A885@engcorp.com> Michael Davis wrote: > > I'm writing a python program which will upload or download files via ftp. > It's intended to be used to deploy a web site from a local machine to a > server. It tries to determine which files are modified on the local machine > by comparing file sizes and modification times. > > I try to compare files using os.stat for the local file and FTP.size for the > remote. The problem is, FTP.size is giving me incorrect results. If I use > the ftp command line client, and look at one of my files on the server (the > output looks like 'ls -l') then I can see that the file size, is, say, > 1200. But the FTP.size function returns, say, 1242. I think you'll find the number of lines in that file is 42. The difference is probably between CRLF and LF line terminations in the file. If you transfer files with FTP and want to preserve the line endings, you have to specify the binary type, not ascii. Don't know how to do this with ftplib, but from the ftp command line you would use 'type binary' or 'type ascii' to switch. -Peter From david_griswold1 at yahoo.com Fri Jun 28 23:49:48 2002 From: david_griswold1 at yahoo.com (David Griswold) Date: Sat, 29 Jun 2002 03:49:48 GMT Subject: I'm an idiot References: Message-ID: I had no idea it could be this compact. Thank you for your help! David Carel Fellinger wrote in news:mailman.1025316799.2919.python-list at python.org: and write it like this: > > g = open('c:/temp/temp1.txt', 'w') > for line in open('c:/temp/temp.txt'): > g.write(line.strip()) > > From maio at stoupa.sh.cvut.cz Tue Jun 25 08:21:54 2002 From: maio at stoupa.sh.cvut.cz (Marian Schubert) Date: Tue, 25 Jun 2002 12:21:54 +0000 (UTC) Subject: Python daemon References: <3d182dd6$1@news.mt.net.mk> Message-ID: On Tue, 25 Jun 2002 10:52:49 +0100, Dave Swegen wrote: >> 4. Logging > >Don't know what the best python way of doing this is. http://www.red-dove.com/python_logging.html pretty nice logging system CU, maio From cliechti at gmx.net Sat Jun 8 13:37:46 2002 From: cliechti at gmx.net (Chris Liechti) Date: 8 Jun 2002 19:37:46 +0200 Subject: Q: scope of module functions References: Message-ID: "Frank Sonnenburg" wrote in news:adte4c$nu8$1 at f1node01.rhrz.uni-bonn.de: > a little tricky problem (at least from my point of view); given module > CALLER: > > # i need "fct" and some other from module "UTILS" > from UTILS import * > fct() > # END of module CALLER > > > Now, inside fct(), how do i determine the module - in this case CALLER - > from where fct() was called? i think __name__ can help in this case but not in the one below. but are you sure that you wan't t do this? a function that behaves differently depending on the namespace gives very hard times debugging... a cleaner solution would be to create an class that contains fct and each module that uses it can create its own object. if you can say what you want to achieve, we might give you a more specifuc advice. > Even concerning cases like (continuation of example): > > # Now we are in __main__ > import CALLER > fct_in_main = CALLER.fct > fct_in_main() -- Chris From gerhard.haering at gmx.de Sun Jun 23 12:54:29 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Sun, 23 Jun 2002 18:54:29 +0200 Subject: Newbie question (anyone programming with curses?) In-Reply-To: References: Message-ID: <20020623165429.GA600@lilith.my-fqdn.de> * hellboy [2002-06-23 18:32 +0200]: > Emile van Sebille wrote: > > > No one has made a Windows port of the curses module. On a Windows > > platform, try the Console module > > 8<--cut--8< > > So there is no way to get fast console input/output + colors in text mode > and code portability? > > btw. there actually is a windows implemetation of curses > (http://pdcurses.sourceforge.net), but it is written in c (of course) and I > am too inexperienced to say if there is some way of incorporating it into > python, and how to do it.... I and somebody else failed at making the Python curses module compile against pdcurses. The proper solution is to build ncurses on win32, then just compile Python against it. ncurses currently works on Cygwin, and AFAIR MS-DOS, too. A mingw32 port should thus be doable, too. If you want curses on Windows now, you can just use the Cygwin port of Python (install Cygwin, then just choose Python as a package during installation). Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 31.3 ?C Wind: 1.2 m/s From dfackrell at DELETETHIS.linuxmail.org Tue Jun 25 10:54:52 2002 From: dfackrell at DELETETHIS.linuxmail.org (Daniel Fackrell) Date: Tue, 25 Jun 2002 08:54:52 -0600 Subject: How to stop a SocketServer? References: <7xhejv9af2.fsf_-_@ruckus.brouhaha.com> <3d1744d4$1_1@hpb10302.boi.hp.com> Message-ID: <3d18843d$1_3@hpb10302.boi.hp.com> Skip, Thanks! This is exactly what I was looking for. For lurkers and searchers, the Python library reference (thread objects, currently 7.5.4) gives the following: --- setDaemon(daemonic) Set the thread's daemon flag to the Boolean value daemonic. This must be called before start() is called. The initial value is inherited from the creating thread. The entire Python program exits when no active non-daemon threads are left. --- Daniel Fackrell (dfackrell at linuxmail.org) When we attempt the impossible, we can experience true growth. "Skip Montanaro" wrote in message news:mailman.1024958494.18742.python-list at python.org... > > Daniel> I faced this problem with a simple chat server I wrote. I > Daniel> expected that termination of the server with should > Daniel> have stopped it immediately, but it instead waits until some > Daniel> communication is received from each thread that was stopped at a > Daniel> read(). > > Just make all the non-main threads daemon threads. I believe the main > thread will be the one to catch the Ctrl-C. It can then cleanup and exit. > Assuming it's the only non-daemon thread, the application will also exit. > > -- > Skip Montanaro > skip at pobox.com > consulting: http://manatee.mojam.com/~skip/resume.html From mikeb at mitre.org Sat Jun 1 14:37:46 2002 From: mikeb at mitre.org (Mike Brenner) Date: Sat, 01 Jun 2002 14:37:46 -0400 Subject: File Iterator - Print - Double New Lines Message-ID: <3CF9147A.14926C08@mitre.org> print "QUESTION: Why did it jump from NO LINE SPACING to DOUBLE SPACING?" print "QUESTION: How to get SINGLE SPACING?" print print "Using Python 2.2.1, it does the same under win32all build 142 and " print " running it from a DOS box without the windows extensions." def writer(list): f=open("tmp.tmp","w") for item in list: f.write(item) f.close() def reader(): f=open("tmp.tmp","r") for line in f: print line f.close() print "trying it without the \\n" writer(["a","b","c"]) reader() print "trying it with the \\n" writer(["a\n","b\n","c\n"]) reader() From mgilfix at eecs.tufts.edu Mon Jun 17 14:20:01 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Mon, 17 Jun 2002 14:20:01 -0400 Subject: Messing with GUIs via Python... In-Reply-To: ; from kondwani@cs.mun.ca on Mon, Jun 17, 2002 at 02:34:07PM -0230 References: Message-ID: <20020617142001.F422@eecs.tufts.edu> I suggest searching the archives since this question is often answered in this newgroup... But if you're too lazy, here's two links to get you started: For basic gui apps: http://www.python.org/doc/current/lib/module-Tkinter.html For more advanced stuff: http://www.wxpython.org http://www.daa.com.au/~james/pygtk/ -- Mike On Mon, Jun 17 @ 14:34, Kondwani Spike Mkandawire wrote: > Howdy Folks is there a way to create simple GUI apps. > using Python ( I have only used it for 4 months)... If so > is there a way of doing this without having it as a language > binding of some graphics software (as OpenGL)... > > Kondwani Spike Mkandawire > CS Intern. Memorial University, Canada... > > > -- > http://mail.python.org/mailman/listinfo/python-list `-> (kondwani) -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From larooy at xtar.co.nz Sun Jun 16 02:57:01 2002 From: larooy at xtar.co.nz (John La Rooy) Date: Sun, 16 Jun 2002 18:57:01 +1200 Subject: I feel stoopid ... this code is to verbose References: <3D0A1791.3060307@mxm.dk> Message-ID: <20020616185701.147c820e.larooy@xtar.co.nz> On Fri, 14 Jun 2002 18:19:29 +0200 Max M wrote: > Hmm ... I am working on a problem. In Danish we have a number format > that looks like: > > 42.000.000,00 which is 42 millions > > So I need to insert dot's at every three character from end of the > string for the integer value of the number. > > Let's discard decimal points and just focus on the meat. I have written > a funcion which works:: > > def stringSlicer(string, chunkSize=3): > chunkList = [] > reverseString = list(string) > reverseString.reverse() > for i in range(0, len(string), chunkSize): > chunk = reverseString[i:i+chunkSize] > chunk.reverse() > chunk = ''.join(chunk) > chunkList.append(chunk) > chunkList.reverse() > return '.'.join(chunkList) > > > print stringSlicer('42000000') > > >>> 40.000.000 > > I just find that it's a lot of code for such a little function an it > annoys my sense of aestetics. I have tried a lot of different approaches > including using zip on a list like ['','','.'], and other weird stuff :-) > > I just cannot seem to find the nice 3-liner I expected from the > beginning. Has anybody got a better solution ? I thought somebody might > find it a fun exercise. Well I have... > > > regards Max M > As other people have pointed out already, the locale module is the way to go but some people do find it a fun exercise too ;o) (this breaks if you have more than 3 digits after the decimal point. what's supposed to happen then anyway?) import re def StringSlicer(s): return re.sub("\\B(\d{3})(?=(\d{3})*(,\d*)?$)",".\\1",s.replace(".",",")) John From K.Rdt at TU-Berlin.DE Thu Jun 27 02:02:16 2002 From: K.Rdt at TU-Berlin.DE (Klaus Reinhardt) Date: Thu, 27 Jun 2002 08:02:16 +0200 Subject: background-processes with win-python? Message-ID: --------------------------------------------------------------------- Hi Is there a possibility to execute system-processes under windows-python in the background? So I can do this system("plink .. tu-berlin.de") without waiting for the real connection. K at Rdt --------------------------------------------------------------------- From mike.christie at athensgroup.com Mon Jun 24 13:45:59 2002 From: mike.christie at athensgroup.com (Mike Christie) Date: Mon, 24 Jun 2002 17:45:59 GMT Subject: wxPython question: window closing event Message-ID: <3D175AD7.9CB28305@athensgroup.com> I have a specific and a general question about wxPython. I have worked with GUIs and event-handlers before, but am new to both wxPython and Python itself. The specific question is: how do I attach code to the window closing event that occurs when (in MS Windows systems) you click the X in the top right corner of the screen? It appears I need to place a "self.close(true)" there, since exiting via an exit menu (which does call "self.close(true)") shuts things down politely, but exiting via the X leaves the Python interpreter still executing my script, and forces me to close Python to shut it down. The general question is: what's the best resource for finding this sort of thing out? I've been working through the tutorial material at http://wiki.wxpython.org/index.cgi/Getting_20Started which has been very helpful indeed. I've also made some use of the online documentation at http://wxpython.org/onlinedocs.php which is also great. However, for a question like this, it seems like the right resource is something like a categorization of events, or a reference guide for event-handling, or something like that. The online docs do have an "Event Handling Overview", but I couldn't find this information there. Is there a book or online reference that I could use as a resource for this kind of question? Thanks in advance for any help. Mike From prestomation at yahoo.com Sun Jun 23 20:43:31 2002 From: prestomation at yahoo.com (Preston Tamkin) Date: Mon, 24 Jun 2002 00:43:31 GMT Subject: HTTP authentication Message-ID: hello all. I've just recently jumped on the python bandwagon, and I need some help! I'm trying to write a program(in python) to go out to several websites and get a few numbers off of the page. Only problem is, I need to give the site a username and password! It's not HTTPS, SSL, or anything like that. I did some packet sniffing and it is a HTTP POST command, the server then requests the information then the client sends the u/p. I'm using raw sockets and can't figure out how to listen for the "request" packet or excatly what to send for the last part. The site uses ASP. It's http://boards.ign.com if you want to look at it. Is there an easier way to do it? Am I just simply missing something? Thanks in advance P.S. Me = TOTAL n00b From steph_lar at videotron.ca Fri Jun 7 21:56:51 2002 From: steph_lar at videotron.ca (Stephane Larouche) Date: 7 Jun 2002 18:56:51 -0700 Subject: Problem with wxPython Message-ID: I use wxPython 2.3.2.1 with Python 2.2.1 on multiple computers running WinNT 4.0 SP6. On one of those computers, which has a setup that is identical to the setup of the other computers (I think), wxPython software crashes when a wxFrame is initialized with any of the window styles wxMAXIMIZE_BOX, wxRESIZE_BOX or wxSYSTEM_MENU (or wxDEFAULT_FRAME_STYLE that includes those styles). Even the demo provided with wxPython crashes. According to DrWatson, the crash is caused by a stack overflow during the execution of the function wxTransformMatrix::operator-. Have your ever seen the same problem? Is there a workaround? Thank you for your help! Stephane Larouche steph_lar at videotron.ca From aoeu at go.com Mon Jun 17 07:06:57 2002 From: aoeu at go.com (Thinkit) Date: 17 Jun 2002 04:06:57 -0700 Subject: List containing objects and subclassing... References: Message-ID: <3eeda89d.0206170306.655f6c72@posting.google.com> "Shagshag13" wrote in message news:... > Hello, > > I need an advice, i have a python list containing only object "node", and i'm wondering if this > is best to hold it in a python list (as by now) or if i should write a "nodes" object subclassing from > list and implementing some other methods i need to process on node object (contained by this list) > and that i do now from "outside", or if i should write my own container implementing __getitem__ > (i also have done that in another version)... > > ... > [hash_i] --> [node_j] -> [node_k]... > ... > > Which way is better OO practice ? which is the efficient one ? > What are the pros and cons (maybe best oo vs efficient ?) ? > > Thanks, > > s13. You'd have problems if you subclass list with possibly adding non-node data into it. Shouldn't you just subclass tuple to get around this? From mgerrans at mindspring.com Fri Jun 21 02:50:13 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Thu, 20 Jun 2002 23:50:13 -0700 Subject: text search?? References: Message-ID: You could either lower() the string before comparing ('WinZip'.lower() == 'winzip'), or use regular expresions (look at the re module). From jonathan at onegoodidea.com Wed Jun 26 04:20:55 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Wed, 26 Jun 2002 09:20:55 +0100 Subject: Parsing strings (\n and \\) References: <3D188006.7050202@thomas-guettler.de> Message-ID: On 25/6/2002 17:01, in article lt0S8.45025$n4.10623651 at newsc.telia.net, "Fredrik Lundh" wrote: >>>> UNPARSED = "__import__('os').system('echo dream on!')" >>>> PARSED = eval(UNPARSED, {}, {}) > dream on! OK. Moving on from the arguments against using 'eval', how about: >>> import re >>> >>> ESCAPE_CRE = re.compile( r'\\(.)' ) >>> ESCAPE_SUBS = { 'n': '\n', 't': '\t' } >>> >>> def replace_match( m ): ... c = m.group( 1 ) ... return ESCAPE_SUBS.get( c, c ) ... >>> def replace_escapes( s ): ... return ESCAPE_CRE.sub( replace_match, s ) ... >>> replace_escapes( '\\\\this is a \\test\\n' ) '\\this is a \test\n' >>> print _ \this is a est >>> Obviously this deals only with the easiest cases, but extending it to handle octal codes and any other special cases shouldn't be too hard (change the regular expression and put some if...then...else magic into replace_match). Jonathan From hjwidmaier at web.de Thu Jun 20 07:25:53 2002 From: hjwidmaier at web.de (Hans-Joachim Widmaier) Date: 20 Jun 2002 04:25:53 -0700 Subject: Advice sought on ps module Message-ID: <6e990e29.0206200325.355f0413@posting.google.com> About 2 years ago I wrote a primitive PostScript module to help me create various things like CD inlays or diagrams. It served that purpose quite well, despite its primitiveness. Since long I wanted to rewrite the whole thing from scratch and do it (at least kind of) "right." But I'm still not so sure as which way to go. At one time I thought I might employ ghostscript, which would have enabled me to, e. g. get the string width for some text, so I can make adjustments (not only to the text). Apart from that I couldn't get a sensible communication with gs through popen2, the PostScript output is created somewhat nonlinear, making it harder to ensure that the gs context is correct (in that query case). I'm convinced that's the wrong way, but the alternative doesn't look too good either. If you want to do some optimizations, you have to double some functionality of the ps interpreter. Examples: - To calculate the with of a string, you have to read the AFM file, add the character widths, aplly kerning, transform it with the CTM and the fonts TM. - To know whether a font must be reset or is already the current font you have to keep track of all the save/restore, gsave/grestore and the like. I do not want to write a "do all, end all" PostScript module. I do not even want to give it away (I'd be simply too embarrassed). Still I hope that some of you might give me some good advice on how to best do it. Thanks for any suggestion! Hans-Joachim From dfackrell at DELETETHIS.linuxmail.org Fri Jun 7 11:33:25 2002 From: dfackrell at DELETETHIS.linuxmail.org (Daniel Fackrell) Date: Fri, 7 Jun 2002 09:33:25 -0600 Subject: Detecting OS and Window Manager References: <3d00bfb5$1_2@hpb10302.boi.hp.com> Message-ID: <3d00d248$1_1@hpb10302.boi.hp.com> "Darren Winsper" wrote in message news:ug1h5q29aulga9 at corp.supernews.com... > In <3d00bfb5$1_2 at hpb10302.boi.hp.com>, Daniel Fackrell wrote: > > > Correct me if I'm wrong, but isn't this exactly the pythonic way of handling > > dynamic loading of modules? > > > > try: > > import kdecore > > except ImportError: > > # do something else > > OK, fair enough. I did only read and write my first line of Python a > few days ago :) Welcome to the group, then. We're all newbies here, for various values of new. > > Of course, this will probably not do what you want in this case, as kdecore > > will probably load if it is installed, without regard to whether the current > > user is running KDE. I don't have much experience with this particular > > topic yet. > > Well, I could attempt to see if something like "kdesktop" is running, > since if it is, the chances of running KDE are very high. It's kludgy, > but I can't really think of anything else, since KDEINIT would be running > if a single kde application is running IIRC. If you're thinking of scanning the currently running processes for the existence of a particular process, then you won't get the results you want there, either. The reason for this is that there can be multiple logins for a single user or multiple users, and KDE-related processes will exist if any one of those logins is running KDE, but not necessarily the current one. Maybe import your kde module(s), and then try to do something KDE specific without KDE running and see what kind of error this causes so you will know what to trap for? Hopefully some other newbie (for a much less significant value of new, AKA expert) is still following this thread to give you a better answer. Daniel Fackrell From aahz at pythoncraft.com Fri Jun 21 20:32:57 2002 From: aahz at pythoncraft.com (Aahz) Date: 21 Jun 2002 20:32:57 -0400 Subject: Tkinter and threads References: <3D0DCC8F.9A6D3B81@ipm.fhg.de> Message-ID: In article , Patricia J. Hawkins wrote: > >Also be aware that the early code examples aren't intended as models, >just as teaching tools -- you don't hit the really useful stuff till >page 48. And the format makes it tough to flip back and forth (not to >mention, tiny amounts of information per page drives me nuts, but >perhaps that's just me) -- and at 84 pages, I'm not going to print it >out to take it downstairs to an armchair and mark it up, which is what >I want to do. And skimming for what you don't know already is >impossible. Yeah, I know. Last summer, I was negotiating with O'Reilly to write a whole book on the subject (their idea). Last November, they canned the project. I haven't had the time/energy to rewrite the slides into a real tutorial, and I'm working on a completely different book now. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From mcherm at destiny.com Thu Jun 6 09:11:52 2002 From: mcherm at destiny.com (Michael Chermside) Date: Thu, 06 Jun 2002 09:11:52 -0400 Subject: array, list, performance... Message-ID: <3CFF5F98.2060406@destiny.com> Here is my understanding of it: li = [x0, x1, x2, ...] li[n] element access is O(1) li.append(x) appending is O(1) (actually, it SOMETIMES takes O(len(li)) as it resizes the list. But if you grow a list by continually appending, the amortized time is linear (ie, constant amortized time per element) li.insert(0) prepending is O(len(li)) (so grow the list from the end!) del li[0] deleting from the front (or middle) is O(len(li)) li.pop() deleting from the end is O(1) li[n] = x assignment to the middle is O(len(li)) len(li) determining length is O(1) li.index(x) search is O(len(li)) (NOT efficient) li.sort() sort is O(len(li)*ln(len(li))) (I believe it uses quicksort, but if a python function has to be executed for the compare that may take some time.) It's really just your basic auto-growing array, but with a bunch of clever things done to speed up common cases, and I don't know those well enough to comment on them. -- Michael Chermside From mgilfix at eecs.tufts.edu Mon Jun 17 11:59:02 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Mon, 17 Jun 2002 11:59:02 -0400 Subject: non blocking socket.accept() In-Reply-To: ; from e9226414@nospam.stud4.tuwien.ac.at on Mon, Jun 17, 2002 at 01:45:05PM +0000 References: Message-ID: <20020617115902.A422@eecs.tufts.edu> Someone else answered what you'll want to do with earlier versions of python but if you're feeling adventurous and want to try out the CVS version: sock.set_timeout(2.0) try: sock.accept() except socket.error, strerror: print strerror -- Mike On Mon, Jun 17 @ 13:45, Zsolt Marx wrote: > I far as I know socket.accept() waits for a client > to ask for a connection with the server. > > This command seems to be blocking, though I would > like to limit the wait time onto a predefined interval > and to throw an error, if there is no connection. -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From d2002xx at myrealbox.com Sat Jun 22 20:42:09 2002 From: d2002xx at myrealbox.com (d2002xx) Date: 22 Jun 2002 17:42:09 -0700 Subject: Python hits the spot References: <3D1482AE.8FA299D8@kfunigraz.ac.at> Message-ID: <8d3f4438.0206221642.607584b9@posting.google.com> Hello. Siegfried Gonzi wrote in message news:<3D1482AE.8FA299D8 at kfunigraz.ac.at>... > In the following I got the advice to install a real user system on my > laptop. Okay, I bought Linux SuSE 8.0 and installed it on my laptop (256 > MB RAM, 1000 MHz Celeron). I also installed Python 2.2 (the ActivePython > version, otherwise I couldn't install idle due to the annoying > "free_software_garbage_2_weeks_installation_nightmare"). > You didn't use offical python distribution, right? It's impossible to show the "free_software_garbage_2_weeks_installation_nightmare". If the binary version can't work, just use source-code and compile yourself. Python 2.2.1 works well on my computer. The difference is that before compiling, you need to install some XXX-devel.rpm if you want use these python modules. (such as openssl-devel) > 1. After starting the process from within idle the complete system > freezes after the first wavelength (after about 20 minutes). I couldn't > kill a process or open a different session (via F2) in order to kill > python. The last resort: turn off the power supply. > NOT use unoffical python distributions, they may change some thing. And I NEVER see similiar problems on offical version, even in beta version. Also, I recommand that NOT use idle, because anything using tk are very slow, if you want an IDE, there is http://boa-constructor.sf.net , it doesn't complete yet, but works very well, and provides some cool features such as UML. It uses wxPython, which is much faster than tkinter, there is http://www.wxpython.org > 2. I thought it is better to start the process from the command line and > in a X terminal: python forcing.py > The same behavior as aforementioned: last resort: power supply. That is > really good and fine because a Linux system really is greedy for "shut > down immediately". > It may be due to X window. > My conclusion: I will rewrite my simulation in Fortran 90 and will > abadon Python. Python is maybe good for some small scripts but not > appropiate for serious programming. Your conclusion is whole wrong! Do you know how many big companies use Zope? See http://www.zope.com/ZopeClientList Well, I don't know much about fortran, but if you just want to do something about math, NO python, it will be slow (at least now). From kseehof at neuralintegrator.com Sun Jun 9 01:09:21 2002 From: kseehof at neuralintegrator.com (Ken Seehof) Date: Sat, 08 Jun 2002 22:09:21 -0700 Subject: Html In-Reply-To: <3d02c220_1@news.iprimus.com.au> Message-ID: Gold Fish wrote: > Anyone can tell me how can i run the script with the argumemt > such as python > example.py -o > What i have to write in script. Use sys.argv. It should look something like this: >>> import sys >>> sys.argv ['example.py', '-o'] > And if i want to render the > script in html > format hov can i do that Do you mean render the script itself, or the output of the script? If you mean "render the script", you need py2html. There are a few versions around. Google for py2html, or look at one of these: http://www.norvig.com/python/py2html.html http://www.egenix.com/files/python/py2html.py.html If that is not what you mean, you need to be much more specific. - Ken Seehof From occeanlinux at linuxmail.org Sun Jun 2 16:56:10 2002 From: occeanlinux at linuxmail.org (Gold Fish) Date: Mon, 03 Jun 2002 04:56:10 +0800 Subject: List Message-ID: <20020602205610.31575.qmail@linuxmail.org> ----- Original Message ----- From: holger krekel Date: Sun, 2 Jun 2002 22:05:45 +0200 To: Gold Fish Subject: Re: List > Gold Fish wrote: > > Charl P. Botha wrote: > > > > > In article <3cfa6ed8_1 at news.iprimus.com.au>, Gold Fish wrote: > > >> Assume we got 2 list > > >> list 1 = ['ABC','CDG','DAV','FE','FECA','FEAFA','FEA'] > > >> list 2 = [] > > >> how can we copy element from list 1 to list 2 say i just want to copy the > > >> 3 element 'CDG','DAV','FE' to list2 only. > > > > > > list1 = ['ABC','CDG','DAV','FE','FECA','FEAFA','FEA'] > > > list2 = list1[1:4] > > > > > > Is that what you meant? > > > > > No i mean if i got from list1 i wanna take 3 elements in any position to > > list2 but i don't know how many item in that list. > > if you have a starting index 'i' then you can do > > list1[i:i+3] > > which returns you at most 3 elements, starting from position 'i'. > > If this is still not what you want, then please give > two or three examples of what you want to achieve. > > holger > What i would achieved is that I got the list of elements say that 10 elements in the list, i want to seperate this list into 2,or 3 sublists depends on user input the number. Then these subject contain the number of elements say 2, or 3 depend on user define. How can i do this. For example. BigList = [e1,e2,e3,e4,e5,e6,e7] this will be divided into 4 small sublists which is sublist1,sublist2,sublist3,sublist4.These sublists will have maximum of 2 elements inside therefore, sublist1 = [e1,e2], sublist2=[e3,e4],sublist3=[e5,e6] and sublist7=[e7] I would appreciate that you could help me this problem. I spend so much time to think about it but it's look like i stuck in the maze when trying to divide biglist into small list and small list to nano list. -- Get your free email from www.linuxmail.org Powered by Outblaze From whisper at oz.net Mon Jun 3 14:43:25 2002 From: whisper at oz.net (David LeBlanc) Date: Mon, 3 Jun 2002 11:43:25 -0700 Subject: Automated Email In-Reply-To: Message-ID: Use the standard smtplib module that comes with Python. There is an example of using it in the python doc. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Ken > Sent: Monday, June 03, 2002 8:22 > To: python-list at python.org > Subject: Automated Email > > > How to do automated emailing when results being processed? > > Thanks > > > -- > http://mail.python.org/mailman/listinfo/python-list From peter at engcorp.com Sun Jun 9 17:51:14 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 09 Jun 2002 17:51:14 -0400 Subject: Correct code/unit testing (was Re: Efficient python programming...) References: <3D00A456.4315EDA3@engcorp.com> <834rgd5isv.fsf@panacea.canonical.org> <3D02FB3B.CF75E925@engcorp.com> Message-ID: <3D03CDD2.78C01DE1@engcorp.com> "John J. Lee" wrote: > > > Kragen Sitaker wrote: > > > It is certainly possible to err too far in the direction of believing > > > your code correct simply because it passes its test suite, and this is > > > a common beginner's error. I think it is also possible to err too far > > > in the direction of writing and running tests instead of desk-checking > > > code. > > Isn't it true that, however much time you're going to spend, the largest > number of bugs are going to get removed by allocating some of the time to > both activities: testing, and staring at the code? Perhaps, assuming you put a lot of bugs in the code, some amount of staring will be necessary. I believe staring is of little or no use, however, having tried it many times with my and others' code which had bugs and not having found those bugs by staring. The nastiest bugs were found by lots and lots of work, which usually included repeated attempts to reproduce the problem, manual runs, and sometimes using a debugger. Staring helped little. And then, having found the bug, we look at the code and say "oh yeah, we should have seen that." Better not to put the bugs in the code in the first place, however, so staring or those other things won't be necessary. Writing the tests and the code together, tests first, in small iterative steps, tends not to lead to buggy code. The payback is high compared to staring. -Peter From observer at NOSPAM.space.pl Thu Jun 13 05:29:52 2002 From: observer at NOSPAM.space.pl (Johann) Date: Thu, 13 Jun 2002 11:29:52 +0200 Subject: How to check version of Python under CGI References: <873cvrin1q.fsf@tux.ntw23.fr> <87y9djh6tg.fsf@tux.ntw23.fr> Message-ID: On 13 Jun 2002 11:22:03 +0200, Sylvain Thenault wrote: >I think the best way to know if a module is available is to try to import it: But it is difficult to import all modules. I found much better sollution. Ready to run CGI script at http://snakefarm.org/ Thanx to Simon :) -- Johann From martin at v.loewis.de Sun Jun 9 04:14:58 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 09 Jun 2002 10:14:58 +0200 Subject: Source formatting for long expressions. References: Message-ID: Christopher Armstrong writes: > Does anyone know of a tool that will beak up a very, very long > expression like this into multiple lines with sane indentation? Emacs indentation gives this: Ref(1, Instance('twisted.internet.app.Application', persistenceVersion=7, services={}, udpPorts=[], gid=1000, connectors=[], uid=1000, tcpPorts=[(9080, Instance('twisted.web.server.Site', sessions={}, resource=Instance('twisted.coil.web.ConfigRoot', children={}, modules=[], widgets={'config': Instance('twisted.coil.web.AppConfiguratorPage', variables={}, dispensers=Instance('twisted.coil.coil.DispenserStorage', dispensers={}})})))]) As you can see, it tries to align further arguments to a function together with the opening parenthesis. I would assume that any other auto-formatters use the same style, so you won't get any "sane" indentation until you drop the nesting level (perhaps in favour of method invocations). Regards, Martin From whisper at oz.net Wed Jun 5 19:48:03 2002 From: whisper at oz.net (David LeBlanc) Date: Wed, 5 Jun 2002 16:48:03 -0700 Subject: Using AT on XP to run python script - MARK HAMMOND PLEASE READ In-Reply-To: Message-ID: This is most curious, but I believe the commands _are_ getting executed! I tried the following (assume time is 16:30) "at 16:32 pythonw j:\python22\tools\idle\idle.py" (without the qoutes of course). At the appointed time, there was disk activity, but no idle window popped up (idle was chosen just to get something to pop up!). However, there _was_ a pythonw process running in the task manager! I think there might be a way to attach a console or get access to the GUI, but i'm not sure - maybe Mark Hammond might have a clue (he being the Python Win guru :) ). I tried the following: #at_test.py import sys import time tst = open("testfile.txt", 'a+') tst.write(time.asctime() + "\n") tst.close() put into an 'at' job as: at xx:xx python j:\python22\at_test.py I expected the output from this to be in j:\python22, but to my surprise, it was in c:\winnt\system32 where cmd.exe resides! testfile.txt contained the exact time the 'at' job was set to run at too! I suspect your last example that produced no visible output did in fact work :) In any case, it works - now if one could just get visible output! David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Chris Stromberger > Sent: Tuesday, June 04, 2002 17:35 > To: python-list at python.org > Subject: Using AT on XP to run python script > > > I'm having trouble getting AT on XP to run a python script for me. > Have tried: > > at xx:xx "c:\python21\python.exe c:\scripts\script.py" > at xx:xx "start c:\scripts\script.py" > at xx:xx "c:\scripts\script.py" > > and get "the system cannot find the file specified" for the first two. > The last version does nothing apparently--no error indication or > anything. > > I imagine it is related to user accounts and such. Anyone have any > pointers? > -- > http://mail.python.org/mailman/listinfo/python-list From rnd at onego.ru Wed Jun 5 17:41:27 2002 From: rnd at onego.ru (Roman Suzi) Date: Thu, 6 Jun 2002 01:41:27 +0400 (MSD) Subject: prototyping good OOdesign in Python? In-Reply-To: <20020605203051.GC1455@isis.gerrietts.net> Message-ID: On Wed, 5 Jun 2002, Geoff Gerrietts wrote: >Quoting Roman Suzi (rnd at onego.ru): >> On Sat, 1 Jun 2002, Sean 'Shaleh' Perry wrote: >> >> Related topic is UML with Python. Does UML has everything to reflect >> Python OO model or does it need to add features? >> (Or maybe in order to interoperate, there is a need not to use some >> of Python features). > >With UML, I generally find that it has TOO MANY features. >If I use >Visio, or Rose, or even the lovely pyut announced a few months ago on >this very list, they'll ask for information about attribute and method >visibility, data types, etc. > >Since Python doesn't care about most of this stuff, modelling it is >only useful if you expect to port the code later. And I prefer not to >plan for an unfortunate event. ;) > >> And if in order to interoperate with less expressive >> languages/systems, how to keep Python pythonic and not fall back to >> some standard universal subset, found in many programming languages. > >Certainly you could use UML and thorough documentation as a hedge >against relying too heavily on Python's dynamic nature. A startling >percentage of the things we take for granted in python can actually be >expressed similarly in other languages, though -- it just takes more >work, more infrastructure, and a few more lines of code. > >I've written code with the thought that I'd eventually rewrite it in >another language, and I shared many of your concerns about how well >ideas would "port". >For the most part, I find myself doing one of two things: either >writing the other (generally Java) language's idioms (like Singleton, >like stateless classes) in Python when it's not too inconvenient, or, >when it is, just writing it off as "the burden of porting". > >For the most part, the really "interesting" parts of your system are >going to port relatively cleanly, because you're doing calculations >and computations. It's the boilerplate crap that you can skip over >pretty effortlessly, and that's going to be the irritation of porting >anyway. Hmmm... Computations could be different. For example, in python I can use a couple of .strip/.split/.join things and get the needed format parsed. In other languages to do the same I need to write it again and again or find some lib to do it for me. Or, sometimes I prefer to put things like (in one breath, without errors): data = """parse|me|heavy 1|2|3 2|3|4 """ data = map(lambda x: x.split("|"), data.strip().split("\n")) and then have fun with a "burden of porting", rewriting the above example in C... Or maybe I became too lazy? >You can, of course, take special steps to avoid hard-to-port code. What are these? Not to use Python features at all and write crap like: data[0][0] = "parse"; data[0][1] = "me"; data[0][2] = "heavy"; .... - often found in VB programs? My examples are data-oriented, but logic-oriented ones are no less funny. Well, maybe I could automate the above with as little as: i = 0 for d in data: j = 0 for dd in d: print """data[%(i)s][%(j)s] = "%(dd)s";""" % vars() # ;-) >That's where you spend time writing foreign idioms into your Python >code. How much time you waste doing that will largely depend on how >quickly you need the "convert to another language" step to go. Anyway, thank you for your ideas, Geoff! >--G. > > Sincerely yours, Roman Suzi -- \_ Russia \_ Karelia \_ Petrozavodsk \_ rnd at onego.ru \_ \_ Tuesday, June 04, 2002 \_ Powered by Linux RedHat 7.2 \_ \_ "Shin: A device for finding furniture in the dark." \_ From fredrik at pythonware.com Thu Jun 20 06:34:06 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 20 Jun 2002 10:34:06 GMT Subject: Useful RE patterns (was: Variable Interpolation - status of PEP 215) References: <4PfQ8.44245$n4.10307683@newsc.telia.net> Message-ID: I wrote: > # match $$ and $var and ${var} > _dosub = sre.compile(r'\$(?:\$|(\w+)|\{([^}]*)\})').sub As part of the python-dev discussion, I mentioned that it might be a good idea to add a couple of standard RE patterns to the standard library, e.g. to match things like integer literals, IP- numbers (etc). If I were to add a dozen (or so) patterns to the (S)RE module, what should I pick? What patterns do you find yourself using over and over again? From loewis at informatik.hu-berlin.de Thu Jun 13 03:50:32 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 13 Jun 2002 09:50:32 +0200 Subject: How to call a function using apply with keyword args? References: Message-ID: "Achim Domma" writes: > I have a function like this: > > def MyFkt(A,B,C): pass > > and some parameters from a config file: > > params = {'A':5,'B':8,'C':9} > > how can I call MyFkt with this parameters? I recommend MyFkt(**params) > I tried apply(MyFkt,[],params) If you want to use apply, it is apply(MyFkt, (), params) The arguments need to be a tuple. Regards, Martin From shalehperry at attbi.com Thu Jun 20 13:54:12 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Thu, 20 Jun 2002 10:54:12 -0700 (PDT) Subject: application development - separating content from function In-Reply-To: Message-ID: > > The more I have tried to solve these requirements in an elegant and > efficient manner, the further I seem to stray from anything remotely > resembling a viable solution. In other words, I can't see the forest for the > trees anymore. > > Anyone working on something similar? Or, just plain brilliant in all things > Python, and ready and willing to point me in the right direction and make it > all worth while again :-) > you should try to solve part of the problem rather than all of it at once. The first implementation almost always reveals hidden issues. If you try to make this thing as full featured as you like from the beginning you will never finish it. Or it will be so overly complex it will crumble. Think about issues like multi-language support when you are coding so it is easier to add in later. Same for user customization. But adding all of those choices at once leads to difficult to implement and test code. From dunklervater at yahoo.com Mon Jun 17 15:51:11 2002 From: dunklervater at yahoo.com (DV) Date: 17 Jun 2002 12:51:11 -0700 Subject: How to distribute py-scripts on windows without requiring the full ActivaState package Message-ID: <2e0f5ffe.0206171151.4305c306@posting.google.com> Hello, A couple of years ago, I experimented with Python on Linux, but somehow got out of touch. Just recently I discovered, that there is a pretty comprehensive Windows-Version for it that even supports pure windows-stuff such as COM or Win32API. Yet, I found out that the ActiveState package is very large to download and install, so this leads me to the question(s): 1)Is there some way to distribute a script foo.py by maybe bundling it with python.exe and python.dll, delivering these three files ONLY (and of course any .py library files that foo.py calls) and not requiring the recipient to download and install the whole ActiveState package? 2)Are there different versions of python.exe and python.dll? What I would find useful was, if there was ONE version of python.exe&python.dll that only could be used for console stuff, so you wouldn?t have such big files to distribute along with foo.py, and another one for true GUI-stuff 3)Concerning COM and other heftier Win32 dependend stuff, or anything that python needs a third-party dll for to use: Can the necessary dll be bundled along with python.exe, python.dll and foo.py, just as mentioned in 1)? Mind, I would?t want to distribute stuff as a single EXE. I could live with having to distribute more than one file, but I would very much like it, if an end user receiving my script would?t have to install the whole ActiveState package. I could imagine that one weak point about this is, that i have read somewhere that dlls must be registered before they are usable, but I also read that this is possible by using rundll.exe or some other Windows system program manually. If so, the registering process could be done by a .BAT file. As for the harddisk-space penalty of havin more than one python.exe and python.dll (one for each distributed script), this is the reason why I asked, whether a console version exists: If it did exist, you could do the GUI by designing a HTML-page that drives it. Sorry, if this posting appears twice under different topics, if so, it is most likely a temporary fault of deja.com, through which I posted this. I would appreciate any info on this matter. Thank you in advance, Bye. Franz From eric.brunel at pragmadev.com Fri Jun 7 12:30:56 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Fri, 7 Jun 2002 16:30:56 +0000 Subject: Program to an interface, not an implementation References: Message-ID: Egbert Bouwman wrote: > All your comments are crystal clear. Thanks. > > My next problem is on nearly the same page (17) of the GoF book: > class versus interface (== type) inheritance, but in the python context. > > "In C++ and Eiffel inheritance means both interface and implementation > inheritance" and > "in Smalltalk inheritance means just implementation inheritance". > I don't know any of these languages. > > Now in my simplistic worldview, if you inherit from a class, > you inherit everything, implementation and interface, > because the implementation defines the interface as well. > Even if all methods of the superclass only contain 'pass'. > But I may be wrong. I know C++ and I looked at SmallTalk a bit, and it seems the line between "implementation + interface" and "implementation only" inheritance is very thin... Apparently, it's quite directly related to strong typing and declarations. "Interface", in this context, seems to describe what's declared. So, as you noted in the beginning of your post, an "interface" is considered as a declared type. Since SmallTalk claims to have no types at all (which is also the case with Python...), they claim not to have such thing as an "interface", so obviously they cannot inherit it... In fact, I don't see the point in this: as you noted, when a class inherits from another, it inherits everything, implementation and interface. So in practice, it's not really significant. As I understand it, the only practical consequence of this distinction *may* be in the following case: class A: def m(self, i): pass class B(A): def m(self, i, j): pass In Python or SmallTalk, the preceding code is completely valid, so one could say that the "interface" of class A was not inherited by class B, since its method m has a different signature than A's method m. Trying to do the same thing in interface-inheriting languages would not have the same effect at all: it would either be forbidden, or even have stranger consequences. In C++ or Java, it would declare a *second* method, also called m, that would be distinguished from the inherited one by its number of parameters or their type: public class A { public int m(int i) { ... } } public class B inherits A { public int m(int i, int j) { ... } } ... o = new B(); o.m(1) // Calls A.m o.m(1, 2) // Calls B.m So, as you see, you probably can live without knowing anything about all this and still be able to do great stuff with whatever language you like :-). However, if anybody knows a bit more than me about implementation/interface inheritance, I'd be glad to learn (I happen to teach OO sometimes and I'd like to be able to answer this question precisely if it ever gets answered to me ;-). -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From boud at valdyas.org Mon Jun 3 15:40:27 2002 From: boud at valdyas.org (Boudewijn Rempt) Date: Mon, 03 Jun 2002 21:40:27 +0200 Subject: different gui-toolkits pros/cons... References: <_rLK8.12$fd2.979@news.ecrc.de> Message-ID: <3cfbc65a$0$52024$e4fe514c@dreader3.news.xs4all.nl> Gerhard H?ring wrote: > > Define "fast". PyGTK loads a lot faster than wxPython or PyQt. AFAIC, > this is because PyQt and wxPython wrap _all_ of a very large toolkit, > that both (wxWindows and Qt) even include a lot of non-GUI stuff. This > might be solved by trying to split the one shared library into many > small ones, that are loaded on demand. This has become a bit better since PyQt was split into several modules. The problem remains, though -- Qt is a very large library, even if you take all the extra's out. -- Boudewijn Rempt | http://www.valdyas.org From Administrator at python.org Thu Jun 20 14:59:44 2002 From: Administrator at python.org (Administrator at python.org) Date: Thu, 20 Jun 2002 12:59:44 -0600 Subject: ScanMail Message: To Recipient file blocking settings matched and action taken. Message-ID: <00dd01c2188c$a3f585a0$0e0fbb82@corp.es.com> ScanMail for Microsoft Exchange has blocked an attachment. Sender = Sylvain Th?nault Recipient(s) = David LeBlanc;python-list at python.org; XML Logilab Mailing list Subject = Re: [ANN] PyReverse 0.3 Scanning Time = 06/20/2002 12:59:43 Action on file blocking: The attachment py2xmi.bat matches the file blocking settings. ScanMail has Deleted it. From emile at fenx.com Sat Jun 29 16:08:14 2002 From: emile at fenx.com (Emile van Sebille) Date: Sat, 29 Jun 2002 20:08:14 GMT Subject: private References: <3D1DE132.4A890D9D@engcorp.com> Message-ID: James Kew > Yes, of course one can circumvent private in C++. But for me the main value > of the public and private specifiers is that they _document_ to the client > of the class what it should access and what it should not. > > I don't -- in my admittedly very limited experience -- find Python classes > as immediately self-documenting. It's not obvious from the class definition > what is intended to be called or modfied by the client and what is internal > to the implementation. > Conventionally, any leading underscore indicates 'private - don't use'. -- Emile van Sebille emile at fenx.com --------- From emile at fenx.com Thu Jun 27 12:08:42 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 27 Jun 2002 16:08:42 GMT Subject: How to find out operating system References: Message-ID: > What is the best way of finding out the kind operating system? > I can use os.name but if the system is Windows I would like also > know if the system is Windows98 or Windows ME or W2K or > Windows XP. Ask Marc Andre to re-release platform.py? [ducking...] -- Emile van Sebille emile at fenx.com --------- From fredrik at pythonware.com Sat Jun 29 08:06:25 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 29 Jun 2002 12:06:25 GMT Subject: joining 2 lists together - an elegant way? References: Message-ID: <5phT8.45580$n4.10822879@newsc.telia.net> Rajarshi Guha wrote: > Right now I do: > > newlist = [] > for i in l1: > newlist.append(i) > for i in l2: > newlist.append(i) newlist = l1 + l2 From ken at hotmail.com Tue Jun 4 09:41:06 2002 From: ken at hotmail.com (Ken) Date: Tue, 4 Jun 2002 23:41:06 +1000 Subject: Automated Email - What did I do wrong here? References: Message-ID: "Ken" wrote in message news:adifmg$11i5ks$1 at ID-49758.news.dfncis.de... > "Ken" wrote in message > news:adg1do$10nmr5$1 at ID-49758.news.dfncis.de... > > How to do automated emailing when results being processed? > > > > Thanks > > > > What did I do wrong? It crash the program. Without these code, the cgi > script works fine. Thanks > > fromaddr = 'ken at hotmail.com' > toaddrs = 'ken at hotmail.com' > msg = "testing\n" > server = smtplib.SMTP('smtp.aol.com') > server.sendmail(fromaddr, toaddrs, msg) > server.quit() > oh...and I did import smtplib... From walnut at froggy.com.au Sat Jun 1 09:14:58 2002 From: walnut at froggy.com.au (Walnut) Date: Sat, 01 Jun 2002 23:14:58 +1000 Subject: Migrating from PHP to Python... References: Message-ID: On Sun, 2 Sep 2001 19:12:00 -0400, "Rick Shin" wrote: > Hi, > > I'm a PHP man looking to migrate to Python for a change of scenery. I've > skimmed over the specs, but missed a few PHP constructs that I find > essential. Forget them both and go with Perl - the most flexible and powerful language anywhere in the world today. You already know the syntax. From sarmstrong13 at mac.com Sat Jun 8 22:25:23 2002 From: sarmstrong13 at mac.com (SA) Date: Sat, 08 Jun 2002 21:25:23 -0500 Subject: Newbie Question (executing Program from within) Message-ID: Hi Everyone- I'm running Python on Mac OSX. (bsd based system) How do I call a program from outside Python to be run from within my Python script/ In other words if I have an executable file, say "someprogram", how would I execute this program from within a python script. Thanks. SA From jknapka at earthlink.net Thu Jun 13 01:01:36 2002 From: jknapka at earthlink.net (Joseph A Knapka) Date: Thu, 13 Jun 2002 05:01:36 GMT Subject: Python GUI References: <9ddd154e.0206122021.1b06f89a@posting.google.com> Message-ID: <3D0818D3.52D2EF84@earthlink.net> "H. Safarzadeh" wrote: > > Hi all, > I know that this subject is discussed in many other places, but I don't > think it is harmful to talk about it more! > > I want to what library I should use to make GUI for my Python apps? > I have examined many of them, but I couldn't find what I need. Here is > the result of some of my examinations: > > -Tkinter: A nice simple lib, but really simple! It dosn't have enough > widgets, and I do not like its look in addition! > -wxPython: Really perfect. It has many widgets, and do many works(not > only in GUI). But it is toooo big!(both on disk and in memory). I need a > smaller one. > -pyGTK and pyQt: I do not know enough about them. But I know that I do > not like GTK look on Windows and Qt for Windows has some problems with > its lisence(and it is tooo big, too!) > -Jython/Swing: ....it's Jython, after all! > -Win32 extensions: It is not portable!!! > > Any comments? Other possibilities? AnyGUI should be releasing again soon. The last release supported wx, gtk, tk, win32, Jython, and curses - you write your code and it "magically" works unchanged on any of those UI platforms. There were a couple of things missing, notably canvasses (eg Tk's Canvas) and menus; the next release may (or may not) remedy that. Disclaimer: I have worked on Anygui in the past, and hopefully will have time to continue to do so in the future... Cheers, -- Joe "I could feel a small polished stone sinking through the darkest waters of my heart." - Haruki Murakami, "Dance Dance Dance" From ngps at vista.netmemetic.com Tue Jun 11 22:29:31 2002 From: ngps at vista.netmemetic.com (Ng Pheng Siong) Date: 12 Jun 2002 02:29:31 GMT Subject: M2Crypto: select() behaves weird on SSL sockets References: <3D04ED17.5070606@NOSPAMREMOVETHISxs4all.nl> <3D066E77.4070901@NOSPAMREMOVETHISxs4all.nl> Message-ID: According to Irmen de Jong : > I looked around a bit and oh boy, M2Crypto supplies a "pending" > method on SSL sockets, that apparently returns the remaining data. > > I now have a workaround; if my socket is an SSL socket, and > there are still bytes pending (socket.pending()>0), I don't > call select. In all other cases it is 'safe' to call select. > > My code (Pyro with SSL and timeouts) now works, I'm happy :-) Coming late into this thread, good to hear your code now works. ;-) Just wondering: Does your code look contrived structured the way you have? IOW, will any (simple) change(s) to M2Crypto's interfaces make it more natural to express what you wish in this case? Thanks. Cheers. (I'm working hard on my start-up. Very little time for M2Crypto, alas. Don't even have time to read mail and Usenet...) -- Ng Pheng Siong * http://www.netmemetic.com From seeger at sitewaerts.de Wed Jun 12 05:39:57 2002 From: seeger at sitewaerts.de (Felix Seeger) Date: Wed, 12 Jun 2002 11:39:57 +0200 Subject: SyntaxWarning: name 'mailcounter' is used prior to global declaration References: Message-ID: Ahh, I have it. global was used after a mailcounter was used. Felix Seeger wrote: > Hi > > I get this warning. > I set mailcounter as a global var because I have to change it's value from > a method in a class. > This was the only way. How can I remove this warning ? > > Mailcounter is defined at the beginning of the script and "global > mailcounter" is called in the method. > > > thanks > have fun > Felix From kragen at pobox.com Thu Jun 13 14:29:29 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 13 Jun 2002 14:29:29 -0400 Subject: What is a classmethod for? References: <83y9dmokh0.fsf@panacea.canonical.org> Message-ID: <833cvrm3qu.fsf@panacea.canonical.org> Frank Tobin writes: > On 10 Jun 2002, Kragen Sitaker wrote: > > That's so you don't have to write this? > > > > class HostPortAddress(tuple): pass > > def HostPortAddress_from_str(s): > > return HostPortAddress(s.split(':', 1)) > > Well, it makes sense to throw all the 'knowledge' of how to stringify and > de-stringify a HostPortAddress into one class. Yes, that's reasonable. But it seems like a small increment of niceness to justify the conceptual complexity it adds to the language. > > Are there times when it's more compelling? > > Another example would be anytime where you have something that is close to > a staticmethod which is a helper to the instance methods ,but needs some > information that only the class can provide. Helpers for instance methods can be instance methods themselves --- there's no need for staticmethods or classmethods here. From cliechti at gmx.net Sat Jun 15 17:19:29 2002 From: cliechti at gmx.net (Chris Liechti) Date: 15 Jun 2002 23:19:29 +0200 Subject: type(socket) != SocketType References: <3D0BAD4D.5050105@NOSPAMREMOVETHISxs4all.nl> Message-ID: Irmen de Jong wrote in news:3D0BAD4D.5050105 at NOSPAMREMOVETHISxs4all.nl: > Hello > > I have to detect if a certain socket object is a regular socket, > or a M2Crypto SSL socket. I do this by checking type(sock), > and then checking if this is a regular socket type. Why this way? > because the systems that run my code do not necessarily have > M2Crypto installed, and thus I cannot compare the socket to > any class/type from M2Crypto, nor just go ahead and catch SSL > exceptions (simply because they are not defined!). > > There is a problem, however. > With Python 2.2.1 on Windows, type(socket) != SocketType: > > >>> from socket import * > >>> s=socket(AF_INET,SOCK_STREAM) > >>> type(s) > > >>> SocketType > > >>> type(s) is SocketTye > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'SocketTye' is not defined > >>> type(s) is SocketType > 0 > >>> type(s)== SocketType > 0 > >>> > > > I find this most unfortunate, because the docs on the socket module > explicitly state that type(socket)=SocketType. what happens to people with timoutsocket? that module repaces the socket.socket class with a custom one and your check will fail.... > BTW on Linux, all is fine. > > Any clues how to fix things on windows? no, sorry maybe there is a cleverer solution that typechecking. the SSL socket has other/additional attributes etc right?. check for them with has_attr(). or use the __name__ attribute of the class. however, typechecking is probably not the right way to go. chris > Thanks a lot, > Irmen > > -- Chris From Chris.Barker at noaa.gov Fri Jun 7 12:43:48 2002 From: Chris.Barker at noaa.gov (Chris Barker) Date: Fri, 07 Jun 2002 09:43:48 -0700 Subject: constructive critisism on pythonwin IDE References: <6bd9f01b.0206050736.f469082@posting.google.com> <3CFE9861.5090200@skippinet.com.au> Message-ID: <3D00E261.CA641C7E@noaa.gov> > sameer wrote: > > The thing I hate about PythonWin > > is, that despite the fact that it's a development environment, there > > is a lot of caching done of modules, and the cached copy is not > > checked against a potentialy modified copy. Whenever I change the > > contents of a file and try to run a module that depends on that file, > > I always end up with the old copy. I have to then import and then > > reload the changed module in the interactive window for it to refresh. This is how Python works, it's not anything specific to PythonWin. It works this way because a given module might be imported dozens of times in a given Python program, and you would want that to be done fresh each time. Many of the other Python IDEs work this way too. > > It would greatly increase my productivity, if I can specify which > > modules can be cached. What I do is the opposite: I specify which modules can not be cached. When a module is under develpment, I import it this way: import modulename reload(modulename) that way it is guaranteed to be reloaded each time. When it's stable, I jsut comment out the reload line. -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From BPettersen at NAREX.com Thu Jun 13 15:27:46 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Thu, 13 Jun 2002 13:27:46 -0600 Subject: why not "'in' in 'in'"? Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192158ED2@admin56.narex.com> > From: holger krekel [mailto:pyth at devel.trillke.net] > > Bjorn Pettersen wrote: > > > From: Grant Griffin [mailto:not.this at seebelow.org] > > > That's not a bad suggestion, Mark, but if I did that I guess > > > I would be forever wondering if I was testing whether the > > > first one was in the second or the second one was in the > > > first. Again, it doesn't read nearly as well as: > > > > > > if x in subject: > > > ... > > > > > > which leaves no doubt. > > > > Ok, how about: > > > > >>> class mystr(str): > > ... def __contains__(self, s): > > ... return self.find(s) >= 0 > > ... > > >>> 'hello' in mystr('hello world') > > 1 > > >>> 'foo' in mystr('hello world') > > 0 > > >>> > > that's fine. but usually you don't want to make up an > instance for every string you get from somewhere. > I still think that patching 'stringobject.c' to get the > reasonable behaviour might be worth a try for python2.3. > > holger I'm in total agreement, but the issue has been discussed here before on numerous occations... nothing ever came of any of it. -- bjorn From kragen at pobox.com Mon Jun 10 17:52:23 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 10 Jun 2002 17:52:23 -0400 Subject: Changing TK References: Message-ID: <83elfepzs8.fsf@panacea.canonical.org> Eric Brunel writes: > However, both are not referenced at all in Tkinter.py, so "tweaking" it > would not be of any help... When you get a new tcl/tk installation, you > *must* recompile the interpreter, or you won't ever see any change. Well, you must at least recompile the _tkinter extension module; you only need to recompile the interpreter if _tkinter is statically linked into it, which is unusual. > But DON'T EVER replace former tcl/tk libraries by newer ones without > recompiling, even if they have the same name! It *may* work, but if it > doesn't, the tk support in your Python will be completely and definitely > broken... In Linux, at least, if you add new Tcl/Tk libraries with different version numbers, Python and Tkinter will happily continue to use the ones they were built against. From gerhard at bigfoot.de Tue Jun 18 21:52:25 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Wed, 19 Jun 2002 03:52:25 +0200 Subject: tomorrow in yyyymmdd format In-Reply-To: References: <20020619004409.GA2583@lilith.my-fqdn.de> Message-ID: <20020619015225.GB2739@lilith.my-fqdn.de> * Sean 'Shaleh' Perry [2002-06-18 18:38 -0700]: > >> > >> Sure there is :-) time.mktime() can take a "malformed" time tuple and > >> do something sensible with it. You can therefore get a time tuple from > >> gmtime, add one to the day position and call time.mktime() on the > >> result: > >> > >> >>> x = (2002, 2, 29, 0, 31, 42, 2, 170, 0) > >> >>> time.gmtime(time.mktime(x)) > >> (2002, 3, 1, 7, 31, 42, 4, 60, 0) > >> >>> > > > > Pure luck that this works. Don't complain if it stops workin in Python > > 2.7 and your code breaks ;-) > > > > actually that is a function of the mktime() function in the C library which the > python module wraps. Based on my reading of a man page or two this behaviour > seems guaranteed by POSIX. Now, the assumption made is the mktime() function > on YOUR system follows POSIX. Fine. I've just read the Python documentation which doesn't make this guarantee. I'll leave it to others to check if this works on win32, MacOS, as I'm using mxDateTime for this kind of tasks, anyway. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From dev at newdeal.ch Sun Jun 23 14:06:37 2002 From: dev at newdeal.ch (erreur) Date: Sun, 23 Jun 2002 20:06:37 +0200 Subject: How to represent the infinite ? References: <3d11ee9b$1@news.swissonline.ch> <20020620.124436.1266235189.32516@software1.logiplex.internal> Message-ID: <3d160e45@news.swissonline.ch> Thanks.... excelent !! "Cliff Wells" wrote in message news:20020620.124436.1266235189.32516 at software1.logiplex.internal... > In article , "Cliff Wells" > wrote: > > > > > On Thu, 20 Jun 2002 17:02:33 +0200 > > erreur wrote: > > > >> Will somebody have an idea, to represent the infinite one? I have > >> variables to initialize with is +inf (or - inf). To be sure that > >> later, all will be smaller (or larger) than my variables. I tried to > >> redefine the operators on an object. It goes for Inf>10 but I do not > >> arrive for 10>Inf (because that takes > of Int). -------------------- > >> def __gt__(self, val): > >> > >> return 1 > >> -------------------- > > > > Hm, for some reason, my last two posts on this thread didn't seem to go > > through... one more try (with a couple of little enhancements): > > Odd, the newsgroup -> mailing list transfer must be really slow (or down) > today, I pulled up Pan and lo, my posts are there, they just haven't made > it to the mailing list yet (after almost 2 hours). > > Or maybe I accidentally killfiled myself ;) From markus.vonehr at ipm.fhg.de Tue Jun 4 02:33:43 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Tue, 04 Jun 2002 08:33:43 +0200 Subject: Using tcl/tk 8.3.4.2 with Python 2.2 on XP References: <3CFB5994.5B2F9839@tds.net> Message-ID: <3CFC5F47.E1D2C048@ipm.fhg.de> Use the module hackicon to change the window icon: http://sourceforge.net/project/showfiles.php?group_id=30460 Markus "Edward K. Ream" schrieb: > Hi all, > > This may be something trivial, but the answer doesn't seem to jump out > at me from the FAQ or the Tkinter page at: > http://python.org/topics/tkinter/download.html > > I would like to use tcl/tk 8.3.4.2 with Python/tkinter 2.2 on Windows > XP. Apparently the Python 2.2 distribution uses tcl/tk 8.3.2. Is there > some way to use tcl/tk 8.3.4.2 with the binary Python 2.2 distribution > on XP? The thoughts I have: > > 1. set an environment variable somewhere or > 2. just move the 8.3.4.2 dll's into the Python22/tcl folder. > > Neither seems likely to work well, as there may be problems with header > compatibility, and there are more 8.3.4.2 dll's than dll's in > Python22/tcl. > > I hope the next version of Python will come with tcl/tk 8.3.4 or higher > right out of the box. This will allow us to use wm_iconbitmap(bitmap) > to set (at last!) the default icon for tk frames. > > Edward > -------------------------------------------------------------------- > Edward K. Ream email: edream at tds.net > Leo: Literate Editor with Outlines > Leo: http://personalpages.tds.net/~edream/front.html > -------------------------------------------------------------------- From dev at newdeal.ch Thu Jun 20 11:02:33 2002 From: dev at newdeal.ch (erreur) Date: Thu, 20 Jun 2002 17:02:33 +0200 Subject: How to represent the infinite ? Message-ID: <3d11ee9b$1@news.swissonline.ch> Will somebody have an idea, to represent the infinite one? I have variables to initialize with is +inf (or - inf). To be sure that later, all will be smaller (or larger) than my variables. I tried to redefine the operators on an object. It goes for Inf>10 but I do not arrive for 10>Inf (because that takes > of Int). -------------------- def __gt__(self, val): return 1 -------------------- Not need to say to me that I can use 99999999999999 or -99999999999999 or I do not know what. Nor from a MAX_INT of the machine... bus Python can go higher. Thank you for you answers (thank you to also answer by email if possible, because I will not have any more access to the news this weekend). PS: Sorry for my English.... From ykingma at accessforall.nl Sat Jun 8 16:09:36 2002 From: ykingma at accessforall.nl (Ype Kingma) Date: Sat, 08 Jun 2002 21:09:36 +0100 Subject: array, list, performance... References: <3D0108B7.3C206C2E@accessforall.nl> Message-ID: <3D02647C.4FF9CFF7@accessforall.nl> John Machin wrote: > > Ype Kingma wrote in message news: > > Multiplying the list's size by a constant factor when necessary would > > give O(log(len(li)) * len(li)) behaviour > > I'm not sure where you get this from. Here's my take: > > The theoretical amortised cost is O(N), not O(log(N)*N), where N is > the utimate size of the list. > > Let F be the factor by which the list size is expanded when necessary. > Let e be the number of expansions required to grow to size N. > F**e is O(N). > > The ith expansion involves fiddling with O(F**i) elements, with O(1) > cost each. The total of this over e expansions is O(F**e). As above, > F**e is O(N). Thanks. I thought each of the e expansions would involve fiddling with O(N) elements. Perhaps I should post before my working day instead of after... Regards, Ype From trentm at ActiveState.com Wed Jun 19 18:46:54 2002 From: trentm at ActiveState.com (Trent Mick) Date: Wed, 19 Jun 2002 15:46:54 -0700 Subject: Windows versions of Python---pros and cons? In-Reply-To: <3D110B55.4D8AD7FA@astro.cornell.edu>; from loredo@astro.cornell.edu on Wed, Jun 19, 2002 at 06:53:09PM -0400 References: <3D110B55.4D8AD7FA@astro.cornell.edu> Message-ID: <20020619154654.C619@ActiveState.com> [Tom Loredo wrote] > > Hi folks- > > I've been using Python heavily on a Solaris box and a Mac for a > few years now. For reasons I'll spare you from, I now am venturing > into Windows territory (a Dell Inspiron 7500 laptop, if that matters). > I see at least two Windows versions of Python---that at Python.org, > and the ActiveState version. The obvious "pro" for the ActiveState > version is simplicity of the install (batteries included, etc.). > But what about after that? Are their substantial differences between > the versions that I will bump into down the line? ActivePython should be 100% binary compatible with the Python installer on python.org. If not, it is a bug. The only real "substantial" difference, as far as your code is concerned, is the presence of some Python extensions like PyWin32. > In particular, I write many C extensions; can one use distutils and > the Borland or gcc free compilers to build C extensions in both > versions? My understanding is that for C extensions to work they must be built with the same compiler as that used to build the Python with which they will run. (I may be wrong. Someone please correct me if I am.) Visual C++ 6.0 is used to build ActivePython and a python.org's Python for Windows. This means that you would have to build Python yourself from source with your free compiler to be able to run your extensions built with the free compiler. Cheers, Trent -- Trent Mick TrentM at ActiveState.com From zsmith at ponymail.com.nospam Sat Jun 15 04:50:21 2002 From: zsmith at ponymail.com.nospam (Zach) Date: Sat, 15 Jun 2002 08:50:21 GMT Subject: Newbie deluxe Message-ID: I've just started taking a look at Python (experienced in Delphi) and so far it looks very clean and comprehensible. My question is, what are the fundamental differences and similarities between it and Perl? I hear so much about these two languages, especially in Linux circles and just wondered what sets them apart. Can full fledged graphical applications be built with Python or does it lean more towards scripting? I'm aware that it has OOP capabilities so I assume it reaches beyond just scripting but like I said, I've no experience with it. I would like to broaden my coding skills with the addition of another language so any general opinions with regards to its usefulness are appreciated. TIA. Zach From paul at soniq.net Sun Jun 16 17:06:29 2002 From: paul at soniq.net (Paul Boehm) Date: Sun, 16 Jun 2002 23:06:29 +0200 Subject: HT telnet interact with auto login? In-Reply-To: <3d0cd198.17917980@news.zrz.tu-berlin.de> References: <3d0cd198.17917980@news.zrz.tu-berlin.de> Message-ID: <20020616210629.GA20626@soniq.net> is this what you want? # On Sun, Jun 16, 2002 at 06:07:30PM +0000, Klaus Reinhardt wrote: import getpass import sys import telnetlib HOST = "...de" tn = telnetlib.Telnet(HOST) user = '...' password = '...' # 2.) tn.read_until("login: ") # this seams to work # but without connection tn.write(user + "\n") if password: tn.read_until("Password: ") tn.write(password + "\n") # 1.) tn.interact() # this is working but with manually .. From not.this at seebelow.org Thu Jun 13 13:09:46 2002 From: not.this at seebelow.org (Grant Griffin) Date: 13 Jun 2002 10:09:46 -0700 Subject: why not "'in' in 'in'"? References: Message-ID: In article , "Mark says... > >> That's not a bad suggestion, Mark, but if I did that I guess I >> would be forever wondering if I was testing whether the first one >> was in the second or the second one was in the first. > >Since you insist on torturing yourself, then, why not name the function: > > def is_the_second_in_the_first(a, b): > ... > >;-) Naw, you got me all wrong. If torture was what I was after, I'd use lambda and not name it anything at all: >>> subject = 'spam, eggs, sausage, spam' >>> eggs = 'eggs' >>> if lambda x, y:y.find(x) >= 0(eggs, subject): ... print 'eggs is in subject' ... eggs is in subject or-better-yet,-write-it-in-perl--ly y'rs, =g2 _________________________________________________________________________ Grant R. Griffin g2 at dspguru.com Publisher of dspGuru http://www.dspguru.com Iowegian International Corporation http://www.iowegian.com From jadestar at idiom.com Wed Jun 19 00:20:46 2002 From: jadestar at idiom.com (James T. Dennis) Date: 19 Jun 2002 04:20:46 GMT Subject: Medium to Large Scale Python Deployments References: <34b82fda.0206061639.67964684@posting.google.com> Message-ID: Stuart Quimby wrote: [top posting corrected] > "Domenic R. Merenda" wrote: >> Greetings, >> I am running a home-grown Enterprise Resource Planning system, written >> entirely in Python, to manage the operations and manufacturing aspects of a >> medium ($100,000,000 annual sales) manufacturing organization. I would be >> interested in hearing from other individuals who are likewise "betting the >> farm" on Python as an ERP or MRP solution, and some of the experiences they >> may have had. > You may be interested in the gnuenterprise project. They are > developing a multi-tier db independant ERP that is open-source. > Details can be found at http://www.gnuenterprise.org. > Stuart Quimby Notably GNUe makes extensive use of Python and PostgreSQL. From duncan at NOSPAMrcp.co.uk Fri Jun 14 05:07:31 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 14 Jun 2002 09:07:31 +0000 (UTC) Subject: Date formats References: <3D09A1B1.6040705@mxm.dk> <3D09ABEB.4000209@mxm.dk> Message-ID: Max M wrote in news:3D09ABEB.4000209 at mxm.dk: > Oh ... I cannot seem to find it in the docs. The closest I come is in: > > 2.2.6.2 String Formatting Operations > > where it says that: > > "# The value conversion will use the ``alternate form'' (where defined > below)." > In 6.9, time: """Additional directives may be supported on certain platforms, but only the ones listed here have a meaning standardized by ANSI C. On some platforms, an optional field width and precision specification can immediately follow the initial "%" of a directive in the following order; this is also not portable. The field width is normally 2 except for %j where it is 3""" The meaning of the additional directives is not in the Python documentation: I used MSDN for that. Microsoft's runtime doesn't support field width and precision, but does use the # flag. In case you didn't know, time.strftime calls the underlying C runtime strftime with a buffer 256 times longer than the format string (since there is no way to know how long a buffer is required). -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From gmuller at worldonline.nl Sun Jun 16 05:46:25 2002 From: gmuller at worldonline.nl (GerritM) Date: Sun, 16 Jun 2002 11:46:25 +0200 Subject: Minor install annoyance on Activestate Python 2.2.1 build 222 References: <3D0BF7B4.21096694@bellatlantic.net> Message-ID: "David Lees" schreef in bericht news:3D0BF7B4.21096694 at bellatlantic.net... > I just downloaded and installed the latest ActiveState build of Python > 2.2.1 off their site and could not get it to install on my win98SE box > even though I had previously run the windows installer. The problem > turns on to be that the name of the file you download is > ActivePython-2.2.1-222.msi.exe > Simply remove the '.exe' extension so the name is: > ActivePython-2.2.1-222.msi and the installation goes just fine. > > David Lees Quite strange, I installed ActivePython-2.2.1-222 last thursday, freshly downloaded and did not have this (or any other) problem. regards Gerrit -- www.extra.research.philips.com/natlab/sysarch From jiri at baum.com.au Wed Jun 5 04:21:12 2002 From: jiri at baum.com.au (Jiri Baum) Date: Wed, 5 Jun 2002 18:21:12 +1000 Subject: Graph distances, how can I speed it up? References: <33803989.0206030235.4134d33e@posting.google.com> Message-ID: Miki Tebeka: > I'm trying to calculate distances in a graph. (The ultimate goal is to > calculate the distances between verbs in WordNet) > The graph is built edge after edge and each time I recalculate the > distances matrix. However this takes ages to complete. (will finish in > ~50H). The matrix version of this might be more efficient, the one that solves the whole thing as a set of simultaneous equations... I think it'd involve one matrix inversion to begin with, and then a dot product each time you need a distance, but I'd have to check. Make sure you use a sparse matrix library if your matrix is sparse (and it will be) - it can take quite some shortcuts. Jiri -- Jiri Baum http://www.csse.monash.edu.au/~jirib MAT LinuxPLC project --- http://mat.sf.net --- Machine Automation Tools From jamespp35 at yahoo.com Fri Jun 28 15:45:25 2002 From: jamespp35 at yahoo.com (Jim Henry) Date: Fri, 28 Jun 2002 12:45:25 -0700 Subject: incorrect upper()/lower() of UTF-8 Message-ID: It appears that python does not uppercase/lowercase utf-8 strings properly: char latin-1 utf-16 utf-8 ? F1 00F1 C3B1 ? D1 00D1 C391 # create unicode/UTF-16 string with ? >>> s = u"set description to ma?ana" >>> s u'set description to ma\xf1ana' <= correct latin-1 or UTF-16 (F1) # encode it as utf-8 >>> s8 = s.encode("utf8") >>> s8 'set description to ma\xc3\xb1ana' <= correct UTF-8 (C3B1) # upshift the UTF-16 string >>> s.upper() u'SET DESCRIPTION TO MA\xd1ANA' <= correct latin-1 or UTF-16 (D1) # upshift the UTF-8 string >>> s8.upper() 'SET DESCRIPTION TO MA\xc3\xb1ANA' <= INCORRECT: should be C391 # updshift the UTF-8 string and convert back to UTF-16 >>> t = s8.upper() >>> t 'SET DESCRIPTION TO MA\xc3\xb1ANA' >>> u.encode("latin-1") 'SET DESCRIPTION TO MA\xf1ANA' <= INCORRECT, will print as "MA?ANA" instead of "MA?ANA" Am I missing something?? From bokr at oz.net Sun Jun 2 21:33:05 2002 From: bokr at oz.net (Bengt Richter) Date: 3 Jun 2002 01:33:05 GMT Subject: variable X procuct - [(x,y) for x in list1 for y in list2] References: <1022619068.34271@newsmaster-04.atnet.at> <1022686332.297659@newsmaster-04.atnet.at> <20020531215914.15202822.larooy@xtar.co.nz> Message-ID: On Fri, 31 May 2002 21:59:14 +1200, John La Rooy wrote: >Perhaps the translation is correct, but the example you give is a cartesian product, not a cross product. >From my algebra book... > > >In many applications of vectors to problems in geometry, physics, and engineering it is of interest to construct a vecotr in 3-space that is perpendicular to two given vectors. In this section we introduce a type of vector multiplication the facilitates this construction > > >DEFINITION: If u=(u1,u2,u3) and v=(v1,v2,v3) are vectors in 3-space, then the cross product >is the vector defined by >u x v = (u2v3 - u3v2 , u3v1 - u1v3 , u1v2 - u2v1) And if i,j,k are the unit vectors, you can also write this as the determinant of the matrix i j k u1 u2 u3 v1 v2 v3 (which is easier to remember for me). The direction of the result is perpendicular to the plane that includes u and v, in the direction a right-hand screw would move if turned as u rotates into v (assuming a right hand coordinate system). Easy to see with pure x and y axis vectors: i j k u1 0 0 0 v2 0 => k*(u1*v2) (+ in the z direction of unit vector k) vs the same vectors but turning the other way (v x u): i j k 0 v2 0 u1 0 0 => -k*(v2*u1) (also along z axis but opposite direction) thought I'd mention, in case someone hadn't seen this before ;-) Regards, Bengt Richter From storminDOTnorm at excite.com Tue Jun 11 15:01:47 2002 From: storminDOTnorm at excite.com (Stormin) Date: Tue, 11 Jun 2002 15:01:47 -0400 Subject: filecmp.cmpfiles on directories Message-ID: <3D06491B.302@excite.com> Hi python pros! I am trying to walk a directory structure and compare directories for duplicates. For some reason I get the filecmp to work on individual files, but not on directories. note: I tried also with double backslash and with backslashes at the end of the directory name - no go. (i.e. c:\\comp1\\) example: DOES NOT WORK: dups=filecmp.cmpfiles("C:\comp1","c:\comp2",common) print dups,"||",common result: ([],[],[])|| WORKS: dups=filecmp.cmp("c:\comp1\testfile.txt","c:\comp1\testfile.txt") print dups result: 1 From maxm at mxm.dk Thu Jun 20 19:06:48 2002 From: maxm at mxm.dk (Max M) Date: Fri, 21 Jun 2002 01:06:48 +0200 Subject: application development - separating content from function References: Message-ID: <3D126008.9090603@mxm.dk> Chris Liechti wrote: > start with: > def _(s): return s > > and write all the string you want to localize later with > _("hello") > _("this can be translated later by replacing the _ function") > > later you can use locale or a simple dictionary lookup to translate. > i saw that technique in "cplay" http://www.tf.hut.fi/~flu/cplay/ > > simple with a dict: > translation = {'hello':'ole'} > def _(s): > return translation.get(s,s) I have a small class I sometimes use when I need to do i18n. class I18n: "Very simple i18n" def __init__(self, textBundle, language='uk'): self.language = language self.textBundle = textBundle def __call__(self, id): language = getattr(self, 'language', self.language) return self.textBundle[language].get(id, 'TRANSLATION MISSING!!') textBundle = {} textBundle['dk'] = {} textBundle['dk']['name'] = 'Navn' textBundle['dk']['address'] = 'Danmark' textBundle['dk']['date_format'] = '%d-%m-%Y %H:%M:%S' textBundle['dk']['money_format'] = '%.2f' textBundle['uk'] = {} textBundle['uk']['name'] = 'Name' textBundle['uk']['address'] = 'Denmark' textBundle['uk']['date_format'] = '%Y.%m.%d %H:%M:%S' textBundle['uk']['money_format'] = '%.2f' language = 'dk' i18n = I18n(textBundle, language) print i18n('names') This works to my satisfaction most of the time. ############################################################## A pattern I frequently use is the view- Adapter/wrapper:: The idea is that the "logic" object is a python object with python types and methods as attributes. To make a view of this ie. on a html page I create an adapter that takes the logic view as a creation parameter, and then it puts a shell/wrapper around the logic object to create a view without changing anything in the logic object. ############################################################### ## The logic object class User: def __init__(self): self.firstName = 'Max' self.lastName = 'M?ller Sneaky code' self.answer = 42 self.books = [ 'Learning Python', 'Python Essential Reference', 'Python & XML' ] ## The view adapter/wrapper # allways escape untrusted code ! import cgi class HtmlViewAdapter: "this can be subclassed for several views" def __init__(self, obj): self._obj = obj def __getitem__(self, item): "Makes usage from string formatting easy" value = getattr(self, item) if callable(value): return str(value()) else: return str(value) class UserHtmlViewAdapter(HtmlViewAdapter): def firstName(self): return cgi.escape(self._obj.firstName) def lastName(self): return cgi.escape(self._obj.lastName) def answer(self): return self._obj.lastName def books(self): return '\n'.join( ['Title %s
' % cgi.escape(book) \ for book in self._obj.books]) userTemplate = """
First name: %(firstName)s
Last name: %(lastName)s
Answer: %(answer)s
Booklist:
%(books)s
""" user = User() # pass the view adapter the user userHtmlViewAdapter = UserHtmlViewAdapter(user) # render the view userHtmlView = userTemplate % userHtmlViewAdapter print userHtmlView ############################################################### The userHtmlViewAdapter can also be used for outputting directly to an .asp page like: ############### <% userView = UserHtmlViewAdapter(user) %> <%
First name: <%= userView.firstName()%>
Last name: <%= userView.lastName()%>
Answer: <%= userView.answer()%>
Booklist:
<%= userView.books()%>
%> This gives a good seperation of logic and view, and it's easy to see months later where to put the generation of view. You can also keep as much of your code as possible in pure Python modules this way. Making it easier to test, debug, cross-platform etc. regards Max M From anoop79 at myrealbox.com Thu Jun 13 02:44:47 2002 From: anoop79 at myrealbox.com (Anoop P B) Date: Thu, 13 Jun 2002 12:14:47 +0530 Subject: tray icon using tkinter Message-ID: <3D083F5F.5030209@myrealbox.com> hi, is there a way that i can provide a tray icon ie. next to the clock (on win32) for my program (using tkinter) ? i know that there is a way of doing this in wxpython but i need to know whether its possible in tkinter. thanks, anoop From gerhard.haering at gmx.de Fri Jun 21 04:28:46 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Fri, 21 Jun 2002 10:28:46 +0200 Subject: compile python witout tkinter In-Reply-To: References: <20020621075938.GA896@lilith.my-fqdn.de> Message-ID: <20020621082846.GA933@lilith.my-fqdn.de> * kosh at aesaeion.com [2002-06-21 01:55 -0600]: > On Fri, 21 Jun 2002, Gerhard [iso-8859-15] H?ring wrote: > > > * kosh at aesaeion.com [2002-06-21 01:40 -0600]: > > > On Fri, 21 Jun 2002, Gerhard [iso-8859-15] H?ring wrote: > > > > > > > * kosh at aesaeion.com [2002-06-21 01:26 -0600]: > > > > > On a machine I need to build python on I need to build it without tkinter. > > > > > > > > Why? Even if Tkinter gets compiled, it doesn't change anything for the > > > > rest. You could even delete the tkinter modules afterwards, if you're > > > > short on disk (quota). > > > > > > Because the libraries it depends on are not installed on that machine and > > > there is no point installing them since they are not needed. > > > > No problem, then. It won't get built if the dependencies are not met. > > As seen in Modules/Setup. > > The problem is that it is trying to build it ayways. All the tkinter lines > in Modules/Setup that I can find are commented out but it doesn't seem to > have done any good. It looks like in Python 2.1.3, Tkinter gets built with distutils in Python's setup.py. I fear I don't have a solution to your problem, as detect_tkinter in Python 2.1.3's setup.py looks fine to me. Maybe you have a very strange or broken Tcl/Tk setup on your machine. As a temporary workaround, you could try to insert a return right at the beginning of detect_tkinter in Python's setup.py. I sincerly hope some Tkinter expert here can come up with a better solution and help finding the real reason behind this. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 24.5 ?C Wind: 2.1 m/s From jdhunter at nitace.bsd.uchicago.edu Sat Jun 29 10:48:51 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Sat, 29 Jun 2002 09:48:51 -0500 Subject: get word base References: Message-ID: Thanks Daniel and Bengt; excellent suggestions both. I have installed both packages and put them into a head to head competition. It appears to me on a VERY LIMITED sample, that wn does better than stemmer. The only error (ie not what I expected) in wn was with 'walking', which stemmer got. So I merged them together for the mother of all morphological root finders. import Stemmer, wntools st = Stemmer.Stemmer('english') def wnroot(w): return wntools.morphy(w, "noun") or \ wntools.morphy(w, "verb") or \ wntools.morphy(w, "adjective") or \ wntools.morphy(w, "adverb") def stemmer_or_wn(word): root = wnroot(word) if root != word: return root return st.stem(word) words = ['sent', 'walking', 'thoughts', 'rakes', 'eaten', 'tried'] print 'words : ', words print 'stemmer : ', st.stem( words ) print 'wntools : ', [wnroot(w) for w in words] print 'combo : ', [stemmer_or_wn(w) for w in words] ~/python/examples $ python wordnet_demo.py words : ['sent', 'walking', 'thoughts', 'rakes', 'eaten', 'tried'] stemmer : ['sent', 'walk', 'thought', 'rake', 'eaten', 'tri'] wntools : ['send', 'walking', 'thought', 'rake', 'eat', 'try'] combo : ['send', 'walk', 'thought', 'rake', 'eat', 'try'] Thanks for the help, John Hunter From spam at fisher.forestry.uga.edu Tue Jun 4 10:24:56 2002 From: spam at fisher.forestry.uga.edu (Chris Fonnesbeck) Date: 4 Jun 2002 07:24:56 -0700 Subject: weave.accelerate? Message-ID: I'm trying to locate a version of weave that includes the accelerate() function; the version posted on scipy.org doesnt seem to have it. Can anyone point me in the right direction. Thanks, cjf From dysfate at gmx.de Fri Jun 14 09:36:37 2002 From: dysfate at gmx.de (Johannes Stiehler) Date: 14 Jun 2002 15:36:37 +0200 Subject: Writing a simple linux daemon type thing... References: Message-ID: Sorry, typo, I meant: redirect the output to /dev/null !! -- Johannes Stiehler CIS der LMU M?nchen From shalehperry at attbi.com Fri Jun 7 11:47:22 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 07 Jun 2002 08:47:22 -0700 (PDT) Subject: Detecting OS and Window Manager In-Reply-To: <3d00d248$1_1@hpb10302.boi.hp.com> Message-ID: > > Maybe import your kde module(s), and then try to do something KDE specific > without KDE running and see what kind of error this causes so you will know > what to trap for? Hopefully some other newbie (for a much less significant > value of new, AKA expert) is still following this thread to give you a > better answer. > there is no way to be sure what he wants is running. He could do a NET_WM_* check and see if a netwm compliant wm was running. He could then request from this wm a window list and see if any of those windows claim to be taskbars. The point is, X is designed to make this hard. One app should only use the interfaces out there and not ask for an implementation (yep, that thread again). Shaleh blackbox window manager co-author From vjovanov at stevens-tech.edu Wed Jun 5 14:40:45 2002 From: vjovanov at stevens-tech.edu (Vojin Jovanovic) Date: Wed, 5 Jun 2002 14:40:45 -0400 Subject: self References: <0%hL8.22575$tK.5490038@news02.optonline.net> <_zpL8.81$pq2.4342892@newnews.cc.stevens-tech.edu> Message-ID: > no his questions go deeper :-) I am glad that somebody here recognizes that. > For every name in such a value you need to evaluate its value again. > IOW it's recursive. The obvious solution is to intercept the namevalue-lookups > during evaluation of an equation. But this doesn't work for exec/eval: > They ignore the interception points. Correct. Every evaluation has to go through __getattr__ method in order to access the instance variables of the object, but that, unfortunately, can only be done with self. This is needed since the left hand sides of the equations must be the variables of the instance and not just some key values in a dictionary. > The next best solution IMO is to preprend a namescope like 'self.' > to every name in an expression. > But you may have to parse the expression to > do this. I have been thinking about this for some time, and realized that there some tricky cases that one has to deal with, and I am not sure that the whole business of appending self. will be error free in every case. For example in 'x + Geometry.x' the correct result should be 'self.x + self.Geometry.x' where Geometry is an instance of Geometry class that is bound to self.Geometry. So one has to distinguish between two names of x in two different places. Maybe stuff like this is not even so tricky. I don't know at this point, I haven't looked at that too closely yet to decide the feasibility of such an approach. I am still trying to resolve the problem in an easier way with whatever Python is offering to me. > Maybe fixing exec/eval behaviour is a better idea? Well, I don't know how to proceed in this regard. I am not familiar with the source code. It seems that the only two options are 1) work directly on the input string or 2) parse the expression and try to correctly append self. in front of the variables. V. Jovanovic From andreas.ames at Tenovis.com Fri Jun 21 07:03:35 2002 From: andreas.ames at Tenovis.com (Andreas Ames) Date: 21 Jun 2002 13:03:35 +0200 Subject: Windows versions of Python---pros and cons? In-Reply-To: <3D1214B6.E9BB77D2@noaa.gov> References: <3D110B55.4D8AD7FA@astro.cornell.edu> <3D1214B6.E9BB77D2@noaa.gov> Message-ID: Hi, Chris Barker writes: > resorting to Py2exe and the like. What I want is something just like: > > chmod +x scriptname > and a #! line at the top Alternatively you can use cygwin here. It comes with it's own python port. cheers, andreas From mwh at python.net Fri Jun 14 05:33:10 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 14 Jun 2002 09:33:10 GMT Subject: filter2 References: Message-ID: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) writes: > It's not that gross, but it only gives 14% speedup, though. Oh yeah. What you've done is kind of obvious... > def filter2a(test, list): > l1 = [] > l2 = [] > funcs = [l1.append, l2.append] > map(lambda x: funcs[not test(x)](x), list) > return l1, l2 > > BTW, what's the reason that using a list for funcs is faster than using a > tuple (as observed under Python 2.2.1 on Linux)? Look at BINARY_SUBSCR in ceval.c... list[int] is special-cased. Cheers, M. -- Ability to type on a computer terminal is no guarantee of sanity, intelligence, or common sense. -- Gene Spafford's Axiom #2 of Usenet From spammers.do.not.bother at void.bogus Sun Jun 23 15:05:14 2002 From: spammers.do.not.bother at void.bogus (Magnus) Date: Sun, 23 Jun 2002 19:05:14 GMT Subject: sys.exc_info() into string Message-ID: Hi, in my program I am catching exceptions that I might have missed by using something like: try: doMyStuff() except: type = sys.exc_info()[0] syslog.syslog(syslog.LOG_EMERG, "My program: unexpected error" + type) The thing is that I can not figure out how to make "type" into a string above so I can use it for e.g. syslog(). Is there an easy way of doing this? Thanks, Magnus From loewis at informatik.hu-berlin.de Wed Jun 12 05:07:59 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 12 Jun 2002 11:07:59 +0200 Subject: compiling error: undefined symbol: __gxx_personality_v0 References: <93523ebb.0206110732.791e745@posting.google.com> Message-ID: dubreus at csit.fsu.edu (mitsch) writes: > gcc -shared -lc getting_started1.o -o getting_started1.so You need to link with g++, not gcc. Regards, Martin From hesterloli at hotmail.com Mon Jun 24 22:47:05 2002 From: hesterloli at hotmail.com (George Hester) Date: Tue, 25 Jun 2002 02:47:05 GMT Subject: enlightenment (Re: python cgi + IIS) References: <3D0F1813.3010304@gmx.de> <3D102AF2.5010204@gmx.de> <3D13522E.6010703@gmx.de> Message-ID: That's right you change it at the server not at the Web. -- George Hester _________________________________ "Axel Grune" wrote in message news:3D13522E.6010703 at gmx.de... > > for, and so forth) give an account of all the steps you have performed > > This steps: http://www.e-coli.net/pyiis.html > > This doc tells you to change the 'App Mapping' in the properties of > [IISAdmin] to enable the execution of python files for the entire server > but for any reason it doesn't work. > In the end our admin suggested to change the properties of 'Default Web > Site' (the node above [IISAdmin]) and then it works. > > Thanks, > Axel > > > -- > > please check /dev/zero for further information > From joe at notcharles.ca Fri Jun 7 15:36:26 2002 From: joe at notcharles.ca (Joe Mason) Date: Fri, 07 Jun 2002 19:36:26 -0000 Subject: Using popen interactively References: Message-ID: In article , Donn Cave wrote: > Right. I expect you'd do better to throw away the file objects > popen2 makes for you, and use the pipe file descriptors directly. > Instead of > infile = app.fromchild > ... > line = infile.readline() > say > infile = app.fromchild.fileno() > ... > data = posix.read(infile, 8192) > # split into lines if you care Ah! Light begins to dawn. Thank you very much. Joe From m_anderson14 at hotmail.com Tue Jun 25 15:12:40 2002 From: m_anderson14 at hotmail.com (Michael Anderson) Date: 25 Jun 2002 12:12:40 -0700 Subject: ASP only runs once Message-ID: <3842735a.0206251112.25609e37@posting.google.com> Hello, I've been using python in my asp pages for over a year now with no problems, and just ran into a problem I can't figure out. I installed it on a new machine and my pages only run the first time you hit them. After that they do nothing. Pages in VBScript and JavaScript run fine. If you edit the file and save it, it will run one time and then nothing. Since a regular script gets compiled to a .pyc on the first execution, I'm guessing it is somehow related. But I don't know how it works in an asp page. Has anyone had this problem? My configuration is Win2000 Pro, IIS 5, Python 2.1.3, win32all build 145. I also tried it with Python 2.2 and win32all 146 but get the same results. Thanks. Mike From pyth at devel.trillke.net Tue Jun 11 20:13:03 2002 From: pyth at devel.trillke.net (holger krekel) Date: Wed, 12 Jun 2002 02:13:03 +0200 Subject: RfD: Automagically making a class instance 'synchronized' (draft impl.) In-Reply-To: <20020611233740.GA28544@lilith.my-fqdn.de>; from gh_pythonlist@gmx.de on Wed, Jun 12, 2002 at 01:37:40AM +0200 References: <20020611205423.GA28113@lilith.my-fqdn.de> <20020612000425.U6609@prim.han.de> <20020611233740.GA28544@lilith.my-fqdn.de> Message-ID: <20020612021303.V6609@prim.han.de> Gerhard H?ring wrote: > ... > Btw. I've only recently started to seriously experiment with > multithreading. Have you read my recent post > > Message-ID: > with the title "Need advice on multithreading problem" > > ? I find it really nifty. It's about wrapping a C library function that > uses callbacks to Python generators. I'd welcome any comments on the > approach I've taken there (Queue.Queue, a deferred producer thread with > the generator in the main thread being the consumer). I think i read it. Although i know something about bigger multithreaded applications (ACE/c++) and some things about python i haven't really digged into the c-extension api so i can't be of much help there. But i am going to enter the wonderful world of extensions Real Soon Now (tm). good luck anyway, holger From mt at open2web.com Thu Jun 20 22:45:49 2002 From: mt at open2web.com (Don Low) Date: 21 Jun 2002 02:45:49 GMT Subject: newbie string question Message-ID: There's probably a very simple explanation, but I can't see it for now, so bear with me. >>>pystr = 'Python' >>>pystr = [5] 'n' >>>pystr [2:5] 'tho' The question is, why isn't pystr [2:5] 'thon' instead of 'tho'. Could somebody explain? -- Thanks, Mark From rpm1deletethis at nospamfrontiernet.net Mon Jun 24 06:56:24 2002 From: rpm1deletethis at nospamfrontiernet.net (RPM1) Date: Mon, 24 Jun 2002 06:56:24 -0400 Subject: Python hits the spot References: <3D1482AE.8FA299D8@kfunigraz.ac.at> <3D14CF95.4030501@kfunigraz.ac.at> <3D158F3E.1010907@kfunigraz.ac.at> <3D16DD5C.1050708@kfunigraz.ac.at> Message-ID: "Siegfried Gonzi" wrote in message news:3D16DD5C.1050708 at kfunigraz.ac.at... > Bengt Richter wrote: > > On Sun, 23 Jun 2002 11:05:02 +0200, Siegfried Gonzi wrote: > > Someone guessed that maybe my processor got too hot. Therefore: what > about a small script of the form: processor 99% ; memory 5%. > > That could at least clarify whether the processor becomes to hot after > beeing used without breaks. > > Writing the memory consumption script was easy, but I do not have any > clue how to write a processor consumption script. > Hey! That's why I was asking if your laptop was a Hewlitt Packard. I had a Hewlitt Packard Pavillion laptop that would die when the fan kicked on. Any chess program will keep your CPU at 100%. GnuChess is probably on your system now. If not, it is a free program. Ask around on rec.games.chess.computer if you need help. Patrick From garyr at fidalgo.net Thu Jun 27 11:21:26 2002 From: garyr at fidalgo.net (Gary Richardson) Date: Thu, 27 Jun 2002 08:21:26 -0700 Subject: connecting embedded Python audio samples with NumPy? References: <3D1B2603.26EA9A9C@fxtech.com> Message-ID: I've written wrappers using CXX for a few FFTW functions that use Python arrays to pass data to/from the library functions. I'll be happy to send you the wrapper code and some example Python code if that would be of interest. Gary Richardson "Paul Miller" wrote in message news:3D1B2603.26EA9A9C at fxtech.com... > I have a C app that reads audio data, and I'd like to pass this audio > data in array format to Python functions so I can use it with NumPy. > > I have this working right now - generating a float array from the sample > stream. But I want to put this array into a form usable by the FFT > functions. I've read over this paper: > > http://www.onlamp.com/pub/a/python/2001/01/31/numerically.html > > Which indicates I need to put my 1D sample stream into a 2D array. Can > anyone elaborate more on this? I'm wondering if I should provide the > array pre-made for FFTs from my C code, or I should build the 2D array > from the 1D array I have in Python. From whisper at oz.net Wed Jun 19 21:12:21 2002 From: whisper at oz.net (David LeBlanc) Date: Wed, 19 Jun 2002 18:12:21 -0700 Subject: using os.chmod in windows In-Reply-To: Message-ID: Well, that was bone-breakingly stupid of me. The 8th group is the last access time LOL. The first group is the mode bits, and that means nothing happened when the hidden attribute was set from the File Explorer - unless I caught some refresh lag. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of David LeBlanc > Sent: Wednesday, June 19, 2002 17:43 > To: Locke; python-list at python.org > Subject: RE: using os.chmod in windows > > > I didn't find any doc for this, so I tried the simple expedient of: > > # Attrtest.py > > import os > > os.stat('testfile.txt') > > raw_input('Change file attribute using File Explorer, then press return') > > os.stat('testfile.txt') > > When I did this, I got: > > (At the start, normal r/w file) > >>> os.stat('testfile.txt') > (33206, 0L, 9, 1, 0, 0, 26L, 1024026085, 1023320564, 1023320564) > (Add hidden attribute using File Explorer) > >>> os.stat('testfile.txt') > (33206, 0L, 9, 1, 0, 0, 26L, 1024532993, 1023320564, 1023320564) > (Add readonly in addition to hidden) > >>> os.stat('testfile.txt') > (33060, 0L, 9, 1, 0, 0, 26L, 1024532997, 1023320564, 1023320564) > > Notice that the last five digits (an int in decimal) of the 8th group have > changed. How you parlay that into something chmod() can use, I > have no idea. > > HTH, > > David LeBlanc > Seattle, WA USA > > > -----Original Message----- > > From: python-list-admin at python.org > > [mailto:python-list-admin at python.org]On Behalf Of Locke > > Sent: Wednesday, June 19, 2002 15:59 > > To: python-list at python.org > > Subject: using os.chmod in windows > > > > > > I never really learned the number codes for file permissions in UNIX. I > > always just did "chmod +r" because it is much easier to remember. I need > > to change a file to be 'hidden' in windows. In UNIX, this is done by > > renaming it with a dot in front of the name. But the python os.chmod > > command says you need to specify the number as the argument. As far as I > > know, there is no number for 'hidden' since it is windows only. So how > > do I do this? > > > > Thanks. > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > -- > http://mail.python.org/mailman/listinfo/python-list From SBrunning at trisystems.co.uk Tue Jun 18 06:56:20 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Tue, 18 Jun 2002 11:56:20 +0100 Subject: Can python have lib to display PDF ? Message-ID: <31575A892FF6D1118F5800600846864DCBD3B7@intrepid> > From: menucool at yahoo.com.cn [SMTP:menucool at yahoo.com.cn] > > i want a python application to display end edit pdf. > where are the lib pdf for python? > thank Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From stefnin.nospam at yahoo.fr Wed Jun 19 08:55:32 2002 From: stefnin.nospam at yahoo.fr (Stephane Ninin) Date: 19 Jun 2002 12:55:32 GMT Subject: tkinter menu (newbie question) References: Message-ID: Eric Brunel a tapote dans news:aepps0$al$1 at wanadoo.fr: Thanks for the help. > This doesn't suffice. With all that code, you just created a frame > that has an attribute named menubar with the menu in it, but you > didn't do anything to actually display the menu (there's no "magical" > attributes in Python: if you do not do something with an attribute, it > is only just that, an attribute...). > > What you should do is to make MyApp a sub-class of Tk instead of Frame > (this is more pratical this way), and add at the end of the > constructor the line: > > self.configure(menu=self.menubar) > If I want to use several of these windows, can still use for base class Tk, instead of Frame ? > And that should do the work. Oh: and don't forget to add parameter > "self" to your "nothing" method, or you'll get a nice traceback when > you do File->Quit... > Yep... already had it before :) I am not completely used to this self first parameter yet. Thanks again. -- Stephane Ninin stefnin.nospam at yahoo.fr Les cons, ca ose tout... C'est meme a ca qu'on les reconnait. From michal.cernoevic at pvt.cz Mon Jun 24 08:28:13 2002 From: michal.cernoevic at pvt.cz (Michal Cernoevic) Date: Mon, 24 Jun 2002 14:28:13 +0200 Subject: Compilation error - no module named os Message-ID: Excuse my question, but I am unable to compile Python 2.2.1 on Linux 2.4.9-31. I only did tar, cd Python-2.2.1; ./configure; make and the compilation finished so: *-s*) CC='gcc' LDSHARED='gcc -shared' OPT='-DNDEBUG -g -O3 -Wall -Wstrict-prototypes' ./python -E ./setup.py -q build;; \ *) CC='gcc' LDSHARED='gcc -shared' OPT='-DNDEBUG -g -O3 -Wall -Wstrict-prototypes' ./python -E ./setup.py build;; \ esac Could not find platform independent libraries Consider setting $PYTHONHOME to [:] 'import site' failed; use -v for traceback Traceback (most recent call last): File "./setup.py", line 6, in ? import sys, os, getopt ImportError: No module named os make: *** [sharedmods] Error 1 Thanks for some ideas. With regards Michal Cernoevic From gerhard at bigfoot.de Tue Jun 18 22:21:10 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Wed, 19 Jun 2002 04:21:10 +0200 Subject: procmail replacement in Python In-Reply-To: References: <20020618235901.GA2197@lilith.my-fqdn.de> Message-ID: <20020619022110.GA6996@lilith.my-fqdn.de> * Fran?ois Pinard [2002-06-18 21:55 -0400]: > [Gerhard H?ring] > > > I've recently looked into the procmail sources and run away screaming. > > ROTFL! If I remember well, the original author knew he had a peculiar > writing style, and was writing in some prominent file (either an FAQ or > the README, or something like) that his style was not to be discussed! :-) > I wondered if the new maintainer revised the sources or not, I did not check. > > > I'd very much prefer a Python replacement to such badly written C code. > > Is it bad style? I never went as far as asserting that it was bad style, > because tastes may differ. Yet in that case, I knew that tastes may differ > very widely. :-). I prefer Python code which I can hack very easily. Hacking well-written C code is just much more difficult. Hacking C code that is written in a style I immediately don't like, is something I'd like to avoid. Btw. I have no serious reasons to dislike it, it's just gut feeling. > Surely, `procmail' successfully addressed difficult problems, and did > it rather solidly, with almost no bugs. I've heard different opinions, wrt. to losing emails and efficiency. And I've seen maildrop recommended as a better alternative multiple times. > > Does anything exist that I can start from? > > This has been discussed on 2000-02-07 on this list. In particular: Many thanks for summarizing all this. Very nice :-) > > If I do this, I'd like to replace fetchmail with getmail as well. > > What is `getmail'? A fetchmail replacement, written in Python. fetchmail is also rumoured to be able to lose mail. Looks like this was one of the reasons for writing getmail. > My experience with `procmail' as a SPAM filter told me that it may get > frustratingly slow, procmail isn't very efficient in my experience. That's also what the maildrop docs say. > when you use hundreds of filtering rules. I have only a few rules, most of them are for putting mailing list messages in the right folders. > In these days, for SPAM and virus filtering, I gave in and wrote a > Python tool which is good for me, but which would not be comprehensive > enough for publication. I'm currently just using spamassassin (the best spam detector around, very configurable, but written in Perl ;-). And a few hardcoded rules that immediately put messages from known bulkmailing software to /dev/null. I'm also investingating Pyzor, as I found the Razor author to be too clueless (also the razor servers aren't open-source). > However, there are also many SPAM filtering systems > around which have been published. You might want to give a comprehensive > look into all these things, before adding yet another one. Maybe! :-) Yup. I've solved the spam filtering problem with spamassassin. I'm only looking into a procmail replacement. Thanks for your answer. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From phlip_cpp at yahoo.com Wed Jun 5 13:57:55 2002 From: phlip_cpp at yahoo.com (Phlip) Date: 5 Jun 2002 10:57:55 -0700 Subject: SNIP IT: tk.Canvas Drag Items Around References: <63604d2.0206031518.2da29d3b@posting.google.com> Message-ID: <63604d2.0206050957.60a47f1@posting.google.com> phlip_cpp at yahoo.com (Phlip) wrote in message news:<63604d2.0206031518.2da29d3b at posting.google.com>... > Hyp Ont: > > Many moons ago one Tom Vrankar posted a snippet to this forum > regarding dragging Tkinter Canvas items around. > > I have upgraded it to actually move the target items. This also > demonstrates canvasx and canvasy, the subject of recent mysteries. > > The snippet does not make allowances for the offset between the > mouse point and the anchor point of the draggee; this should be > easy to add. But the symptom is clicking an object and starting > to drag makes it "snick" over to the mouse location. This version of the snippet drags around polygons. These are trick because one must update all the coords, not just the first one. import sys, os, string, time, copy import Tkinter tk = Tkinter # A Python example of drag and drop functionality within a single Tk widget. # The trick is in the bindings and event handler functions. # Tom Vrankar twv at ici.net # empirical events between dropee and target, as determined from Tk 8.0 # down. # leave. # up, leave, enter. class CanvasDnD (tk.Frame): def __init__ (self, master): self.master =master self.loc =self.dragged =0 tk.Frame.__init__ (self, master) canvas =tk.Canvas (self, width =256, height =256, relief =tk.RIDGE, background ="white", borderwidth =1) self.defaultcolor =canvas.itemcget (canvas.create_text (30, 25, text ="Item 1", tags ="DnD"), "fill") canvas.create_text (175, 175, text ="Item 4", tags ="DnD") canvas.create_text (225, 225, text ="Item 5", tags ="DnD") x,y = 50, 200 canvas.create_polygon(x,y, [[x+0,y+0], [x+10,y+10], [x-10,y+10]], fill='pink', tags = 'DnD') x,y = 150, 40 canvas.create_polygon(x,y, [[x+0,y+0], [x+0,y+15], [x-15,y+10]], fill='green', tags = 'DnD') x,y = 120, 120 canvas.create_polygon(x,y, [[x+0,y+0], [x+15,y+0], [x+15,y+15], [x+0,y+15]], fill='red', tags = 'DnD') x,y = 120, 170 canvas.create_polygon(x,y, [[x+0,y+0], [x+15,y+0], [x+15,y+15], [x+0,y+15]], fill='gray', tags = 'DnD') canvas.pack (expand =1, fill =tk.BOTH) canvas.tag_bind ("DnD", "", self.down) canvas.tag_bind ("DnD", "", self.chkup) canvas.tag_bind ("DnD", "", self.enter) canvas.tag_bind ("DnD", "", self.leave) def down (self, event): # print "Click on %s" %event.widget.itemcget (tk.CURRENT, "text") # print "Click on %s" % event.widget.itemconfigure (tk.CURRENT) print event.widget.coords(tk.CURRENT) self.loc =1 self.dragged =0 event.widget.bind ("", self.motion) def motion (self, event): root.config (cursor ="exchange") cnv = event.widget cnv.itemconfigure (tk.CURRENT, fill ="blue") xy = cnv.canvasx(event.x), cnv.canvasy(event.y) points = event.widget.coords (tk.CURRENT) anchors = copy.copy(points[:2]) print points for idx in range(len(points)): # print idx, xy[idx % 2], anchors[idx % 2] mouse = xy[idx % 2] zone = anchors[idx % 2] points[idx] = points[idx] - zone + mouse print points apply(event.widget.coords, [tk.CURRENT] + points) def leave (self, event): self.loc =0 def enter (self, event): self.loc =1 if self.dragged == event.time: self.up (event) def chkup (self, event): event.widget.unbind ("") root.config (cursor ="") self.target =event.widget.find_withtag (tk.CURRENT) event.widget.itemconfigure (tk.CURRENT, fill =self.defaultcolor) if self.loc: # is button released in same widget as pressed? self.up (event) else: self.dragged = event.time def up (self, event): event.widget.unbind ("") if (self.target ==event.widget.find_withtag (tk.CURRENT)): print #"Select %s" %event.widget.itemcget (tk.CURRENT, "text") else: event.widget.itemconfigure (tk.CURRENT, fill ="blue") self.master.update() time.sleep (.1) print "%s Drag-N-Dropped onto %s" \ %(event.widget.itemcget (self.target, "text"), event.widget.itemcget (tk.CURRENT, "text")) event.widget.itemconfigure (tk.CURRENT, fill =self.defaultcolor) root =tk.Tk() root.title ("Drag-N-Drop Demo") CanvasDnD (root).pack() root.mainloop() -- Phlip http://www.greencheese.org/MakeItSo -- DARE to resist drug-war profiteering -- From oliphant at ee.byu.edu Tue Jun 18 14:00:55 2002 From: oliphant at ee.byu.edu (Travis Oliphant) Date: Tue, 18 Jun 2002 12:00:55 -0600 Subject: Confidence intervals, stats modules? In-Reply-To: References: <3D047944.7070305@cardiff.ac.uk> Message-ID: > > Assuming your are talking about a normal variate, the stats.py module > has a function > for the sample std deviation but not, as far as I recall, for the > Student's t distribution, > which is needed to calculate confieence intervals where the popuation > std deviation is > unknown (which is most of the time). The scipy.stats module in scipy (www.scipy.org) has Student's t distribution and many many others. It could be used to compute confidence intervals. Happy computing, -Travis O. From graham_guttocks at yahoo.co.nz Tue Jun 4 14:22:55 2002 From: graham_guttocks at yahoo.co.nz (Graham Guttocks) Date: Tue, 4 Jun 2002 11:22:55 -0700 (PDT) Subject: os.path.expanduser ignores os.seteuid Message-ID: <20020604182255.97926.qmail@web10306.mail.yahoo.com> Why doesn't os.path.expanduser pay attention to the fact that I've changed the process's effective user id? As root: Python 2.1.3 (#1, Apr 11 2002, 18:30:30) [GCC 2.95.3 20010315 (release) [FreeBSD]] on freebsd4 Type "copyright", "credits" or "license" for more information. >>> import os >>> os.seteuid(667) >>> os.path.expanduser("~") '/root' >>> Other functions like os.getlogin() don't have this problem. Any workarounds? __________________________________________________ Do You Yahoo!? Yahoo! - Official partner of 2002 FIFA World Cup http://fifaworldcup.yahoo.com From sholden at holdenweb.com Thu Jun 6 08:55:50 2002 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 6 Jun 2002 08:55:50 -0400 Subject: HttpServer help! References: <3CFF4C14.450850D8@millfilm.co.uk> Message-ID: "Eric Texier" wrote in message news:3CFF4C14.450850D8 at millfilm.co.uk... > I am trying to get some simple example running locally on my > machine of http(server/client) code from the book 'Python & Xml' > and I am having trouble. > > if someone can look at the following script and tell me if > the problem can be because I don't have the privilege and/or > I didn't setup my system properly: > Thanks. > > I am running on Linux Red Hat with python2.2. > > > The client code to POST: > """ > post.py > """ > from httplib import HTTP > from urllib import quote > > # establish POST data > myquote = 'This is my quote: "I think therefore I am."' > > # be sure not to quote the key= sequence... > postdata = "favquote=" + quote(myquote) > > print "Will POST ", len(postdata), "bytes:" > print postdata > > # begin HTTP request > > #req = HTTP("127.0.0.1") # change to your IP or localhost > #req = HTTP("localhost") # change to your IP or localhost > > ##### MY IP address > req = HTTP("10.16.3.132") # change to your IP or localhost > > > #req.putrequest("POST", "/c8/favquote.cgi") > req.putrequest("POST", > "file:/usr/people/erict/python/srcToolskit/pythonXmlBook/c8/favquote.cgi") > > . Hold it right here. How is a FILE supposed to process the input you are trying to send it? Your .putrequest() call should give the path to the CGI script *relative to the server root*, not it's location in the server's file store. > . > . > > ##### That the Error after the ruprequest->"##### > Traceback (most recent call last): > File "post.py", line 25, in ? > req.putrequest("POST", > "file:/usr/people/erict/python/srcToolskit/pythonXmlBook/c8/favquote.cgi") > > File "/usr/people/erict/bin//lib/python2.2/httplib.py", line 453, in > putrequest > self.send(str) > File "/usr/people/erict/bin//lib/python2.2/httplib.py", line 395, in > send > self.connect() > File "/usr/people/erict/bin//lib/python2.2/httplib.py", line 379, in > connect > raise socket.error, msg > socket.error: (111, 'Connection refused') > Sure enough, when the client tries to create a connection, it can't. [...] Hope this helps. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From kragen at pobox.com Tue Jun 4 18:03:37 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 04 Jun 2002 18:03:37 -0400 Subject: Python-URL! correction Message-ID: <83lm9u4s7a.fsf@panacea.canonical.org> Python-URL! this week said someone was having trouble using McMillan Installer with Gadfly, and that Gordon had tried and failed to help the poster. This was wrong --- the (anonymous) person in question was having trouble with py2exe, not the McMillan Installer. Gordon, please accept my apologies for the error, and thank you for correcting me. From buzzard at urubu.freeserve.co.uk Sat Jun 8 09:25:41 2002 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Sat, 8 Jun 2002 14:25:41 +0100 Subject: Confidence intervals, stats modules? References: Message-ID: "Stephen Boulet" wrote in message news:ug2r3aac4etnef at corp.supernews.com... > Are there any stats modules to calculate things like confidence intervals, > mean, standard deviation? Thanks. > > -- Stephen http://www.nmr.mgh.harvard.edu/Neural_Systems_Group/gary/python.html From mitnick at sobral.org Fri Jun 21 20:40:12 2002 From: mitnick at sobral.org (KEVIN MITNICK) Date: Sat, 22 Jun 2002 00:40:12 GMT Subject: =?iso-8859-1?Q?Elei=E7=F5es?= Brasileiras/Brasilian Election Message-ID: <20020622004012.11719.qmail@linux.sobral.org> PORTUGU?S O que um governo corrupto ? capaz de fazer pra manter-se no poder?! TUDO:manipula??o da imprensa, da economia, das pesquisas eleitorais, mentiras e falsas acusa??es s?o apenas alguns dos expedientes usados por FHC e sua equipe (de corruptos) pra manter-se no poder. Acordem brasileiros. N?o podemos deixar que esse terrorista social volte a eleger os seus. Basta!Vamos dar uma resposta nas urnas! Vamos dar uma chance a esquerda. Vamos eleger LULA pra presidente!!! ENGLISH What a corrupt goverment is capable to make to keep the power itself?! EVERYTHING:manipulation of press, of economy, of electoral research, lies and false accusation are just some resources used by FHC and his team (of corrupts) to keep the power themselves. Brasilians wake up. We can't let this social terrorist elect his friends again. That's enough!Let's give an answer in the elections. Let's give a chance to Left Hand. Let's elect LULA for president of Brazil. From dfackrell at DELETETHIS.linuxmail.org Fri Jun 7 11:17:10 2002 From: dfackrell at DELETETHIS.linuxmail.org (Daniel Fackrell) Date: Fri, 7 Jun 2002 09:17:10 -0600 Subject: Efficient python programming... References: <20020606215349.GA13474@node1.opengeometry.net> Message-ID: <3d00ce76$1_2@hpb10302.boi.hp.com> "Shagshag13" wrote in message news:adpktk$17j3k$1 at ID-146704.news.dfncis.de... ... > set = {} > map(set.__setitem__, alist, []) > alist = set.keys() > > But that's not trivial !!! And quite difficult to find... The reason that this example does not seem trivial to you or to me is most likely that we don't fully grasp the concept and usage of map(). Once we get that behind us, I'm sure that this example will turn into something that we use all the time without much thinking about it. > > > those things doesn't make your code obfuscated.. > > I agree :) > > > [file.printsize() for file in directory] > > > > they're the same, and everyone would recommend you the last one.. > > Yes but i would have asked why this is the best... And i think that > your answer would have helped me to become a better pythoner... This concept (I believe it's called "list comprehensions") is another like the map() usage. Obscure and arcane to those who don't fully grasp it (like me, again), but very powerful. I'm not sure what either of them has to do with optimization, though, except that they are both probably very well optimized at the underlying C level. Daniel Fackrell From oren-py-l at hishome.net Sat Jun 15 06:25:19 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Sat, 15 Jun 2002 13:25:19 +0300 Subject: Pronouncing '__init__' Message-ID: <20020615132519.A14452@hishome.net> There has been a thread about this issue in the past. Below are some of the proposals people made. I'd like to have an informal vote - how do *you* say Python's magic names when talking with other Pythoneers? (all my Python-related communication is written) double underscore init double underscore under under init under under double bar init double bar bar bar init bar bar unders init unders under init under bar init bar magic init pyinit Most of these pronounciations also have a shorter version with the trailing part omitted. Oren From pyth at devel.trillke.net Wed Jun 12 12:05:51 2002 From: pyth at devel.trillke.net (holger krekel) Date: Wed, 12 Jun 2002 18:05:51 +0200 Subject: methods to parse big foreign ascii-file? Message-ID: <20020612180551.Y6609@prim.han.de> Hello, tommorrow i want to convince an old skool C-programmer to use python. We are going to make a one-day project :-) It involves reading 50MB+ files of a strange ascii-format containing names, floats and flags all around. These items span multiple lines and should be grouped in lists or objects. How would you go about it? Options that come to my mind: - using the re module to parse line for line and try to get it all right by hand. - come up with a grammar and let a parser do the hard work (which one?) - using some module i don't yet know? thanks for pointers or comments, holger From Sascha.Ferley at infineon.net Sun Jun 23 22:00:46 2002 From: Sascha.Ferley at infineon.net (Sascha Ferley) Date: Sun, 23 Jun 2002 20:00:46 -0600 (MDT) Subject: PIL, Python and CGI In-Reply-To: <200206241138.19665.rjones@ekit-inc.com> Message-ID: On Mon, 24 Jun 2002, Richard Jones wrote: > On Mon, 24 Jun 2002 11:30, Sascha Ferley wrote: > > Thanks for replying back to me, this thing has been driving me nuts for a > > while now. Anyways, i removed the try/catch block from the Image.py lib, > > and checked the error output: > > > > Traceback (most recent call last): > > File "/export/server/web/CPSC461/cgi-bin/interfce.py", line 15, in ? > > print Image.open(urlretrieve(sourcePath, '/tmp/img1')[0]).histogram() > > File "/usr/local/lib/python2.2/site-packages/PIL/Image.py", line 577, in > > histogram > > self.load() > > File "/opt/sfw/lib/python2.2/site-packages/PIL/ImageFile.py", line 126, > > in load > > self.load_prepare() > > File "/opt/sfw/lib/python2.2/site-packages/PIL/ImageFile.py", line 180, > > in load_prepare > > self.im = Image.core.new(self.mode, self.size) > > AttributeError: 'module' object has no attribute 'core' > > "core" is assigned just after the "import _imaging" line in Image.py. Are you > sure there isn't another traceback we're missing? What happens if you just > have a simple CGI script that just does "import _imaging"? Hi Richard Thanks again, well here is what occurs, program/script: import sys import _imaging sys.stderr = sys.stdout print "Content-Type: text/plain" print sys.path The error that results: [Sun Jun 23 19:58:32 2002] [error] (8)Exec format error: exec of /export/server/web/CPSC461/cgi-bin/test3.py failed [Sun Jun 23 19:58:32 2002] [error] [client 136.159.3.51] Premature end of script headers: /export/server/web/CPSC461/cgi-bin/test3.py After 48hours of straight coding i might not have done the best job here:). Sascha From james.kew at btinternet.com Sat Jun 29 15:56:41 2002 From: james.kew at btinternet.com (James Kew) Date: Sat, 29 Jun 2002 20:56:41 +0100 Subject: private References: <3D1DE132.4A890D9D@engcorp.com> Message-ID: "Peter Hansen" wrote in message news:3D1DE132.4A890D9D at engcorp.com... > Rhymes wrote: > > > > Is there any possibility to build up a _real_ private attribute? > > Such as C++ private data members... > > You realize that it's quite possible to get at private data members > in C++, don't you? I can't help feeling this is overly dismissive! Yes, of course one can circumvent private in C++. But for me the main value of the public and private specifiers is that they _document_ to the client of the class what it should access and what it should not. I don't -- in my admittedly very limited experience -- find Python classes as immediately self-documenting. It's not obvious from the class definition what is intended to be called or modfied by the client and what is internal to the implementation. I suspect I'm still in the crossover period from strictly declarative C/C++ and the "anything goes" Pythonic way and that, given time, I'll find my groove and feel comfortable. > This has been discussed about 479 times in the last decade. I'll bet. I'll shut up about it now. James From jbublitzNO at SPAMnwinternet.com Tue Jun 18 16:37:23 2002 From: jbublitzNO at SPAMnwinternet.com (Jim) Date: Tue, 18 Jun 2002 20:37:23 GMT Subject: Embedding Python - time module problem References: Message-ID: <3D0F99EA.7060904@SPAMnwinternet.com> Richard Townsend wrote: > If I substitute "os" or "sys" for "time" then no error occurs. However > "math" does give a similar error. > If I run the interpreter on its own, I can import time and math with no > problems. > I am using Python 2.2.1 on HP-UX 11i > Is there something special I need to do to be able to import time and > math modules when using embedded Python? This sounds similar to the problem I had under Linux - sys is builtin, time and math aren't, and the interpreter symbols needed aren't available to the time and math libs. If you're using something like 'dlopen' to import the interpreter, it needs to happen with the RTLD_GLOBAL flag set. If you're statically linking, there's probably an equivalent linker switch. I was using KDE which has a method for globally loading libs. libtool looked messier, but fortunately I didn't need to get into it. man dlopen (at least for Linux). Jim From steve.bond at btinternet.com Wed Jun 19 06:20:42 2002 From: steve.bond at btinternet.com (Steve) Date: Wed, 19 Jun 2002 10:20:42 +0000 (UTC) Subject: newbie: help please! Message-ID: hello, i have python 2.2.1 installed on my mandrake 8.1 system, which seems to work fine. The problem is im trying to install Tk exstensions, i have downloaded both tcl8.3.4 and tk8.3.4 files and installed using the ./configure, make and then make install commands. I then when into the setup file in the Python-2.2.1/Modules directory where i understand i have to enable the tkinter extension module, by uncommenting the approritae lines. Lastly i run 'make' at the top of my Python-2.2.1 directory but i get this error: gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H -DWITH_APPINIT -I/usr/local/include -I/usr/X11R6/bin -c ./Modules/_tkinter.c -o Modules/_tkinter.o In file included from ./Modules/_tkinter.c:49: /usr/include/tk.h:83:29: X11/Xlib.h: No such file or directory i have the Xlib.h in the Python-2.2.1/Include directory the tkinter part of my setup file looks like this and everything was installed in the default places # *** Always uncomment this (leave the leading underscore in!): _tkinter _tkinter.c tkappinit.c -DWITH_APPINIT \ # *** Uncomment and edit to reflect where your Tcl/Tk libraries are: -L/usr/local/lib \ # *** Uncomment and edit to reflect where your Tcl/Tk headers are: -I/usr/local/include \ # *** Uncomment and edit to reflect where your X11 header files are: -I/usr/X11R6/bin \ # *** Or uncomment this for Solaris: # -I/usr/openwin/include \ # *** Uncomment and edit for Tix extension only: # -DWITH_TIX -ltix8.1.8.2 \ # *** Uncomment and edit for BLT extension only: # -DWITH_BLT -I/usr/local/blt/blt8.0-unoff/include -lBLT8.0 \ # *** Uncomment and edit for PIL (TkImaging) extension only: # (See http://www.pythonware.com/products/pil/ for more info) # -DWITH_PIL -I../Extensions/Imaging/libImaging tkImaging.c \ # *** Uncomment and edit for TOGL extension only: # -DWITH_TOGL togl.c \ # *** Uncomment and edit to reflect your Tcl/Tk versions: -ltk8.3 -ltcl8.3 \ # *** Uncomment and edit to reflect where your X11 libraries are: -L/usr/X11R6/lib \ # *** Or uncomment this for Solaris: # -L/usr/openwin/lib \ # *** Uncomment these for TOGL extension only: # -lGL -lGLU -lXext -lXmu \ # *** Uncomment for AIX: # -lld \ # *** Always uncomment this; X11 libraries to link with: -lX11 Any help would be much appreciated! Thanks Steven From hesterloli at hotmail.com Wed Jun 19 09:42:58 2002 From: hesterloli at hotmail.com (George Hester) Date: Wed, 19 Jun 2002 13:42:58 GMT Subject: python version? References: <3D0E8AC8.6C5C96EE@engcorp.com> <37TP8.47886$GY.15021139@twister.nyroc.rr.com> <3D1010C3.C321F8B0@engcorp.com> <3D107948.B3FEE4BB@engcorp.com> Message-ID: Well I know quite a lot about limits. Nothing about Maple. But the reason I mentioned is that I hoped that my students would take an interest in the subject and learn the concept. They were not interested but they needed the credit to graduate. In my case I was not necessarily interested in learning Python. But I did want to determine my version of Python in ASP. I suppose I was like my students and ya'll were like the teacher. Yes basically I wanted it handed to me on a platter. What I did with the platter may have surprised you. So just becasue somebody wants something handed to them on a platter does not mean the contribution has less value. -- George Hester _________________________________ "Peter Hansen" wrote in message news:3D107948.B3FEE4BB at engcorp.com... > George Hester wrote: > > > > Yes my take on it was that you said "I needed to crawl before I walk." Please > > don't hold my inference against me. > > That's precisely what I said. Nothing derogatory about it, except > in your own mind. We /all/ need to crawl before we walk, in all > things, unless we're lucky. I was just reminding you of this > fact of life. > > If I were attempting to learn limit calculus, and simultaneously > apply it to a difficult problem while using Maple, and I knew > nothing about Maple and little about limit calculus, you would > be helping me if you said "crawl before you walk... just learn > the basics of limit calculus before you try to figure out how > to use Maple too". I hope I would not be so sensitive as to > take that the wrong way. > > -Peter > > P.S.: I know little about limit calculus, and nothing about > Maple, so please forgive the above example if it combines > the two infeasibly.... :) From jtt at hnc.com Wed Jun 5 09:57:36 2002 From: jtt at hnc.com (Jim) Date: 5 Jun 2002 06:57:36 -0700 Subject: DCOracle2 - Can't get cursor.execute to return data when SQL query involves datetimes. References: Message-ID: Here is better version of the same program. Sorry for last posting. ! /usr/bin/env python import DCOracle2 #************************************************************* # Define variables and constants #************************************************************* TRUE = 1 FALSE = 0 FalconPwd = 'uid/pwd' Results_count = 0 db = DCOracle2.connect(FalconPwd) # # Open a new cursor # dbCursor = db.cursor() tran_date = '19970116124248' dt = DCOracle2.Timestamp(int(tran_date[0:4]), int(tran_date[4:6]), int(tran_date[6:8]), int(tran_date[8:10]), int(tran_date[10:12]), int(tran_date[12:14])) Results_count = DCOracle2.execute(dbCursor,'select * from falcon.falt002d where ACCT_NBR = :1 and trn_dt = :2',"2222222222222222 ",dt) tabledata = dbCursor.fetchone() print tabledata From oren at hishome.net Sat Jun 29 11:24:48 2002 From: oren at hishome.net (Oren Tirosh) Date: Sat, 29 Jun 2002 18:24:48 +0300 Subject: Shell-like functionality in Python Message-ID: <20020629182448.A24662@hishome.net> Check out http://www.tothink.com/python/shell It's still in a pretty early state but already provides a very convenient syntax for flexible execution of external commands from Python. External commands appear as virtual methods of an object called 'cmd'. Example: Python 2.2 (#1, Jan 30 2002, 23:44:31) [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from shell.all import * >>> cmd.ls() all.py command.py __init__.py It supports output redirection in the form of iterable commands: >>> for x in cmd.ls['-l']: ... print 'line:', x ... line: total 20 line: -rw-rw-r-- 1 oren oren 216 Jun 27 20:49 all.py line: -rw-rw-r-- 1 oren oren 8259 Jun 27 20:53 command.py line: -rw-rw-r-- 1 oren oren 136 Jun 27 20:49 __init__.py Passing the output of one command as arguments to another: >>> cmd.chmod('+r', cmd.find['.', '-name', '*.html']) And some other nifty features. Oren From erict at millfilm.co.uk Fri Jun 21 12:24:43 2002 From: erict at millfilm.co.uk (Eric Texier) Date: Fri, 21 Jun 2002 17:24:43 +0100 Subject: property type missing Message-ID: <3D13534A.843A616A@millfilm.co.uk> I am using "property" and I would like to retrieve their name automatically from the dict-proxy of my class. I do something like: class foo: .... >>> a = foo() >>> d = vars(a.__class__) >>> d.items() [('ouputType', ),..... know I would like now, to check again the "types" module the type of all the value to define which one are of type property. But types doesn't have it define. I am wondering why and if it will be a way around. Thanks Eric From slhath at charter.net Fri Jun 21 14:09:33 2002 From: slhath at charter.net (Scott Hathaway) Date: Fri, 21 Jun 2002 13:09:33 -0500 Subject: ssl on windows Message-ID: I would like to use ssl on Windows with Python 2.2. Is this available yet? If so, how can I go about getting it installed? When I try to get an https address with urllib, it tells me that https is an unknown protocol. Thanks, Scott From fredrik at pythonware.com Thu Jun 20 05:38:28 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 20 Jun 2002 09:38:28 GMT Subject: object object References: <3D1195BE.9B10EE00@millfilm.co.uk> Message-ID: Eric Texier wrote: > I didn' t find a lot about class object. > and I would like to know what I can > inherit from it and what is the difference > between, class foo(object): and class foo: the former creates a "new-style class" or subtype, the latter a "classic class": to learn more, start here: http://www.amk.ca/python/2.2/index.html#SECTION000310000000000000000 http://www.python.org/2.2.1/descrintro.html From cimarron+google at taylors.org Sun Jun 9 04:21:41 2002 From: cimarron+google at taylors.org (Cimarron Taylor) Date: 9 Jun 2002 01:21:41 -0700 Subject: Tkinter Help Please References: Message-ID: <29e28c51.0206090021.72466d4b@posting.google.com> Since I started working with Pmw, I've had to do this a few times on linux machines (RedHat 7.1). Here is the procedure I follow: 1. install X11 headers and libraries if necessary (rpm -i XFree86-devel-4.0.3-5.i386.rpm) 2. put tcl8.3.4.tar.Z, tk8.3.4.tar.Z, Python-2.2.1.tgz and Pmw.0.8.5.tar.gz into a temporary directory 3. copy my standard Makefile and Setup.dist (see end of message) files into the temporary directory. 4. su to root 5. run 'make untar tcl tk python pmw' You might not need Pmw If you aren't doing your own Tkinter development (in which case you can omit it). Pmw is not strictly required to use Tkinter but I have found it very helpful. Cim My standard Makefile contains the text in between the lines of dashes: ------------------------------------------------------------------------- all: @echo you need to be root, then type @echo make untar tcl tk python pmw pmw: mv Pmw /usr/local/lib/python2.2/site-packages python: mv Python-2.2.1/Modules/Setup.dist Python-2.2.1/Modules/Setup.dist- cp Setup.dist Python-2.2.1/Modules (cd Python-2.2.1 && ./configure && make && make install) tk: (cd tk8.3.4/unix && ./configure && make && make install) ldconfig -v tcl: (cd tcl8.3.4/unix && ./configure && make && make install) untar: tar xfz Python-2.2.1.tgz tar xfz tcl8.3.4.tar.Z tar xfz tk8.3.4.tar.Z tar xfz Pmw.0.8.5.tar.gz ------------------------------------------------------------------------- My Setup.dist contains the text in between the lines of dashes. It is essentially the same as the Setup.dist which comes with Python except that the tkinter module settings have been modified appropriately. ------------------------------------------------------------------------- # -*- makefile -*- # The file Setup is used by the makesetup script to construct the files # Makefile and config.c, from Makefile.pre and config.c.in, # respectively. The file Setup itself is initially copied from # Setup.dist; once it exists it will not be overwritten, so you can edit # Setup to your heart's content. Note that Makefile.pre is created # from Makefile.pre.in by the toplevel configure script. # (VPATH notes: Setup and Makefile.pre are in the build directory, as # are Makefile and config.c; the *.in and *.dist files are in the source # directory.) # Each line in this file describes one or more optional modules. # Modules enabled here will not be compiled by the setup.py script, # so the file can be used to override setup.py's behavior. # Lines have the following structure: # # ... [ ...] [ ...] [ ...] # # is anything ending in .c (.C, .cc, .c++ are C++ files) # is anything starting with -I, -D, -U or -C # is anything ending in .a or beginning with -l or -L # is anything else but should be a valid Python # identifier (letters, digits, underscores, beginning with non-digit) # # (As the makesetup script changes, it may recognize some other # arguments as well, e.g. *.so and *.sl as libraries. See the big # case statement in the makesetup script.) # # Lines can also have the form # # = # # which defines a Make variable definition inserted into Makefile.in # # Finally, if a line contains just the word "*shared*" (without the # quotes but with the stars), then the following modules will not be # included in the config.c file, nor in the list of objects to be # added to the library archive, and their linker options won't be # added to the linker options, but rules to create their .o files and # their shared libraries will still be added to the Makefile, and # their names will be collected in the Make variable SHAREDMODS. This # is used to build modules as shared libraries. (They can be # installed using "make sharedinstall", which is implied by the # toplevel "make install" target.) (For compatibility, # *noconfig* has the same effect as *shared*.) # # In addition, *static* reverses this effect (negating a previous # *shared* line). # NOTE: As a standard policy, as many modules as can be supported by a # platform should be present. The distribution comes with all modules # enabled that are supported by most platforms and don't require you # to ftp sources from elsewhere. # Some special rules to define PYTHONPATH. # Edit the definitions below to indicate which options you are using. # Don't add any whitespace or comments! # Directories where library files get installed. # DESTLIB is for Python modules; MACHDESTLIB for shared libraries. DESTLIB=$(LIBDEST) MACHDESTLIB=$(BINLIBDEST) # NOTE: all the paths are now relative to the prefix that is computed # at run time! # Standard path -- don't edit. # No leading colon since this is the first entry. # Empty since this is now just the runtime prefix. DESTPATH= # Site specific path components -- should begin with : if non-empty SITEPATH= # Standard path components for test modules TESTPATH= # Path components for machine- or system-dependent modules and shared libraries MACHDEPPATH=:plat-$(MACHDEP) # Path component for the Tkinter-related modules # The TKPATH variable is always enabled, to save you the effort. TKPATH=:lib-tk COREPYTHONPATH=$(DESTPATH)$(SITEPATH)$(TESTPATH)$(MACHDEPPATH)$(TKPATH) PYTHONPATH=$(COREPYTHONPATH) # The modules listed here can't be built as shared libraries for # various reasons; therefore they are listed here instead of in the # normal order. # This only contains the minimal set of modules required to run the # setup.py script in the root of the Python source tree. posix posixmodule.c # posix (UNIX) system calls _sre _sre.c # Fredrik Lundh's new regular expressions new newmodule.c # Tommy Burnette's 'new' module # The rest of the modules listed in this file are all commented out by # default. Usually they can be detected and built as dynamically # loaded modules by the new setup.py script added in Python 2.1. If # you're on a platform that doesn't support dynamic loading, want to # compile modules statically into the Python binary, or need to # specify some odd set of compiler switches, you can uncomment the # appropriate lines below. # ====================================================================== # The Python symtable module depends on .h files that setup.py doesn't track _symtable symtablemodule.c # The SGI specific GL module: GLHACK=-Dclear=__GLclear #gl glmodule.c cgensupport.c -I$(srcdir) $(GLHACK) -lgl -lX11 # Pure module. Cannot be linked dynamically. # -DWITH_QUANTIFY, -DWITH_PURIFY, or -DWITH_ALL_PURE #WHICH_PURE_PRODUCTS=-DWITH_ALL_PURE #PURE_INCLS=-I/usr/local/include #PURE_STUBLIBS=-L/usr/local/lib -lpurify_stubs -lquantify_stubs #pure puremodule.c $(WHICH_PURE_PRODUCTS) $(PURE_INCLS) $(PURE_STUBLIBS) # Uncommenting the following line tells makesetup that all following # modules are to be built as shared libraries (see above for more # detail; also note that *static* reverses this effect): #*shared* # GNU readline. Unlike previous Python incarnations, GNU readline is # now incorporated in an optional module, configured in the Setup file # instead of by a configure script switch. You may have to insert a # -L option pointing to the directory where libreadline.* lives, # and you may have to change -ltermcap to -ltermlib or perhaps remove # it, depending on your system -- see the GNU readline instructions. # It's okay for this to be a shared library, too. #readline readline.c -lreadline -ltermcap # Modules that should always be present (non UNIX dependent): #array arraymodule.c # array objects #cmath cmathmodule.c # -lm # complex math library functions #math mathmodule.c # -lm # math library functions, e.g. sin() #struct structmodule.c # binary structure packing/unpacking #time timemodule.c # -lm # time operations and variables #operator operator.c # operator.add() and similar goodies #_weakref _weakref.c # basic weak reference support #_codecs _codecsmodule.c # access to the builtin codecs and codec registry #_testcapi _testcapimodule.c # Python C API test module #unicodedata unicodedata.c # static Unicode character database #_locale _localemodule.c # access to ISO C locale support # Modules with some UNIX dependencies -- on by default: # (If you have a really backward UNIX, select and socket may not be # supported...) #fcntl fcntlmodule.c # fcntl(2) and ioctl(2) #pwd pwdmodule.c # pwd(3) #grp grpmodule.c # grp(3) #errno errnomodule.c # posix (UNIX) errno values #select selectmodule.c # select(2); not on ancient System V # Memory-mapped files (also works on Win32). #mmap mmapmodule.c # Dynamic readlines #xreadlines xreadlinesmodule.c # for socket(2), without SSL support. #_socket socketmodule.c # Socket module compiled with SSL support; you must comment out the other # socket line above, and possibly edit the SSL variable: #SSL=/usr/local/ssl #_socket socketmodule.c \ # -DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \ # -L$(SSL)/lib -lssl -lcrypto # The crypt module is now disabled by default because it breaks builds # on many systems (where -lcrypt is needed), e.g. Linux (I believe). # # First, look at Setup.config; configure may have set this for you. #crypt cryptmodule.c # -lcrypt # crypt(3); needs -lcrypt on some systems # Some more UNIX dependent modules -- off by default, since these # are not supported by all UNIX systems: #nis nismodule.c -lnsl # Sun yellow pages -- not everywhere #termios termios.c # Steen Lumholt's termios module #resource resource.c # Jeremy Hylton's rlimit interface # Multimedia modules -- off by default. # These don't work for 64-bit platforms!!! # These represent audio samples or images as strings: #audioop audioop.c # Operations on audio samples #imageop imageop.c # Operations on images #rgbimg rgbimgmodule.c # Read SGI RGB image files (but coded portably) # The md5 module implements the RSA Data Security, Inc. MD5 # Message-Digest Algorithm, described in RFC 1321. The necessary files # md5c.c and md5.h are included here. #md5 md5module.c md5c.c # The sha module implements the SHA checksum algorithm. # (NIST's Secure Hash Algorithm.) #sha shamodule.c # The mpz module interfaces to the GNU Multiple Precision library. # You need to ftp the GNU MP library. # The GMP variable must point to the GMP source directory. # This was originally written and tested against GMP 1.2 and 1.3.2. # It has been modified by Rob Hooft to work with 2.0.2 as well, but I # haven't tested it recently. # A compatible MP library unencombered by the GPL also exists. It was # posted to comp.sources.misc in volume 40 and is widely available from # FTP archive sites. One URL for it is: # ftp://gatekeeper.dec.com/.b/usenet/comp.sources.misc/volume40/fgmp/part01.Z #GMP=/ufs/guido/src/gmp #mpz mpzmodule.c -I$(GMP) $(GMP)/libgmp.a # SGI IRIX specific modules -- off by default. # These module work on any SGI machine: # *** gl must be enabled higher up in this file *** #fm fmmodule.c $(GLHACK) -lfm -lgl # Font Manager #sgi sgimodule.c # sgi.nap() and a few more # This module requires the header file # /usr/people/4Dgifts/iristools/include/izoom.h: #imgfile imgfile.c -limage -lgutil -lgl -lm # Image Processing Utilities # These modules require the Multimedia Development Option (I think): #al almodule.c -laudio # Audio Library #cd cdmodule.c -lcdaudio -lds -lmediad # CD Audio Library #cl clmodule.c -lcl -lawareaudio # Compression Library #sv svmodule.c yuvconvert.c -lsvideo -lXext -lX11 # Starter Video # The FORMS library, by Mark Overmars, implements user interface # components such as dialogs and buttons using SGI's GL and FM # libraries. You must ftp the FORMS library separately from # ftp://ftp.cs.ruu.nl/pub/SGI/FORMS. It was tested with FORMS 2.2a. # NOTE: if you want to be able to use FORMS and curses simultaneously # (or both link them statically into the same binary), you must # compile all of FORMS with the cc option "-Dclear=__GLclear". # The FORMS variable must point to the FORMS subdirectory of the forms # toplevel directory: #FORMS=/ufs/guido/src/forms/FORMS #fl flmodule.c -I$(FORMS) $(GLHACK) $(FORMS)/libforms.a -lfm -lgl # SunOS specific modules -- off by default: #sunaudiodev sunaudiodev.c # A Linux specific module -- off by default; this may also work on # some *BSDs. #linuxaudiodev linuxaudiodev.c # George Neville-Neil's timing module: #timing timingmodule.c # The _tkinter module. # # The command for _tkinter is long and site specific. Please # uncomment and/or edit those parts as indicated. If you don't have a # specific extension (e.g. Tix or BLT), leave the corresponding line # commented out. (Leave the trailing backslashes in! If you # experience strange errors, you may want to join all uncommented # lines and remove the backslashes -- the backslash interpretation is # done by the shell's "read" command and it may not be implemented on # every system. # *** Always uncomment this (leave the leading underscore in!): _tkinter _tkinter.c tkappinit.c -DWITH_APPINIT \ # *** Uncomment and edit to reflect where your Tcl/Tk libraries are: -L/usr/local/lib \ # *** Uncomment and edit to reflect where your Tcl/Tk headers are: -I/usr/local/include \ # *** Uncomment and edit to reflect where your X11 header files are: -I/usr/X11R6/include \ # *** Or uncomment this for Solaris: # -I/usr/openwin/include \ # *** Uncomment and edit for Tix extension only: # -DWITH_TIX -ltix8.1.8.2 \ # *** Uncomment and edit for BLT extension only: # -DWITH_BLT -I/usr/local/blt/blt8.0-unoff/include -lBLT8.0 \ # *** Uncomment and edit for PIL (TkImaging) extension only: # (See http://www.pythonware.com/products/pil/ for more info) # -DWITH_PIL -I../Extensions/Imaging/libImaging tkImaging.c \ # *** Uncomment and edit for TOGL extension only: # -DWITH_TOGL togl.c \ # *** Uncomment and edit to reflect your Tcl/Tk versions: -ltk8.3 -ltcl8.3 \ # *** Uncomment and edit to reflect where your X11 libraries are: -L/usr/X11R6/lib \ # *** Or uncomment this for Solaris: # -L/usr/openwin/lib \ # *** Uncomment these for TOGL extension only: # -lGL -lGLU -lXext -lXmu \ # *** Uncomment for AIX: # -lld \ # *** Always uncomment this; X11 libraries to link with: -lX11 # Lance Ellinghaus's modules: #rotor rotormodule.c # enigma-inspired encryption #syslog syslogmodule.c # syslog daemon interface # Curses support, requring the System V version of curses, often # provided by the ncurses library. e.g. on Linux, link with -lncurses # instead of -lcurses; on SunOS 4.1.3, insert -I/usr/5include # -L/usr/5lib before -lcurses). # # First, look at Setup.config; configure may have set this for you. #_curses _cursesmodule.c -lcurses -ltermcap # Wrapper for the panel library that's part of ncurses and SYSV curses. #_curses_panel _curses_panel.c -lpanel -lncurses # Generic (SunOS / SVR4) dynamic loading module. # This is not needed for dynamic loading of Python modules -- # it is a highly experimental and dangerous device for calling # *arbitrary* C functions in *arbitrary* shared libraries: #dl dlmodule.c # Modules that provide persistent dictionary-like semantics. You will # probably want to arrange for at least one of them to be available on # your machine, though none are defined by default because of library # dependencies. The Python module anydbm.py provides an # implementation independent wrapper for these; dumbdbm.py provides # similar functionality (but slower of course) implemented in Python. # The standard Unix dbm module has been moved to Setup.config so that # it will be compiled as a shared library by default. Compiling it as # a built-in module causes conflicts with the pybsddb3 module since it # creates a static dependency on an out-of-date version of db.so. # # First, look at Setup.config; configure may have set this for you. #dbm dbmmodule.c # dbm(3) may require -lndbm or similar # Anthony Baxter's gdbm module. GNU dbm(3) will require -lgdbm: # # First, look at Setup.config; configure may have set this for you. #gdbm gdbmmodule.c -I/usr/local/include -L/usr/local/lib -lgdbm # Berkeley DB interface. # # This requires the Berkeley DB code, see # ftp://ftp.cs.berkeley.edu/pub/4bsd/db.1.85.tar.gz # # Edit the variables DB and DBPORT to point to the db top directory # and the subdirectory of PORT where you built it. # # (See http://electricrain.com/greg/python/bsddb3/ for an interface to # BSD DB 3.x.) # Note: If a db.h file is found by configure, bsddb will be enabled # automatically via Setup.config.in. It only needs to be enabled here # if it is not automatically enabled there; check the generated # Setup.config before enabling it here. #DB=/depot/sundry/src/berkeley-db/db.1.85 #DBPORT=$(DB)/PORT/irix.5.3 #bsddb bsddbmodule.c -I$(DBPORT)/include -I$(DBPORT) $(DBPORT)/libdb.a # Helper module for various ascii-encoders #binascii binascii.c # Fred Drake's interface to the Python parser #parser parsermodule.c # Digital Creations' cStringIO and cPickle #cStringIO cStringIO.c #cPickle cPickle.c # Lee Busby's SIGFPE modules. # The library to link fpectl with is platform specific. # Choose *one* of the options below for fpectl: # For SGI IRIX (tested on 5.3): #fpectl fpectlmodule.c -lfpe # For Solaris with SunPro compiler (tested on Solaris 2.5 with SunPro C 4.2): # (Without the compiler you don't have -lsunmath.) #fpectl fpectlmodule.c -R/opt/SUNWspro/lib -lsunmath -lm # For other systems: see instructions in fpectlmodule.c. #fpectl fpectlmodule.c ... # Test module for fpectl. No extra libraries needed. #fpetest fpetestmodule.c # Andrew Kuchling's zlib module. # This require zlib 1.1.3 (or later). # See http://www.cdrom.com/pub/infozip/zlib/ #zlib zlibmodule.c -I$(prefix)/include -L$(exec_prefix)/lib -lz # Interface to the Expat XML parser # # Expat is written by James Clark and must be downloaded separately # (see below). The pyexpat module was written by Paul Prescod after a # prototype by Jack Jansen. # # The Expat dist includes Windows .lib and .dll files. Home page is at # http://www.jclark.com/xml/expat.html, the current production release is # always ftp://ftp.jclark.com/pub/xml/expat.zip. # # EXPAT_DIR, below, should point to the expat/ directory created by # unpacking the Expat source distribution. # # Note: the expat build process doesn't yet build a libexpat.a; you can # do this manually while we try convince the author to add it. To do so, # cd to EXPAT_DIR, run "make" if you have not done so, then run: # # ar cr libexpat.a xmltok/*.o xmlparse/*.o # #EXPAT_DIR=/usr/local/src/expat #pyexpat pyexpat.c -I$(EXPAT_DIR)/xmlparse -L$(EXPAT_DIR) -lexpat # Example -- included for reference only: # xx xxmodule.c # Another example -- the 'xxsubtype' module shows C-level subtyping in action xxsubtype xxsubtype.c ------------------------------------------------------------------------- From gerhard at bigfoot.de Mon Jun 3 07:09:09 2002 From: gerhard at bigfoot.de (Gerhard =?unknown-8bit?Q?H=E4ring?=) Date: Mon, 3 Jun 2002 13:09:09 +0200 Subject: word wrap on different OS In-Reply-To: <3CFB4994.DD35AEA2@textraeume.de> References: <3CFB4994.DD35AEA2@textraeume.de> Message-ID: <20020603110909.GB17944@gargamel.hqd-internal> * Sabine Richter [2002-06-03 12:48 +0200]: > Hello, > > I am not sure if I think clear on this subject: > > A simple text file has been created for example on MS Dos or MacOS. So > the sign for a word wrap will be "\r\n" on MS Dos or "\r" on MacOS. > Then I save the file on a windows file system. The sign for the word > wrap will be converted to "\n". Normally, you want to process the file line by line. Is this the case for you, too? Then, you can use the following pattern: f = open("foo") for line in f.xreadlines(): # Get rid of any trailing whitespace, including CR and LF characters line = line.rstrip() # do something with the line now f.close() There is no need to read the whole file and split it at line endings, the readlines() and xreadlines() methods of file objects are invented just for that. > And next question: > If I write a script, which uses MyODBC and the odbc-module from win32 > extensions to connect to a MySQL-database, it can only be used on > windows. Isn't it? Yes. I already recommended the MySQLdb module to you, which will work fine on Windows and Unix. If you can spare a few euros, you can get a commercial license for mxODBC. This is an ODBC solution that will also work on Unixen. If you target MySQL only, MySQLdb is the way to go. Everything else is superfluous, and doesn't have any technical advantages. Cheers, Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From pinard at iro.umontreal.ca Wed Jun 19 16:39:38 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 19 Jun 2002 16:39:38 -0400 Subject: procmail replacement in Python In-Reply-To: <20020619022110.GA6996@lilith.my-fqdn.de> References: <20020618235901.GA2197@lilith.my-fqdn.de> <20020619022110.GA6996@lilith.my-fqdn.de> Message-ID: [Gerhard H?ring] > I'm currently just using spamassassin (the best spam detector around, > very configurable, but written in Perl ;-). I wanted to peek at Spamassassin, which seems to have a good reputation. And now, you are trying to discourage me? :-) It's really a strange phenomenon: more I work with Python, more Perl gets unreadable :-) > I'm also investingating Pyzor, as I found the Razor author to be too > clueless (also the razor servers aren't open-source). Thanks both for pointers and hints. I'm glad that this discussion popped up `pycmail', yet the warning of its documentation are a bit chilling... -------------- next part -------------- -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From ken at hotmail.com Sat Jun 1 04:18:50 2002 From: ken at hotmail.com (Ken) Date: Sat, 1 Jun 2002 18:18:50 +1000 Subject: How to open a HTML file when the python cgi program is executing? References: Message-ID: "Sheila King" wrote in message news:ad95l1.i0.1 at kserver.org... > On Sat, 1 Jun 2002 16:43:01 +1000, "Ken" wrote in > comp.lang.python in article : > > > How do I open a HTML file when the cgi program is executing? > > > > The only method I can think of, which doesn't work is this: > > > > What do you mean by "open an HTML file when the cgi program is executing"? > > Are you talking about displaying the resulting HTML output. > > HTML output from a cgi script is simply printed to standard output. > > Here is a very simply cgi script (basically "Hello World"): > > =============(begin hello script)=============== > #!/usr/bin/env python > > print "Content-type: text/html\n" > print "Hello, World!" > print "

HELLO, WORLD!!!

" > > =============(end hello script)=============== > > Change the interpreter path > > #!/usr/bin/env python > > as appropriate for your server. > > Save the above as something like hello.py or hello.cgi > upload it to the cgi-bin on your server. Make sure file permissions are set > for executable (this will probably be 777 or 755 depending on your server > configuation). Make sure you upload it in ASCII/TEXT mode. > > Then point your browser to > > http://www.example.com/cgi-bin/hello.py > > where you replace example.com with your actual domain name. > > This should display an HTML page with the H1 header saying "Hello, World!!" > > -- > Sheila King > http://www.thinkspot.net/sheila/ > http://www.k12groups.org/ > No, I mean at some point in the script, I want to get out of it and use ordinary HTML instead (main.html in this example). I don't mean the "print" command. Can anyone help? Thanks From cpbotha at i_triple_e.org Sun Jun 2 15:27:45 2002 From: cpbotha at i_triple_e.org (Charl P. Botha) Date: Sun, 2 Jun 2002 19:27:45 +0000 (UTC) Subject: List References: <3cfa6ed8_1@news.iprimus.com.au> Message-ID: In article <3cfa6ed8_1 at news.iprimus.com.au>, Gold Fish wrote: > Assume we got 2 list > list 1 = ['ABC','CDG','DAV','FE','FECA','FEAFA','FEA'] > list 2 = [] > how can we copy element from list 1 to list 2 say i just want to copy the 3 > element 'CDG','DAV','FE' to list2 only. list1 = ['ABC','CDG','DAV','FE','FECA','FEAFA','FEA'] list2 = list1[1:4] Is that what you meant? -- charl p. botha http://cpbotha.net/ http://visualisation.tudelft.nl/ From bokr at oz.net Fri Jun 7 15:42:16 2002 From: bokr at oz.net (Bengt Richter) Date: 7 Jun 2002 19:42:16 GMT Subject: Medium to Large Scale Python Deployments References: <38C31EBA-79A4-11D6-9A7D-003065B33450@intersight.com> <3D003EC7.C72D27BE@engcorp.com> <3D006320.5040805@web.de> <3D00A209.EC24F671@engcorp.com> Message-ID: On Fri, 07 Jun 2002 08:07:37 -0400, Peter Hansen wrote: >J?rgen Hermann wrote: >> >> Peter Hansen wrote: >> > How big is that when run through pycount? >> > >> > (I.e. comments and blank lines don't count!) >> >> Summary on "twisted" >> ==================== >> files 256 >> lines 51654 >> bytes 1728211 >> comments 5993 >> empty lines 10029 >> non-commentary lines 29910 > >Thanks! Similar results to what I've seen over about 50000 >lines in 235 files. Roughly 50-60% code content, and >almost twenty percent blank lines. > >I suspect such numbers (perhaps excluding lines of comments) >are more consistent for Python code, whoever wrote it, >than for many other languages. > Is the "comments" number a count of _pure_ comment lines, # (like this one) ? I think it would be interesting to analyze comments further, to see what the relative comment byte count is overall, and for lines with both code and comments, """like this line:""" # (this has code and comment). Also maybe separate doc-string lines into a separate category, since they have a dual nature. Regards, Bengt Richter From jbublitzNO at SPAMnwinternet.com Wed Jun 19 14:42:50 2002 From: jbublitzNO at SPAMnwinternet.com (Jim) Date: Wed, 19 Jun 2002 18:42:50 GMT Subject: SWIG and Callbacks References: <3d0a8b6e@nntp.server.uni-frankfurt.de> <3d0b4fd6@nntp.server.uni-frankfurt.de> <3d0c6d67@nntp.server.uni-frankfurt.de> <3D0CE698.1050806@SPAMnwinternet.com> <3D0D3223.5070500@SPAMnwinternet.com> <3D0E2606.5050001@SPAMnwinternet.com> <3D0F807A.40203@SPAMnwinternet.com> Message-ID: <3D10D0A6.6030401@SPAMnwinternet.com> David Abrahams wrote: > "Jim" wrote in message > news:3D0F807A.40203 at SPAMnwinternet.com... > >>David Abrahams wrote: >> >>>"Jim" wrote in message >>>That's a given with Boost.Python; with v2 conversions are automatically >>>registered in a global repository so they can be re-used automatically >>>across extension modules. >>For C++ code with a lot of templates Boost.Python has an >>advantage, particularly if you're early on the learning curve. > Well, yes, but I wasn't talking about that. I was talking about re-usability > of conversions. My point was that if you wrap a class X in one module, you > can can wrap [member] functions that operate on X in another module. %Import links you to all of the code from another module (and it's antecedents). >>>OK. The C++ code you're wrapping still has to get by with #ifdef, I >>>suppose... >>Depends on the code I suppose. Qt and KDE just issue all >>new files - no versioning in the C++ code. > Ah. I guess if they were wrapped with Boost.Python, the wrapping code would > be treated the same, then? If you want to support that many filesets - I'm on the 8th PyKDE version (KDE2.1.1 -> KDE3.0.1) in 14 months (all still supported), amd I'll probably do one or two more releases in the next 6 months. Any of the versions can build against one of 3 or more different Qt versions (Qt2.3.0 -> Qt2.3.2, or Qt3.0.0 -> Qt3.0.4). It adds up. >>I finally went back to your website - I took your 'like an >>IDL' comments a little too literally. IMHO, the fact that >>Boost.Python *is* C++ is a big advantage for people who >>want/need that. Personally, I don't want to write C++, >>which is how I got into this in the first place. > A lot of people seem to feel that way. I believe they're called "Python users" :) (j/k) >>Thin wrappers are easily implementable with sip too. In >>contrast to the very large packages like PyQt and PyKDE, >>they tend to be very lightweight and quick to build. > Sorry, I think you misunderstood what I meant by "thin wrapper". A classic > trivial example might be used to wrap a function with default args: > // function to wrap > void f(int a, char* b = expression-1, Foo const& c = expression-2); > Thin wrappers: > void f1(int a, char* b) { f(a,b); } > void f2(int a) { f(a); } > wrapping code: > > module("my_module") > .def("f", f) > .def("f", f1) // overloads handle > .def("f", f2) // default args > ; > Obviously you can do arbitrary pre- and post- processing inside a thin > wrapper function. I think we mean the same thing. I've done thin wrappers for a spreadsheet plugin, and basically re-architected the entire API for Python, including things like changing the grid addressing from numeric row and col to more typical alphanumeric (eg (2, 6) -> "B6"). Full bindings would compile to several MB; binding just the wrapper took about 100K plus about the same for the wrapper. Most of the methods in the wrapper were 5 lines or less. sip code: void f (int, char * = expression1, Foo const& = expression2) [1] void f1 (int, char *); void f2 (int); [1] Might depend on what the expressions are - I've done constants and function/method calls as defaults, but not arbitrary expressions, so I'm not sure. It might take more than a line. OTOH, a real wrapper could throw out the defaults for 'f' (in Python) and replace them with f1, f2, etc. >>>>Yes, but I don't write it - I just edit it mostly to correct >>>>mistakes my description file generator creates and to handwrite >>>>code where the generator has flagged that. Crude but effective (TM) >>>>Even without automation, the process is easiest if you start by >>>>saving the h file with a .sip extension and then (mostly) delete >>>>the things that sip doesn't want/need, so it's still mostly >>>>editing (sometimes A LOT of editing). >>>That seems to be the key difference. It's not clear wether it's really >>>an advantage, but I suppose that time will tell. >>I doubt that it's ever clearly an advantage. > Really? It seems like it should lower the barrier to entry > and get people> started with an iterative development > process, at least. It certainly depends on the code you're generating bindings for, your knowledge of C++, maintability requirements, lots of other factors. > Probably the docs are the main obstacle there. It's amazing how many > different wrapping tools there seems to be a market for; people will try > anything once ! There's a lot of C++ compilers too, most of which are incompatible to some extent (certainly at the binary level). Choice is good. > Well, code comparisons are important in showing the system's user-interface. Project wide code comparisons might be useful, but that's more work than I'd want to do. >>Yes - it looks like that should be possible. Virtual code >>might require a little more work in generating Boost.Python >>code automatically, but the tradeoff is probably less things >>flagged as requiring handwritten code. > Not sure what you mean here about the tradeoff. Example? Basically a parser/code generator to create input files for sip is easier than the equivalent for Boost.Python, since for sip input files, I don't need to know anything about a class member except whether it's an enum, method or variable. Stuff like 'virtual', 'static', 'const', pure virtuals or default values is just syntactic noise - it just gets passed on to sip, which already knows how to deal with that stuff. Also, I can generate versioned code by comparing the code generated for a new h file with the previous version's sip (input) file - the same parser does both since the syntax is nearly identical. The version state transition logic is tricky and that's where I have problems automatically generating input files at the moment. Just generating a sip input file is pretty simple to automate and seems to work well. OTOH, Boost.Python seems to care more about whether methods are virtual or handling default values, and the 'input' files for Boost.Python are cpp files and the syntax is method calls instead of declarations - all that makes a parser harder to write IMO. There might be a different way to approach it that's easier - some intermediate file for example, or a variation on diff. The tradeoff is that it would be easier to automatically generate code for templates with Boost.Python than with a sip input file generator and in fact I just flag that stuff and write it manually the first time - it gets recycled on subsequent versions. The parser/input file generator/version generator in general seems to be easier with sip. It's probably not a concern for most people. Jim From radix at twistedmatrix.com Thu Jun 6 20:19:28 2002 From: radix at twistedmatrix.com (Christopher Armstrong) Date: 06 Jun 2002 20:19:28 -0400 Subject: Medium to Large Scale Python Deployments In-Reply-To: <38C31EBA-79A4-11D6-9A7D-003065B33450@intersight.com> References: <38C31EBA-79A4-11D6-9A7D-003065B33450@intersight.com> Message-ID: <87lm9sx7n3.fsf@twistedmatrix.com> > I'm also curious about large amounts of Python, period. Who knows of ~50K > Python lines-of-code (LOC) systems? 100K LOC? More? chris at radii:~/Projects/Twisted$ find -name '*.py' | xargs wc -l ... 56051 total http://twistedmatrix.com Twisted is a framework for writing asynchronous network apps. The reason it's so big, though, is that we pack a lifetime supply of batteries in the box. ;-) -- Chris Armstrong << radix at twistedmatrix.com >> http://twistedmatrix.com/users/carmstro.twistd/ From tim.one at comcast.net Sun Jun 23 17:38:36 2002 From: tim.one at comcast.net (Tim Peters) Date: Sun, 23 Jun 2002 17:38:36 -0400 Subject: Python hits the spot In-Reply-To: <7xfzzdhf07.fsf@ruckus.brouhaha.com> Message-ID: [P?r Kurlberg, sees this freeze some Linux box] > for i in range(50*1000*1000): > pass [Matt Gerrans] > You call that a bug? Did you consider trying xrange()? [Paul Rubin] > Maybe not a bug, but a pretty serious misfeature IMO. If it is, it's a serious misfeature of Linux's overcommitment policies. Python does a malloc() sufficient for 50*1000*1000 list elements at the start (about 200Mb), malloc doesn't return NULL, and Python believes it can use the memory. What would you like it to do instead? The platform libc and platform OS don't give any clue that they're making promises they can't keep. If at any point in the process this-- or any subsequent --malloc() returned NULL, Python would raise a well-behaved MemoryError and clean up the partial junk. But when the OS+libc refuse to give any hint of trouble, and themselves go nuts later, I don't accept that as being Python's problem. As noted, more recent versions of Linux kill the process (well, kill *some* process(es), probably including at least this one) instead of going completely insane. That sounds like a misfeature to me too, but it's outside of Python's control. python-isn't-an-operating-system-ly y'rs - tim From nas at python.ca Sat Jun 29 19:52:21 2002 From: nas at python.ca (Neil Schemenauer) Date: Sat, 29 Jun 2002 16:52:21 -0700 Subject: newbie Q: delete list few lines in file In-Reply-To: <7fe97cc4.0206291519.1c95ce31@posting.google.com>; from xah@xahlee.org on Sat, Jun 29, 2002 at 04:19:16PM -0700 References: <7fe97cc4.0206291519.1c95ce31@posting.google.com> Message-ID: <20020629165221.A12739@glacier.arctrix.com> Xah Lee wrote: > i have a folder full of individual email text file, whose ending may > be the following: > > _______________________________________________ > some mailing list > some at list.com > http://some.com/ttt > > I want to delete them, but only if they are the last few lines in the > file. I would use something like the following untested code: import os marker = ('some mailing list\n' 'some at list.com\n' 'http://some.com/ttt\n') for filename in os.listdir(sys.argv[1]): f = open(filename) f.seek(-1000, 2) tail = f.read() if tail.find(marker) >= 0: os.unlink(filename) The seek() call is only necessary if you're dealing with really large files. If you know the files are all pretty small and the script is a "one off job" then you could leave it out and read the whole file into memory. > * how to write to file inplace? (or, do i write to a new file, then > delete original, and rename the new file?) You need to open the file using the 'r+' or 'a+' flag. > * as far as a newbie, i use "xreadlines" module. I wasn't able to get > the total number of lines in a file. > li=xreadlines.xreadlines(f) > num=len(li) > fails. xreadlines returns something that conforms to the iterator protocol. The protocol does not require the __len__ method (which len() uses). You can probably just use readlines() instead. If the file is really big you need to explicitly exhaust the iterator and keep a count, eg: n = 0 for line in f.xreadlines(): n += 1 > is there a site or mailing list that collect very small trivial python > programs for learning purposes? Search for "Python Cookbook". Neil From emile at fenx.com Mon Jun 3 13:09:48 2002 From: emile at fenx.com (Emile van Sebille) Date: Mon, 03 Jun 2002 17:09:48 GMT Subject: UnboundLocalError: local variable part 2 References: <40a8aa92.0206030903.466fc3ff@posting.google.com> Message-ID: Daniel > That last example was a bit too contrived... instead of blah='abc', > blah is actually a list and i'm appending and popping elements so > func1 actually truly does affect the global blah. So a better example > of the logic is: There must be something else going on. I get exactly what you expected: def func1(): blah.pop() def func2(): print blah blah.pop() def main(): func1() func2() print blah blah=[1,2,3] main() [1, 2] [1] -- Emile van Sebille emile at fenx.com --------- From jadestar at idiom.com Wed Jun 19 20:26:07 2002 From: jadestar at idiom.com (James T. Dennis) Date: 20 Jun 2002 00:26:07 GMT Subject: directory References: Message-ID: Sean 'Shaleh' Perry wrote: > On 04-Jun-2002 Gold Fish wrote: >> How to read the subdirectories in the directory >> Support i have the directory /home/ which have some subdirectories >> /home/sub1 >> /home/sub2 >> /home/sub3 >> I am using os.listdir('/home/') to read in the list so it will be >> ['sub1','sub2','sub3'] now i want to read inside the sub directory sub2 >> once again i using os.listdir(os.listdir('/home/')[1]) but it came out with >> an errors: not a file or directory. Can anyone tell me what did i wrong. >> Anh how to fix it. > notice the values given by listdir('/home/') -> 'sub1', 'sub2'. listdir() > expects full path to a file. You need to do > listdir(os.path.join('/home', 'sub1')). More likely a better option would be > to use os.path.walk(). os.path.walk() uses an awkward interface. I wrote and posted this a couple of months ago: #!/usr/bin/env python2.2 ## Change the shebang line to match your needs! import os def dirwalk(startdir=None): if not startdir: startdir="." if not os.path.isdir(startdir): raise ValueError ## Is this the right exception stack = [startdir] while stack: cwd = stack.pop(0) try: current = os.listdir(cwd) except (OSError): continue for each in current: each = os.path.join(cwd,each) if os.path.islink(each): pass elif os.path.isdir(each): stack.append(each) yield(each) if __name__ == "__main__": import sys for i in sys.argv[1:]: for j in dirwalk(i): print j Notice that it implements a generator which is generally considered more pythonic than os.path.walk()'s "visitor" function. However, some people may prefer os.path.walk() or prefer a recursive version of dirwalk; some might prefer to make this a class, to instantiate directory walkers and obviate the need for the __future__ import. From shalehperry at attbi.com Wed Jun 5 21:01:06 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 05 Jun 2002 18:01:06 -0700 (PDT) Subject: Detecting OS and Window Manager In-Reply-To: Message-ID: On 05-Jun-2002 Andrew Wilkinson wrote: > Thanks for all the replies guys. > > Basically I want to have a program that hides itself in the taskbar of > whatever the user is running. Unfortunately there isn't (or at least I don't > know of) a portable way of doing this. I guess I'll just have to mess around > with looking for the environment variables and then code it up for > KDE/Gnome/whatever. > environment variables won't help you, they are not guaranteed. Also, even if the user is running parts of GNOME/KDE they may not have a panel running. Do you care if they see your window? If not perhaps you could just ask for it to be iconified. If you do care your best bet is to read about about "netwm" a quick google search should help. This is the mechanism for inter client talking in KDE, GNOME and other desktops. Using this you can make your app as a taskbar/panel style app and if they can accept it they will otherwise it gets treated like any other window. Shaleh Blackbox maintainer From idot at vt.edu Wed Jun 5 23:56:16 2002 From: idot at vt.edu (Carl Banks) Date: 5 Jun 2002 20:56:16 -0700 Subject: another near-sighted, time-wasting syntax enhancement idea Message-ID: class BigLongClassThatRunsUntilEOF:: def __init__ (self): pass def whatever (self): pass ... Two colons after the class (or whatever) definition means the block continues until EOF and is not indented. Good for big, long classes that take up a whole module. Been suggested before, I'm sure. -- CARL BANKS From ktf at nospamathotmail.com Sat Jun 15 01:33:00 2002 From: ktf at nospamathotmail.com (KTF) Date: Sat, 15 Jun 2002 17:33:00 +1200 Subject: VBA to Python Message-ID: In moving from using Access front end forms and code connected to an Access back end I am looking at changing to Java front end to SQL back end with a business rules engine using Python. These are busy forms and there is a lot of data validation (checking data input for correct format, string length etc), if this do that's, and directing of drop-down list content based on the entry or selection of the previous field (if this make, populate the next list with the models of the chosen make etc). Is Python a good choice to manage and run the rules and is there a way of transcribing the VBA code across to Python other than literally doing it line by line? Thanks, Keith From martin at v.loewis.de Sun Jun 9 15:57:23 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 09 Jun 2002 21:57:23 +0200 Subject: problem with isinstance and relative/absolute import References: <87adq8jsq1.fsf@tux.ntw23.fr> <87k7p8z8vv.fsf@tux.ntw23.fr> Message-ID: Sylvain Thenault writes: > actually I did understood what was the problem, I was only asking if this > behaviour should be considered as normal... Yes, certainly. > Since it's current in a package to mix relative (to the python file > directory) and absolute (package) import, isn't there a risk to > obtain a strange behaviour without being in the package directory ? If the current directory is not inside a package, then relative imports won't resolve through sys.path, but instead will resolve through the package which executes the import. Hence, the imported module will correctly show up as a submodule. Notice that you can produce the same problem in Java, which solves this problem with the package declaration on top of each file (so the problem exists only if you omit the package declaration). Guido is tempted to solve the problem by banning relative imports. Regards, Martin From peter at engcorp.com Mon Jun 17 20:36:47 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 17 Jun 2002 20:36:47 -0400 Subject: Problems with importing; must do it twice? References: Message-ID: <3D0E809F.AD9746A2@engcorp.com> Stew LG wrote: > > > My web host just switched hardware, and in > the process I've been moved to Solaris and > Python 2.1.1. > > My old scripts are breaking now, at the > very first line: > > import cgi; > > I think their Python install is broken, > but I wanted to be very sure before > I complained about it, since I've been > acting somewhat hysterically towards the > company's support lately - the move broke > a few things for me. Presumably the hosting company is escape.com? I just went through trouble-shooting the same problem for a friend (on my vacation in Manhattan! :-) and although this is out of my area of expertise, I concluded that they had either compiled Python with the wrong switch (asking for ssl support when they didn't have it installed) or that they were caught by an apparent glitch in the build process wherein it finds the header files for OpenSSL and builds support, even though the library itself (libssl.so, as you found) is not present. Two options I guess: get them to rebuild Python without SSL support, or get them to install the properly SSL libraries. (I'd appreciate hearing when/if you get this fixed, in case you manage to do it before my friend succeeds.) -Peter From achim.domma at syynx.de Tue Jun 18 02:50:21 2002 From: achim.domma at syynx.de (Achim Domma) Date: Tue, 18 Jun 2002 08:50:21 +0200 Subject: ImageMagick for Python incl. Source References: Message-ID: "Fernando P?rez" wrote in message news:aelo0t$sog$1 at peabody.colorado.edu... > Sorry to display my ignorance here, but what on earth is a "Jamfile"? You > should either specify that to build this on other platforms you need 'bjam' > (non-standard in the Unix world) giving a link to it, or (more likely to be > useful) provide a normal Makefile for the build. I tried google(bjam) and got > all sorts of irrelevant links. Under Linux, 99% of the people will try to > build this using gcc/make, so a simple makefile will probably do. ImageMagick for Python is based on boost.python, which uses the boost build system so ImageMagick for Python uses it also. I realy like it, because it works on windows and unix and was much easier to learn for me than make and autoconf. But your are right, that the webpage was not clear enough. I added a link to the required tools. > An unrelated question: do you know what advantages ImageMagick has over PIL? I > ask out of honest curiosity. I've long been an ImageMagick fan, but since > Python has sort of 'builtin' imaging support via PIL, I wonder what the Because I have used both mainly for resizing and converting the image format, my experiences are somewhat restricted. ImageMagick seems to support much more image formats. I had some problems with PIL with some png types. In general ImageMagick looks more complete to me. > differences are. Anyway good luck with this, I love ImageMagick so I hope > your project can be built under Unix soon. Thanks, I'll do my best but I usually work on windows only, so I can't test other plattforms. Achim From DLNXPEGFQVEB at spammotel.com Tue Jun 11 04:19:53 2002 From: DLNXPEGFQVEB at spammotel.com (Christos TZOTZIOY Georgiou) Date: Tue, 11 Jun 2002 11:19:53 +0300 Subject: Newby: What's the problem with this string? References: Message-ID: On 10 Jun 2002 13:04:18 GMT, rumours say that fishfinger might have written: >For some reason I can't read this string from the command line ... [snip of multi-line string] >Why is that? And how can I make it work properly? The method I'm using is >....... > >ttt = raw_input("a string:") raw_input stops reading as soon as you press the Return / Enter key. IIUC, you need to ask for more lines until some predefined condition is met. The following returns a multiline string (keeps asking for more until you input a single period): # tested python>=2.2.1 def raw_multi_input(prompt): prompted_input= lambda: raw_input(prompt) input_lines= [] for input_line in iter(prompted_input, "."): input_lines.append(input_line) return '\n'.join(input_lines) -- TZOTZIOY, I speak England very best, Real email address: 'dHpvdEBzaWwtdGVjLmdy\n'.decode('base64') From kp at kyborg.dk Mon Jun 17 08:24:01 2002 From: kp at kyborg.dk (Kim Petersen) Date: Mon, 17 Jun 2002 14:24:01 +0200 Subject: Tkinter and threads References: <3D0DCC8F.9A6D3B81@ipm.fhg.de> Message-ID: <3D0DD4E1.40803@kyborg.dk> Markus von Ehr wrote: > Hi, > > I'd like to have a progress bar increasing while a calculation process > calculates some results. > Unfortunately there is no mainloop processing while the calculation is > running and so the progress bar begins after the calculation. > Another thread neither can access the Tkinter resources, how can > I manage this problem? sprinkle the loop with tk.update() calls, would be my best guess > > I appreciate any help, > > Markus > > > From talon34 at hotmail.com Tue Jun 25 22:34:54 2002 From: talon34 at hotmail.com (Talon) Date: Wed, 26 Jun 2002 02:34:54 GMT Subject: Installation problems DCOracle2 & W2000 Message-ID: Hi all, I am having a heck of a time getting DCOracle2 to funcion properly. I am running on a W2K machine, python2.1.3 and Zope 2.5.1, both of which run just fine. I installed DCOracle2 and the ZOracleDA under Zope and it works fine. But standalone python scripts don't see the dco2.py module. So I tried to install DCOracle2 in the python21/lib folder. I got that latest version from Zope.org and it said it installed properly. But it doesn't run. If you try to import it into a script, you get complaints that it can't find this or that module, all of which are part of the Zope path. I tried the odbc package, and it works for SELECT's but has a problem with INSERT's. I downloaded the mxODBC package, but haven't tried it yet and I've read about the cxOracle module. Does anyone have any advice? The docs for Windows install of DCOracle2 are really poor and inconsistent. I would like to stay with DCOracle2 if possible, since that is what is running on Zope, but I will consider anything that works. TIA, Mark From pedrovl at yahoo.com Thu Jun 6 04:43:37 2002 From: pedrovl at yahoo.com (Pedro Vale Lima) Date: 6 Jun 2002 01:43:37 -0700 Subject: Medium to Large Scale Python Deployments References: Message-ID: <82afc355.0206060043.d26564e@posting.google.com> "Domenic R. Merenda" wrote in message > > I am running a home-grown Enterprise Resource Planning system, written > entirely in Python Hello, Could you tell us more information about your system (Database Server, User Interface, Communication protocol, etc)? I am running an ABAP based ERP but I'm pretty sure your is better :-) regards, Pedro Lima From tchur at optushome.com.au Sat Jun 22 17:22:18 2002 From: tchur at optushome.com.au (Tim Churches) Date: Sun, 23 Jun 2002 07:22:18 +1000 Subject: Web templating/db tool with best designer/coder separation? References: Message-ID: <3D14EA8A.E1027830@optushome.com.au> Bengt Richter wrote: > > E.g., if you were hoping for an improvement over current practice, > which do you consider to be the tool(s) to beat, and what would > the killer improvement(s) be? TIA. Albatross by Object Craft (see http://www.object-craft.com.au ) does an excellent job of separating the presentation layer from the underlying logic - my understanding is that such separation was one of its main design goals. However, it does not take a pedantic position on this - it still allows Python code to be embedded in HTML templates - such practice is discouraged, but Albatross provides mechanisms to allow you to do it if you insist. But more usefully, Albatross provides tags which allow conditional processing (if-elif-else) and most usefully, iteration, to be placed in the HTML template. So your Python business logic code can assemble a Python sequence of, say, database query results, but it is the HTML template which iterates through that list to create the final HTML which is sent to the user's browser. Such a feature is essential, because otherwise the business logic Python code ends up needing to creating HTML output itself, which is then merely substituted into the HTMl template. Thus, the Albatross model is really more like: "all HTML-related stuff, including conditional processing and iteration, is looked after in the HTML templates, and all business logic stuff, divorced from the manner in which it will be presented, is handled by Python modules." Of course, this is just the well-known model-view-controller approach, but Albatross implements this very nicely, IMO. See http://www.object-craft.com.au/projects/albatross/albatross/fig-presimpexec.html for more information about this (and to get an idea of the depth of the Albatross documentation). I suspect that the Object Craft guys would welcome help with further development of Albatross. What the world really needs are more Pythonic Web applications, rather than more Pythonic Web application frameworks. Tim C From tjreedy at udel.edu Tue Jun 4 11:37:51 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 04 Jun 2002 15:37:51 GMT Subject: sharing data in list sub-classes References: <87znybyzsg.fsf@zaraza.fep.ru> Message-ID: "Sergei Barbarash" wrote in message news:87znybyzsg.fsf at zaraza.fep.ru... > Hello, > > Is there a way to share list data in classes that inherit the "list" class? > > Example: > > ,---- > | class A(list): > | > | > | mem = [1,2,3,4,5] > | > | a1 = A(mem) > | a2 = A(mem) Try a2 = a1 instead > | > | a1[0] = 1024 > | if a2[0] == 1024: > | print "Everything's fine" > `---- > > With obsolete UserList module it works fine, because it stores the data in > self.data variable. Is there a "right" 2.2-ish way to do the same thing? > > Thanks, > -- > Sergei From tim.one at comcast.net Thu Jun 6 15:28:11 2002 From: tim.one at comcast.net (Tim Peters) Date: Thu, 06 Jun 2002 15:28:11 -0400 Subject: array, list, performance... In-Reply-To: <3CFFB86A.4114459A@accessforall.nl> Message-ID: [Michael Chermside] > li = [x0, x1, x2, ...] > ... > li.append(x) appending is O(1) > (actually, it SOMETIMES takes O(len(li)) as it > resizes the list. But if you grow a list by > continually appending, the amortized time is > linear (ie, constant amortized time per element) [Ype Kingma] > Append is often enough linear in the length of the list > that growing by appending is O(len(li) * len(li)). For Python 2.2 Michael is correct. For Python 2.1 and earlier, you're correct "in theory", although in practice it was often linear-time anyway, depending on internal details of the platform realloc. > You can prevent that by creating a list a large enough list > when starting, eg: > > li = [None] * neededSize Yup, and that can save time regardless. From pyth at devel.trillke.net Thu Jun 13 19:25:42 2002 From: pyth at devel.trillke.net (holger krekel) Date: Fri, 14 Jun 2002 01:25:42 +0200 Subject: returning traceback strings In-Reply-To: ; from cliechti@gmx.net on Fri, Jun 14, 2002 at 12:50:09AM +0200 References: Message-ID: <20020614012542.O6609@prim.han.de> Chris Liechti wrote: > Matthew Boedicker wrote in > > > > This is the best workaround I was able to come up with: > > > > import cStringIO > > import traceback > > > > def print_exc_str(): > > buf = cStringIO.StringIO() > > traceback.print_exc(file=buf) > > return buf.getvalue() > > try that: > ''.join(traceback.format_exception(*sys.exc_info())) yeah. why not take the easy road :-) holger From huaiyu at gauss.almadan.ibm.com Fri Jun 7 18:24:13 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Fri, 7 Jun 2002 22:24:13 +0000 (UTC) Subject: positional modifiers in python? References: Message-ID: Eric Brunel wrote: >fuf wrote: >> hello everyone, >> >> does python support positional parameters in the print method? ie. >> something like: >> print "there %2$s something %1$s" % ("there", "is") >> it doesn't work but maybe there's some other way? > >There's an utterly ugly way to do this: > >def toPosDict(l): > d = {} > map(lambda k,v,d=d: d.update({str(k):v}), range(len(l)), l) > return d >print "there %(1)s something %(0)s" % toPosDict(("there", "is")) > >For post-Python 2.2 users (I'm still 2.1, sorry), the "map" line may >certainly be replaced by: > >map(d.__setitem__, [str(i) for i in range(len(l))], l) > >but it may be less efficient than the code above (one map + one list >comprehension instead of a single map in the first solution). Maybe the >second's a little more readable (or a little less unreadable ;-). Or if you prefer functional programming style (Only for 2.2): def str_enum_dict(x): return dict(zip(map(str, range(len(x))), x)) print "there %(1)s something %(0)s" % str_enum_dict(('there', 'is')) Huaiyu From peter at engcorp.com Mon Jun 24 21:51:10 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 24 Jun 2002 21:51:10 -0400 Subject: Suggestions for good programming practices? References: Message-ID: <3D17CC8E.ABB72D14@engcorp.com> Brian Quinlan wrote: > > Peter Hansen wrote: > > You _are_ returning them "in a struct". It's spelled "tuple" > > but other than that what's the difference? > > struct members are access by name while tuple elements are accessed > positionally. Okay. So why is that a problem? Or to ask it from the other side, what's stopping you from returning items in an object? class Struct: pass def returnStruct(): result = Struct() result.anInt = 5 result.aString = 'foo bar baz' result.spam = ('eggs', 'brian') return result -Peter From sonnenbu at informatik.uni-bonn.de Sat Jun 8 13:58:43 2002 From: sonnenbu at informatik.uni-bonn.de (Frank Sonnenburg) Date: Sat, 8 Jun 2002 19:58:43 +0200 Subject: scope of module functions References: Message-ID: "Chris Liechti" schrieb im Newsbeitrag news:Xns9227C812CD4B2cliechtigmxnet at 62.2.16.82... > "Frank Sonnenburg" wrote in > news:adte4c$nu8$1 at f1node01.rhrz.uni-bonn.de: > > a little tricky problem (at least from my point of view); given module > > CALLER: > > > > # i need "fct" and some other from module "UTILS" > > from UTILS import * > > fct() > > # END of module CALLER > > > > > > Now, inside fct(), how do i determine the module - in this case CALLER - > > from where fct() was called? > > i think __name__ can help in this case but not in the one below. > but are you sure that you wan't t do this? a function that behaves > differently depending on the namespace gives very hard times debugging... > > a cleaner solution would be to create an class that contains fct and each > module that uses it can create its own object. > > if you can say what you want to achieve, we might give you a more specifuc > advice. > > > Even concerning cases like (continuation of example): > > > > # Now we are in __main__ > > import CALLER > > fct_in_main = CALLER.fct > > fct_in_main() > > > -- > Chris > Yes, actually i thought of classes as a workaround. I have a tool with a large amount of functions, so i grouped them into a menu tree. My first approach was a package solution, which has nice advantages: easy to build, unique access to any function. But there is a main disadvantage: function names can get very long, for instance: utils.database.sql.fetch() Instead i want to enter: >> import utils >> database() # do something in database, then switch to submenu sql >> sql() # now sql commands like fetch() are visible >> val = fetch('name') # now return to parent menu database >> end() # now fetch() is not available any more ......... Anyway, thanx a lot for your quick response! Frank From hst at empolis.co.uk Tue Jun 11 05:59:08 2002 From: hst at empolis.co.uk (Harvey Thomas) Date: Tue, 11 Jun 2002 10:59:08 +0100 Subject: Sorting list (maybe stupid) Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB04F3CF@hendrix.empolisuk.com> J?rvinen Petri wrote > > Hey, > > I have a problem and can't solve it: > > There is lines of text like: > > 2. Header2 > 1. Header1 > 102. Header102 > > and so on... > > And I need to sort them according to the number (1,2,3,4...) > > Am I missing something.. I have tried to split the lines by > whitespace and > create lists. But how can i sort the list by first element... > > Thanks, Petri > -- Here's a quick and dirty 2.2 program illustrating one way. It uses a regular expression to extract the leading number, creates a tuple of the leading number (zero if none) and the original text. It then sorts the list of tuples in place and prints the second element of each tuple. import re r = re.compile('\d+') afile = open('myfile.txt') tuplelist = [] for aline in afile: m = r.match(aline) if m: tuplelist.append((int(m.group(0)), aline)) else: tuplelist.append((0, aline)) tuplelist.sort() for x in tuplelist: print x[1] HTH Harvey _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From gerhard at bigfoot.de Wed Jun 19 03:02:25 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Wed, 19 Jun 2002 09:02:25 +0200 Subject: zlib/gzip + anydbm or ... In-Reply-To: References: Message-ID: <20020619070225.GA9430@lilith.my-fqdn.de> * James T. Dennis [2002-06-19 03:40 +0000]: > > Is there an obvious and simple way to use the existing standard > libraries to support transparently compressed dbm files? I don't think so. If at all, you'll need to hack dumbdbm to achieve this goal, I think only two approaches are feasible: - compress the whole file with zlib, this means you need to keep the whole file in memory - compress only values with zlib Option two could even be written with a simple wrapper around anydbm, but will obviously only help if your average values are relatively large. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 25.2 ?C Wind: 3.4 m/s From pyth at devel.trillke.net Tue Jun 18 18:14:14 2002 From: pyth at devel.trillke.net (holger krekel) Date: Wed, 19 Jun 2002 00:14:14 +0200 Subject: python version? In-Reply-To: <%%NP8.46690$GY.14560922@twister.nyroc.rr.com>; from hesterloli@hotmail.com on Tue, Jun 18, 2002 at 09:56:11PM +0000 References: <3tingu8psfmefoab93pl8gips8hg7sgpvp@4ax.com><9YBP8.44418$GY.13865843@twister.nyroc.rr.com> <20020619091900.70ae2b7f.larooy@xtar.co.nz> <%%NP8.46690$GY.14560922@twister.nyroc.rr.com> Message-ID: <20020619001414.G15079@prim.han.de> George Hester wrote: > oops: > > No George was asking for a script he could put in a ASP to determine his version > of Python. well. your original question was: What is a simple script that will tell me the version of python I am currently running? IIS 5.0 Windows 2000. Had you given the details above i guess you would have received other and fewer answers. I for one tried to answer the sentence up to the question mark. which didn't help you. But no matter if people answer to your satisfaction or not. IMO it's bad style to be aggreesive for not beeing served exactly the way you expect it. regards, holger From gumuz at looze.net Fri Jun 21 06:53:41 2002 From: gumuz at looze.net (Guyon Morée) Date: Fri, 21 Jun 2002 12:53:41 +0200 Subject: Socket Disconnection Message-ID: <3d1304d0$0$224$4d4ebb8e@news.nl.uu.net> Hi! I have written a small and simpel server and I was wondering how do you find out that a client has disconnected? thnax, Guyon From whisper at oz.net Sun Jun 2 16:15:23 2002 From: whisper at oz.net (David LeBlanc) Date: Sun, 2 Jun 2002 13:15:23 -0700 Subject: Does this widget exist? In-Reply-To: <24d8090a.0206011740.49d253e3@posting.google.com> Message-ID: Yep: MCScrolledListBox A scrolled list with multiple columns. Supports various selection modes. Display and selection values are sequences of tuples (no formatting or parsing!). http://pmwcontribd.sourceforge.net/ Populating one with files data is left as an exercise for the reader ;-) David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Corey Woodworth > Sent: Saturday, June 01, 2002 18:40 > To: python-list at python.org > Subject: Does this widget exist? > > > Is there a Tk widget that lists files like you see in napster or > winMX. (you know with the kb/sec and frequency buttons up top to sort > things.) > > If I use the search feature in windows and I select the details view I > get a widget very similar (except of course windows isn't written in > python) :) > > Corey > -- > http://mail.python.org/mailman/listinfo/python-list From emile at fenx.com Tue Jun 25 11:42:02 2002 From: emile at fenx.com (Emile van Sebille) Date: Tue, 25 Jun 2002 15:42:02 GMT Subject: Sending string var with apply sends all chars as params!??? References: Message-ID: Etienne > value = apply(formatter,(str(value))) Try passing in a tuple, eg: value = apply(formatter,(str(value),)) >>> def fmt(*args): ... print args ... >>> s = '20020625140609' >>> apply(fmt,s) ('2', '0', '0', '2', '0', '6', '2', '5', '1', '4', '0', '6', '0', '9') >>> apply(fmt,(s,)) ('20020625140609',) >>> -- Emile van Sebille emile at fenx.com --------- From tjreedy at udel.edu Mon Jun 3 09:59:21 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 03 Jun 2002 13:59:21 GMT Subject: solarwolf display ? References: Message-ID: "Tae kyon" wrote in message news:slrnafl9gv.5h4.Taekyon at macchinetta.miadimora... > On a Mandrake 8.2 system I compiled pygame 1.5 and solarwolf 1.5.1. > I have a matrox millennium g200 8 Mb video ram graphics card with 3d support > by XFree86 4.2.0, and a SVGA non-interlaced video with HSync 30-54, > VSync 50-90. I even get to play tuxracer at a good framerate ! But for > some reason 800x600 fullscreen displays will not work (some loki games > have to be played in a window, for instance, and nethack must be played > on a 1024x768 display). > > Unfortunately it seems that solarwolf uses this type of display. > I know very little about python, nothing about pygame; anyway I tried > setting the video mode by changing the relevant options in > pygame.display.set_mode(()) ... but nothing seems to work. > > Any tips ? I believe that there is a PyGame mailing list. A question this specific is more likely to get a proper answer there. TJR From K.Rdt at TU-Berlin.DE Sun Jun 16 15:07:37 2002 From: K.Rdt at TU-Berlin.DE (Klaus Reinhardt) Date: Sun, 16 Jun 2002 19:07:37 GMT Subject: HT telnet interact with auto login? References: <3d0cd198.17917980@news.zrz.tu-berlin.de> Message-ID: <3d0ce0df.21829780@news.zrz.tu-berlin.de> On 16 Jun 2002 21:55:15 +0200, Chris Liechti wrote: >K.Rdt at TU-Berlin.DE (Klaus Reinhardt) wrote in >news:3d0cd198.17917980 at news.zrz.tu-berlin.de: >> I want to combine: >> >> 1.) >> tn.interact() # this is working but with manually .. >> 2.) >> tn.read_until("login: ") # this seams to work >> # but without connection >> tn.write(user + "\r\n") >> if password: >> tn.read_until("Password: ") >> tn.write(password + "\r\n") > >i don't understand your question... but often a '\r\n' is required >as end of line. maybe this helps :-) > >chris The \r don't help. Well, I want to have a script, which establishes automatically a telnet-connection, so I can there do some console-processing. My feeling is wrong, that I can give user and password to interact() .. perhaps there is another function .. Thanks Klaus From FooWeissBarMike at hotmail.com Mon Jun 24 11:44:49 2002 From: FooWeissBarMike at hotmail.com (Michael Weiss) Date: Mon, 24 Jun 2002 11:44:49 -0400 Subject: Numerical Python array math with different sized arrays Message-ID: <3d173f56$1@news.mhogaming.com> I'm using Numeric Python's arrays. I want to perform the various math operators between arrays (+-*/ etc...) . While all my arrays are 1 dimensional, they may be different lengths. The result I'd like in a mis-matched size case is the following: >>> a = Numeric.array([1,2,3,4]) >>> b = Numeric.array([1,2]) >>> print a+b [2,4,3,4] I assume the answer is to resize b, and make the new elements all zero. My question is what is the fastest way to do this. Resize() does that repeating thing, which is not what I want (I want zeros in those new elements). I've tried the following, is there a better way? ##### lena = len(a) lenb = len(b) if lena == lenb: numa = Numeric.array(a) numb = Numeric.array(b) elif lena > lenb: numa = Numeric.array(a) zeros = Numeric.zeros((lena-lenb,)) numb = Numeric.concatenate((b, zeros, )) else: zeros = Numeric.zeros((lenb-lena,)) numa = Numeric.concatenate((a, zeros, )) numb = Numeric.array(b) numans = numa+numb ##### From logiplexsoftware at earthlink.net Wed Jun 26 13:49:23 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Wed, 26 Jun 2002 10:49:23 -0700 Subject: question od default args In-Reply-To: References: Message-ID: <20020626104923.45f54821.logiplexsoftware@earthlink.net> On Wed, 26 Jun 2002 18:45:25 +0100 Gon?alo Rodrigues wrote: > Hi, > > When I want default args I usually do > > def (arg = None): > ... > > But what if I want to make None a reasonable argument too? That is, I > want to know if the user has in fact passed an argument, and if not to > do something special, with None (or whatever object) being a reasonable > arg to be passed. How about: def foo(*args, **kwargs): argc = len(args) + len(kwargs) if argc == 0: print "no arguments" # set default values else: print argc, "arguments" # assign arguments to attributes or whatever Then if the user passes None as an argument, argc will still be 1. You can then get the arguments from args and kwargs. Regards, -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From michael at damaru.com Sun Jun 9 13:07:15 2002 From: michael at damaru.com (Michael Davis) Date: Sun, 09 Jun 2002 13:07:15 -0400 Subject: libftp.size function gives wrong results! References: <3D038A19.D991A885@engcorp.com> Message-ID: <%ULM8.903$Yw3.118334@news20.bellglobal.com> Peter Hansen wrote: > Michael Davis wrote: >> >> I'm writing a python program which will upload or download files via ftp. >> It's intended to be used to deploy a web site from a local machine to a >> server. It tries to determine which files are modified on the local >> machine by comparing file sizes and modification times. >> >> I try to compare files using os.stat for the local file and FTP.size for >> the remote. The problem is, FTP.size is giving me incorrect results. If I >> use the ftp command line client, and look at one of my files on the >> server (the output looks like 'ls -l') then I can see that the file size, >> is, say, 1200. But the FTP.size function returns, say, 1242. > > I think you'll find the number of lines in that file is 42. The > difference > is probably between CRLF and LF line terminations in the file. If you > transfer files with FTP and want to preserve the line endings, you have > to specify the binary type, not ascii. Don't know how to do this with > ftplib, but from the ftp command line you would use 'type binary' or > 'type ascii' to switch. Thanks Peter, I had already thought of that. Both my local and the remote systems are unix, and so don't have CRs. But you're right - the difference in size is the same as the number of lines, as though the ftp size command assumed that I wanted to convert the end-of-lines to CRLF. I had specified binary mode transfers. And if I do 'ftp size' on true binary files, the same problem happens! Anyway, I just found out that one of the servers I need to talk to doesn't allow me to use 'size' anyway, so I'm going to ask a different python question in a different message. Thanks again, -- Michael Davis Damaru Custom Programming - Web Development - Database Design http://www.damaru.com 416-540-1284 From hesterloli at hotmail.com Wed Jun 19 16:27:08 2002 From: hesterloli at hotmail.com (George Hester) Date: Wed, 19 Jun 2002 20:27:08 GMT Subject: python version? References: <3D0E8AC8.6C5C96EE@engcorp.com> <37TP8.47886$GY.15021139@twister.nyroc.rr.com> <3D1010C3.C321F8B0@engcorp.com> <3D107948.B3FEE4BB@engcorp.com> Message-ID: All fixed -- George Hester _________________________________ "Huaiyu Zhu" wrote in message news:slrnah1l0i.6o5.huaiyu at gauss.almadan.ibm.com... > George Hester wrote: > > But the reason I > >mentioned is that I hoped that my students would take an interest in the subject > >and learn the concept. They were not interested but they needed the credit to > >graduate. In my case I was not necessarily interested in learning Python. But > >I did want to determine my version of Python in ASP. I suppose I was like my > >students and ya'll were like the teacher. Yes basically I wanted it handed to > >me on a platter. What I did with the platter may have surprised you. So just > >becasue somebody wants something handed to them on a platter does not mean the > >contribution has less value. > > Being able to communicate effectively in Usenet may be an important skill > for your students to master. You may want to teach them some lessons you > have learned yourself. Here's a mini multiple choice questionair to get you > started: > > 1. Suppose you want to get an answer to a question handed down on a platter, > which would be the more effective question? > a) What is the simplest script to get Python version? > b) I know nothing about Python. I just want to know its version from ASP, > what's the easiest way to get it? > > 2. Suppose you are given an answer that is all Greek to you, which would be > the more effective response? > a) I don't think you guys know anything about this. > b) I think I need a script to do this. > c) This is well over my head. I'm newbie. Please explain the details, > keeping in mind that I only want to get the version from ASP. > > 3. If someone tells you that you are going about it the wrong way and gives > you some advice which sounds like a detour to you, do you judge it based > on > a) whether he is your daddy. > b) whether the advice has merits. > > 4. Once you realize that all the answers people gave you were real, some > much simpler than you imagined before, and that your accusations earlier > were largely based on arogance, do you > a) Say: Hey, you guys didn't gave me the answers the way I wanted, and > your tones were derogotory. > b) Go away quietly. > c) Say: Thanks for all the answers. Even though I didn't ask the > question clearly, one of answer was exacted what I wanted. Sorry for the > tone of my earlier posts, which was largely because I didn't recognize > the answers. > > > No doubt others can add more lessons learned from this episode. > > Huaiyu From usenet at minus1.de Mon Jun 24 03:05:00 2002 From: usenet at minus1.de (Konrad Anton) Date: Mon, 24 Jun 2002 09:05:00 +0200 Subject: mail-problem over t-online References: Message-ID: Klaus Reinhardt schrieb: >Testing python and email I adapted this script: > > host=smtplib.SMTP('mailszrz.zrz.tu-berlin.de') > host.sendmail(zwi_eck(From),zwi_eck(Tp),al) > host.quit > >This is working, when I'm directly connected to my >old ISP TU-Berlin via ISDN. But the same is failing, >when I'm connected at t-online via ADSL, with >authentification required .. Providing my log and pass >produces errors, too. First, try if this also happens if you do the SMTP dialogue using telnet. telnet mailszrz.zrz.tu-berlin.de 25 HELO meinhostname.meinedomain.de MAIL FROM: soundso at tu-berlin.de RCPT TO: blabla at tu-berlin.de DATA Dies ist ein Test . -- Konrad -- Konrad Anton ; Web: www.minus1.de ; gpg: 0x22954D8A Tel. +49-761-881-2122, Fax +49-721-151318943. Alice: And I've something: such as the two looking at the directions, just the earls of the Duchess, I didn't! From edream at tds.net Sat Jun 22 22:33:00 2002 From: edream at tds.net (Edward K. Ream) Date: Sun, 23 Jun 2002 02:33:00 GMT Subject: ConfigParser & converting strings to lists References: <3D152A28.2177B054@tds.net> <3D152C69.CC41ADB0@tds.net> <3D1531DD.ACF06E31@engcorp.com> Message-ID: <3D15335C.8CB1558D@tds.net> > > so it is strings of the form "['file1' 'file2' ...]" that must be > > converted to a list of strings. > > >>> s = "['file1' 'file2' '...']" > >>> [x[1:-1] for x in s[1:-1].split()] > ['file1', 'file2', '...'] > > Does that do it? I'm not sure. Here is what I did: s = config.get(section,"recentFiles") files = [x[1:-1] for x in s[1:-1].split()] Is this what you intended? This doesn't work for me: it "doubles" every backspace. I am already regretting trying to be clever. It is easy enough to set file individual filenames like this: for i in xrange(len(files)): config.set(section, "file"+`i`, files[i]) and to get up to n file names like this: try: for i in xrange(n): files.append(config.get(section, "file" + `i`)) except: pass This is bulletproof: filenames can contain any character at all. The only drawback is that the config file looks like: [recent files] file0 = filename0 file1 = filename1 ... But this isn't so bad, is it? Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From whisper at oz.net Sat Jun 15 12:20:43 2002 From: whisper at oz.net (David LeBlanc) Date: Sat, 15 Jun 2002 09:20:43 -0700 Subject: SWIG and Callbacks In-Reply-To: <3d0b4fd6@nntp.server.uni-frankfurt.de> Message-ID: No, that understanding is not wrong, but it will enable you to write python callbacks. From reading the doc and looking at examples, writing Boost/Python interfaces isn't all that arduous. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Michael 'Mickey' Lauer > Sent: Saturday, June 15, 2002 7:32 > To: python-list at python.org > Subject: Re: SWIG and Callbacks > > > David Abrahams wrote: > > > "Michael 'Mickey' Lauer" > wrote in > > message news:3d0a8b6e at nntp.server.uni-frankfurt.de... > > > > > >> I had a quick look at the other wrappers (SILOON, GRAD, CXX, etc.) > >> but most look either outdated or not appropriate for this task. > >> Do you know an (automatic) wrapper generator which has this feature? > >> > >> I know sip can do this for c++ libraries - can sip also be used > >> to wrap plain c-libs without "handwriting" code? > > > > On most platforms, Boost.Python would work for you. The > determining issue is > > whether or not the C++ compiler treats "C" and "C++" linkage function > > pointers the same way. If the appended program will compile > with your C++ > > compiler, you're probably OK: > > The attached program compiles fine here. However, regarding boost.python I > thought this was more of a c++ library for handcrafting tightly integrated > bindings rather than an automatic wrapper generator? Is this > understanding wrong? > > Yours, > > :M: > > -- > http://mail.python.org/mailman/listinfo/python-list From vjovanov at stevens-tech.edu Tue Jun 4 14:35:24 2002 From: vjovanov at stevens-tech.edu (Vojin Jovanovic) Date: Tue, 4 Jun 2002 14:35:24 -0400 Subject: self References: Message-ID: > Which of i, j and k are instance variables? Which are locals? Which are > globals? For all its virtues, Python isn't telepathic . Well, now that you pointed it out, I think that Python should be telepathic. Those i,j and k variables should have been found in class C, otherwise they should have been searched outside of the class. I read the FAQ page that somebody sent me and I really think that the main reason for self is ... "When classes were added to Python, this was (again) the simplest way of implementing methods without too many changes to the interpreter. " which is the main and really lousy argument. All, other arguments are debatable. Now let me give you the problem with self which is making my life complicated. Consider this class. class Foo: def __init__(self): self.__dict__['Equations']={ 'a':str(5), 'b':'self.a+5', 'c':'self.b*self.a'} def __getattr__(self,arg): if self.Equations.has_key(arg) == 0: raise AttributeError, "Foo instance has no attribute '" + arg + "'" try: try: #first check if this is a simple expression return eval(self.Equations[arg]) except: #if not try to execute it exec self.Equations[arg] except: #if even that didn't work then just return undefined return '#U' def __setattr__(self,arg,val): self.__dict__['Equations'][arg]=str(val) def __delattr__(self,arg): del self.__dict__['Equations'][arg] This class implements a kind of symbolic behavior with the ability to add new equations on the fly. For example... >>> import foo >>> A=foo.Foo() >>> A.Equations {'b': 'self.a+5', 'c': 'self.b*self.a', 'a': '5'} >>> A.f='self.b*self.c' >>> A.f 500 >>> A.Equations {'f': 'self.b*self.c', 'b': 'self.a+5', 'c': 'self.b*self.a', 'a': '5'} As you can see, equations get added on the fly and the parsing gets done as the attribute is being called. Now, notice that ugly self. thing in the equations. Instead of just typing >>>A.f='a*c' I have to add self in front a and c to achieve the desired effect. I could not find any other way to implement the class in order to avoid typing self. which of course it doesn't mean that there isn't any. If anybody has an idea how to do this please let me know. Otherwise, here is the situation where the self concept is bad and having such a dynamic language like Python I think there has to be a way out of this problem. Why is this all relevant? Well, I am working on embedding an interpreted language in a large engineering application and Python is one of few candidates. So I have been looking for its pros and cons. So far it passed all the tests except the above. Because, imagine if we required from the user of our system that he needs to type self. or even s. in front of every new variable that he has in his equation, it would be a big turn off. Vin From shalehperry at attbi.com Thu Jun 27 16:13:51 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Thu, 27 Jun 2002 13:13:51 -0700 (PDT) Subject: self destruction :) In-Reply-To: Message-ID: On 27-Jun-2002 Guyon Mor?e wrote: > i've got a list of dynamicaly instantiated objects of a class of my own. how > can i let one of the objects delete itself? > > i've tried: 'del self', but somehow it didn't work. afterwards it should > also _not_ be in the list anymore. > mylist = [obj1, obj2, ....] del obj1 # mylist still has a reference to obj1 so # the del simply decrements the ref count From erict at millfilm.co.uk Thu Jun 6 09:36:41 2002 From: erict at millfilm.co.uk (Eric Texier) Date: Thu, 06 Jun 2002 14:36:41 +0100 Subject: HttpServer help! References: <3CFF4C14.450850D8@millfilm.co.uk> Message-ID: <3CFF6568.7EE613CE@millfilm.co.uk> The server and the client run from the same directory. and the cgi file is in the same directory. all the following failled. req.putrequest("POST", "favquote.cgi") req.putrequest("POST", "/favquote.cgi") req.putrequest("POST", "./favquote.cgi") What is the meaning of *relative to the server root* Steve Holden wrote: > "Eric Texier" wrote in message > news:3CFF4C14.450850D8 at millfilm.co.uk... > > I am trying to get some simple example running locally on my > > machine of http(server/client) code from the book 'Python & Xml' > > and I am having trouble. > > > > if someone can look at the following script and tell me if > > the problem can be because I don't have the privilege and/or > > I didn't setup my system properly: > > Thanks. > > > > I am running on Linux Red Hat with python2.2. > > > > > > The client code to POST: > > """ > > post.py > > """ > > from httplib import HTTP > > from urllib import quote > > > > # establish POST data > > myquote = 'This is my quote: "I think therefore I am."' > > > > # be sure not to quote the key= sequence... > > postdata = "favquote=" + quote(myquote) > > > > print "Will POST ", len(postdata), "bytes:" > > print postdata > > > > # begin HTTP request > > > > #req = HTTP("127.0.0.1") # change to your IP or localhost > > #req = HTTP("localhost") # change to your IP or localhost > > > > ##### MY IP address > > req = HTTP("10.16.3.132") # change to your IP or localhost > > > > > > #req.putrequest("POST", "/c8/favquote.cgi") > > req.putrequest("POST", > > "file:/usr/people/erict/python/srcToolskit/pythonXmlBook/c8/favquote.cgi") > > > > . > Hold it right here. How is a FILE supposed to process the input you are > trying to send it? Your .putrequest() call should give the path to the CGI > script *relative to the server root*, not it's location in the server's file > store. > > > . > > . > > > > ##### That the Error after the ruprequest->"##### > > Traceback (most recent call last): > > File "post.py", line 25, in ? > > req.putrequest("POST", > > "file:/usr/people/erict/python/srcToolskit/pythonXmlBook/c8/favquote.cgi") > > > > File "/usr/people/erict/bin//lib/python2.2/httplib.py", line 453, in > > putrequest > > self.send(str) > > File "/usr/people/erict/bin//lib/python2.2/httplib.py", line 395, in > > send > > self.connect() > > File "/usr/people/erict/bin//lib/python2.2/httplib.py", line 379, in > > connect > > raise socket.error, msg > > socket.error: (111, 'Connection refused') > > > Sure enough, when the client tries to create a connection, it can't. > > [...] > > Hope this helps. > > regards > ----------------------------------------------------------------------- > Steve Holden http://www.holdenweb.com/ > Python Web Programming http://pydish.holdenweb.com/pwp/ > ----------------------------------------------------------------------- From rnd at onego.ru Sun Jun 2 23:31:49 2002 From: rnd at onego.ru (Roman Suzi) Date: Mon, 3 Jun 2002 07:31:49 +0400 (MSD) Subject: prototyping good OOdesign in Python? In-Reply-To: Message-ID: On Sat, 1 Jun 2002, Sean 'Shaleh' Perry wrote: >> >> Well, if you still follow this thread, the question is - how well >> Python could serve as an ARCHITECTURAL prototype if it has too rich >> OOP facilities? That is, is Python of help when trying to >> prototype certain design? Developing in C++ looks so unnecessary hard >> after things were done in Python... >> Or, it may be put this way: what discipline a Python programmer must >> obey to allow it's prototype to be conveniently rewriten in C++? >> >> The above thoughts aren't probably well-formed. But I hope >> my concern is understood. >> > >architectural prototyping is what I usually use python for when I prototype, >the other use is rapid class creation for behaviour testing. You have to keep >in mind the goal of eventually porting to C++ but it is a prototype so there is >not a lot of code there anyway. But, for example, C++ has 3 categories of object attributes. Do you mark them somehow in Python, group them to be later marked as public, protected, private? And there are lot's of details like this one. Related topic is UML with Python. Does UML has everything to reflect Python OO model or does it need to add features? (Or maybe in order to interoperate, there is a need not to use some of Python features). And if in order to interoperate with less expressive languages/systems, how to keep Python pythonic and not fall back to some standard universal subset, found in many programming languages. Sincerely yours, Roman Suzi -- \_ Russia \_ Karelia \_ Petrozavodsk \_ rnd at onego.ru \_ \_ Monday, June 03, 2002 \_ Powered by Linux RedHat 7.2 \_ \_ "Bugs are Sons of Glitches!" \_ From eikeon at eikeon.com Fri Jun 7 14:22:14 2002 From: eikeon at eikeon.com (Daniel 'eikeon' Krech) Date: 07 Jun 2002 14:22:14 -0400 Subject: Memory leaks when embedding python (debug-version) ? In-Reply-To: References: <1eed5b9.0206070157.6d281f65@posting.google.com> Message-ID: Michael Hudson writes: > The interned string dict? There's some call for getting rid of that, > but I can't remember it off hand. It sounds like a call to release the unused strings from the interned dict is on its way: http://mail.python.org/pipermail/python-dev/2002-June/025127.html --eikeon, http://eikeon.com/ From peter at engcorp.com Sun Jun 9 11:24:48 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 09 Jun 2002 11:24:48 -0400 Subject: Simple pychecker question References: <3D02FDE9.19198F33@engcorp.com> Message-ID: <3D037340.A9689E39@engcorp.com> Neal Norwitz wrote: > > Peter Hansen wrote: > > Neal Norwitz wrote: > >> I personally think that superfluous use of named args are bad, but that > >> the feature is good when used properly. > > > > transmit('this is a string', timeout=5) > > > > My point: named arguments can increase readability and maintainability. > > That's not superfluous, to me. > > I agree that they can enhance readability. With the example above, > it's questionable, but that's my opinion. Suppose the function was > transmitWithTimeout()? Or suppose the code looked like this: transmitWithTimeout() would imply it always had a timeout. (In my example it did, with the default of 1.0, but I could as well have had timeout=0.0 for the default.) > timeout = 5 > transmit('this is a string', timeout) This would be just fine. Quite readable, although the name 'timeout' is duplicated unnecessarily. With the named argument, the intention is clear but there is no need for duplication. > There really doesn't seem to be a right way, it just depends. Exactly, which was my point. Why give a warning for one of two perfectly acceptable alternatives? -Peter From chris.gonnerman at newcenturycomputers.net Mon Jun 24 08:06:09 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Mon, 24 Jun 2002 07:06:09 -0500 Subject: Newbie question (anyone programming with curses?) References: Message-ID: <003001c21b77$8af27980$0101010a@local> ----- Original Message ----- From: "David LeBlanc" > Forgive me if i'm incorrect - it's been awhile since I mucked with curses. > > Isn't the purpose of curses to convert ANSI standard codes into whatever a > particular terminal understands? Um, no. curses layers a virtual screen system on top of an abstract terminal interface. There's nothing "ANSI" about it. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From Chris.Barker at noaa.gov Thu Jun 20 15:27:11 2002 From: Chris.Barker at noaa.gov (Chris Barker) Date: Thu, 20 Jun 2002 12:27:11 -0700 Subject: logical statements (in Python and Numeric) References: <3D11F1B2.21587F31@lanl.gov> Message-ID: <3D122C5D.C6985686@noaa.gov> Fernando P?rez wrote: > > it has to do with a using an and statement... > > y = y + (x >= -2. and x < 0.) * (x + 6.) > I agree that the above failure is bloody counterintuitive, to the point where > I'd call it a bug. It's easy to illustrate with: I don't know if it is a bug or not, but it is annoying. Python 2.1 introduced "rich comparisons", which allowed NumPy to overload >,<,== , etc, but you can't overload "and" and "or". I think this is because of how "and" shortcuts but not evaluating the second operand if the first is false, etc. In Python, a non-empty sequence is TRUE, so x and y. will always evaluate to true if x and y are not empty, and the value returned is teh first one that answers the question, so, for y and y not empty: x and y #returns y x or y #returns x One solution is to use the bitwise operators instead: y = y + (x >= -2. & x < 0.) * (x + 6.) or y += ( (x >= -2. & x < 0.) * (x + 6.) ) to use += This should work fine in this case, and most comon cases. You might also want to take a look at the where() and putmask() functions: y = y + where( (x >= -2. & x < 0.), (x + 6.), 0 ) > You may consider posting to the Numeric mailing list about this. before you do that, look at the archives, it has been discussed a lot. > The 'and' > operator should either not work at all or work correctly. I'm not sure either of these is possible without significant changes to Python. -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From eddie at holyrood.ed.ac.uk Fri Jun 7 07:06:51 2002 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Fri, 7 Jun 2002 11:06:51 +0000 (UTC) Subject: Efficient python programming... References: Message-ID: "Shagshag13" writes: > I'm looking for any state of art, optimizing techniques, tips, that a >python beginner couldn't know by itself, but should learn and >would be aware to write "efficient and good looking"python's code... > (not the kind of thing which made you an obfuscated python nerd, >but that "map" should be preferred to "for in loop" if possible, that >dictionary are very well optimized, etc.) A friend is fond of quoting this to me: Rules of Optimization: Rule 1: Don't do it. Rule 2 (for experts only): Don't do it yet. -- M.A. Jackson I wasn't going to bother contributing since others have said the same thing but the more people say the more you'll believe it :) Especially for a beginner the important thing is to get clear and obvious code. Later, IF IT ISN'T FAST ENOUGH, then you think about ways to speed it up. There are may reasons for this, one of them is that it is often counter intuitive exactly what the fastest approach is anyway. Just concentrate on finding sensible algorithms as you would in any other procedural language. Eddie From rch at baustatik.rwth-aachen.de Thu Jun 20 04:29:16 2002 From: rch at baustatik.rwth-aachen.de (Rostislav Chudoba) Date: Thu, 20 Jun 2002 10:29:16 +0200 Subject: how to configure the search path for PyBuildExt.detect_modules in setup.py Message-ID: Hi everyone, Is it possible to compile the suite Tcl, Tk, Tix, BLT and Python with Tkinter in nonstandard directories: /usr/lib, /usr/include _without_ having to modify anything in Modules/Setup? There is a setup.py script which can detect whether there is tcl and tk in the directories /usr/include and /usr/lib. Why does this script does not use any environment variables for the library and include paths? Of course, I could edit Modules/Setup but I would have to do that for every time I include a new version of Python. Setting enviromnent variables would allow just copy & install procedure. My goal is to have a system-independent suite of the mentioned packages to avoid tedious work after each linux system upgrade. Rostislav Chudoba From phlip_cpp at yahoo.com Thu Jun 13 00:47:36 2002 From: phlip_cpp at yahoo.com (Phlip) Date: 13 Jun 2002 04:47:36 GMT Subject: ANN: PyUnitTestBrowser 004 Message-ID: Pynt Ho: First the non-good news. I've done everything but retest under Windows. It could work perfectly, screw up a test over some trivial 'os.sep' issue, or even go boom because I replaced 'reload' with 'import imp' and the internal calls like 'find_module' and 'load_module'. They started totally instantly and aggressively working (on Linux), so I stopped asking questions. Dox: http://flea.sourceforge.net/BrowseMe.html Get: http://flea.sourceforge.net/browser004.zip Spin: http://www.c2.com/cgi/wiki?PyUnitTestBrowser Pitch: An alternative guitestrunner for PyUnit. Its features, in combination with your editor and your console, form a plug-n-play Python Test-First IDE, tuned for very-large scale pythonic projects, hypothetically on any platform. The highlights: - trigger a test event when your file saves - incrementally test... - a single test case - a single test suite - a single test module - all test files in the current folder - an entire folder hierarchy, recursively - keyboard or mouse support to - run the UI, - launch tests, - and launch your editor - your __doc__ strings displayed at test selection time - dynamic refresh when you add new test suites or cases - locate tests thru a module's 'suite' function, - or by scanning it for descendents of TestCase. - selectively navigate Kate, Idle or Vim to - test failure points - syntax errors - test suites - test cases - testee classes - testee methohs - a debugging trace statement - arbitrarily complex command lines now supported - non-heinous documentation in one handy Web page Put them together, and you select the test in question, keep your keyboard focus in your editor with your digits on the home row and your hands off the mouse, hit Save over and over again, perceive the Green Bar, and achieve Flow. Satisfaction guaranteed or triple your money back. -- Phlip http://www.greencheese.org/PhilosophyBrethrenThree -- It's a small Web, after all... -- From tdelaney at avaya.com Thu Jun 13 20:43:24 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Fri, 14 Jun 2002 10:43:24 +1000 Subject: Why does Python mix OO concepts and non OO concepts for opera tion s on basic types? Message-ID: > From: holger krekel [mailto:pyth at devel.trillke.net] > Delaney, Timothy wrote: > > > From: holger krekel [mailto:pyth at devel.trillke.net] > > > > > > probably. With python 1.6 many methods of the string *module* were > > > included included directly with the *type* string ('str'). Most > > > python developers think that the string module should be > deprecated > > > > I think "most" is a little bit strong. The general feeling > that I get seems to be pretty much split down the middle. > > maybe. IIRC GvR is in favor of deprecating it (but not any time soon). > He does have not-to-be-underestimated influence on such issues :-) My apologies. I misread "python developers" as "developers using python" rather than "people developing python". You do appear to be right concerning the python developers ... and GvR counts somewhat ... Tim Delaney From dsavitsk at e-coli.net Sun Jun 23 01:44:02 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Sun, 23 Jun 2002 05:44:02 GMT Subject: python cgi + IIS References: <3D0F1813.3010304@gmx.de> Message-ID: very nice. i don't actually use iis on that computer. i opened it long enough to take a screen shot, but, on that computer anyway, i use apache. oddly enough, the e-coli.net site does run on IIS, but not on my computer. -d "George Hester" wrote in message news:Y4OP8.46694$GY.14566397 at twister.nyroc.rr.com... > Have you noticed this guy/gal has errors in their IIS? > > http://www.e-coli.net/pyiis_server.html > > -- > George Hester > _________________________________ > "Steve Holden" wrote in message > news:x0NP8.165989$Fp1.91529 at atlpnn01.usenetserver.com... > > "Axel Grune" wrote in message > > news:3D0F1813.3010304 at gmx.de... > > > Hi, I'm trying to get my IIS (Win2k Pro) execute my python scripts. > > > I added the 'App Mapping' info for '.pycgi' files in the properties of > > > IISAdmin (Computermanagement) as I read in the internet. The string > > > for the executable file is 'D:\Python22\python.exe -u %s %s' (the path > > > is valid). > > > But when i try to call it within my browser, it just displays it like a > > > normal text file instead of executing it. > > > > > > > > > the script (its called test.pycgi): > > > #!/usr/bin/python > > > > > > print "Content-Type: text/plain\n\n" > > > print "Hallo Welt" > > > > > > > > > has anyone an idea? > > > > > You have almost certainly made a typo, or you didn't apply the changes to > > the directory you are trying to run the CGI from. I just followed the steps > > at > > > > http://www.e-coli.net/pyiis.html > > > > to install .cgipy as a Python-executing extension, and everything worked -- > > the following program printed out a complete list of environment variables. > > # > > # Python CGI script > > # > > import os > > print """Content-Type: text/html > > > > > > > > Python Web Page > > > > > > """ > > > > for k, v in os.environ.items(): > > print "%s=%s
\n" % (k, v) > > > > print """ > > > > > > """ > > > > Personally I'd rather run CGI than use ASP under IIS, so I hope you can get > > it to work. Clearly at the moment IIS isn't recognising the .cgi extension > > as needing to run the Python interpreter. > > > > regards > > ----------------------------------------------------------------------- > > Steve Holden http://www.holdenweb.com/ > > Python Web Programming http://pydish.holdenweb.com/pwp/ > > ----------------------------------------------------------------------- > > > > > > > > > > > > From monsegur at mad.scientist.com Tue Jun 4 14:10:09 2002 From: monsegur at mad.scientist.com (Xavier Monsegur) Date: Tue, 04 Jun 2002 13:10:09 -0500 Subject: using getopt Message-ID: <20020604181009.33890.qmail@mail.com> I can't wait -- that would be marvelous... getopt should have been eradicated long ago. ----- Original Message ----- From: Mark Hammond Date: Tue, 04 Jun 2002 01:53:38 GMT To: python-list at python.org Subject: Re: using getopt > Fernando P?rez wrote: > > > > getopt sucks. Period. Take a look at DPyGetOpt, which implements the > > Getopt::Long perl facilities. It's very very nice. I've also heard good > > things about optik, but haven't used it myself. > > It looks like optik will be incorporated into the core Python library > (but possibly inside the getopt module). However it actually appears, > using optik now will almost certainly make your future transition to the > standard library simpler. > > Mark. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- _______________________________________________ Sign-up for your own FREE Personalized E-mail at Mail.com http://www.mail.com/?sr=signup From ngiven at lanl.gov Tue Jun 25 10:59:29 2002 From: ngiven at lanl.gov (Nathan Given) Date: Tue, 25 Jun 2002 08:59:29 -0600 Subject: Integrals with Python Message-ID: <3D188551.6BA00DED@lanl.gov> Hello All, I'm somewhat familiar with MATLAB, and I'm trying to move completely over to python... and I was wondering if there is a function out there that will compute integrals for me... here's what I've found so far... http://pylab.sourceforge.net/ but I'm not sure what I need off that page... I already have Numeric... what else do I need? Thanks! -- Nathan From claird at starbase.neosoft.com Wed Jun 5 11:41:03 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 5 Jun 2002 10:41:03 -0500 Subject: writing a chat program References: Message-ID: In article , Shaun Whelden wrote: . . . >I'm writing this on a Windows machine, so curses is out of the >question. Also, I want this to be a text based program, so I don't . . . There *are* implementations of curses for Windows; does that help? -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From shaunw at liberateschool.com Tue Jun 4 12:40:33 2002 From: shaunw at liberateschool.com (Shaun Whelden) Date: 4 Jun 2002 09:40:33 -0700 Subject: writing a chat program Message-ID: Hi all, I'm trying to throw together a simple text-based chat program in Python. Here's the problem I have right now: I need a way to allow the user to be entering in a message they want to send, while at the same time waiting for any data that may come through the socket. If data does come through the socket, I need the user to be able to continue typing while the data is printed to the screen. I'm writing this on a Windows machine, so curses is out of the question. Also, I want this to be a text based program, so I don't want to have to mess around with Tkinter or any other forms of GUI unless I have to. I'm pretty sure that I need to do something involving thread.py and/or threading.py, but I've never used a thread before in my life. Can anyone help? Shaun Whelden shaunw at liberateschool.com From BPettersen at NAREX.com Tue Jun 18 15:23:41 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Tue, 18 Jun 2002 13:23:41 -0600 Subject: Python to MS SQL Server Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192158EDF@admin56.narex.com> > From: Mark McEahern [mailto:marklists at mceahern.com] > > > I am interested in using Python in a MS SQL Server > > environment, but do > > not see any database modules out there, especially for > > native versus > > using ODBC. Is there such a module? > > This is a total guess, because I haven't done this myself: > > Have you tried using win32com to use ADO? AFAIK, there is no Python database module that goes directly to MS SQL Server db lib. ADO does work however, so that's certainly an option. Personally, I would probably investigate e.g. mxODBC first (the interface is much easier to use from Python). -- bjorn From BPettersen at NAREX.com Thu Jun 20 18:52:35 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Thu, 20 Jun 2002 16:52:35 -0600 Subject: Windows versions of Python---pros and cons? Message-ID: <60FB8BB7F0EFC7409B75EEEC13E201922151A8@admin56.narex.com> > From: Chris Barker [mailto:Chris.Barker at noaa.gov] [snip] > > On that note: does anyone know if there is a way to turn a > Python script into something that acts like an application on > Windows...without resorting to Py2exe and the like. What I > want is something just like: > > chmod +x scriptname > and a #! line at the top > > on Unix. I want it to work on the windows command line. If you use the ActiveState version (not sure about the python.org version) this should work out-of-the-box. Just type the name of the script, you can even leave out the .py extension. Someone else will probably tell you how it works, I just know it's got something to do with registering the .py extension as an executable extension in the registry... -- bjorn From jeremy at alum.mit.edu Tue Jun 18 00:03:01 2002 From: jeremy at alum.mit.edu (Jeremy Hylton) Date: 17 Jun 2002 21:03:01 -0700 Subject: urllib2 getting a webapage authenticating proxy... References: <3D0DD287.7B221A42@a.com> Message-ID: Adam wrote in message news:<3D0DD287.7B221A42 at a.com>... > this code doesnt work for me... i have replaced the proxy details for > security... can anyone help... as i havent been able find any helpfull > websites/examples for urllib2... is urllib2 what i realy want to use for > this... > > import urllib2 > > def get_page(url): > proxy = > urllib2.ProxyHandler({'http':'http://userid:pass at proxy.com:port/'}) > opener = urllib2.build_opener(proxy) > site = urllib2.urlopen(url).read() > print(site) > > get_page('http://www.python.org/') There is a SF patch that should fix this problem. See http://sourceforge.net/tracker/index.php?func=detail&aid=527518&group_id=5470&atid=305470 If it works, you might add a comment saying that it worked for you. I expect this will be integrated in Python CVS soon, and should get into future bug fix releases. Jeremy From gmcm at hypernet.com Wed Jun 12 08:07:32 2002 From: gmcm at hypernet.com (Gordon McMillan) Date: 12 Jun 2002 12:07:32 GMT Subject: filecmp.cmpfiles on directories References: <3D06491B.302@excite.com> Message-ID: Stormin wrote: > I am trying to walk a directory structure and compare directories for > duplicates. For some reason I get the filecmp to work on individual > files, but not on directories. > example: > DOES NOT WORK: > dups=filecmp.cmpfiles("C:\comp1","c:\comp2",common) > print dups,"||",common > result: > ([],[],[])|| For each filename in common, cmpfiles will compare the files with that basename in the two directories. What you want is: x = filecmp.dircmp("C:\\comp1","c:\\comp2") print x.same_files print x.diff_files which will figure out "common" and call cmpfiles for you. -- Gordon http://www.mcmillan-inc.com/ From cmonahan at yahoo.com Tue Jun 11 18:10:37 2002 From: cmonahan at yahoo.com (Collin Monahan) Date: Tue, 11 Jun 2002 15:10:37 -0700 (PDT) Subject: lists and sequences Message-ID: <20020611221037.36421.qmail@web13303.mail.yahoo.com> What is a python list? Is it a linked list or a random access structure in contiguous memory? What type of situations should be avoided when using it? E.g. when does n^2 time happen using it? What sorting algorithm is used by its sort member function? Are the answers to these questions the same for Jython? If there is a good situation to use a Java collection from Jython because of above considerations, how bad are the constant factors which arise from doing so? That is, how preferable is it to stick with the python-language structures when using Jython? I'm not on the list so please copy me. Thank you Collin Monahan __________________________________________________ Do You Yahoo!? Yahoo! - Official partner of 2002 FIFA World Cup http://fifaworldcup.yahoo.com From ffjhenon at club-internet.fr Wed Jun 26 17:31:28 2002 From: ffjhenon at club-internet.fr (Fabien =?iso-8859-1?Q?H=E9non?=) Date: Wed, 26 Jun 2002 23:31:28 +0200 Subject: continuous redirection of stdout & stderr to Tkinter Text Message-ID: <3D1A32B0.CA7D3618@club-internet.fr> I am using Tkinter as an editor and a launcher (under Linux) for a raytracer (POV-RAY) Once started, the raytracer does two things in the same time : - it displays the image being raytraced - it spits out information to the console (ie : the line which is being raytraced). I get the image displayed but not the redirection of stdout That is why I use the root.after function to (try to) update every 10th second. With the script below, I get the image displayed, but not the stdout (or stderr). What am I doing wrong ? To the pipe-redirectors gurus : Help ! 8<---------snip------------------------->8 from Tkinter import * import sys, os import popen2 root = Tk() class StringVarFile: def __init__(self,stringVar,window): self.__newline = 0 self.__stringvar = stringVar self.__window = window def write(self,s): new = self.__stringvar.get() for c in s: if c == '\n': self.__newline = 1 else: if self.__newline: new = "" self.__newline = 0 new = new+c self.set(new) def set(self,s): self.__stringvar.set(s) self.__window.update() def get(self): return self.__stringvar.get() class mainWin: def __init__(self,tkRoot): self.tkRoot=tkRoot self.createWidgets() return None def runpov(): cmd='megapovplus +i1.pov +w320 +h240 +dgt +v -f +p' run=popen2.Popen3(cmd) upd() def upd(): resultat.insert('1.0',statusVar)) root.after(100,upd()) mframe=Frame(root) bouton=Button(mframe,text="Feu !", command=runpov) bouton.pack() statusVar = StringVar() #resultat=Label(mframe, width=60, height=10,justify=LEFT, anchor=W, textvariable=statusVar) resultat=Text(mframe) resultat.pack(fill=X,expand=Y) mframe.pack(expand=1, fill=BOTH) status = StringVarFile(statusVar,root) sys.stderr=status root.mainloop() 8<---------snap------------------------->8 From peter at engcorp.com Wed Jun 26 23:56:09 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 26 Jun 2002 23:56:09 -0400 Subject: Most efficient way to write data out to a text file? References: <3d1a6993.248534625@netnews.attbi.com> Message-ID: <3D1A8CD9.C8B8EC28@engcorp.com> candiazoo at attbi.com wrote: > > I assume some sort of block i/o or preallocating a large block of file space > would be the best way to do it? I am outputting about 700,000 records to a text > file and my program only spits out about 20 records per second. This is using > standard file open and write... You're not opening and closing the file for each record that is written, are you? Can you post more detail on the amount of data in a record, and the format? Why not profile the code using the profile.py module and actually see where the problem is? -Peter From matt at mondoinfo.com Sun Jun 23 21:36:40 2002 From: matt at mondoinfo.com (Matthew Dixon Cowles) Date: Mon, 24 Jun 2002 01:36:40 GMT Subject: Problems with Pmw References: Message-ID: On Sun, 23 Jun 2002 19:35:33 -0500, Mark Rivers wrote: > In a previous post I mistakenly attributed one problem to Pmw.Blt, while > subsequent testing has shown that the problem has nothing to do with Blt, it > is a problem (?) with Pmw. > > The problem is illustrated by the following short script: > ######################################## > from Tkinter import * > import Pmw > t1 = Tk() > t2 = Tk() > l = Label(t2, text='A label'); l.pack() > b = Button(t2, text='Press me'); b.pack() > e = Pmw.EntryField(t2, labelpos=W, label_text='Enter something'); e.pack() > ######################################## [. . .] > I think it should be legal to create multiple Tk() windows in an > application, so this seems like a serious bug? The usual way to create another window is with the Toplevel() call. I don't know whether the bug is in Tkinter's allowing a second Tk() call or Pmw's assuming that no one ever makes a second Tk() call but you shouldn't have a problem if you use Toplevel(). Regards, Matt From mgilfix at eecs.tufts.edu Mon Jun 10 19:21:25 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Mon, 10 Jun 2002 19:21:25 -0400 Subject: wxPlotCanvas documentation? In-Reply-To: ; from thehaas@binary.net on Mon, Jun 10, 2002 at 11:10:35PM +0000 References: Message-ID: <20020610192125.C5683@eecs.tufts.edu> On Mon, Jun 10 @ 23:10, thehaas at binary.net wrote: > > 3. How do I find anything in the documentation? > > > My inability to find my wxButt in the wxDark with both > > wxHands (with or without a wxFlashlight) is not > > limited to PlotCanvas, so I'm hoping that the problem > > is on my end. The wxPython website, as far as I can > > tell, only has one documentation link, and it's a link > > to wxWindows, not the wxPython objects that wrapper > > it. There's a sample code section, but every last one > > of the examples is marked "To Be Written When I Have > > More Time." ^^^ This is very funny. > I love wxPython, but the initial learning curve is quite steep. Once you > get past the very initial stage, though, it grows on you. I really agree with this statement. The initial learning curve is a little high but then you become quite productive. My major problem starting with wxPython is that the sizers didn't work quite the way I expected. I suggest looking through the many tutorials about sizers (after I bitched about them plenty, they actually went and wrote one :) ). But if you have experience with autolayout mechanisms from pygtk, throw them out the window before you start with wxPython and that might help some. The wxPython ones just behave differently, and I found that a little confusing at first. But once you get the hang of it, wxPython is great. -- Mike -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From shalehperry at attbi.com Sat Jun 8 11:16:40 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Sat, 08 Jun 2002 08:16:40 -0700 (PDT) Subject: Removing ^M In-Reply-To: <200206081448.g58Empj11746@localhost.localdomain> Message-ID: > > There's a program called dos2unix that will do this. From your mail > headers it looks to me like you have a Unix/Linux system in which case > it may already be installed. If not do a google search on dos2unix. > another possibility is fromdos (and its brother todos). As Chris Gonnerman pointed out ^M is '\r' or 'carriage return'. Under Windows every line ends in '\r\n', under Unix it is just '\n' and I think Macs only use '\r'. This is usually hidden from you because python, the C libs, etc all know how to translate behind the scenes. If you have some one at work (or a friend) ftp'ing files have them set the mode to ASCII before transfer and FTP will do the conversion for you. From Chris.Barker at noaa.gov Thu Jun 20 14:09:28 2002 From: Chris.Barker at noaa.gov (Chris Barker) Date: Thu, 20 Jun 2002 11:09:28 -0700 Subject: How to represent the infinite ? References: <3d11ee9b$1@news.swissonline.ch> <20020620193230.53d58f8f.christophe.delord@free.fr> Message-ID: <3D121A29.A733609F@noaa.gov> Christophe Delord wrote: > There is another simple solution. Just use a float that is bigger than any 64-bit float. For example 10^1000. This float has a special encoding meaning +oo ! this is part of the IEEE 754 standard for floating point computation (http://cch.loria.fr/documentation/IEEE754/) It is not guaranteed to be implimented by Python (someone please correct me if I'm wrong). whether this works is a function of the machine, compiler and library used to compile Python. I'm not sure how common it is, but if you want your code portable, it may not be reliabel on all machines, which is too bad, because IEEE 754 is pretty darn good standard. BTW: I'd love to see literals for Inf, -Inf and NaN in Python. -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From gerhard.haering at gmx.de Fri Jun 21 07:07:37 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Fri, 21 Jun 2002 13:07:37 +0200 Subject: I'd give up Perl tomorrow if only... In-Reply-To: References: Message-ID: <20020621110737.GA13324@lilith.my-fqdn.de> * David Mitchell [2002-06-21 20:48 +1000]: > ASCII<->EBCDIC conversion is pretty easy to implement in just about any > language, but it's also easy to make a typo somewhere when you're typing in > lots and lots of ASCII codes. I know; I've done it ;-> No need to do it yourself. In Python 2.2+: >>> u"foo".encode("ebcdic_cp_us") '\x86\x96\x96' Of course, if you have ascii, you'll have to construct the unicode string first: unicode("foo", "ascii").encode(...) > However, when speed of development is absolutely crucial, Perl can't > be beat. For me, nothing beats Python. I don't know Perl (I've tried to learn it, but it was too frustrating). And I don't believe Perl were more efficient for me. The more terse code argument doesn't count, because I'm a fast typist :-) Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From peter at engcorp.com Tue Jun 18 00:12:50 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 18 Jun 2002 00:12:50 -0400 Subject: Listing all available (not just loaded) modules References: Message-ID: <3D0EB342.43DB0FE3@engcorp.com> Michael Steuer wrote: > > I've been searching the newsgroup for information on this but so far have been > unsuccessful: > > Is there a way to dynamically list all available modules (not just those that > are already loaded) in python? By available I mean those modules, which are > installed on the machine executing python (in the lib path(s)). http://snakefarm.org/ ? -Peter From cliechti at gmx.net Wed Jun 26 14:52:28 2002 From: cliechti at gmx.net (Chris Liechti) Date: 26 Jun 2002 20:52:28 +0200 Subject: printing (again!!) References: Message-ID: "Geoff Tarrant" wrote in news:afcusp$66r$1 at newsg2.svr.pol.co.uk: > I want to use Python as the language in a Computing course that I > teach. However, I can't find a way that is relatively straightforward > to send data to a printer in a Windows environment. If I can't find a > way around this, I will have to revert to Delphi or VB. Please help. > I like the idea of sending 20 or so Python programmers to University > each year. you can try different things. 1. use reportlab and generate PDF. save the trees, make achiving easy. its has many more uses, e.g on the fly PDF for CGI etc. 2. use the printing framework of a GUI. i've successfuly printed with wxPython. win32all has printing support too, through the standard windows API. win32all is a defacto standard for python on windows users anyway. i prefer 1) as it's more versatile, platform indepent and just cool. chris -- Chris From candiazoo at attbi.com Mon Jun 24 21:18:49 2002 From: candiazoo at attbi.com (candiazoo at attbi.com) Date: Tue, 25 Jun 2002 01:18:49 GMT Subject: Help with MySQLdb insert with data extracted from odbc <-- Oracle References: <3d13d5fb.651829078@netnews.attbi.com> <3d147e64.694941703@netnews.attbi.com> Message-ID: <3d17c4a5.75241265@netnews.attbi.com> In a year or two, God willing, we'll have no need for this particular program!! :) You are, however, absolutely right and it would probably be questioned in a code review. Thanks! Mike From guy at lightwork.co.uk Thu Jun 27 08:31:48 2002 From: guy at lightwork.co.uk (Guy) Date: 27 Jun 2002 05:31:48 -0700 Subject: sys.argv[0] - Returns path and filename. Message-ID: Hi I work on multiple platforms, at the moment, I have python installed on my win32 box which I mainly work on, a MacOSX box and a linux box which has a very old version installed on it. The only major problem that I have come across at the moment is the argv[0], on my win32 box it retruns the path and a filename, on the mac osx and the linux only the filename are returned. How do I get the current path of the script I am running, on the mac osx and the linux box ? (Any work around would be great, I don't want to have to hardcode the path into the script, or even give the path as an argument,I want the script to know where it is.) I've tryed searching for this but can't find it anywhere. Example script called arguments.py : import sys print sys.argv[0] Result Win32 : >>> D:\TestArg\arguments.py Result Mac OSX : MacOSX% python arguments.py arguments.py Result Linux : linux% python arguments.py arguments.py From bokr at oz.net Fri Jun 28 18:46:42 2002 From: bokr at oz.net (Bengt Richter) Date: 28 Jun 2002 22:46:42 GMT Subject: generate all combinations of a list (with variable output length) References: Message-ID: On Fri, 28 Jun 2002 15:09:47 -0500, "Mark McEahern" wrote: >> i'm looking for a way to generate all possible combinations of all items >> in a list. list = ["A","D","$","5","R"] > >i don't have a solution, but some questions to clarify: > >if you think of your list as comprising the digits, then you're asking for >an n-length string composed of all possible digits where the digits include: > > A, D, $, 5, R, and None (the representation of the latter is '') > >so, for n = 10, this is a possible value: > > AAAAAAAAAA > >as well as: > > [ ] > >omit the brackets. > >True? > >anyway, this might get you started: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/105962 > >// m > Or, implementing your base-5 digits idea, and leaving out '': >>> def adD5r(n): ... codes='AD$5R' # <=> 01234 ... out = []; m = n ... while 1: ... n,d = divmod(n,5) ... out.append(codes[d]) ... if not n:break ... out.reverse() ... return '%d:%s' % (m,''.join(out)) ... >>> [adD5r(5**n) for n in range(5)] ['1:D', '5:DA', '25:DAA', '125:DAAA', '625:DAAAA'] >>> [adD5r(5**n+1) for n in range(5)] ['2:$', '6:DD', '26:DAD', '126:DAAD', '626:DAAAD'] >>> [adD5r(n) for n in range(26)] ['0:A', '1:D', '2:$', '3:5', '4:R', '5:DA', '6:DD', '7:D$', '8:D5', '9:DR', '10:$A', '11:$ D', '12:$$', '13:$5', '14:$R', '15:5A', '16:5D', '17:5$', '18:55', '19:5R', '20:RA', '21:R D', '22:R$', '23:R5', '24:RR', '25:DAA'] The smallest and biggest 10-"digit" numbers would be >>> adD5r(0) '0:A' (I'll leave it as an exercise for the OP to prefix leading "zeroes" to desired print width for that set of strings ;-) >>> adD5r(5**10-1) '9765624:RRRRRRRRRR' generated analogously to >>> 10**10-1 9999999999L Regards, Bengt Richter From deathtospam43423 at altavista.com Sat Jun 8 03:19:52 2002 From: deathtospam43423 at altavista.com (netvegetable) Date: 8 Jun 2002 07:19:52 GMT Subject: Newby: How do I strip HTML tags? References: <3d00e1b1.47853937@news.t-online.de> Message-ID: Andy McKay wrote in news:mailman.1023469751.21489.python-list at python.org: >> This is a quite straight forward function: > > This of course assumes that there are no "<" or ">" anywhere else in > attributes etc... > > I would recommend using HTML Parser to get an accurate representation, or > even stripogram which is pretty good (note it doesnt need Zope at all), > although the html2text isnt perfect: > >>>> from stripogram import html2text html2text("This is a >>>> test") 'This is a test' Thanx. Is there an "HTMLParser Tutorial for Dummies" anywhere on the web? -- netvegetable at excite.com From gerhard.haering at gmx.de Fri Jun 28 15:12:19 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 28 Jun 2002 19:12:19 GMT Subject: distutils/boost question References: Message-ID: Achim Domma wrote in comp.lang.python: > "Gerhard H?ring" wrote: >> The easiest solution is to statically link in the Boost.Python library. > > With boost.python V2 dynamic linking will be a requirement. Isn't > there another solution? On Windows, the DLL search rules are such that putting the support DLL in the same directory as the .pyd does help. If you get that working with distutils, please drop me a note. On Unix, you need to put the shared library in a directory that is in the dynamic loader's search path. /usr/lib, /usr/local/lib, ... That's AFAIK currently not possible with distutils. It's no problem when using your favourite Unix package format. Writing a SPEC file, for example, is pretty straightforward, when using the documentation and existing SPEC files as a template. Another ugly solution is to write a little wrapper script that sets the LD_LIBRARY_PATH environment variable appropriately before running Python. That's the quick and dirty fix. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From andreas.ames at Tenovis.com Thu Jun 27 09:16:01 2002 From: andreas.ames at Tenovis.com (Andreas Ames) Date: 27 Jun 2002 15:16:01 +0200 Subject: Interactive session via tcp In-Reply-To: <20020627120602.3659.37119.Mailman@mail.python.org> References: <20020627120602.3659.37119.Mailman@mail.python.org> Message-ID: Hi, > Sorry, if this if wrong, I read your post quickly. > Doesn't "telnet jabber_port" do what you want? Nope, it doesn't. My main problem is the python (interpreter) side. And while it's possible to jabber via telnet it's not exactly what I call fun (I've tried it). cheers, Andreas From pj at engr.sgi.com Tue Jun 18 19:46:58 2002 From: pj at engr.sgi.com (Paul Jackson) Date: 18 Jun 2002 23:46:58 GMT Subject: python version? References: Message-ID: > Don't worry I won't return here. Thank-you, sir. -- -- I won't rest till it's the best ... Programmer, Linux Scalability Paul Jackson 1.650.933.1373 From skip at pobox.com Thu Jun 20 11:08:26 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 20 Jun 2002 10:08:26 -0500 Subject: MySQLdb question In-Reply-To: References: Message-ID: <15633.61418.44706.32731@localhost.localdomain> John> Use the %s thingie: John> c.execute('SELECT spam, eggs, sausage FROM %s John> WHERE price < %s', (table_name, max_price)) I'd amend that slightly: c.execute('SELECT spam, eggs, sausage FROM %s WHERE price < %%s'%table_name, (max_price,)) or stmt = ('SELECT spam, eggs, sausage FROM %s WHERE price < %%s' % table_name) c.execute(stmt, (max_price,)) to make the two substitution ops clearer. For variable substitution I recommend people always use the DB API argument quoting facility. In this case it doesn't matter since presumably max_price won't need escaping. For string args it definitely would though. -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From steele at cs.brandeis.edu Sat Jun 1 06:36:01 2002 From: steele at cs.brandeis.edu (Oliver Steele) Date: 1 Jun 2002 03:36:01 -0700 Subject: extended list comprehensions References: Message-ID: <92f9b8a8.0206010236.1ac5e3f2@posting.google.com> fxj at hotmail.com (F. Jamitzky) wrote in message news:... > It would be great to have something like a list comprehension for the > reduce function. It would work in the same way as the comprehension > for the map function, which is: > > [foo(x) for x in xs] <-is the same as-> map(foo,xs) > > and maybe it could be written as: > > {y=y+x for x in xs} <-would be-> reduce(operator.add,xs) > > what do the experts think about that ? > > ferdinand What about using ellipsis? These could do foldl (reduce): ...+x for x in xs operator.add(..., x) for x in xs This leaves an obvious extension for foldr (reduce from the right): swap the identifier and the ellipsis: x+... for x in xs operator.add(x, ...) for x in xs The bug in this (putting aside the question of whether it's worth adding anything to the language) is that it suggests that ... is a way to write curry (similar to (x+) and (+x) in Haskell), and then: [...+x for x in xs] becomes ambiguous between a singleton list containing a reduction, and a list of lambdas. Any way to save this? From dl at bestpriceeu.com Sun Jun 9 09:03:35 2002 From: dl at bestpriceeu.com (Dan Larsen) Date: Sun, 9 Jun 2002 15:03:35 +0200 Subject: newbie system() question Message-ID: <3d035180$0$7017$bc7fd3c@news.sonofon.dk> Hi all :o) Im trying to run a script on a FreeBSD 4.0 system. It works as long as I start it like "python myprogram.py", but as soon as I run it in the background, it is stopped, and I have to make it run in the foreground to continue i.e. "fg %1"... I know it is a call to a system(""), that makes it stop... The system() call runs a program that outputs some text... how do I stop it doing so? It doesn't help telling it to do stuff like "program >& /dev/null &"... Isn't there a function, where all output from the command, is parsed to a variable? Thanx in advance :o) Dan Larsen From paul at boddie.net Mon Jun 3 13:01:51 2002 From: paul at boddie.net (Paul Boddie) Date: 3 Jun 2002 10:01:51 -0700 Subject: Compiling python2.2.1 on redHat 6.1 - doesn't work References: <23891c90.0205220343.4aa581c8@posting.google.com> <23891c90.0205230743.7ea59255@posting.google.com> Message-ID: <23891c90.0206030901.26402dd0@posting.google.com> paul at boddie.net (Paul Boddie) wrote in message news:<23891c90.0205230743.7ea59255 at posting.google.com>... > > matthew.russell at securetrading.com (Matt Russell) wrote in message news:... > > > > has anyone else had this problem? I would be very suprised if no one > > else out there has not tried to compile Python2.2.1 on RedHat 6.1!! > > I'll try and have a look in the next few days, at least. OK. My suggestion can be found at the following location: http://sourceforge.net/tracker/?group_id=5470&atid=305470&func=detail&aid=563954 That's patch #563954 in the Python project at SourceForge (http://sf.net/projects/python). Paul From gabor at realtime.sk Thu Jun 6 16:40:26 2002 From: gabor at realtime.sk (gabor) Date: 06 Jun 2002 16:40:26 -0400 Subject: array, list, performance... In-Reply-To: <_gKL8.314196$%u2.248214@atlpnn01.usenetserver.com> References: <3CFF5F98.2060406@destiny.com> <_gKL8.314196$%u2.248214@atlpnn01.usenetserver.com> Message-ID: <1023396026.7322.4.camel@wintermute.atriaky.sk> On Thu, 2002-06-06 at 10:20, Steve Holden wrote: > "Christopher Armstrong" wrote in message > news:mailman.1023373030.31871.python-list at python.org... > > > > > Michael Chermside writes:: > > > li[n] = x assignment to the middle is O(len(li)) > > > > This doesn't seem right. Shouldn't that be O(1), just like > > access-time? > >sorry, but i don't understand... how can you use li[n] = x to INSERT an element into a list.. IndexError: list assignment index out of range as far as i know: if n <3D122E79.A189C72E@astro.cornell.edu> Message-ID: Tom Loredo wrote: > Fernando P?rez wrote: >> >> If you're an old unix hand and want to preserve your sanity, you have two >> options: >> >> 1- put linux on that laptop and be happy. > > Actually, I've reserved a big chunk of the disk for linux. Just gotta > decide which version (is there a "best" one for Python? E.g., Redhat > uses Python, but does their reliance on an old version still cause > problems?). I'll stay there when I'm developing for *me* on it! Well, I'm a big fan of Mandrake over RedHat: more oriented towards 'workstation' users than 'server' users, more out-of-the box tools for scientific use (lyx, gnuplot, octave, Numeric, Lapack,...). Plus redhat made the most boneheaded decision on the planet with the two-version python setup, which you'll have to duct-tape your way around. _My_ (redhat fanatics, keep off :) simple experience so far is: everytime I need to get something done on a mandrake machine, it works in under 15 minutes. Everytime I have to deal with a redhat machine, I'm pissed off after two hours. But YMMV, as always. >> 2- if (1) is not an option for some reason, put cygwin on it. > > Actually, I need to develop stuff that other Win32 users can use, > some probably distributed via the McMillan installer (which I presume > works as well with Active State as with the python.org version). > So I'm stuck here.... Don't know if there's a misunderstanding here: cygwin is a unix-like environment under Windows. So at least you'll have a terminal worthy of the name, plus all the command-line tools you neeed on a day to day basis (grep, sed, awk, etc.). I don't use it (I simply don't use windows except in rare cases), but I've heard it's quite good and makes life under windows at least bearable. >> If you have to work in the normal, >> crippled windows environment, that laptop is going to suffer a painful >> death after being hurled through the nearest window very soon :) > > I've only had it two weeks, and only the power cord to the battery > charger has saved it! The fact that Dell shipped it with a defective > install of Win98 did not help its cause. Well, if you do have to live with windows, I'd recommend at least using XP. It's still an annoying crippled toy, but at least it _is_ much more stable than Win9x, and when things crash they typically don't take down the whole system with them. Don't expect unix-class stability, but it won't drive you nuts like win9x will. Best, f From peter at engcorp.com Mon Jun 3 21:43:44 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 Jun 2002 21:43:44 -0400 Subject: python and windows and pydoc and favorite editor == True References: Message-ID: <3CFC1B50.E830AC46@engcorp.com> Syver Enstad wrote: > > "J?rgen Hermann" writes: > > > "Syver Enstad" schrieb im Newsbeitrag > > news:un0ugnxa3.fsf at online.no... > > > Post if there is any interest. > > > > OK, post. :) > > > > > > http://home.online.no/~syver-en/software.html/files/PyDocEditorStarter.py Looks like this should be: http://home.online.no/~syver-en/files/PyDocEditorStarter.py The other 404's me. -Peter From d_blade8 at hotmail.com Thu Jun 20 14:46:10 2002 From: d_blade8 at hotmail.com (Lemniscate) Date: 20 Jun 2002 11:46:10 -0700 Subject: Problems with mayavi, pyvtk References: <7396d2b2.0206191025.3351a888@posting.google.com> Message-ID: <7396d2b2.0206201046.4f0530fa@posting.google.com> Hey, thanks for the info. Here's the only problem... I still get errors. Here is what happens when I try to import vtkpython... >>> import vtkpython Traceback (most recent call last): File "", line 1, in ? File "C:\Python22\Lib\site-packages\VTK\vtkpython.py", line 29, in ? exec "from "+kit_name+" import *" File "", line 1, in ? ImportError: DLL load failed: The specified procedure could not be found. >>> import sys >>> sys.path ['', 'C:\\py22', 'C:\\vtk4', 'C:\\Python22\\Lib\\site-packages\\VTK', 'C:\\Program Files\\MayaVi'... The main problem, though, is that I just want MayaVi to work from inside python, here is one of the errors I get when I try to import it (per the manual). I have pyvtk and it imports with absolutely no problems, i can generate vtk files that open in the MayaVi.exe program, I just can't use python to interface with MayaVi (I have the MayaVi modules, not just the binary version, btw). I think it has something to do with the vtk installations. I looked and it wants 'vtk'+kit+'Python' but all the zip files on the page you gave me (for Python 2.2) don't have the files. I was willing to go back to Python 2.1 (his file list for those files showed the files I needed) but the Python2.1 link is no longer valid. I also downloaded the vtkcore and the vtkpython from the vtk page (http://public.kitware.com/VTK/files/release/4.0/). Also, I added the following to my PythonPath (in order to access the dlls): C:\Program Files\vtk40\bin Thanks a bunch, Lem >>> import mayavi Traceback (most recent call last): File "", line 1, in ? File "C:\Python22\Lib\site-packages\mayavi\__init__.py", line 5, in ? import Common, Base.Objects File "C:\Python22\Lib\site-packages\mayavi\Base\__init__.py", line 19, in ? import Objects File "C:\Python22\Lib\site-packages\mayavi\Base\Objects.py", line 20, in ? import Tkinter, vtkpython, math, tkColorChooser File "C:\Python22\Lib\site-packages\VTK\vtkpython.py", line 29, in ? exec "from "+kit_name+" import *" File "", line 1, in ? ImportError: DLL load failed: The specified procedure could not be found. Fernando P?rez wrote in message news:... > Lemniscate wrote: > > > > > I just downloaded and installed the latest versions of pyvtk and > > mayavi.??However,?when?I?try?to?follow?the?instructions?at > > http://mayavi.sourceforge.net/docs/guide/c827.html#VIZ-DATA for using > > mayavi, I get the ImportError as below.??For?the?like?of?me,?I?can't > > seem to figure out why I don't have any vtkpython modules anywhere > > (doing searches on the internet for the module hasn't been a big help > > so far > > Well, google's second hit on 'vtkpython' is > http://basic.netmeg.net/godzilla/, which sounds like what you want. At least > it should be a good start. > > Cheers, > > f From =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= Tue Jun 25 04:46:24 2002 From: =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= (=?iso-8859-5?Q?=B4=D0=DC=F8=D0=DD_=B3=2E?=) Date: Tue, 25 Jun 2002 10:46:24 +0200 Subject: Python daemon Message-ID: <3d182dd6$1@news.mt.net.mk> Hello, I'm writing a Python daemon on Unix and I need the folowing features: 1. going to background, diassociate from controling tty (done) 2. watchdog, the program should never be stuck 3. restarting of the program if it fails, or the watchdog doesn't trigger 4. Logging The issue 1. I solved, it's on ActiveState's site. Issue 4. is not that hard to do I guess. Any suggestions about 2 and 3 ? -- ?????? "One world, one web, one program" -- Microsoft promotional ad "Ein Volk, ein Reich, ein Fuehrer" -- Adolf Hitler From sholden at holdenweb.com Mon Jun 3 07:59:05 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 3 Jun 2002 07:59:05 -0400 Subject: Behavior of += (was Re: [Python-Dev] Customization docs) References: <06da01c208f4$d69003c0$6601a8c0@boostconsulting.com> <200206010121.g511LxX19223@pcp742651pcs.reston01.va.comcast.net> <073501c20960$23f367e0$6601a8c0@boostconsulting.com> <200206011334.g51DY1D21669@pcp742651pcs.reston01.va.comcast.net> <07d801c20970$cdebe050$6601a8c0@boostconsulting.com> Message-ID: "Emile van Sebille" wrote ... > wrote: > > IMO the following is an odder behavior: > > >>> t > > ([1], [2], [3]) > > >>> t[1] += [3] > > Traceback (most recent call last): > > File "", line 1, in ? > > TypeError: object doesn't support item assignment > > >>> t > > ([1], [2, 3], [3]) > > > > Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 > >>> class myTuple(tuple): > ... def __setitem__(self, attr, value): > ... print 'in setitem:', attr > ... > >>> a = myTuple(([1],[2],[3])) > >>> a > ([1], [2], [3]) > >>> a[1] += [4] > in setitem: 1 > >>> a > ([1], [2, 4], [3]) > >>> > > > Here's another that's differently wrong: > >>> a = ('aaa',) > >>> a[0]+='bbb' > Traceback (most recent call last): > File "", line 1, in ? > TypeError: object doesn't support item assignment > >>> a > ('aaa',) > >>> Why do you consider either of these examples wrong? The whole point of tuples is that if d is a dictionary, then d[t1] == d[t2] if, and only if, t1 == t2. Both of these examples are trying to make changes that will modify an (immutable) tuple. There's every reason to treat these modifications as illegal, since a before the fiddling is not equal to a after the fiddling, but tuples aren't mutable so such changes are illegal. regards -- ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From Joal.Heagney at student.gu.edu.au Sun Jun 23 16:53:26 2002 From: Joal.Heagney at student.gu.edu.au (Joal Heagney) Date: Mon, 24 Jun 2002 06:53:26 +1000 Subject: bloody freshman question regarding strings References: <1024821351.3424.12.camel@dorian.blaue-elise.net> Message-ID: <3D163546.8010707@student.gu.edu.au> Christian Guenther wrote: > Wow, that was quick. Many thanks for the responses. I suppose > I have to learn a lot about pythons sysntax and way it handles > objects and stuff. > > I always had bit of a problem understanding OO-concepts. > > chris The responses in this group usually are very quick. One of the best things about the language. :) Have you had a chance to try some of the tutorials available at www.python.org? If you can read more complex documents, the official Python documents have a section on the syntax of the language. Joal Heagney/BCDragon From gleki at gol.ge Tue Jun 4 06:36:04 2002 From: gleki at gol.ge (Giorgi Lekishvili) Date: Tue, 04 Jun 2002 12:36:04 +0200 Subject: property in Py2.2 Message-ID: <3CFC9814.4761F3CB@gol.ge> Hi all! I wonder if someone finds time to send me a real code of how to use properties in Py2.2 I would be much obliged, if you also send me a version of the code for Py2.1, with __setattr__ and __getattr__. Thx, Giorgi PS. Prior to post here, I have read the materials on www.python.org. I find them very helpful. From gerhard.haering at gmx.de Wed Jun 5 12:40:11 2002 From: gerhard.haering at gmx.de (Gerhard =?unknown-8bit?Q?H=E4ring?=) Date: Wed, 5 Jun 2002 18:40:11 +0200 Subject: [ANN] pyPgSQL 2.1 released In-Reply-To: <23891c90.0206050721.49b31f50@posting.google.com> References: <23891c90.0206050721.49b31f50@posting.google.com> Message-ID: <20020605164010.GB32960@gargamel.hqd-internal> CC-ing to pypgsql-users list, maybe other users have comments on this issue, too. * Paul Boddie [2002-06-05 08:21 -0700]: > Gerhard wrote: > > > > * Fixed the array parsing so it also works with PostgreSQL versions 7.2.x. > > I doubt that this is related, but does the 'IN' operator work with > statement parameters (bind variables) in pyPgSQL yet? I recently found > that doing something like this... > > cursor.execute("SELECT * FROM CAGES WHERE NAME IN %s", > (("mammals", "apes"),)) > > ...gives some kind of parsing error inside pyPgSQL. It is indeed a related issue. If you want to show which queries pyPgSQL produces, the trick is to access a special attribute like this: conn.conn.toggleShowQuery This would show the following query is executed: QUERY: DECLARE PgSQL_08120A6C CURSOR FOR select * from cages where name in '{"mammals","apes"}' ... which obviously cannot work. The reason is that if pyPgSQL encounters a tuple or a list in the statement parameters, it will quote them suitable for use as an ARRAY. Unfortunately, the ARRAY syntax is different from what you would need for the IN operator in SQL. I'm not sure if something can be done about this problem. It seems to me that it's an either/or with ARRAY vs. your desired conversion for the IN operator. > [...] Another thing: pyPgSQL seems to be fine with Unicode query strings > (unlike psycopg, apparently), but it doesn't like Unicode parameter values. > Is there some explicit encoding step I should be performing? I've fiddled with adding Unicode support for some time now, but I didn't get enough testers yet to make me comfortable enough with it for adding it to a pyPgSQL release. On the Sourceforge patches section, I've uploaded a patch for full Unicode support, including getting Unicode results back from the database, insert Unicode strings, and automatic encoding conversions. I'll try to update this patch today to work with the latest pyPgSQL 2.1 release and drop you a note when it's ready. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 25.7 ?C Wind: 4.5 m/s From whisper at oz.net Mon Jun 10 23:29:14 2002 From: whisper at oz.net (David LeBlanc) Date: Mon, 10 Jun 2002 20:29:14 -0700 Subject: python and shared libaray In-Reply-To: Message-ID: Yes, you could use that in Python, but it's not a matter of just importing the .so library. In order to use it, you'll have to create a wrapper .lib or .so that converts between python objects and C/C++ procedure calls and data types. The doc that comes with Python includes information on creating Python extensions and a couple of other good places to start are: www.boost.org if it's C++ www.swig.org if it's C The missing init function is one of the things you'll have to add. In there is where you would import the C/C++ .so lib - or it gets auto-included as a consequence of your having linked against it. Regards, David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Steven Pokrandt > Sent: Monday, June 10, 2002 19:21 > To: python-list at python.org > Subject: python and shared libaray > > > I have a vendor supplied .so file, header file and docs. I would like > to use this > .so file in python but don't have the src. Is it possible to link > this library ie: > > import filename.so > > when I try the python complains about no init function.. can I add > this to the .so without having the src? > > can someone point me to a howto? > > please send message to the following address.. spokra (AT) attbi > (dot) com > > you get the meaning of the email address, and hopefully the spammers > don't > -- > http://mail.python.org/mailman/listinfo/python-list From BPettersen at NAREX.com Tue Jun 4 17:09:07 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Tue, 4 Jun 2002 15:09:07 -0600 Subject: self Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192158EA7@admin56.narex.com> > From: Vojin Jovanovic [mailto:vjovanov at stevens-tech.edu] > > I don't see how that is going to work. In fact I tried > things like that before without success. Just sticking the > dictionary into eval/exec is missing the point. Every time > parsing is done flow needs to go through __getattr__ special > method to evaluate nested equations. Without self. you can't > achieve that effect. Try the approach you suggested and > you'll get '#U'. Perhaps something like this? -- bjorn class Eval: def __init__(self): self.__dict__['dict'] = {} exec "from math import *" in self.dict def __call__(self, expr): try: return eval(expr, self.dict, self.dict) except SyntaxError: exec expr in self.dict, self.dict def __getattr__(self, attr): return self.dict[attr] def __setattr__(self, attr, val): self.dict[attr] = eval(val, self.dict, self.dict) e = Eval() print e('pi * 3') e('x = sin(0.5)') print e.x e.y = 'sin(0.5)' print e.y From menucool at yahoo.com.cn Tue Jun 18 23:50:16 2002 From: menucool at yahoo.com.cn (coolmenu) Date: 18 Jun 2002 20:50:16 -0700 Subject: Can python have lib to display PDF ? References: Message-ID: Simon Brunning wrote in message news:... > > From: menucool at yahoo.com.cn [SMTP:menucool at yahoo.com.cn] > > > > i want a python application to display end edit pdf. > > where are the lib pdf for python? > > thank > > > > Cheers, > Simon Brunning > TriSystems Ltd. > sbrunning at trisystems.co.uk > Thank all :-) i will try it.. From gleki at gol.ge Mon Jun 24 05:17:19 2002 From: gleki at gol.ge (Giorgi Lekishvili) Date: Mon, 24 Jun 2002 11:17:19 +0200 Subject: HTTP authentication References: Message-ID: <3D16E39F.E164D5D@gol.ge> Hi all! I would be much obliged if someone provides an example of the working code. Grtz, Giorgi Preston Tamkin wrote: > hello all. I've just recently jumped on the python bandwagon, and I need > some help! > I'm trying to write a program(in python) to go out to several websites and > get a few numbers off of the page. Only problem is, I need to give the site > a username and password! It's not HTTPS, SSL, or anything like that. I did > some packet sniffing and it is a HTTP POST command, the server then requests > the information then the client sends the u/p. I'm using raw sockets and > can't figure out how to listen for the "request" packet or excatly what to > send for the last part. The site uses ASP. It's http://boards.ign.com if you > want to look at it. Is there an easier way to do it? Am I just simply > missing something? Thanks in advance > > P.S. Me = TOTAL n00b From dkt at registriesltd.com.au Mon Jun 24 19:30:47 2002 From: dkt at registriesltd.com.au (David K. Trudgett) Date: Tue, 25 Jun 2002 09:30:47 +1000 Subject: SOLVED (Re: Python hits the spot) In-Reply-To: ; from cliechti@gmx.net on Mon, Jun 24, 2002 at 10:27:55PM +0200 References: <3D14CF95.4030501@kfunigraz.ac.at> <3D158F3E.1010907@kfunigraz.ac.at> <3D16DD5C.1050708@kfunigraz.ac.at> <3D171291.2060905@kfunigraz.ac.at> Message-ID: <20020625093047.A1568@regdp-02.intint.registriesltd.com.au> On Monday 2002-06-24 at 22:27:55 +0200, Chris Liechti wrote: > >> It was really the laptop processor. I tried the calculation on a > >> stationary machine (Pentium II 450 MHz and SuSE 8.0), and it works. > >> > > you have to admit that it was a nasty failure... is bad hardware your first > thought when your program fails? Should be an object lesson in that: software engineers need to keep an eye on hardware issues, including potential failures. It is actually more common than one would think that 100% CPU for extended periods can cause hardware failure. Reason: most PCs are engineered and tested under light load conditions such as those that 95% of users subject their machines. Many servers, however, run at or near 100% CPU for extended periods of time, with near continuous disk activity and so on. Therefore, server class machines are engineered and tested to a higher standard, and are less prone to such failures (although all hardware fails eventually). I remember that I could never do serious image processing on an "old" Intel Pentium 166 MMX machine because after five minutes it would become overheated with buzzers sounding to remind me of the fact! It had the regulation heat sink and CPU fan but still overheated. Go figure. Classic symptom of heat failure: machine reboots, stops responding, or specific components (such as a video card) fail after X minutes from power on, or X minutes of high CPU usage. Memory faults can be even harder to spot because they often cause bizarre symptoms that seem unrelated to memory issues. I once spent several hours diagnosing and fixing a random "CDROM" fault, including swapping in a replacement drive and data cable, only to find that the problem went away after replacing a faulty SIMM card. David Trudgett From znu at znu.dhs.org Fri Jun 7 02:08:14 2002 From: znu at znu.dhs.org (ZnU) Date: Fri, 07 Jun 2002 02:08:14 -0400 Subject: Method call from string References: <3D004DB1.62BEB68A@engcorp.com> Message-ID: In article <3D004DB1.62BEB68A at engcorp.com>, Peter Hansen wrote: > ZnU wrote: > > > > Say I've got a variable with the value 'do_something', and I have an an > > object that happens to have a do_something method. How can I call that > > method based on the value of the variable? Preferably without using > > eval() or similar. > > >>> var = 'do_something' > >>> class A: > ... def do_something(self): > ... print 'ooga booga' > ... > >>> a = A() > >>> getattr(a, var) > > > >>> f = getattr(a, var) > >>> f() > ooga booga Now that I actually think things though, that makes perfect sense. I should have been able to figure that one out myself. Thanks. -- Right now the Internet gives an awfully good imitation of providing superhuman intelligence capability, both in terms of the total hardware that is out there and the fact that the 'net has all these human-equivalent peripheral devices called "users" that can be appropriated in a distributed way to attack problems. --Vernor Vinge From altis at semi-retired.com Sun Jun 23 14:26:56 2002 From: altis at semi-retired.com (Kevin Altis) Date: Sun, 23 Jun 2002 11:26:56 -0700 Subject: The best GUI library in python References: <8d3f4438.0206220457.b820418@posting.google.com> Message-ID: <_moR8.392$Fb7.37368@news.uswest.net> PythonCard uses wxPython as its underlying GUI toolkit, so it should be fast enough for your needs. PythonCard comes with over 30 samples that you can learn from and modify for your own purposes as well as tools for editing source code and building layouts and menus. http://www.pythoncard.org/ The documentation page can help you get started quickly. http://pythoncard.sourceforge.net/documentation.html ka "d2002xx" wrote in message news:8d3f4438.0206220457.b820418 at posting.google.com... > Hello!! > > I want to learn GUI in python, who would tell me which GUI library is > the best? (don't tell me Tkinter, it's too slow......) From plugin at supercable.es Sun Jun 23 14:19:23 2002 From: plugin at supercable.es (Ugo García) Date: Sun, 23 Jun 2002 20:19:23 +0200 Subject: Redirecting StdOut Message-ID: <1024856420.145085@seux119> Hi all. I'm making a game and I'm using Python as the script language. I'm including a console to communicate with Python. I can interactively send commands to the interpreter but I can't obtain the response from it. Is there any way to redirect stdout and stderr in order to print its contain to the screen? Thank in advance --ugo From shalehperry at attbi.com Wed Jun 26 13:22:58 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 26 Jun 2002 10:22:58 -0700 (PDT) Subject: Problems using samples In-Reply-To: <337619fa.0206260913.41e08940@posting.google.com> Message-ID: On 26-Jun-2002 Raphael Ribeiro wrote: > 1 x = 8 > 2 y = 4 > 3 v = x - y > 4 > 5 print v > 6 if x = y: > 7 print "Eles s?o o mesmo valor" > 8 else: > print "Eles n?o s?o iguais , manja?" > > this is my code, it says there's an error in line 6, but i can't find > what **** error is that, can anyone help me? you are not allowed to do an assignment inside of a control statement. if foo = 2: # invalid while line = readline(): # invalid did you mean to use: if x == y? if not the python idiom is: x = y if x: # do something From peter at engcorp.com Wed Jun 19 22:05:57 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 19 Jun 2002 22:05:57 -0400 Subject: Threading question References: Message-ID: <3D113885.13815FCF@engcorp.com> David LeBlanc wrote: > > with a thread sitting in a loop processing intermittant transactions from a > buffer, how does one wait if reading an empty buffer does not block - how do > you relinquish control to other threads/processes? As Aahz points out, use Queue. If that's not acceptable, the usual approach is to do a time.sleep() of some size when nothing is available. Depending on how much CPU you wish to waste versus how long a latency you are willing to suffer, you might use anything from time.sleep(0.01) to time.sleep(10) ... -Peter From robin at jessikat.fsnet.co.uk Sat Jun 29 18:49:18 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sat, 29 Jun 2002 23:49:18 +0100 Subject: yield equivalent in C/JavaScript? References: <7xy9cxhlvx.fsf@ruckus.brouhaha.com> Message-ID: In article <7xy9cxhlvx.fsf at ruckus.brouhaha.com>, Paul Rubin writes >There's no native way to do it in C; in some enviroments you might be >able to simulate it with longjmp madness or threads. > >In Javascript the only approach I can think of is make a "virtual >machine" that executes javascript statements using JS's eval function, >and implement something like threads or coroutines in the virtual >machine. I did something like that once--it wasn't as bad as it >might sound, but it may not be worth it for your application. >You can just organize your generator functions like a state machine >instead, saving their locals and yielding location in some structure >returned to the caller. I haven't examined any Python generator >bytecode but I suspect that's how it works. By being limited to >"simple" generators (can't yield except to one's direct caller) >it's enough to just save the local variables and "return" address >in the state object, rather than a full continuation including >the call stack. the generators here are things associated with compression or decompression methods. The complexity is such that a severe reformulation will be tough. I understand the concept, but I think it's easier to just try and consume the whole input at one go and pass it on. -- Robin Becker From spenrose at intersight.com Thu Jun 6 19:22:08 2002 From: spenrose at intersight.com (Sam Penrose) Date: Thu, 6 Jun 2002 16:22:08 -0700 Subject: Medium to Large Scale Python Deployments Message-ID: <38C31EBA-79A4-11D6-9A7D-003065B33450@intersight.com> [Domenic R. Merenda raises the topic of Python used in large contexts] I'm also curious about large amounts of Python, period. Who knows of ~50K Python lines-of-code (LOC) systems? 100K LOC? More? From jbublitzNO at SPAMnwinternet.com Sun Jun 16 15:27:38 2002 From: jbublitzNO at SPAMnwinternet.com (Jim) Date: Sun, 16 Jun 2002 19:27:38 GMT Subject: SWIG and Callbacks References: <3d0a8b6e@nntp.server.uni-frankfurt.de> <3d0b4fd6@nntp.server.uni-frankfurt.de> <3d0c6d67@nntp.server.uni-frankfurt.de> Message-ID: <3D0CE698.1050806@SPAMnwinternet.com> Michael 'Mickey' Lauer wrote: > David Abrahams wrote: >>With Boost.Python, what you write looks like a kind of IDL (interface >>description language), which just happens to be built out of C++ source >>code. Lots of jobs (function argument type checking, conversion, arity >>checking) are done automatically, but the library doesn't decide which >>elements to wrap. Unlike SWIG and a few others, there's no attempt to parse >>your source code. Instead, the compile-time introspection capabilities of >>C++ are exploited to automatically build wrappers from function and member >>function pointers. > I see. So it seems in order to get a nice object oriented Python interface, > I can 1.) use SWIG to parse the header file and automatically produce a wrapper > 1.1.) and then use this low-level wrapper to write some high-level python classes around it or > 2.) use Boost.Python and do the two steps in one by writing a "handcrafted" interface? > How would sip come into this picture? Is it more like SWIG for C++ or more like Boost.Python? > (Apart from not beeing concerned about the total lack of documentation ;) Basically, sip requires that you create a description file (.sip file) from the h files you want to bind. While there isn't any documentation as such, the entire process is pretty well described in a recent thread on the PyKDE mailing list concerning libkdegames, and you can use PyQt and PyKDE as examples. I looked at Boost a while ago and it looks very nice. I've recommended it to people basically because is *has* documentation and for a single project with a small number of files would probably be more efficient to use than sip, given the difficulties in learning sip and setting up the configure/makefile framework. On the other hand, I maintain PyKDE (I should point out I'm not the sip author however), and for an actively maintained project with nearly a dozen libraries and several hundred files, sip seems preferable. It's possible to automate a lot of the *.sip file generation, including the versioning (both PyQt and PyKDE use a single set of description files that cover ALL supported versions). As far as the example posted earlier in the thread, it doesn't look like it would be a problem for sip, other than exposing the member variables publicly seems like poor design and could lead to problems in Python bindings if not used carefully. The difficulty with sip is that while it's a very good tool for general purpose use, it's maintained primarily for PyQt/PyKDE and there hasn't been a lot of time available to generate documentation or tools to go with it. It is open source, however, and I'm sure plenty of support would be available for anyone wanting to do work in the areas of docs or tools, or wanting to use sip to generate bindings.. Jim From tdelaney at avaya.com Mon Jun 24 20:23:06 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Tue, 25 Jun 2002 10:23:06 +1000 Subject: GOTO w/ Python? Message-ID: > From: Daniel Fackrell [mailto:dfackrell at DELETETHIS.linuxmail.org] > > After skimming the linked page to get a feel for the CAME > FROM statement, is > it conceptually different from short procedures? Does the > only difference > lie in the fact that for compiled languages one of the > instances will be > inline? I do understand that it would have some effect on > variable scoping, > but this can be easily handled in other ways. > > So what's the benefit that might outweigh the opacity of the > code created? I hope you're not serious ... :) COME FROM is a joke. Literally. It is a parody of GOTO whose only redeeming feature is that it is not GOTO. Tim Delaney From cliechti at gmx.net Sun Jun 23 14:36:02 2002 From: cliechti at gmx.net (Chris Liechti) Date: 23 Jun 2002 20:36:02 +0200 Subject: Redirecting StdOut References: <1024856420.145085@seux119> Message-ID: "Ugo Garc?a" wrote in news:1024856420.145085 at seux119: > Hi all. I'm making a game and I'm using Python as the script language. > I'm including a console to communicate with Python. I can > interactively send commands to the interpreter but I can't obtain the > response from it. Is there any way to redirect stdout and stderr in > order to print its contain to the screen? sure. just assign a file like object to sys.stderr and stdout. class DummyFileForWrites: def write(self, text): #write 'text' to GUI here sys.stdout = sys.stderr = DummyFileForWrites() so you can do the same for sys.stdin but then you would need read, readline, and readlines. chris -- Chris From jepler at unpythonic.net Mon Jun 17 10:52:53 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 17 Jun 2002 09:52:53 -0500 Subject: Getting pixel values under cursor In-Reply-To: <3eeda89d.0206170256.4ba75ec@posting.google.com> References: <3eeda89d.0206170256.4ba75ec@posting.google.com> Message-ID: <20020617145252.GC8814@unpythonic.net> I don't know that Tk offers the general capability to find the color under a pixel. However, it is possible to find the color at a particular coordinate within a photo image. In tcl/tk, " get x y" returns the RGB triple .. This doesn't seem to be provided in Tkinter.Image, so I derive a class here. from Tkinter import * class ImagePlus(Image): def get(self, x, y): return tuple(map(int, self.tk.splitlist( self.tk.call(self.name, "get", x, y)))) def update_it(evt): x = evt.x y = evt.y rgb = p.get(x,y) print `rgb` l.configure(text="#%02x%02x%02x" % rgb) t = Tk() p = ImagePlus("photo", master=t, file="dilbert2001114622012.gif") l = Label(t) x = Label(t) x.configure(image=p) x.bind("", update_it) l.pack() x.pack() t.mainloop() Jeff From K.Rdt at TU-Berlin.DE Tue Jun 25 09:48:46 2002 From: K.Rdt at TU-Berlin.DE (Klaus Reinhardt) Date: Tue, 25 Jun 2002 13:48:46 GMT Subject: mail-problem over t-online References: Message-ID: <1103_1025012926@127.0.0.1> Am Sun, 23 Jun 2002 23:01:56 +0200 hat Klaus Reinhardt geschrieben: --------------------------------------------------------------------- Hi With putty-tunnel! K at Rdt --------------------------------------------------------------------- From toddg at math.utexas.edu Mon Jun 10 12:03:18 2002 From: toddg at math.utexas.edu (Todd Gillespie) Date: Mon, 10 Jun 2002 16:03:18 +0000 (UTC) Subject: Embed python in multi-thread environment References: Message-ID: Arlo wrote: : i've tried to embed python in multi-thread application( written in c++) : the flow is: First thing, I recommend you look at a successful implementation: http://pywx.idyll.org/ From donn at u.washington.edu Tue Jun 25 12:57:37 2002 From: donn at u.washington.edu (Donn Cave) Date: 25 Jun 2002 16:57:37 GMT Subject: Suggestions for good programming practices? References: Message-ID: Quoth brueckd at tbye.com: | On 25 Jun 2002, Chris Liechti wrote: (someone said) | > >> * Avoid exec, execfile, eval, and input. | This view is a overly extreme. Rather than teaching people to fear certain | features like eval/exec, it's better to explain the risks so that they can | make informed decisions as to when it's wise to use them. It's not overly extreme! It's just about extreme enough. | So... rather than teaching "avoid W!", let's say "be careful with W | because of X, Y, and Z". I still wouldn't use eval/exec on code posted | through a web form, for example, but there are times when they are very | useful and I can use them in good confidence because I understand their | risks. But you weren't going to be deterred by that pronouncement anyway. "Avoid exec, execfile, eval, and input" is good advice. Taken at face value, it doesn't necessarily absolutely prohibit their use - if I said "avoid walking in the road", you could reasonably reasonably assume I'm saying something like "walk on the sidewalk when possible". Someone whose software engineering skills have been honed by years of wrestling with ugly code monsters will apply a different perspective to that advice. A 1-week newbie could do worse than to follow that advice religiously. Donn Cave, donn at u.washington.edu From shagshag13 at yahoo.fr Wed Jun 12 05:29:30 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Wed, 12 Jun 2002 11:29:30 +0200 Subject: parse tar file with python Message-ID: hello, i 'm not sure this is the right place to ask, but maybe somebody had already do some kind of python code on this : i had hundred thousand of small files, my program is very slow. I'm thinking that i loose time waiting for opening/closing, and i think this could be best if i "tar" my files by blocks. But in this case i don't know how to check for the end of a file and how to get its name (both in a tar archive) ... (i don't want to tar/untar with python, just to be able to do a sequential reading of a tar file to get its content) do you have an idea ? thanks in advance, s13. From kragen at pobox.com Sun Jun 2 22:38:03 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 02 Jun 2002 22:38:03 -0400 Subject: Why no open(f, "w").write()? References: <20020531225504.248c92ce.larooy@xtar.co.nz> Message-ID: <83sn45rss4.fsf@panacea.canonical.org> Paul Foley writes: > GC is just an optimization to allow reuse of > memory used by objects that the program will never access again, > because you don't really have infinite memory. > > Correct optimizations don't change the behaviour of correct code. > > [Therefore, if the behaviour of your code does change depending on > whether or not the optimization is done, either the optimization is > in error or your code is. So all finalizers should be considered bugs? I think that's a supremely unpragmatic approach to programming. From jjl at pobox.com Tue Jun 4 17:10:34 2002 From: jjl at pobox.com (John J. Lee) Date: Tue, 4 Jun 2002 22:10:34 +0100 Subject: Cookie question In-Reply-To: References: Message-ID: On Wed, 5 Jun 2002, Ken wrote: [...] > If I have many different cgi scripts checking UserID this way, are they all > refering to the same cookie? They are if and only if the browser sends back the same cookie as last time. I don't think I understand what you're getting at. > If it is so, how come my other scripts can't read userid correctly? What did > I do wrong? Can you be more specific? > Also, where does the cookie get saved in my computer (using Win2000 Pro)? I > don't seem to find any cookie inside the Tempory Internet Files folder. Why should they get saved in there? Firstly, this is Python, not IE, that you're programming. Secondly, you're talking about the server end of the cookie protocol, and it's the client's responsibility to save cookies -- that's the whole point! Am I misunderstanding you? John From pyth at devel.trillke.net Wed Jun 12 08:20:15 2002 From: pyth at devel.trillke.net (holger krekel) Date: Wed, 12 Jun 2002 14:20:15 +0200 Subject: Python Virtual File System: A spike test In-Reply-To: <3D070F27.9050608@rogers.com>; from mcfletch@rogers.com on Wed, Jun 12, 2002 at 05:06:47AM -0400 References: <3D070F27.9050608@rogers.com> Message-ID: <20020612142015.X6609@prim.han.de> Hi Mike, [you wrote] > Purpose: > > A class for representing file system paths which supports both > method-based operations, and abstraction through object encapsulation to > eventually allow for Virtual File System operations (for instance, > transparently accessing the contents of zip files). > > Status: > > An initial implementation (spike test) exploring the viability of the > approach. Implementation provides: > > equality testing > parent/child/ancestor/descendent retrieval/testing > filesystem-role testing (file/dir/root) > root retrieval and root comparisons > "walking" (callback-based recursive iteration) > listing (returning Paths which include their parent directory) > fragment determination (i.e. c:\\temp\\test -> "c:\\", "temp", "test" > recursive directory-tree removal (including files) > open( ) method for path specifiers Interesting. I have written a similar 'filename' class. It is not based on the str-type but accepts strings in many places. Also the filename class offers all of the methods found in 'os' or 'os.path' under the exact name. I think this is important to make using it easy. Many people already know and use the stdlib-methods. One of the nice features is that you can do stuff like: fn=filename('/usr/src') cfilter=filters.OR(filters.hasext('.cpp'), filters.hasext('c')) mfilter=filters.rmatch('.*/[Mm]akefile.*') recursefilter=rignore('.*/CVS') for makefiles, cppfiles in fn.filterwalk([mfilter,cfilter], recursefilter): # work with list of makefiles # work with cppfiles 'filterwalk' is a generator which honors a recursion filter and one or more filename-filter. It allows to recurse once and get back categories of files (as lists). No further checking like 'islink' etc. needed. You makeup your filters and call filterwalk and afterwards work with the lists. > Future: > > If there is interest, I am planning on creating a new SourceForge > project with the eventual goal of creating a virtual file system package > with a consistent interface to most of the major file-and-directory > systems (zip files, FTP sites, local file systems) and hooks for adding > new systems. Having an abstraction for 'Names'/URLs and working from there would be very interesting IMO. At the moment we only work with (relatively untyped) strings which places the burden of calling the right methods (urllib/httplib/urllib2/os.path/ftplib/webdav...) on the programmer (who just has a string). > Request: > > If you're interested in working on such a project (or even using it), > let me know, so I can decide whether to devote any more resources to it. > You can find the module here: > > http://members.rogers.com/mcfletch/programming/filepath.py i am interested but we should discuss if our approaches/viewpoints work well together :-) cheers, holger From aahz at pythoncraft.com Thu Jun 13 13:09:58 2002 From: aahz at pythoncraft.com (Aahz) Date: 13 Jun 2002 13:09:58 -0400 Subject: Threading tutorial wanted. References: Message-ID: In article , Gerhard =?iso-8859-15?Q?H=E4ring?= wrote: > >Aahz has written a tutorial that you were already referred to. It's >useful info, but nowhere near complete. Maybe you can write a tutorial >yourself once you've mastered threading? ;-) Maybe there's a Python >book that covers multithreading in depth? I'd be interested which one >this is if so. I was negotiating with O'Reilly to write such a book, but even though threading is a popular topic here, it's pretty clearly a marginal book project and various external events (including the economy) consipired to kill the book (at least for now -- and I'm currently working on a different book that will keep me busy until next year). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I had lots of reasonable theories about children myself, until I had some." --Michael Rios From whisper at oz.net Thu Jun 6 15:57:14 2002 From: whisper at oz.net (David LeBlanc) Date: Thu, 6 Jun 2002 12:57:14 -0700 Subject: Using AT on XP to run python script - MARK HAMMOND PLEASE READ In-Reply-To: Message-ID: I just discovered that you can use /interactive to cause a scheduled task to show output. I wonder if this would work for your email problem... at xx:xx /interactive python j:\python22\tools\idle\idle.py This worked as expected and idle came up! Dave LeBlanc Seattle, WA USA From mike at radiomag.com Tue Jun 18 02:52:39 2002 From: mike at radiomag.com (Michael Steuer) Date: Tue, 18 Jun 2002 16:52:39 +1000 Subject: Listing all available (not just loaded) modules References: Message-ID: > Idle, PythonWin and Boa (at least) do this, with PythonWin being the most > detailed - it shows classes and methods within the modules. The version of > Pythonwin I have does not show the contents of the site-packages tree, but > that would be easily fixable. They "do this" and how? Don't tell me you mean the dir() command ... Cheers, Mik.e From shalehperry at attbi.com Fri Jun 21 12:32:06 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 21 Jun 2002 09:32:06 -0700 (PDT) Subject: Newbie-Question: Oberserving an directory In-Reply-To: <3d1352a7@news.piro.net> Message-ID: On 21-Jun-2002 Marcus Klein wrote: > Hi there, > > I want to observe an directory to check if a new file has been put in, if > that happens I want to start an event. > > Does anyone have a good idea how to start, I've tried it with signal, but > either I am too stupid or it is the complete wrong way :-/ > under UNIX the only way to accomplish this is to periodically poll the directory with stat. There is no signal you can watch for. I can not speak for either Mac or Windows. From tdelaney at avaya.com Mon Jun 10 22:33:49 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Tue, 11 Jun 2002 12:33:49 +1000 Subject: Correct code/unit testing (was Re: Efficient python programmi ng...) Message-ID: > From: Peter Hansen [mailto:peter at engcorp.com] > > Perhaps, assuming you put a lot of bugs in the code, some > amount of staring will be necessary. > > I believe staring is of little or no use, however, having > tried it many times with my and others' code which had bugs and > not having found those bugs by staring. Staring in and of itself is not of much use ... however, simply getting another set of eyes on the code is. I have found that in the majority of cases, one of two things will occur: 1. The new set of eyes will immediately see the thing you've been failing to see for the past 2 hours ... OR 2. While explaining to the new set of eyes enough for them to understand the problem, *you* will see what you've been failing to see for the past 2 hours ... Any time I find myself staring at something and making no progress, I get someone else to look at it. Likewise, I make myself available to others. Again, this requires egoless programming - it doesn't work if you get upset when someone else finds your boneheaded mistake; or if you are unwilling to point out your own boneheaded mistake in front of someone else; or if you are unwilling to point out someone else's boneheaded mistake because *they* will get upset. Tim Delaney From mruiz at safa.es Fri Jun 21 07:22:00 2002 From: mruiz at safa.es (Manuel Ruiz) Date: Fri, 21 Jun 2002 11:22:00 GMT Subject: CR+LF problem References: <3d11bc33.1129927479@news.mad.ttd.net> <12q3hukse2cepcm9tpern92jc71a5vrhvi@4ax.com> Message-ID: <3d1309ff.1215379262@news.mad.ttd.net> Hi, char * txt = "print 123\r\n" is only a sample, I am storing scripts in a database, I put the script into the database with \n but when I get it, It has \r\n as end of line, I have assumed this is a database problem. The rare thing is that PyRun_Simple() function can't execute this kind of python code using \r\n as end of line, however I saved that code to file and ran "python2 myfile.py" (with \r\n as end of line too) and it ran fine, very fine. Where is the diferrence between the api of python and the interprete itself. Because first one can't execute this code and the second one can do it ? Regards Manuel Ruiz On Thu, 20 Jun 2002 17:38:43 +0300, Christos "TZOTZIOY" Georgiou wrote: >On Thu, 20 Jun 2002 11:33:55 GMT, rumours say that mruiz at safa.es (Manuel >Ruiz) might have written: > >>char * txt = "print 123\r\n"; >>result = PyRun_Simple( txt, Py_file_input, PyDict_New(), NULL ); > >did you try > char *txt= "print 123\n"; >by any chance? >I am not very sure if I do help, but in C, newlines are just "\n". >"\r\n" is by convention the text line terminator of VMS IIRC, MS-DOS & >window derivatives etc. > >>this code fails to exec txt, I got a SyntaxError exception, >>however I if save to file the statement "print 123\r\n" and try to run >>it ussing python interprete (version 2.2.1) It run fine. >> >>Can anyone tell me anything about this rare behaviour > >-- >TZOTZIOY, I speak England very best, >Real email address: 'dHpvdEBzaWwtdGVjLmdy\n'.decode('base64') From pyth at devel.trillke.net Thu Jun 6 20:30:10 2002 From: pyth at devel.trillke.net (holger krekel) Date: Fri, 7 Jun 2002 02:30:10 +0200 Subject: self In-Reply-To: ; from vjovanov@stevens-tech.edu on Thu, Jun 06, 2002 at 10:34:09AM -0400 References: <0%hL8.22575$tK.5490038@news02.optonline.net> <_zpL8.81$pq2.4342892@newnews.cc.stevens-tech.edu> Message-ID: <20020607023010.B16359@prim.han.de> Vojin Jovanovic wrote: > I don't think you tested your code, because I can't get the output you > specified. In fact it seems that you broke your own code. of course i tested it! Do you really think i am making up results which can be proven wrong in ten seconds? Why such a harsh reaction without bothering to correct the obvious 'typo'? I don't actually know what went wrong while pasting the code ('Namerror' instead of 'NameError'). Anyway, here is the paste-typo-corrected version: class Evaluator: def __init__(self, eqs={}): self.__dict__['equations']=eqs def __getattr__(self, name): value = self.equations[name] if type(value)!=str: return value # if it's not a string, just give it back scope={} while 1: try: return eval(value, scope) except NameError, n: var=str(n).split("'")[1] scope[var]=getattr(self, var) def __setattr__(self, name, value): self.equations[name]=value class Berta: a=5 >>> e=Evaluator({'a':3}) >>> e.berta=Berta() >>> e.g='berta.a*a' >>> e.g 15 regards, holger From kzaragoza at attbi.com Sat Jun 15 15:42:59 2002 From: kzaragoza at attbi.com (Kris J. Zaragoza) Date: 15 Jun 2002 14:42:59 -0500 Subject: ADO Command object/Parameters problem... References: <3d09426d.313465031@netnews.attbi.com> Message-ID: In article <3d09426d.313465031 at netnews.attbi.com>, candiazoo at attbi.com wrote: > Has anyone else run into this (note: I have seen other entries for the same > error, which is rather generic, but not for my specific reason). I've never seen this specific error before when using ADO from Python or any other language. The exact error text below may be a red herring or otherwise not accurately describe the problem. Looking quickly at the code you provided, however, a few things smell fishy. Comments below. > HERE is an example of what I am doing... (note, I added the long() typecasting > to make sure the value was coerced into a long integer)... > > sql = "select pty.orgname " + \ > "from ccc_party pty, ccc_right_rightsholder rgh, ccc_right rgt " + \ > "where pty.pty_inst = rgh.rgh_inst " + \ > "and rgh.rgt_inst = rgt.rgt_inst " + \ > "and rgt.rgt_inst = ?" First of all, you are performing one more join than needed for what you are selecting. If you need to restrict your record set based on the rgt_inst field, you only need to join ccc_party and ccc_right_rightsholder as the latter already has the foreign key reference which is exactly the field you are restricting on. In other words, you only need to use: select pty.orgname from ccc_party pty, ccc_right_rightsholder rgh where pty.pty_inst = rgh.rgh_inst and rgh.rgt_inst = ? Or, using the more modern join syntax select pty.orgname from ccc_party pty join ccc_right_rightsholder rgh on rgh.rgh_inst = pty.pty_inst and rgh.rgt_inst = ? > cmdOracle.ActiveConnection = cnnOracle > cmdOracle.CommandType = 1 > cmdOracle.CommandText = sql > > trsInst = long(rstTempDB.Fields("trs_inst").Value) > aasInst = long(rstTempDB.Fields("aas_inst").Value) > anyInst = trsInst or aasInst > > cmdOracle.Parameters.Append(cmdOracle.CreateParameter("orgname", 200, 2, 80)) > cmdOracle.Parameters.Append(cmdOracle.CreateParameter("rgt_inst", 3, 1, 4, > long(anyInst))) > rstOracle, status = cmdOracle.Execute() Here's another point that confused me. Why are you adding two parameters when you only have one parameter placeholder? The orgname field is what will be returned in the record set rstOracle. You don't need to add it as a parameter. I don't know how helpful this has been. If you need further clarification or help, you may want to provide a more accurate or complete piece of code. Kris -- Kris J. Zaragoza | On the face of it, Microsoft complaining about kzaragoza at attbi.com | the source license used by Linux is like the | event horizon calling the kettle black. | -- Adam Barr, article on kuro5hin.org From sandskyfly at hotmail.com Tue Jun 4 14:24:12 2002 From: sandskyfly at hotmail.com (Sandy Norton) Date: 4 Jun 2002 11:24:12 -0700 Subject: Kalman Filters, Particle Filters and SVM's References: <671ybne7zm.fsf@mail.uni-oldenburg.de> Message-ID: > Support Vector Machines in (Numerical) Python ? > > Especially the latter would be fine, I'm dreaming to implement a SVM > based script with the capability to distinguish spam from personal > mails.... but I'm way to lazy to write my own SVM. Here's a couple of alternatives: - python SVM using orange machine learning framework (Aleks Jakulin) http://ai.fri.uni-lj.si/~aleks/orng/ or - you can use jython and tap the Java Weka Machine Learning Framework which also has an SVM implementation http://www.cs.waikato.ac.nz/ml/weka/ This is fun stuff... enjoy! Sandy Norton From mdk at mdk.com Thu Jun 20 11:21:51 2002 From: mdk at mdk.com (mdk) Date: 20 Jun 2002 15:21:51 GMT Subject: Fill a file with some text. Message-ID: Hello, I need to fill a file with differnt amounts of some text, either just the letter x or random, doesn't matter. But I need the size to be, for example, 6070784 bites. What is the best and or fastest way to do this? Thanks. From rs at onsitetech.com Thu Jun 13 16:53:44 2002 From: rs at onsitetech.com (Robb Shecter) Date: 13 Jun 2002 20:53:44 GMT Subject: another near-sighted, time-wasting syntax enhancement idea References: Message-ID: <3D0905FF.7050003@onsitetech.com> Chris Liechti wrote: > i don't see any advantages for that... I agree. That code looks pretty horrific. :-) Looks like someone's been doing lots of C++ programming? (Just guessing) From chris_mk at hotmail.com Wed Jun 5 13:00:48 2002 From: chris_mk at hotmail.com (Christopher) Date: 5 Jun 2002 10:00:48 -0700 Subject: Problem with urllib.urlopen() References: Message-ID: Yeah, me too! ;-) What happens is that a browser takes the user to the correct page but the urllib functions return a page that says an error has occured during the search. Thanks. "John J. Lee" wrote in message news:... > On 3 Jun 2002, Christopher wrote: > > There were some problem with posting the whole link so I'll break each > > one up... > [...lengthy URLs snipped...] > > chris_mk at hotmail.com (Christopher) wrote in message news:... > [...] > > > You should, like I said, get the XML version of the original links > > > (with some extra information, which is why I want to interface with > > > the XML site, btw). Now, if you do an interface with Python instead > > > of your browser you get a response of an error page instead. Why is > > > that and what can I do to change it? If you have any information, I > > > would appreciate it ver much. Thanks. > > What was the error? Sorry, too lazy to follow the urls. > > > John From gnufnork at fuckspam.hetdigitalegat.nl Mon Jun 10 22:51:12 2002 From: gnufnork at fuckspam.hetdigitalegat.nl (Wladimir) Date: Tue, 11 Jun 2002 04:51:12 +0200 Subject: python and shared libaray References: Message-ID: On Tue, 11 Jun 2002 04:20:44 +0200, Steven Pokrandt wrote: > I have a vendor supplied .so file, header file and docs. I would like > to use this > .so file in python but don't have the src. Is it possible to link this > library ie: > > import filename.so > > when I try the python complains about no init function.. can I add this > to the .so without having the src? I don't think that shared object is meant to be imported in python, concluding from your post it's just a generic one with C header files that define the interface. To use it in python you'd have to make a wrapper, I'm afraid, that's not too easy a job. Wladimir From imcmeans at home.com Sun Jun 30 22:58:21 2002 From: imcmeans at home.com (Ian McMeans) Date: Mon, 01 Jul 2002 02:58:21 GMT Subject: Is this a __slot__ bug? References: Message-ID: I wasn't able to find a good documentation of slots on the python website. Do you have a link handy? I guess I'm just bad at searching, I couldn't find a description in the first few pages of google either. "Steve Menard" wrote in message news:pan.2002.06.30.00.21.54.133520.5016 at vodeotron.ca... > OK, this is probably me not understanding something, but then again, you > never know. > > First things first, I love __slots__. For the paranoid programmer I am, > knowing I will never again assing to a variable with a typo and then > wonder ehat the hell is going wring is a godsend. > > However, I also love(need) private variables (those __X). It seems they > dont work with slots. try the following simple example under ptyon 2.2 on > linux : > > class O(object) : > __slots__ = [ > '__a' > ] > > def __init__(self) : > object.__init__(self); > self.__a = 3 > o = O() > > I get thoe following error : > AttributeError: 'O' object has no attribute '_O__a' > > Now, I know I can easily work around this by manually obfuscating the > private variables names in the __slots__, but I would rather not. Feels > wrong somehow to rely on what should be a hidden way of generating > private variables. > > So if this is by design, I will not agree but I will do the workaround. > If not, well then seems I founda bug :) > > Steve From gerhard at bigfoot.de Fri Jun 28 11:02:59 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 28 Jun 2002 15:02:59 GMT Subject: Is Python growing? References: Message-ID: Mark McEahern wrote: > [...] What's so > beautiful about Python is that all I had to do was fire up the interactive > interpreter and do this to remind myself of what map does: > > >>> print map.__doc__ help(map) in 2.2. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From whisper at oz.net Tue Jun 11 09:54:52 2002 From: whisper at oz.net (David LeBlanc) Date: Tue, 11 Jun 2002 06:54:52 -0700 Subject: How to play a .wav sound? In-Reply-To: Message-ID: Perhaps the "Snack" sound extension can help - it's primarily Tcl, but has a python binding too. It is cross-platform. http://www.speech.kth.se/snack/ David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of James T. Dennis > Sent: Tuesday, June 11, 2002 2:08 > To: python-list at python.org > Subject: Re: How to play a .wav sound? > > > Erlend J. Leiknes wrote: > > > Think this should work... not tested. > > I doesn't. I doesn't in principle (cat foo.wav > /dev/dsp doesn't work > for me) and the code is wrong in at least one spot: > > ... > > sdata = f.read(1024) > > while sdata: > > d.write(sdata) > ... > > that would only copy 1K of data > > > "Bruno Bellamy" wrote in message > > news:ad8jo7$ohl$1 at wanadoo.fr... > >> I guess the question has probably been asked many times, sorry for > >> bothering... > >> But I searched here and there, and I couldn't find how to do > that, simply > >> play a .wav sound from a python program using Tkinter. > > >> Moreover, I need to do that in a program that would run similarly under > >> Linux and Windows. > > >> I saw there's a python module called wave, but it seems it can > only read > >> .wav files. I coulnd't find a way to actually play the sound. > Maybe it's > >> hidden somewhere? > > >> If anybody can help me, that would be cool. :) > > > I was stumped for a little while last night as well. Unfortunately > I don't have a simple working example, yet; but it looks like > pysolsoundserver.so and the PySol (Python Solitaire) sources might > be a good start. Apparently PyGame also has some sophisticated > sound handling. There doesn't seem to be a way to do it (easily) > with the standard libraries, though. > > > -- > http://mail.python.org/mailman/listinfo/python-list From whisper at oz.net Mon Jun 10 01:40:40 2002 From: whisper at oz.net (David LeBlanc) Date: Sun, 9 Jun 2002 22:40:40 -0700 Subject: How to capture stdout into a string? In-Reply-To: Message-ID: No, it's GTSL - Grep the Source Luke :-> David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Matt Gerrans > Sent: Sunday, June 09, 2002 20:59 > To: python-list at python.org > Subject: Re: How to capture stdout into a string? > > > > :-) Actually, I assumed you already had RTFM.... > > Still helpful sometimes to read the source. > > Maybe you guys can coin (or have coined) a new acronym: RTFS > > > -- > http://mail.python.org/mailman/listinfo/python-list From kseehof at neuralintegrator.com Mon Jun 10 10:03:00 2002 From: kseehof at neuralintegrator.com (Ken Seehof) Date: Mon, 10 Jun 2002 07:03:00 -0700 Subject: Does Python need a '>>>' operator? In-Reply-To: Message-ID: Beni Cherniavsky wrote: > On 2002-06-10, Ken Seehof wrote: > > Unfortunately, I don't see an easy way to clean up this blemish: > > ... > ... This is correct behaviour ....etc. Of course I listed the three cases together for contrast: >>> 0xffff 65535 >>> 0xffffffff -1 >>> 0xfffffffff 68719476735L Obviously, only the second case is incorrect. - Ken Seehof From radix at twistedmatrix.com Tue Jun 11 13:55:12 2002 From: radix at twistedmatrix.com (Christopher Armstrong) Date: 11 Jun 2002 13:55:12 -0400 Subject: XML/Source Persistence (was: Source formatting for long expressions.) In-Reply-To: <20020611132003.I5683@eecs.tufts.edu> References: <874rgcxy99.fsf@twistedmatrix.com> <6bd9f01b.0206110543.168b0f83@posting.google.com> <878z5lx4vl.fsf@twistedmatrix.com> <20020611132003.I5683@eecs.tufts.edu> Message-ID: <874rg9wvi7.fsf_-_@twistedmatrix.com> >>>>> "Michael" == Michael Gilfix writes: Michael> On Tue, Jun 11 @ 10:32, Christopher Armstrong wrote: >> XML is a terrible format for object persistence, due to the lack of >> robust mappings. Twisted's XML uses attributes in some cases, but that >> is only possible when you have string:string mappings. In *any* other >> case, you have to resort to children nodes, with such ugly syntax as:: [snip..] >> *That* is why I don't just use XML. Michael> I'm not disagreeing with you because I don't think you're wrong Michael> in this case and well, XML isn't for everything. I think XML can Michael> work here just as well but it's just more work. I'm not sure about Michael> the lack of robustness of the mappings - you just have to define Michael> them and can use a DTD to verify that your mappings are Michael> intact. But you have to write extra code for the mappings that I meant the mappings that attributes provide. Creating mappings with multiple tags is overbearingly verbose, no matter if you formalize it or not. (Am I understanding you correctly?) Perhaps I should've said "flexible" rather than "robust". BTW, ONX (http://www.seairth.com/web/onx/onx.html) provides a better type of mapping: string:arbitrary object. It's not arbitrary object:arbitrary object, but it's a bit better. Michael> isn't quite worth it in such a domain specific case. XML costs Michael> extra for being general. Er, you don't have any between Michael> version/backwards-compat issues though do you? In which case, have Michael> you thought those out thoroughly? Forgive me if it isn't Michael> relavent. Not sure exactly where these will be used. Versioning the persistent data is pretty much irrelevant wrt the format used -- and yes, I have thought about it. Marmalade right now uses it's own versioned state-getters/setters (jellyToDOM_X where X is the version number), but AOT doesn't have its own interface -- it just uses __getstate__/__setstate__ like pickle. I'm probably going to write a mixin class for versioned state that supports methods like __getstate_X__ where X is the version of the persisted state. Note that Twisted has a class for versioning state that's orthogonal to persisted format: twisted.persisted.styles.Versioned. This allows you to define 'upgradeToVersionX' methods that will be called in order to upgrade an object to the current version of the code. The only reason to use versioned state getters/setters as opposed to this is if you want the format of the persistent state to change for cosmectic reasons. -- Chris Armstrong << radix at twistedmatrix.com >> http://twistedmatrix.com/users/carmstro.twistd/ From pyth at devel.trillke.net Thu Jun 13 18:09:50 2002 From: pyth at devel.trillke.net (holger krekel) Date: Fri, 14 Jun 2002 00:09:50 +0200 Subject: dictionary: keys() and values() In-Reply-To: <3D09160A.2030402@NOSPAMREMOVETHISxs4all.nl>; from irmen@NOSPAMREMOVETHISxs4all.nl.trillke.net on Fri, Jun 14, 2002 at 12:00:42AM +0200 References: <3D09160A.2030402@NOSPAMREMOVETHISxs4all.nl> Message-ID: <20020614000950.L6609@prim.han.de> Irmen de Jong wrote: > Andrew Koenig wrote: > > From the library reference, 2.2.7, footnote 3: > > > > If keys() and values() are called with no intervening modifications to the > > dictionary, the two lists will directly correspond. This allows the creation > > of (value, key) pairs using zip(): "pairs = zip(a.values(), a.keys())". > > Why would you want to do that if you have .items()? i almost fell for the same question untill i looked harder. order-sometimes-matters-ly y'rs, Holger From mwh at python.net Wed Jun 12 13:04:02 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 12 Jun 2002 17:04:02 GMT Subject: JIT Complier for python? References: <8d3f4438.0206111905.7934664b@posting.google.com> <20020612120936.W6609@prim.han.de> Message-ID: Skip Montanaro writes: > holger> d2002xx wrote: > >> Is there any JIT Compiler for Python? > > holger> you might want to take a look at > > holger> http://homepages.ulb.ac.be/~arigo/psyco/ > > I think the Psyco project on Sourceforge might be more up-to-date: > > http://sourceforge.net/projects/psyco Same thing (as in both of those pages link to each other). Cheers, M. -- People think I'm a nice guy, and the fact is that I'm a scheming, conniving bastard who doesn't care for any hurt feelings or lost hours of work if it just results in what I consider to be a better system. -- Linus Torvalds From cliechti at gmx.net Fri Jun 14 16:10:52 2002 From: cliechti at gmx.net (Chris Liechti) Date: 14 Jun 2002 22:10:52 +0200 Subject: PythonWin - an operational question References: <3D09F28B.19AB5929@sympatico.ca> Message-ID: "Colin J. Williams" wrote in news:3D09F28B.19AB5929 at sympatico.ca: > I am using PythonWin with WinXP. >

I would like to be able to tile the Editor and Interactive windows, > but use the editor area for all programs viewed.  Is there some > simple way to arrange this as the default set up? >

Tiling doesn't seem to have a registry setting and doesn't do quite > what I would like. >

There are registry settings which permit one to place the > Interactive and Editor windows on the screen.  Is this the way to > go?

Colin W goto options->general options and check "dockable window" in the "interactive window" section. i think you must restart the editor to make it work. however this might be close to that what you want. chris PS: please try to post text only, no HTML. many people will apreciate it. -- Chris From pyth at devel.trillke.net Sun Jun 16 14:04:39 2002 From: pyth at devel.trillke.net (holger krekel) Date: Sun, 16 Jun 2002 20:04:39 +0200 Subject: Snort alert tail... In-Reply-To: <1024248055.1899.3.camel@localhost.localdomain>; from logiplexsoftware@earthlink.net on Sun, Jun 16, 2002 at 10:20:54AM -0700 References: <1024248055.1899.3.camel@localhost.localdomain> Message-ID: <20020616200439.J15079@prim.han.de> Cliff Wells wrote: > On Sun, 2002-06-16 at 05:51, Jan-Eric wrote: > > HEllo ! > > I'm trying to write a dynamic firewall script in python that scans the Snort > > alert file like 'tail -f' and takes action based on the infomation it gets > > from that file. But I can't get the 'tail' function to work.It reads the > > file, but any new information that Snort is writing to the file doesn't > > show up to the script. > > > > ex. > > file = open('/var/log/snort', 'r') > > while 1: > > file = file.read() > > print file > > .... > > > import os, stat > import time > > def snort(pathname): > size = os.stat(pathname)[stat.ST_SIZE] > > while 1: > lastsize = size > size = os.stat(pathname)[stat.ST_SIZE] > if size > lastsize: # there's new data > f = open(pathname, 'r') > f.seek(lastsize) > print f.readlines() > f.close() > else: > time.sleep(2) i'd recommend checking for 'size <3D129BB7.C7EA15D2@engcorp.com> Message-ID: > 0 1 2 3 4 5 <-- subscript index > +---+---+---+---+---+---+ > "| P | y | t | h | o | n |" > +---+---+---+---+---+---+ > 0 1 2 3 4 5 6 <-- slice index > > Your slice went from 2 to 5, so it got only the "tho" part of the string. > Here's what you got: > > +---+---+---+ > | t | h | o | > +---+---+---+ > 2 3 4 5 > > Other languages confuse the indices used when slicing things (as in > the common substring() method) and when subscripting things (when you > take just a single item, such as pystr[4] which is "o" in the above). > > Python avoids up this confusion by realizing they are not the same > thing. (Of course, this can confuse newcomers who don't realize > what happened, but at least the pain happens for you only once. :-) > So if I understand, pystr[3] refers to the subscript index, but pystr[3:] refers to the slice index. pystr[2:5] means slice at slice index 2 and 5, not start at subscript index 2 and slice at slice index 5. I just want to understand this once and for all. -- Thanks, Mark From morton at dennisinter.com Thu Jun 13 00:33:16 2002 From: morton at dennisinter.com (damien morton) Date: 12 Jun 2002 21:33:16 -0700 Subject: Something faster then sgmllib for sucking out URLs References: Message-ID: <4abd9ce7.0206122033.67f31e42@posting.google.com> Alex Polite wrote in message news:... > I'm working on a webspider to fit my sick needs. The profiler > tells me that about 95% of the time is spent in sgmllib. I use sgmllib > solely for extracting URLs. I'm looking for a faster way of doing > this. Regular expressions, string searches? What's the way to go? I'm > not a python purist. Calling some fast C program with the html as > argument and getting back a list of URLs would be fine by me. Ive got a ittle webspider that can max out my cable connection. You can download it from www.bitfurnace.com/python/crawler.py Uses regexes to grab anything that looks like a url. From gerhard at bigfoot.de Tue Jun 4 11:55:20 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 4 Jun 2002 15:55:20 GMT Subject: Need advice on multithreading problem References: Message-ID: In article , Aahz wrote: > Gerhard H?ring wrote: >> >>The problem is this: I have a C library with a function of the following >>interface: >> >> def sqlite_exec(conn, sql, callback, arg1): >> >>The only important parameter here is 'callback', it is a callback >>function that you need to give to sqlite_exec. The callback function >>will be called with the items sqlite_exec returns. If the callback >>functions returns a value other than zero, sqlite_exec will stop its >>processing. >> >>On the Python side, I wanted to force this C library call into a >>generator. Which I did using a thread that's spawned for a new >>sqlite_exec call and Queue.Queue. > > Is SQLite thread-safe? If compiled with the right options, it is. > Do you provide a thread-local conn? No, but I can guarantee that the connection will only be accessed by one thread at a time. I believe the current code already does guarantee that. > Does sqlite_exec() return a brand-new cursor? As you can see in the code, it doesn't return anything. All it does is call the callback function. The implementation of my callback function writes to a queue, and the fetchone/fetchmany/fetchall methods of Cursor read from the queue. > If the answer to any question is "no", your code is probably broken (haven't > actually read it). Thanks for commenting, but I did knew these basics of multithreading already. Gerhard From sholden at holdenweb.com Tue Jun 25 11:02:15 2002 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 25 Jun 2002 11:02:15 -0400 Subject: Python daemon References: Message-ID: "Cameron Laird" wrote ... > In article , > Roman Suzi wrote: > . > . > . > >> 3. restarting of the program if it fails, or the watchdog doesn't trigg= > >er > > > >Run the program from the /etc/inittab - if it terminates,=20 > >init will restart it for you. > . > . > . > This is one of the great FMMs under Unix--the under-utilization > of init(1). From everything I know, Roman's exactly right, that > /etc/inittab is the right way to set up a process that you truly > want to keep running. However, many, MANY Unix hosts have all > kinds of ugly home-brewed hacks to duplicate this functionality. > I don't have an explanation, beyond the rather tautologous ob- > servation that init(1) simply isn't as widely understood as it > deserves to be. You're probably right. Don't forget you need to specify "respawn" to have the process restarted when it terminates. Of course, this doesn't address the issue of if the controlled process stops making progress but doesn't die. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From alf at logilab.fr Tue Jun 11 05:00:05 2002 From: alf at logilab.fr (Alexandre Fayolle) Date: Tue, 11 Jun 2002 09:00:05 +0000 (UTC) Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 10) References: Message-ID: Hello, Sorry to interrupt, but I have to correct a misleading statement in the latest Dr. Dobb's Python URL. Kragen Sitaker a ?crit : > Programming Libraries: > > Logilab's 'constraint', a constraint satisfaction problem > programming environment for Python, which lets you program in > Prolog style in Python, has released version 0.2. ^^^^^^^^^^^^ This is not true. For programming in Prolog style in Python, you can use Christophe Delord's Pylog (http://christophe.delord.free.fr/en/pylog/). This will give you facts, and rules, as you would have using SWI-Prolog or GnuProlog. The constraint module won't let you do variable unification as you would do it in prolog. It takes a set of variables with their domains and a set of constraints on the values of these variables to find all possible simultaneous assignments to these variable that satisfies the constraints. Cheers, Alexandre Fayolle -- LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org Narval, the first software agent available as free software (GPL). From quinn at upchuck.ugcs.caltech.edu Thu Jun 27 01:47:40 2002 From: quinn at upchuck.ugcs.caltech.edu (Quinn Dunkan) Date: 27 Jun 2002 05:47:40 GMT Subject: Suggestions for good programming practices? References: Message-ID: On Mon, 24 Jun 2002 18:55:22 -0700, David LeBlanc wrote: >They may be returned in a tuple, but they're PUT in discrete variables and >not kept in a tuple that I have to programmatically unpack. > >Language lawyer should be shot, _then_ heard. So you'd prefer whole threads like this: > > AAAAAAAAAAAAAAAAAAAAAaaaaaaaaaaaahhhhhhhhhhhhhhhhhhhhhhhh > > > > . > > > > . > > > > . > > > > *gurgle* > > *hurk* ... *thud* Yaaaaaaahhhhhh!!!!! *wheeze* SHRIEK!! From sholden at holdenweb.com Tue Jun 18 07:50:53 2002 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 18 Jun 2002 07:50:53 -0400 Subject: Writing a simple linux daemon type thing... References: Message-ID: "Michael Gilfix" wrote ... > Wouldn't it be nice if some daemonizing code and basic log support > was built into SocketServer? SocketServer aims at simplifying > the infrastructure for people who don't need a full-blown server > app. Might also be a nice addition for smaller projects who don't want > to deal with this sort of thing... Might make an interesting patch > IMHO. > That wouldn't be quite such a good idea as it sounds. The SocketServer code is only really intended as a demonstration of basic techniques, and certainly hasn't been coded as industrial-strength. There would probably be aa lot more work in the patch than you anticipate. Any daemon process needs to ensure it 1. Detaches from its controlling terminal, using safe alternatives to stdout and stderr, and 2. Creates a new process group so it is invulnerable to signals received by the triggering process. SocketServer and their derivatives don't do either of these things IIRC regards -- ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From op73418 at mail.telepac.pt Wed Jun 26 12:04:32 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Wed, 26 Jun 2002 17:04:32 +0100 Subject: question on properties Message-ID: Hi, Suppose in a class Klass I have a property prop. Suppose also that I have class AnotherKlass(Klass): ... I can override property prop in AnotherKlass by just redefining it, but what if I want to acess the base class prop how do I do it? TIA and all the best, Gon?alo Rodrigues From kragen at pobox.com Mon Jun 3 12:38:05 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 03 Jun 2002 12:38:05 -0400 Subject: HTML links in a GUI tkinter References: <83elfprs1x.fsf@panacea.canonical.org> Message-ID: <83y9dwqpw2.fsf@panacea.canonical.org> "Steve Holden" writes: > "Kragen Sitaker" wrote in message > news:83elfprs1x.fsf at panacea.canonical.org... > > Sorry about the empty reply --- in Python 2.x, the webbrowser module > > has a webbrowser.open() method that does what you want. > > So, all Aurel needs to know now is how to run wxPython widgets inside > tkinter programs... Why would Aurel want to do that? webbrowser.open() doesn't use wxPython. At least, I don't have wxPython installed, and it works for me. From ark at research.att.com Fri Jun 7 14:32:07 2002 From: ark at research.att.com (Andrew Koenig) Date: Fri, 7 Jun 2002 14:32:07 -0400 (EDT) Subject: Python 2.2.1 vs. gcc 3.1? In-Reply-To: <15616.64407.863059.729351@12-248-41-177.client.attbi.com> (message from Skip Montanaro on Fri, 7 Jun 2002 13:29:43 -0500) References: <15616.57963.519636.730290@12-248-41-177.client.attbi.com> <200206071747.g57HlbH01057@europa.research.att.com> <15616.62634.635544.905055@12-248-41-177.client.attbi.com> <200206071804.g57I4fp01212@europa.research.att.com> <15616.63342.559215.644086@12-248-41-177.client.attbi.com> <200206071815.g57IFjg01303@europa.research.att.com> <15616.64407.863059.729351@12-248-41-177.client.attbi.com> Message-ID: <200206071832.g57IW7n01369@europa.research.att.com> Skip> Dunno. Try "find . -name 'struct*'. It should be in your build/lib* Skip> directory (where "*" matches your configuration name). Did that; didn't find anything obvious. Before I do anything else, I'm going to try rebuilding from scratch using GCC 2.95.something to be sure I haven't changed anything else that might have broken it. From irmen at NOSPAMREMOVETHISxs4all.nl Thu Jun 13 18:00:42 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Fri, 14 Jun 2002 00:00:42 +0200 Subject: dictionary: keys() and values() References: Message-ID: <3D09160A.2030402@NOSPAMREMOVETHISxs4all.nl> Andrew Koenig wrote: > From the library reference, 2.2.7, footnote 3: > > If keys() and values() are called with no intervening modifications to the > dictionary, the two lists will directly correspond. This allows the creation > of (value, key) pairs using zip(): "pairs = zip(a.values(), a.keys())". Why would you want to do that if you have .items()? Irmen From phr-n2002b at NOSPAMnightsong.com Sat Jun 29 16:15:02 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 29 Jun 2002 13:15:02 -0700 Subject: private References: <3D1DE132.4A890D9D@engcorp.com> Message-ID: <7x3cv5j0zd.fsf@ruckus.brouhaha.com> "James Kew" writes: > Yes, of course one can circumvent private in C++. But for me the main value > of the public and private specifiers is that they _document_ to the client > of the class what it should access and what it should not. C++ may have been a bad example since the process's whole address space is exposed to all parts of the program. In Java though, private methods and variables are enforced. Actually someone should mention the rexec/Bastion module in Python, which gives a kludgy way to enforce privacy within a process. It makes a sandbox-like mechanism where an object can enforce access controls against a caller provided that the caller runs wrapped in a special restricted environment. From bokr at oz.net Sat Jun 29 12:38:24 2002 From: bokr at oz.net (Bengt Richter) Date: 29 Jun 2002 16:38:24 GMT Subject: question od default args References: <6NhT8.45584$n4.10824585@newsc.telia.net> Message-ID: On Sat, 29 Jun 2002 12:32:02 GMT, "Fredrik Lundh" wrote: >Mark Jackson wrote: > >> More quickly: >> >> def myfunc(arg=[]): >> if arg is myfunc.func_defaults[0]: >> print "no argument" >> else: >> ... > >while the func_ attributes are documented, a quick peek in >the standard library should tell you that it's best to treat them >as an implementation detail. > >the less such stuff you depend on in your production code, >the more portable it gets... > Perhaps accessing "implementation details" should depend on importing a module that enables access one way or another? E.g., import __version_2_2_implementation_details__ could serve to signal that Guido et al didn't really mean to define a portable abstraction for production use? Regards, Bengt Richter From shalehperry at attbi.com Wed Jun 26 13:48:56 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 26 Jun 2002 10:48:56 -0700 (PDT) Subject: question od default args In-Reply-To: Message-ID: On 26-Jun-2002 Gon?alo Rodrigues wrote: > Hi, > > When I want default args I usually do > > def (arg = None): > ... > > But what if I want to make None a reasonable argument too? That is, I > want to know if the user has in fact passed an argument, and if not to > do something special, with None (or whatever object) being a reasonable > arg to be passed. > >>> def func(arg1, *args): ... if len(args): ... print "user gaves us %d args" % (len(args) + 1,) ... else: ... print "only have arg1" ... >>> func('sean') only have arg1 >>> func('sean', 'perry') user gaves us 2 args this means you need to throw an exception if you only want 3 args and the user gives you 4 (or more). From nospam at bigfoot.com Tue Jun 18 07:23:14 2002 From: nospam at bigfoot.com (Gillou) Date: Tue, 18 Jun 2002 13:23:14 +0200 Subject: Is there a Text to HTML conversion module? References: <3CFBDF95.92099C9E@alcyone.com> Message-ID: Did not test but... Zope has got a StructuredText package that can be used "standalone" (outside of a Zope site). www.zope.org Otherwise, here's a simple snip that will help if you want to do it by yourself : It changes the markup from the original plain text and replaces against entities and changes http, ftp and mail markups against hyperlinks. Can be improved of course. import string, re # Subtitute HTML markup chars by entities text = string.replace(text, '&', '&') text = string.replace(text, '<', '<') text = string.replace(text, '>', '>') text = string.replace(text, '\n', '

\n

') # Make hyperlinks from HTTP or FTP URLs pat = re.compile(r'((ftp|http)://[\w-]+(?:\.[\w-]+)*(?:/[\w\-\.?=]*)*)') text = pat.sub('\\1', text) # Make hyperlinks from email addresses pat = re.compile(r'([\w-]+(?:\.[\w-]+)*@[\w-]+(?:\.[\w-]+)*)') text = pat.sub('\\1', text) HTH --Gilles "James T. Dennis" a ?crit dans le message news: aempf6$1nq2$1 at news.idiom.com... > Erik Max Francis wrote: > > Andrew Dalke wrote: > > >> > > >>>(sorry... couldn't resist) > >> Neither could I. :) > > Ah, but that's XML, not HTML. :-) > > Of course it might be some future extension to XHTML > From syver-en+usenet at online.no Wed Jun 5 07:41:13 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: 5 Jun 2002 04:41:13 -0700 Subject: manipulating child processes under Windows References: Message-ID: Douglas Alan wrote in message news:... > Syver Enstad writes: > > > Hmm, my first reaction is to think in terms of window handles in > > some way, there's a FindWindow function in win32 (and win32all) that > > let's you search for a window by name, I'll have to check the msdn > > library to find out how to get the owning process handle from a > > window handle. > > What if there were more than one process with the same name. How > would I tell which one is the right one? The FindWindow function doesn't search for the ProcessName it uses the window title, which is often unique. Hope that helps. From irmen at NOSPAMREMOVETHISxs4all.nl Thu Jun 27 18:05:16 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Fri, 28 Jun 2002 00:05:16 +0200 Subject: OT: timeout with SSL sockets? (was Re: How to stop a SocketServer? ) References: <7xhejv9af2.fsf_-_@ruckus.brouhaha.com> <3d1744d4$1_1@hpb10302.boi.hp.com> <3D1757DF.776A428F@engcorp.com> <3d176a0c$1_3@hpb10302.boi.hp.com> <3D17BF72.2E1CCF40@engcorp.com> Message-ID: <3D1B8C1C.2020802@NOSPAMREMOVETHISxs4all.nl> Skip Montanaro wrote: > Peter> By the way, look into "timeoutsocket.py" which is a plug-in > Peter> replacement for the standard socket.py and which might do the > Peter> trick for you. > > Note socket objects grow a settimeout() method in 2.3. If you get Python > from CVS you can have it today: [...] snip That is nice indeed. Will this also work with (M2Crypto) SSL sockets? I've had some struggles with M2Crypto SSL sockets, timeouts and select... Thanks Irmen de Jong From dan at eevolved.com Mon Jun 3 13:43:58 2002 From: dan at eevolved.com (Daniel Parisien) Date: Mon, 03 Jun 2002 13:43:58 -0400 Subject: encoding and decoding repr'd version of strings Message-ID: <1YNK8.9622$cE6.591635@wagner.videotron.net> Hi is there an codec that bundles with python so you can transform strings into the repr'd (escaped) version and back? If not, how easy would it be to code? I don't want to use eval(...) because I don't trust the source of the string and I might mistakenly eval an expression like "' '*(2**30)" which would allocate about 1 GB of data (eek!) Thanks, Dan From sarmstrong13 at mac.com Mon Jun 3 03:10:11 2002 From: sarmstrong13 at mac.com (SA) Date: Mon, 03 Jun 2002 02:10:11 -0500 Subject: Is there a Text to HTML conversion module? Message-ID: Does anyone know of a module that converts a text file to html? I started writing my own, but decided I better make sure I'm not re-inventing the wheel here. Thanks. SA From marklists at mceahern.com Fri Jun 28 16:20:47 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 28 Jun 2002 15:20:47 -0500 Subject: Introspection: determining parent classes? In-Reply-To: <3D1CC1CA.70004@onsitetech.com> Message-ID: isinstance will do the trick. class A:pass class B(A):pass class C(B):pass c = C() print isinstance(c, A) 1 If you need to traverse the bases: c.__class__.__bases__ // m - From sheershion at mailexpire.com Fri Jun 21 09:30:50 2002 From: sheershion at mailexpire.com (Robert Amesz) Date: Fri, 21 Jun 2002 13:30:50 -0000 Subject: GOTO w/ Python? References: <3d10ed95@xpl-sdf1-sec1.> Message-ID: Angela Williams wrote: > I'm looking for the equivalent of the GOTO command for Python > 2.2.1 running on Windows 98. I have programmed very little and am > new to Python. I found the following information on the FAQ page > but it doesn't make any sense to me. Pleas don't go looking for GOTOs. If you find yourself needing those, in 99.9% of the cases there's something not quite right with your code. Usually, by splitting a large function/method into several smaller ones the problem will go away by itself. The resulting code will also be clearer and more maintainable. (If after that you're still having trouble, post a page or so of your code here. This is a helpful group, and I'm sure somebody will give you some points on how to improve your code.) The most goto-like contructs in Python are 'return' (which exits from a function/method before the end is reached) and 'break' (which exits a loop, continuing with statement followin that loop). In a pinch you can indeed raise some kind of exception, but you really should use those for things like errors. Robert Amesz From python at rcn.com Wed Jun 26 02:54:37 2002 From: python at rcn.com (Raymond Hettinger) Date: Wed, 26 Jun 2002 02:54:37 -0400 Subject: buffer() survey Message-ID: I'm interested in learning knowing whether the builtin function buffer() is much used and how it is being used. If anyone has this in their own real-world code, I would be interesting in hearing from you. Also, it would be helpful to know whether use of the array or mmap modules was considered. Raymond Hettinger From aahz at pythoncraft.com Wed Jun 12 13:57:16 2002 From: aahz at pythoncraft.com (Aahz) Date: 12 Jun 2002 13:57:16 -0400 Subject: postscript processing in python References: Message-ID: In article , David Bear wrote: > >I know these are tall orders but I've written a filter in python that takes >a postscript stream generated by an IBM mainframe and uses ghostscript to >convert it to pdf. The problem is ghostscript seems rather picky about >some strange things that the mainframe puts in the postscript stream -- so >I was hoping to do some cleanup on it and conversion without having to >depend on ghostscript. If you're already handling postscript, try using ReportLab to handle creating the PDF: http://www.reportlab.com/ -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I had lots of reasonable theories about children myself, until I had some." --Michael Rios From gcordova at hebmex.com Thu Jun 13 17:18:15 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Thu, 13 Jun 2002 16:18:15 -0500 Subject: Type subclassing: bug or feature Message-ID: > > > > Consider the following code: > > > > class MyStr(str): > > def contains(self, value): > > return self.find(value) >= 0 > > > > s = MyStr("hello, world!") > > s = s.capitalize() > > if s.contains('Hello'): > > print "Found it!" > > > > It fails with an AttributeError when it calls s.contains(), because > > s.capitalize() returned a str instead of a MyStr. Anyone > want to take a > > whack at defending this as the correct behavior? > > -- > > Aahz (aahz at pythoncraft.com) <*> > > http://www.pythoncraft.com/ > > Looks like a bug to me. How can self be something else then > what it is? > Should MySocket return a socket, thus stripping off any additional > functionality added by my derived class? > > David LeBlanc > Seattle, WA USA > Hmmm... maybe all methods of builtin types should do: return self.__class__(return_value) when returning a new object (like str methods). -gustavo From ak at silmarill.org Sat Jun 1 23:16:41 2002 From: ak at silmarill.org (Andrei Kulakov) Date: Sun, 02 Jun 2002 03:16:41 GMT Subject: wxPython performance References: <332c7c11.0206011639.a396f84@posting.google.com> Message-ID: In article <332c7c11.0206011639.a396f84 at posting.google.com>, Benno wrote: > Andrei Kulakov wrote in message > news:... >> Hello, >> >> "hello world" type program from wxPython tutorial takes 6 >> seconds to start on my cel 366 128mb system (running Debian). Is >> this typical? Why is it so slow? I'm looking for a graphic >> toolkit that'd be fairly quick. I don't want to use Tk because of >> the looks. > > I was using wxPython for a while. The main advantage being that it was > going to be cross platform, however I found its speed too slow. (Not startup > speed, which is fairly irrelevant to me, but just general responsiveness.) > I'm not sure if this was just wxWindows itself or the python bindings. > > I have started using pygtk (easily > apt-getable). The only problem I've had with this is the lack of docs. > http://www.moeraki.com/pygtktutorial/gtk-tut.html, seems to be the best > available, followed by reading the source. > > Cheers, > > Benno Thanks, I think that's exactly what I'm gonna have to do. -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From eric.brunel at pragmadev.com Mon Jun 3 14:08:21 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Mon, 3 Jun 2002 18:08:21 +0000 Subject: Changing TK References: Message-ID: Salim Zayat wrote: > Hey all. I have a quick question about something. If I were to install > a newer version of Tcl/Tk on my computer, would Tkinter.py recoginze it > automatically, or do I need to tweak the Tkinter.py code itself? On what kind of platform are you? Things will be a lot different if you're on Unix or Windows... In fact, if your tcl/tk installation changes, there's two things that must be taken into account: the dynamic libraries used at run-time, and the tcl/tk API header files used when compiling the Python interpreter. However, both are not referenced at all in Tkinter.py, so "tweaking" it would not be of any help... When you get a new tcl/tk installation, you *must* recompile the interpreter, or you won't ever see any change. If you're on Windows, you probably didn't compile your interpreter yourself. If you want to do it, you'll have to download the interpreter's sources. I can't help you any further here, since I didn't ever compile an interpreter on Windows. You'll have to reference your new tcl/tk installation somewhere, but I don't know how it can be done. On Unix, you should already have the interpreter's sources. So go to the subdirectory "Modules" of your Python installation directory, edit the file named "Setup", change the part for the "_tkinter" module to reference the new location for your tcl/tk installation, recompile the interpreter and voila! But DON'T EVER replace former tcl/tk libraries by newer ones without recompiling, even if they have the same name! It *may* work, but if it doesn't, the tk support in your Python will be completely and definitely broken... HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From sanjay2kind at yahoo.com Wed Jun 26 07:45:28 2002 From: sanjay2kind at yahoo.com (sanjay) Date: 26 Jun 2002 04:45:28 -0700 Subject: how to remove HTML attributes from web pages ( HTML parseing) Message-ID: <63170f57.0206260345.2b61b7ec@posting.google.com> Hi, New to python and doing one application. i would like to web page content after removing specific html tag, attribute etc. Like taking out color,bgcolor and ,

tag from the web pages. Which one will be helpful : regular expression or HTMLParser helpfully. Thx, From jepler at unpythonic.net Tue Jun 25 19:45:54 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Tue, 25 Jun 2002 18:45:54 -0500 Subject: bug in os.getgroups? In-Reply-To: References: <1025033152.17806.TMDA@nightshade.la.mastaler.com> <20020625202442.GG4435@unpythonic.net> Message-ID: <20020625184554.A7559@unpythonic.net> On Tue, Jun 25, 2002 at 03:53:06PM -0600, Jason R. Mastaler wrote: > Jeff Epler writes: > > > This is liely to be because /tmp is "sticky": > > /tmp was a bad choice for my example. The problem is the same in a > non-sticky directory such as /home. This is still a matter of Unix permissions. The action of removing a file from a directory depends on the permission to modify the directory, not permission to modify the file. Jeff From erict at millfilm.co.uk Thu Jun 20 14:52:09 2002 From: erict at millfilm.co.uk (Eric Texier) Date: Thu, 20 Jun 2002 19:52:09 +0100 Subject: Proper number alignment References: Message-ID: <3D122459.2E338453@millfilm.co.uk> You have a function newstring1 = string.rjust(astring 1,numberofblankSpace) newstring2 = string.rjust(astring 1,numberofblankSpace) finalLine = newstring1 + newstring2 mdk wrote: > I am using \t\t (tabs) to align these numbers (disregard the math): > > Total RAM 2,141,056 > Available RAM 12,934,032 > Used RAM 1,024 > > But they are left justified and I need them right justified. > > Any ideas? > > Thanks. From karczma at info.unicaen.fr Thu Jun 20 09:37:31 2002 From: karczma at info.unicaen.fr (Jerzy Karczmarczuk) Date: Thu, 20 Jun 2002 15:37:31 +0200 Subject: GOTO w/ Python? References: <3d10ed95@xpl-sdf1-sec1.> <3D11A21D.9010809@mxm.dk> Message-ID: <3D11DA9B.163A7BD0@info.unicaen.fr> John Roth after Michael Hudson after Max M.: > > Goto's are simple ;-) > > def goto(lable): > > lable() > > def start(): > > > > print 'starting' > > goto(lable2) > > > > def lable1(): > > > > print 'at lable 1' > > goto(stop) etc. > Those aren't goto's in the classical sense. For a real goto, > you need to think assembler: if it's a statement anywhere, > you can branch to it, and who cares about the execution > history! Having the compiler manage your flow control is > for sissys! Gentlemen, what are you talking about? (I confess I didn't follow this thread, so forgive me if I try to open a non-existent door) Before, John Roth suggested using structured exceptions as GOTOs, and Michael Hudson wrote something like that: > There are also technical difficulties implementing it (the > blockstack), or I'd have probably done goto functionality in > bytecodehacks :) Well... 1. The "solution" of Max M. is erroneous for two reasons. A. A procedure call stacks the return address, so a few hundreds such gotos, and the system blows up. Unfortunately Python does not optimize tail calls, I WONDER WHY; for a member of the Functional Programming Church this is a mortal sin, and I am serious. B. The code chunks linked in such a way provide different variable scopes, so there is little sense in calling it a "branching". 2. "Structured exception" is something quite heavy, it may be heavier than the setjump/longjump contraption, and may also be useless to those who simply would love to do some Python programming ? la Fortran. 3. No, in order to speak about genuine gotos *you don't need to think assembler*. What you need is to understand correctly the notion of continuation (something quite standard - again - in the Functional Programming world). This is a high-level model of "flat" branching, but may be used to more exquisite constructions, such as backtracking. I don't believe that there are any technical difficulties in the implementation of gotos at the low level. At the high level this is then a question of the language structure, as seen by Van Rossum, the lack of gotos was a conscious decision. Jerzy Karczmarczuk Caen, France From tismer at tismer.com Sat Jun 29 13:46:16 2002 From: tismer at tismer.com (Christian Tismer) Date: Sat, 29 Jun 2002 19:46:16 +0200 Subject: EuroStackless slides online Message-ID: <3D1DF268.8040706@tismer.com> Hi all, as promised, I've uploaded the slides from my Stackless talk to the stackless site. It can be downloaded here: http://www.stackless.com/#EuroSlides The page has also been updated to reflect the recent evalution. Some code concerning thread pickling will be added, soon. EuroPython was just -- great! I'm sure this will be repeated next year or even earlier. 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 pager +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 edream at tds.net Sun Jun 23 06:12:23 2002 From: edream at tds.net (Edward K. Ream) Date: Sun, 23 Jun 2002 10:12:23 GMT Subject: ConfigParser & converting strings to lists References: <3D152A28.2177B054@tds.net> Message-ID: <3D159F06.2154D3F3@tds.net> To complete this topic, let me restate the problem and JohnJacob's elegant solution. Suppose files is a list of strings, and we have written a configuration section like this: config = ConfigParser.ConfigParser() config.set("recent files", "recentFiles, files) Then the elegant way of retrieving files _as a list_ is: files = eval(config.get("recent files", "recentFiles")) Thanks to all who replied. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From K.Rdt at TU-Berlin.DE Sun Jun 16 14:07:30 2002 From: K.Rdt at TU-Berlin.DE (Klaus Reinhardt) Date: Sun, 16 Jun 2002 18:07:30 GMT Subject: HT telnet interact with auto login? Message-ID: <3d0cd198.17917980@news.zrz.tu-berlin.de> Hi! I want to combine: import getpass import sys import telnetlib HOST = "...de" tn = telnetlib.Telnet(HOST) user = '...' password = '...' 1.) tn.interact() # this is working but with manually .. 2.) tn.read_until("login: ") # this seams to work # but without connection tn.write(user + "\n") if password: tn.read_until("Password: ") tn.write(password + "\n") TiA for each tip Klaus From NKluge at optonline.net Wed Jun 5 01:45:01 2002 From: NKluge at optonline.net (Nicola Kluge) Date: Wed, 05 Jun 2002 05:45:01 GMT Subject: self References: Message-ID: This is an interesting idea. However, your approach doesn't handle the dot notation. For example, If object.x was = to 3 and g was = to 4 I need that e.f='object.x*g' gives 12. Just having e=Evaluator({'a':'3', 'b':'a*17', 'c': 'b*a','object.x':'3','g':'4'}) doesn't work. While parsing, 'object.x' is not taken as one symbol in your approach. I need to have object capabilities in the equations. Vojin Jovanovic "holger krekel" wrote in message news:mailman.1023224648.434.python-list at python.org... > Vojin Jovanovic wrote: > > Now let me give you the problem with self which is making my life > > complicated. Consider this class. > > > > class Foo: > > def __init__(self): > > self.__dict__['Equations']={ > > 'a':str(5), > > 'b':'self.a+5', > > 'c':'self.b*self.a'} > > > > (...) > > To get rid of 'self' you might like to try this: > > class Evaluator: > def __init__(self, eqs={}): > self.__dict__['equations']=eqs > def __getattr__(self, name): > begin={} > while 1: > try: > return eval(self.equations[name], begin) > except NameError, n: > var=str(n).split("'")[1] > begin[var]=getattr(self, var) > def __setattr__(self, name, value): > self.equations[name]=value > > >>> e=Evaluator({'a':'3', 'b':'a*17', 'c': 'b*a'}) > >>> > >>> e.c > 153 > >>> e.f='a*c' > >>> e.f > 459 > > I don't really think that 'execing' is a good idea here > but i don't know your complete usecase. > > With a little more care it should be possible to > catch cyclic equations. > > have fun, > > holger > > From michael at damaru.com Sun Jun 9 13:10:30 2002 From: michael at damaru.com (Michael Davis) Date: Sun, 09 Jun 2002 13:10:30 -0400 Subject: How to capture stdout into a string? Message-ID: <2YLM8.905$Yw3.119357@news20.bellglobal.com> Hi, I'm using libftp. The FTP.dir() function gets the remote directory listing and prints it to standard out. How can I capture that in a string? If I were using an external process, I know I could open a pipe to it. But it's not an external process. I'm sure there's a tricky way of doing it by getting the file descriptor for stdout and reading from it directly, but I was hoping to avoid going that low-level. I will if I must though. Thanks in advance, -- Michael Davis Damaru Custom Programming - Web Development - Database Design http://www.damaru.com 416-540-1284 From opus at value.net Sun Jun 30 06:09:09 2002 From: opus at value.net (Opus) Date: Sun, 30 Jun 2002 03:09:09 -0700 Subject: Python needs better error reporting In-Reply-To: <20020630095830.C20310@prim.han.de> References: <3D1E5376.32716.DF5C94@localhost>; from opus@value.net on Sun, Jun 30, 2002 at 12:40:22AM -0700 Message-ID: <3D1E7655.29975.167945D@localhost> Interesting idea. Would these statistics be built from normal usage of the language or from that person's usage? Actually, just to do the statistics on the language would be very interesting. On 30 Jun 2002 at 9:58, holger krekel wrote: > Opus wrote: > > > At the most, I might suggest that there be an option to run just the parser, > > with more verbose output. Maybe even a different parser would be in order. > > Idea for anyone???? > > i'd suggest a heuristic approach. Compute statistics for which token > usually comes after a group of others. Just look at AST-structures not > values. This way you can suggest a hint to the user what he might have > done wrong. I think it's not feasible and too verbose to tell the user > what is actually correct. A simple "Maybe you forgot ..." would cover > 90% of the cases, i guess. > > holger --Opus-- The more absurd the belief, the more deeply it must be held, the more aggressively it must be promoted and angrily defended if the is to see himself as right and sane. - Unknown -------------------------------------------------------- Get added to my Humor list: mailto:opus at value.net?subject=ADD_HUMOR Get added to my Neat list: mailto:opus at value.net?subject=ADD_NEAT Get my PGP public key: mailto:opus at value.net?subject=PSEND&body=send%20PublicKEY.asc Visit My Home Page: http://value.net/~opus/ From emile at fenx.com Fri Jun 28 07:53:39 2002 From: emile at fenx.com (Emile van Sebille) Date: Fri, 28 Jun 2002 11:53:39 GMT Subject: Be the first on your block to register your computer. References: <3D1B6E69.1090204@earthlink.net> Message-ID: <77YS8.22903$Uu2.4194@sccrnsc03> Neil Hodgson > I suspect that a Python interpreter could be built out of a set of > Outlook message processing rules although I wouldn't be the one to volunteer > to do it whereas I will volunteer to do the Excel port if it should ever be > needed. > I volunteer to do the Outlook messaging implementation, if it ever should be needed. ;-)) -- Emile van Sebille emile at fenx.com --------- From marklists at mceahern.com Tue Jun 18 06:45:16 2002 From: marklists at mceahern.com (Mark McEahern) Date: Tue, 18 Jun 2002 05:45:16 -0500 Subject: why len(list) instead of list.len() ? In-Reply-To: Message-ID: [Markus Jais] > I way wondering why one has to write > > list = [2, 3, 5] > print len(list) > > instead of list.len() Imagine for one moment that you are not the first person to wonder this. Why not search the newsgroup's archives for the umpteen times this topic has come up, peruse them, and if you find a new angle on the discussion, please, share it with us. Cheers, // mark - From gscott at peregrine.com Thu Jun 6 11:30:06 2002 From: gscott at peregrine.com (Gordon Scott) Date: Thu, 6 Jun 2002 08:30:06 -0700 Subject: Program to an interface, not an implementation Message-ID: I found it a little bit helpful to think of 'program to an interface, not an implementation' as 'treat all objects the same' The Composite pattern of DP is a good example. The example they give is of a grouping/collection/tree of various GUI widgets. This might be a common method of keeping track of and displaying various windows on a panel. When a widget needs to be updated, various things have to happen for different widgets, a Button needs a button update, an edit field needs an edit update etc... One way of doing this is to step though the tree, find out what type of widget we are dealing with and call the appropriate draw function for widget in tree: if widget.type == button.type: widget.drawButton() elif widget.type == edit.type: widget.drawEdit() etc.. Of course this is a poor way to do things, and makes adding new types of widgets to the tree extremely difficult. By programming to an interface, you treat all objects the same way by calling the same function regardless of the object. This is shown in the Composite example by having all widgets implement the Graphic interface which defines a single Draw() function that specific classes override. For C++ or Java this is done by having the widgets either subclass the parent Graphic class, or (java only) implementing a Graphic interface. Then the tree does not know whether or not it has Buttons or Edit fields all, it is dealing with Graphic objects, so all the tree needs to know is the Graphic.Draw() function. This way you can add or modify specific widgets to the tree pretty easily. In python the updated code for drawing all the objects in the Composite might be for graphic in tree: graphic.Draw() MUCH simpler than the above. Now comes the beautiful part, Python's dynamic typing. When the GoF refers to an 'interface' it is an abstract term that means 'a set of functions an object implements', which isn't necessarily a concrete thing like a Java Interface is. So for two Python objects to share the same interface, (assume the Graphic interface) above, they simply have to have the functions that a Graphic object has, they do not need to be subclassed from a common parent or related in any way!!!! When you say object.Draw() python simply looks to see if that object has a Draw() function, if it does great. This way you can keep radically different objects in your Composite tree and treat them the same way regardless of what they are, no casting or subclassing required! Because of it's dynamic typing Polymorphism is a snap in Python. You can see this quite frequently in many Python programs that operate with 'file-like' objects, ie objects that have read() and write() operations, and these can be sockets, files, or StringIO's which are not part of any common class hierarchy yet the programs work normally with any of those. Hope that helps... -----Original Message----- From: Egbert Bouwman [mailto:egbert at bork.demon.nl] Sent: Thursday, June 06, 2002 3:12 AM To: python-list at python.org Subject: Program to an interface, not an implementation Hello, Can someone shed some light on the GoF adagium: 'program to an interface, not an implementation' and especially what it means for programming in Python ? GoF is not easy. egbert -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== -- http://mail.python.org/mailman/listinfo/python-list From emile at fenx.com Sat Jun 15 10:28:14 2002 From: emile at fenx.com (Emile van Sebille) Date: Sat, 15 Jun 2002 14:28:14 GMT Subject: Pronouncing '__init__' References: Message-ID: <2aIO8.81731$pw3.3985@sccrnsc03> Mark McEahern > But I think saying, for example, the str method, in the context of a user > class, is clear enough to indicate __str__. If you're talking about len(), > you probably just say "len." If you're talking about __len__, you probably > say, "the len method of x" or just "the len method." Or "the magic len > method." > I agree. I often think in terms of the instances, so I also use 'it's [ imul | repr | str] method. When I need to spell it out though, my choice wasn't in the list of options: underscore underscore r-e-p-r [ underscore underscore ] -- Emile van Sebille emile at fenx.com --------- From marklists at mceahern.com Fri Jun 28 11:31:06 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 28 Jun 2002 10:31:06 -0500 Subject: aspect-oriented demo using metaclasses Message-ID: Hi, I have tried and failed several times to understand metaclasses. This morning, I trudged up the learning curve a little further than I have before and I wanted to share what I discovered. I've been intrigued by the idea of using metaclasses as a way to implement aspect-oriented programming (AOP) in Python. To me, the promise of AOP is you should ideally write your classes in complete ignorance of the aspects that you want to plug in later. Tracing is probably the simplest example of an aspect I can think of. Persistence is a more complicated aspect (to me, anyway). So I figured I'd start with tracing. I owe much to previous threads on AOP, in particular Pedro Rodriguez's non-metaclass implementation: http://groups.google.com/groups?selm=pan.2002.01.13.11.22.54.248401.9857%40c lub-internet.fr This is written in the style of a tutorial, but admittedly, it's not very polished. I would appreciate any and all comments, criticism, feedback, suggestions, amplifications, discussion, etc. ** A simple AOP framework in Python using metaclasses Let's start with a simple class: class foo: def bar(self, *args, **kwargs): pass f = foo() f.bar() As expected, this doesn't do anything. Suppose I want to be notified before and after the bar method is called. (The wording of that is purposefully vague.) And I don't want to have to modify the foo class at all in order to do this. I want to intervene in the creation of this class (not just instances of the class) and insert pre and post methods for each function. Let's start with a simple metaclass definition that doesn't do anything: class aspect(type): def __init__(cls, name, bases, dict): super(aspect, cls).__init__(name, bases, dict) __metaclass__ = aspect class foo: def bar(self, *args, **kwargs): pass f = foo() f.bar() Again, this doesn't have any noticeable effect. Let's insert some print statements to see what's happening though: class aspect(type): def __init__(cls, name, bases, dict): super(aspect, cls).__init__(name, bases, dict) for k,v in dict.items(): print "type(%s) --> %s" % (k, type(v)) __metaclass__ = aspect print "before class foo:" class foo: def bar(self, *args, **kwargs): pass print "before f = foo()" f = foo() f.bar() before class foo: type(__module__) --> type(bar) --> before f = foo() This shows us that the aspect metaclass' __init__ gets called as a result of declaring our foo class, before any instance's of foo are created. We want to iterate through the class's dict and do something for each method (I'm not worried about distinguishing staticmethod and classmethod type methods for now): class Aspect(type): def __init__(cls, name, bases, dict): super(Aspect, cls).__init__(name, bases, dict) for k,v in dict.items(): if type(v) == type(lambda x:x): print "%s is a function." % k __metaclass__ = Aspect class foo: def bar(self, *args, **kwargs): print "real bar(%s, %s)" % (args, kwargs) f = foo() f.bar("a", "b", foo="c") bar is a function. real bar(('a', 'b'), {'foo': 'c'}) Rather than importing types and using types.FunctionType, I just compare the type of the item to the type of an anonymous function (via lambda). Is that cool or what? ;-) Also, notice that I replaced pass in the body of bar() with a simple print statement that tells me how the real bar() is being called. That will be useful later. For each method (or function), I want to wrap that method so that I get notified when it's called. So I created a wrapped_method class that is somewhat (exactly?) like a field descriptor (e.g., property): class wrapped_method(object): def __init__(self, cls, method): self.class_name = cls.__name__ self.method = method self.method_name = method.func_name self.observers = [] def __call__(self, *args, **kwargs): self.before(*args, **kwargs) self.method(self, *args, **kwargs) self.after(*args, **kwargs) def before(self, *args, **kwargs): print "before %s.%s(%s, %s)" % (self.class_name, self.method_name, args, kwargs) def after(self, *args, **kwargs): print "after %s.%s(%s, %s)" % (self.class_name, self.method_name, args, kwargs) class Aspect(type): def __init__(cls, name, bases, dict): super(Aspect, cls).__init__(name, bases, dict) for k,v in dict.items(): if type(v) == type(lambda x:x): setattr(cls, k, wrapped_method(cls, v)) __metaclass__ = Aspect class foo: def bar(self, *args, **kwargs): print "real bar(%s, %s)" % (args, kwargs) f = foo() f.bar("a", "b", foo="c") before foo.bar(('a', 'b'), {'foo': 'c'}) real bar(('a', 'b'), {'foo': 'c'}) after foo.bar(('a', 'b'), {'foo': 'c'}) Now we're starting to get somewhere! The next step is to create a framework where multiple observers can plug into the before and after events for any given method call. Rather than taking more baby steps to get there, this is the complete implementation I have so far: import sys class wrapped_method(object): def __init__(self, cls, method): self.class_name = cls.__name__ self.method = method self.method_name = method.func_name self.observers = [] def __call__(self, *args, **kwargs): self.before(*args, **kwargs) self.method(self, *args, **kwargs) self.after(*args, **kwargs) def before(self, *args, **kwargs): for o in self.observers: o.before(self.class_name, self.method_name, *args, **kwargs) def after(self, *args, **kwargs): for o in self.observers: o.after(self.class_name, self.method_name, *args, **kwargs) def notify_me(self, observer): self.observers.append(observer) class VirtualClassError(Exception):pass class Observer: def __init__(self, *args, **kwargs): if self.__class__ is Observer: raise VirtualClassError(self.__class__.__name__) def before(self, class_name, method_name, *args, **kwargs): pass def after(self, class_name, method_name, *args, **kwargs): pass class Trace(Observer): def __init__(self, filename=None): self.filename = filename def write(self, prefix, class_name, method_name, *args, **kwargs): cls = class_name s = "%s: %s.%s(%s, %s)" % (prefix, cls, method_name, args, kwargs) if not self.filename: f = sys.stdout else: f = file(self.filename) f.write(s) f.write("\n") if self.filename: f.close() def before(self, class_name, method_name, *args, **kwargs): self.write("before", class_name, method_name, *args, **kwargs) def after(self, class_name, method_name, *args, **kwargs): self.write("after", class_name, method_name, *args, **kwargs) class Aspect(type): def __init__(cls, name, bases, dict): super(Aspect, cls).__init__(name, bases, dict) for k,v in dict.items(): if type(v) == type(lambda x:x): setattr(cls, k, wrapped_method(cls, v)) __metaclass__ = Aspect class foo: def bar(self, *args, **kwargs): print "real bar(%s, %s)" % (args, kwargs) def main(): foo.bar.notify_me(Trace()) f = foo() f.bar("a", "b", foo="c") if __name__ == "__main__": main() before: foo.bar(('a', 'b'), {'foo': 'c'}) real bar(('a', 'b'), {'foo': 'c'}) after: foo.bar(('a', 'b'), {'foo': 'c'}) The output is the same, but it's actually being generated by an instance of the Trace class. ************ Observations ************ Obviously, Trace is designed so that I can specify a filename when creating an instance of it and that would use that file rather than sys.stdout. Observers should probably be able to register for particular events (i.e., just before). They should be able to unregister. It should also be possible to register for some classes, some methods, and not others. What is a good way to write the rules for enrolling in notifications? (And what's the word for this that AspectJ uses?) I explicitly pass self from the wrapped_method instance to the actual wrapped method. However, this is not really the instance of the class, it's the instance of the wrapped_method object. How do I pass the actual instance to the wrapped method--whether explicitly or implicitly? I should probably explicitly set the metaclass for wrapped_method, Trace, Observer, and even VirtualClassError to "type" (the default metaclass) to avoid weird infinite loops where the members of the aspect framework are themselves being aspected. I need to think more about how this would be used. My vague impression of AspectJ is that you use it from an IDE, specifying different conditions for filtering classes and methods (what's the word for that again?). When you compile with aspect support turned on, the generated code has the aspects weaved in. What are the equivalent developer use cases for weaving aspects into Python code? The whole point it seems to me is that when I author the classes to be aspected, I shouldn't have to do a thing--no subclassing, no method definition. I just write my classes, omitting entirely any consideration of the future aspects to be weaved in. I mean, that's the whole point, right? To simplify the code. In the example, foo doesn't know diddly about the fact that it's being traced. And we could turn that tracing on or off simply by changing the module-level __metaclass__ variable. I should probably and try:...except:pass to the framework so that it doesn't generate errors. During development of the framework itself, of course, I want to know about errors. Observer is an interface-type base class. It doesn't provide implementation. It could easily be omitted, but it servers to document what Trace and other potential observers need to look like. It would be easy to add aspects for error handling. This is a very quick and dirty example for error notification: In wrapped_method, I would change __call__ like this: def __call__(self, *args, **kwargs): self.before(*args, **kwargs) try: self.method(self, *args, **kwargs) except Exception, e: self.on_error(e, *args, **kwargs) raise self.after(*args, **kwargs) Rather than using sys.stdout, I could have specified a file. and add on on_error() method to wrapped_method: def on_error(self, error, *args, **kwargs): for o in self.observers: o.on_error(error, self.class_name, self.method_name, *args, **kwargs) Observer: def on_error(self, error, class_name, method_name, *args, **kwargs): pass and Trace: def on_error(self, error, class_name, method_name, *args, **kwargs): self.write("error %s" % error, class_name, method_name, *args, **kwargs) - From goodger at users.sourceforge.net Mon Jun 3 23:51:14 2002 From: goodger at users.sourceforge.net (David Goodger) Date: Tue, 04 Jun 2002 03:51:14 GMT Subject: Is there a Text to HTML conversion module? In-Reply-To: References: Message-ID: SA wrote: > Does anyone know of a module that converts a text file to html? Try reStructuredText, part of Docutils (URLs below). -- David Goodger Open-source projects: - Python Docutils: http://docutils.sourceforge.net/ (includes reStructuredText: http://docutils.sf.net/rst.html) - The Go Tools Project: http://gotools.sourceforge.net/ From BPettersen at NAREX.com Tue Jun 11 15:59:27 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Tue, 11 Jun 2002 13:59:27 -0600 Subject: Hap debugger released Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192158EC5@admin56.narex.com> > From: nealj [mailto:mwarden22 at hotmail.com] > > Version 2.1 of the Hap python debugger (and ide) has just > been released to sourceforge. This version improves > performance, stability and adds a number of useful features > such as an interactive window, watch tooltips and more. > > We've been using it in house on our next product for six > months now and everyone is very happy with it. > > Try it out at http://sourceforge.net/projects/hapdebugger This looks really good (I know a couple of people who're going to be pleased :-) A couple of minor issues I noticed: - the color scheme is awful (the Idle/PythonWin scheme is much less jarring on the eyes :-) - I like the MSVC key bindings, but I was surprised that Shift-F11 wasn't bound to "step out of". - I couldn't step over a list comprehension (instead I was taken through each iteration of the for 'loop'). All in all, great work however! -- bjorn From kragen at pobox.com Sat Jun 8 22:01:31 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 08 Jun 2002 22:01:31 -0400 Subject: Efficient python programming... References: <3D013FB1.3D7477EA@engcorp.com> Message-ID: <83y9dp43d0.fsf@panacea.canonical.org> Peter Hansen writes: > Roman Suzi wrote: > > To prove that code is correct is very difficult (practically impossible). > > Unittests are there to prove that you have errors, not the other way > > around. > > I disagree, if the tests are written first (and run, proving that > they will fail when the code is wrong or missing). I think you are disagreeing because you are ignorant of formal methods. > The tests are executable requirement specifications. Running > them "proves" (yes, not 100%... nothing could) that the code > meets the specs. The specs could be wrong of course, but that > doesn't mean the code is broken... Typically specs specify the behavior of the code in an infinite set of situations. Tests test the behavior of the code in a finite set of situations, one situation per test. You said "nothing could", but you are mistaken. Computer programs are sufficiently amenable to mathematical analysis that it is possible to prove rigorously that a particular routine meets a particular spec, 100% of the time, if the spec is phrased in sufficiently rigorous terms. This has the following drawbacks: - specs can be wrong (but if they're shorter than the code, they'll probably have fewer bugs) - proofs can be wrong (but at least they make you think about the assumptions you made when writing the code) - writing the proofs takes a long time, so long that it's practical only for small programs - your proof is dependent upon your specification of the program's environment as well as upon your requirements specification; if your program depends on a lot of other complicated software, your proof may not be worth much This is important not because rigorously proving a program correct is a worthwhile activity --- maybe it is, but I'm not convinced --- but because proving a program correct is a more rigorous version of what good programmers do all the time in writing good code. You should learn a little bit about it, at least in its lighter-weight forms like cleanroom programming. From loredo at astro.cornell.edu Fri Jun 28 15:38:34 2002 From: loredo at astro.cornell.edu (Tom Loredo) Date: Fri, 28 Jun 2002 15:38:34 -0400 Subject: C API for Python's RNG? Message-ID: <3D1CBB3A.E1C43D8A@astro.cornell.edu> Hi folks- I'm doing some Monte Carlo calculations, and to speed things up I'm dumping parts of it into an extension. I'll be needing random numbers both in the Python code and in the extension. I'd like to use Python's RNG in the extension so I can easily maintain the state of the whole calculation if necessary. So I need to know the C API for Python's RNG. I don't see it documented in the standard documentation. I'll dig in the source to try to puzzle it out, but I thought I should ask publicly: is this documented anywhere? If not, is there anything I should be careful about that may not be obvious? How stable is the API from version to version of Python? I suppose I could switch to the Numeric Random module, but the C API for that isn't documented either, so I have the same questions about that. Thanks, Tom Loredo From fredrik at pythonware.com Wed Jun 19 18:13:46 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 19 Jun 2002 22:13:46 GMT Subject: GOTO w/ Python? References: <3d10ed95@xpl-sdf1-sec1.> Message-ID: Angela Williams wrote: > I'm looking for the equivalent of the GOTO command for Python 2.2.1 running > on Windows 98. I have programmed very little and am new to Python. like most modern programming languages, Python doesn't have a GOTO command. for a brief explanation of why, and what you should use instead, check the "branching" chapter in Alan Gauld's "Learning to Program" tutorial: http://www.freenetpages.co.uk/hp/alan.gauld/ (if you're new to programming, I suggest working through the entire tutorial) you can find more Python tutorials here: http://www.python.org/doc/Newbies.html From phr-n2002b at NOSPAMnightsong.com Thu Jun 20 03:39:44 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 20 Jun 2002 00:39:44 -0700 Subject: Variable Interpolation - status of PEP 215 References: Message-ID: <7xu1ny4cvz.fsf@ruckus.brouhaha.com> aahz at pythoncraft.com (Aahz) writes: > Peter already told you what you really wanted to know, but for the > benefit of other people, PEP 215 is dead and PEP 292 is currently the > subject of a LARGE thread on python-dev. I didn't know 215 was dead. A shame. I thought it was a good idea. 292 seems ok, maybe clumsier than 215 but an improvement over the % mess inherited from C. What's the deal with the curly braces in 292? That's not discussed at all in the PEP. I don't see what's wrong with print "My name is $name".sub() (which is similar to what 215 allowed) instead of print "My name is ${name}".sub() I understand that preferences can run either way, but I think PEP 292 should face this question instead of ignoring it. From s1336one562 at bach.sun.ac.za Thu Jun 6 17:40:16 2002 From: s1336one562 at bach.sun.ac.za (Hugo van der Merwe) Date: Thu, 06 Jun 2002 23:40:16 +0200 Subject: distutils and distributing "scripts" References: Message-ID: That already helps though, thanks. I'll go without .pyw for now. But I still wonder how .pyw files, and all scripts, for that matter, are distributed. bdist does place scripts in /usr/bin as one would want, but one would want to be able to build a bdist from an sdist, which one cannot if the scripts aren't included. Or, does one usually, in the case of a .py script, add it both to py_modules and script lists? Hugo Erlend J. Leiknes wrote: > oh, sorry, didnt read your question good enough... > > =( > > "Erlend J. Leiknes" wrote in message > news:nAqL8.10168$fG3.343408 at news2.ulv.nextra.no... >> do not call the files .pyw, just use py >> >> when you then use py2exe, do the following >> python setup.py py2exe -w >> >> the -w means --window or --windows (dont remember), anyway, this will use >> the pythonw.exe. From aahz at pythoncraft.com Mon Jun 17 20:39:58 2002 From: aahz at pythoncraft.com (Aahz) Date: 17 Jun 2002 20:39:58 -0400 Subject: If you use Python -OO is it a permanent condition?? References: Message-ID: In article , Georg Mischler wrote: >Jeff Sasmor wrote: >> >> 'Fascinating' >> I'm sure there's a logical reason... somehow. Anyway, I found >> that if I renamed all the .pyo files to .pyc everything works fine. >> I guess that's because there's little difference between them. It's >> too bad that there's no way to switch optimized mode on and >> off programmatically - would be useful for apps that use compile(). > >It would be enough to simply look for the respective "other" >bytecode file type as well, if nothing else has been found >when trying to import a module. The -O setting only has any >real relevance when freshly compiling from *.py, after all. >Some small amount of added convenience from the side of the >interpreter would be highly appreciated in this point. File a bug on SourceForge. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From sjmachin at lexicon.net Fri Jun 7 22:06:52 2002 From: sjmachin at lexicon.net (John Machin) Date: 7 Jun 2002 19:06:52 -0700 Subject: array, list, performance... References: <3D0108B7.3C206C2E@accessforall.nl> Message-ID: Ype Kingma wrote in message news: > Multiplying the list's size by a constant factor when necessary would > give O(log(len(li)) * len(li)) behaviour I'm not sure where you get this from. Here's my take: The theoretical amortised cost is O(N), not O(log(N)*N), where N is the utimate size of the list. Let F be the factor by which the list size is expanded when necessary. Let e be the number of expansions required to grow to size N. F**e is O(N). The ith expansion involves fiddling with O(F**i) elements, with O(1) cost each. The total of this over e expansions is O(F**e). As above, F**e is O(N). The O(1) cost each is theoretical. The operating system's memory allocator may exhibit worse-than-linear behaviour. Cheers, John From joerg.baumann at stud.informatik.uni-erlangen.de Wed Jun 5 06:55:37 2002 From: joerg.baumann at stud.informatik.uni-erlangen.de (=?ISO-8859-1?Q?J=F6rg?= Baumann) Date: Wed, 05 Jun 2002 12:55:37 +0200 Subject: Fastest way to read / procsess / write text? References: <3CFD5229.2060803@excite.com> Message-ID: Brent Miller wrote: ... > This works beautifully most of the time (it's super fast), except when I > pipe large files (>50megs) to it and then it usually dies half way > through complaining of memory errors because it ran out of ram. ... Since you alter only texte inside single lines, you can process the file line by line, instead of loading it into memory as a whole. (See Python docs for xreadlines(), xranges, ...) #!/usr/bin/python2 import sys, re try: outfilename = sys.argv[1] except: raise "usage: %s "%sys.argv[0] infile = sys.stdin outfile = open(outfilename, "w") for line in infile.xreadlines(): outfile.write(re.sub('[.](?=\d\d\d\d\d\d)|[.](?=\w+[ ][<|>])|[.](?=\w+[:])|[ ](?!0x)', '\t', line)) From jknapka at earthlink.net Tue Jun 25 12:30:02 2002 From: jknapka at earthlink.net (Joseph A Knapka) Date: Tue, 25 Jun 2002 16:30:02 GMT Subject: Python and Eclipse References: <3D17FAF4.35CC9F1B@earthlink.net> <81CC01E58BF2A99B.DFCD5EC6E4654907.32D731380951B9CA@lp.airnews.net> Message-ID: <3D189A8A.577C8186@earthlink.net> Cameron Laird wrote: > > In article <3D17FAF4.35CC9F1B at earthlink.net>, > Joseph A Knapka wrote: > >Hi folks, > > > >I am interested in having Python support in > >Eclipse - interested > >enough to contribute code, or to tackle the > >task myself, if need be. Of course, I'd like > >the Python support to be at least as good as the > >Java support, which is a pretty tall order, > >'cause the Java support in Eclipse is awfully > >damn good --- it nearly allows me to *enjoy* > >writing Java code :-) > > > >Anyway, I know some other folks have expressed > >interest in this as well, and I'd like to hook > >up with them. If you're working on Python+Eclipse > >and you've got code in any state of completion, > >I'm willing to alpha- or beta-test, fix stuff, > >add new stuff, etc. > . > . > . > Can you say a few more words about Eclipse? It ... well, I'm > wary. I understand its marketing more than its technology, > and on hostile days, I think it's *only* marketing. Maybe you > can make it more appealing. "[It] nearly allows me to *enjoy* > writing Java ..." is certainly a good start. I don't know about the marketing angle. I've been using Visual Age for the past few years, and IMO, after having used Eclipse for just a couple of weeks, it is a great deal better than Visual Age as an IDE. True, it doesn't do visual UI layout, but I must say that VA's UI builder never caused me anything but grief anyhow. Someone could add a UI builder to Eclipse if they wanted. Eclipse does everything else as well as or better than VA - syntax- aware editing, including context-sensitive completion (definitely better than VA's!), incremental compilation, debugging, edit- compile-and-continue in the debugger... Eclipse feels more solid than either Visual Age or MS Visual Studio - I have had no crashes or anomalous behavior while using Eclipse rather intensively over the past couple of weeks, save for an episode yesterday that I believe was triggered by a low-VM condition caused by another process. Eclipse nevertheless exited cleanly and saved my work, which is something I have *not* come to expect from Visual Age. Eclipse does like to have RAM to play in - the Eclipse JVM on my NT laptop is currently about 60MB large. Of course, Visual [Age|Studio] have similar RAM demands. Eclipse is open source, so no matter what IBM decides, interested parties could pick it up and run if necessary. It is designed to be a platform upon which to build various IDEs. It seems to be quite well documented for IDE extension developers, although I have not actually written any such extension yet, so the perceived documentation quality may be illusory. I have not tried JBuilder. All my Java work prior to Eclipse was done either in Visual Age or at the command line, and I strongly prefer Eclipse over either of those other methods. For the price, it's hard to beat. -- Joe "This is Radio Clash / using audio ammunition." -- The Clash, "Radio Clash" From not.this at seebelow.org Thu Jun 13 17:14:58 2002 From: not.this at seebelow.org (Grant Griffin) Date: 13 Jun 2002 14:14:58 -0700 Subject: why not "'in' in 'in'"? References: Message-ID: In article , "Bjorn says... > ... >Ok, how about: > >>>> class mystr(str): >... def __contains__(self, s): >... return self.find(s) >=3D 0 >... >>>> 'hello' in mystr('hello world') >1 >>>> 'foo' in mystr('hello world') >0 >>>> Well, sure--but where's the fun in that? Actually, I don't much like this approach for a couple of reasons. First, you then have to remember to wrap each string literal inside the name of your new class, a practice which is both tedious and ugly. It isn't worth it. Second, although Python's newfound ability to subclass from built-in types allows one to change nearly anything one doesn't like about the way the type works, I generally think that's going in the wrong direction because it makes your code work different than it reads. Instead, I find the ability to subclass from built-in types to be useful primarily to _add_ behavior to a type. The most common example is some sort of specialized list or dictionary which provides new methods appropriate only for its special use. These cases are, of course, simply a more elegant way of implementing what we used to implement less elegantly via an explicit list member, e.g., "self.list". just-because-guido-allows-it-doesn't-mean-you-should-use -it-injudicious-ly y'rs, =g2 _________________________________________________________________________ Grant R. Griffin g2 at dspguru.com Publisher of dspGuru http://www.dspguru.com Iowegian International Corporation http://www.iowegian.com From phd at phd.pp.ru Thu Jun 20 06:54:53 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Thu, 20 Jun 2002 14:54:53 +0400 Subject: Useful RE patterns (was: Variable Interpolation - status of PEP 215) In-Reply-To: ; from fredrik@pythonware.com on Thu, Jun 20, 2002 at 10:34:06AM +0000 References: <4PfQ8.44245$n4.10307683@newsc.telia.net> Message-ID: <20020620145453.B25214@phd.pp.ru> On Thu, Jun 20, 2002 at 10:34:06AM +0000, Fredrik Lundh wrote: > As part of the python-dev discussion, I mentioned that it might > be a good idea to add a couple of standard RE patterns to the > standard library, e.g. to match things like integer literals, IP- > numbers (etc). > > If I were to add a dozen (or so) patterns to the (S)RE module, > what should I pick? What patterns do you find yourself using > over and over again? IP address (but it is required to test that every nibble is < 256) URL e-mail address (yes, I know very good how hard it is) identificator (letters+digits, starting with a letter) empty line line consisted only with whitespaces comment line, starting with #, may have whitespaces before # Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From threeseas at earthlink.net Tue Jun 25 23:43:14 2002 From: threeseas at earthlink.net (Timothy Rue) Date: Wed, 26 Jun 2002 03:43:14 GMT Subject: Reminder of a python Project. References: <2218.941T781T12224051threeseas@earthlink.net> <3D193728.663CA774@engcorp.com> Message-ID: <1708.941T2398T14045676threeseas@earthlink.net> On 25-Jun-02 22:38:16 Peter Hansen wrote: >Timothy Rue wrote: >> >> First off, it's ok that I got such a high level of resistance to my >> initial posting here about this project. >Obviously the level was not high enough. Sorry, we'll try harder. >> $81 Billion = 31% of software development gets cancelled before complete >> $59 Billion = 53% of software development has cost over-runs of 189% >> 16% success - project success and failure ratio >[...] >> My 1997 estimate of software failures all around (total of industry and >> consumer level development and use): Low estimate of 300 Billion. >Your information is out of date. Agile software development processes >developed since 1997 have improved the success rate of software development >projects to the point where this is no longer an issue. It is now possible >to deliver software with a 96% success rate, for less cost than previous >methods, with greater sustainability for the development teams, and at >a much higher quality level than appeared possible in the past. >I'm afraid there is no longer any need for an autocoder. >-Peter Geee, maybe you should tell that to NIST http://www.computerworld.com/printthis/2002/0,4814,72245,00.html Hmmm, I coulda sworn I put that in the post. You wouldn't know what happened to it would you? --- *3 S.E.A.S - Virtual Interaction Configuration (VIC) - VISION OF VISIONS!* *~ ~ ~ Advancing How we Perceive and Use the Tool of Computers!* Timothy Rue What's *DONE* in all we do? *AI PK OI IP OP SF IQ ID KE* Email @ mailto:timrue at mindspring.com >INPUT->(Processing)->OUTPUT>v Web @ http://www.mindspring.com/~timrue/ ^<--------<----9----<--------< From findler_lambda at yahoo.com Fri Jun 7 10:12:10 2002 From: findler_lambda at yahoo.com (Robert Hanlin) Date: 7 Jun 2002 07:12:10 -0700 Subject: About writing Jython tutorial... Message-ID: Hi all, I'm indoctrinating friends into the dark, beautiful world of Jython. But I find there is no good online documentation, and I only have an easy time because I happen to own the O'Reilly Jython Essentials book. (For example, when you use jythonc to compile classes, if something is missing on the classpath you're more likely to get a null pointer exception than an appropriate class not found exception.) If I happened to write a walkthrough, is there a website where it would be welcome? If not, maybe I should make a weblog... Thanks! findler From michael at belgacom.net Wed Jun 19 08:00:34 2002 From: michael at belgacom.net (Michael Anckaert) Date: Wed, 19 Jun 2002 14:00:34 +0200 Subject: how i use =?iso-8859-1?Q?'=E3?= =?iso-8859-1?Q?'?= in python??? In-Reply-To: <3D0F6623000017AA@www.zipmail.com.br>; from jubafre@zipmail.com.br on Wed, Jun 19, 2002 at 01:38:45AM -0300 References: <3D0F6623000017AA@www.zipmail.com.br> Message-ID: <20020619140034.A2009@carpathia.anckaert.net> On Wed, Jun 19, 2002 at 01:38:45AM -0300, jubafre at zipmail.com.br wrote: > i?m brazilian, and in my laguage(Portguese) there are many other caracters > how ?, ?, ? and a string in python doesn?t support this > how i can use??? have a import module for this??? > > BRASILEIROS DA LISTA COMO VCS CONSEGUEM USAR ACENTO NO PYTHON?? > > for exmple: > s='?' > doesn?t work?why?? > It works for me. I tried the ? and ? characters and they both work out fine if I want to asign a string these variables. Maybe there is a problem with your editor? What exactly is the error message you get? LINUX: The Choice of a GNU Generation... ---------------------------------------------- Michael Anckaert manckaert at belgacom.net xantor at linux.be xantor at xantor.tk http://www.xantor.tk Jabber: xantor at jabber.org If you use envelopes, why not use encryption? OpenPGP: 0xC3300BEC ---------------------------------------------- -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From tismer at tismer.com Fri Jun 21 06:37:51 2002 From: tismer at tismer.com (Christian Tismer) Date: Fri, 21 Jun 2002 12:37:51 +0200 Subject: GOTO w/ Python? References: <3d10ed95@xpl-sdf1-sec1.> <3D11A21D.9010809@mxm.dk> <3D11DA9B.163A7BD0@info.unicaen.fr> <3D12EEAA.9C3A3D29@info.unicaen.fr> Message-ID: <3D1301FF.3070201@tismer.com> Jerzy Karczmarczuk wrote: > John Roth comments my observation concerning the relation between gotos > and continuations: ... >>Continuations, on the other hand, have been discussed, and may >>very well wind up in Python some day. See the discussion around >>a variant called 'stackless.' Guys, I'm watching you! :-) > Yeah, I know it. I follow the Mission Impossible Software Team (Tismer > et al.) for some time. I am interested in scientific computing, and I > believe that generators, coroutines etc. are essential for the simu- > lation. So, the idea to use continuations was for me always very > appealing (even if sometimes appalling...). Still, the notion of a > full continuation, as implicit in the letter of GvR > http://www.stackless.com/continuations.guido.van.rossum.html, > the machinery which makes a snapshot of the actual state, and which > is implemented in Scheme through call/cc, is not necessarily the > very essence of the concept itself, which is simpler. My turn to send > you to some references. I suggest the Andrew Appel's book 'Compiling > with Continuations'. In fact, Guido isn't correct with copying the full execution stack. The continuations implementation which I did is completely different in that sense and tries to copy the minimum necessary to survive. Appel's book can really be recommended if you like to learn a new way of thinking. Still, I'm not planning to support full continuations again. The immutability of continuations is a hard requirement, and I didn't find an application yet where mutable tasklets didn't suffice. ciao - 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 pager +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 whisper at oz.net Sat Jun 8 03:40:26 2002 From: whisper at oz.net (David LeBlanc) Date: Sat, 8 Jun 2002 00:40:26 -0700 Subject: no module named windowsc? In-Reply-To: <3b738180.0206072145.1c4a655b@posting.google.com> Message-ID: The windows.py in \python22\lib\site-packages is _not_ the example windows.py that is mentioned in the FXPy doc. It seems you have to download and unpack the source distribution in order to get the examples and local documentation. Then try running "python windows.py" in the fxpy-1.0.5\examples directory and I think you'll find things will work. BTW, I believe that under Windows 2000 Pro, you can actually just type "windows" in the example dir and it will run - a nice feature of Windows 2000 long since overdue. If that doesn't work, let me know and I think I can tell you how to make it work that way. Regards, David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Mr Blah > Sent: Friday, June 07, 2002 22:46 > To: python-list at python.org > Subject: no module named windowsc? > > > I installed python 2.2 for windows on my windows 2000 professional > machine and also installed fxpy for python 2.2. > > When I try to run any of the example programs that come with fxpy I > get the same error - a complaint about windowsc: > > C:\Python22\FXPy>python windows.py > Traceback (most recent call last): > File "windows.py", line 2, in ? > import windowsc > ImportError: No module named windowsc > > Searching on windowsc I can't seem to come up with much of anything. > Can anyone give me a clue about what might be going on? > > Mr Blah > blah at calico-consulting.com > -- > http://mail.python.org/mailman/listinfo/python-list From max at alcyone.com Sun Jun 23 20:59:00 2002 From: max at alcyone.com (Erik Max Francis) Date: Sun, 23 Jun 2002 17:59:00 -0700 Subject: HTTP authentication References: Message-ID: <3D166ED4.FBE9E2C8@alcyone.com> Preston Tamkin wrote: > hello all. I've just recently jumped on the python bandwagon, and I > need > some help! Derive from the urllib.FancyURLopener class, and override the proper_use_password method to return the (user, password) 2-tuple you want: http://www.python.org/doc/current/lib/urlopener-objs.html -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From ianb at colorstudy.com Thu Jun 20 14:11:33 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 20 Jun 2002 13:11:33 -0500 Subject: Variable Interpolation - status of PEP 215 In-Reply-To: <7xu1ny4cvz.fsf@ruckus.brouhaha.com> References: <7xu1ny4cvz.fsf@ruckus.brouhaha.com> Message-ID: <1024596693.605.174.camel@lothlorien.colorstudy.net> On Thu, 2002-06-20 at 02:39, Paul Rubin wrote: > What's the deal with the curly braces in 292? That's not discussed > at all in the PEP. I don't see what's wrong with > > print "My name is $name".sub() > > (which is similar to what 215 allowed) instead of > > print "My name is ${name}".sub() The PEP allows either, just like the shell. It just uses the second form in most of the examples. Ian From loewis at informatik.hu-berlin.de Sun Jun 9 07:00:39 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 09 Jun 2002 13:00:39 +0200 Subject: xml.* getting the hang... References: Message-ID: Uwe Mayer writes: First you write > i figured that xml.sax and xml.parsers.expat is where to look for. > problem number first: and then > - in order to build an xml dom object i have to get started on a > Document(); If you want to build a DOM, I recommend not to use sax or expat directly. Instead, you should use the minidom build, xml.parse.minidom.parse. > and this is the problem: i couldn't find anything; with one > exception, i can create xml documents using > xml.dom.minidom.Document(), if this is the regular case then i don't > quite see how xml.sax.* and xml.dom.minidom relate to eachother. They relate to each other through xml.dom.minidom.parse, which uses xml.dom.pulldom.parse, which either uses the parser given as a parameter, or uses xml.sax.make_parser, which either uses a parser specified in an environment variable, or uses xml.sax.expatreader, which uses xml.parsers.expat. > Secondly i found the package xml.dom.pulldom which seems to be just what > i'm looking for, however the documentation is very poor on these classe. > what, f.e. is a "documentFactory"? pulldom was originally not designed for "public" use, so I recommend you ignore it. > I don't want to do xml validating, so xml.parsers.expat could be used, > too. So now i don't know what to use at all: You should use xml.dom.minidom.parse. Regards, Martin From vinay_sajip at yahoo.co.uk Tue Jun 4 20:19:11 2002 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 4 Jun 2002 17:19:11 -0700 Subject: ANN: Logging Module v0.4.5 released Message-ID: <2e37dc1.0206041619.787971f1@posting.google.com> A new version of the proposed Python standard logging module (as per PEP 282) has been released. You can get all the information from http://www.red-dove.com/python_logging.html There are "download" and "recent changes" links at the top of that page. The new stuff includes some bug fixes, better support for class-based filtering and logging, more documentation of the configuration file format, an example hand-coded configuration file for those people who can't use the GUI configurator, an example Filter for regular-expression match-based filtering, and more! As always, your feedback is most welcome (especially bug reports, patches and suggestions for improvement). Cheers Vinay Sajip Red Dove Consultants Ltd. Changes since the last version: ================================= Fixed bug which caused problem if no args to message (suggested by Hye-Shik Chang). Fixed bug in _fixupParents (thanks to Nicholas Veeser) and added log_test19.py as a test case for this bug. Added getMessage to LogRecord (code was moved here from Formatter.format). Applied str() to record.msg to allow arbitrary classes to determine the formatting (as msg can now be a class instance). Table of Contents added to python_logging.html, the section on Loggers updated, and the logconf.ini file section annotated. Added log_test20.py which demonstrates how to use class instances to provide alternatives to numeric severities as mechanisms for control of logging. Added log_test21.py which builds on log_test20.py to show how you can use a regular expression-based Filter for flexible matching similar to e.g. Protomatter Syslog, where you can filter on e.g. "a.*" or "*.b" or "a.*.c". _levelNames changed to contain reverse mappings as well as forward mappings (leveltext->level as well as level -> leveltext). The reverse mappings are used by fileConfig(). fileConfig() now more forgiving of missing options in .ini file - sensible defaults now used when some options are absent. Also, eval() is used less when interpreting .ini file contents - int() and dict lookup are used in more places. From mgerrans at mindspring.com Sat Jun 15 03:52:37 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Sat, 15 Jun 2002 00:52:37 -0700 Subject: I feel stoopid ... this code is to verbose References: <3D0A1791.3060307@mxm.dk> <3d0a240f.15785671@news.t-online.de> Message-ID: > strfmt = lambda x:"".join(map(lambda c,l,y=len(x):(l==3) and c+"," or > (not (l-3)%3 and c+"." or c),list(x),range(len(x),0,-1))) Needs a little more tweaking; try this: strfmt(str(-10000)) From david_griswold1 at yahoo.com Fri Jun 28 21:00:22 2002 From: david_griswold1 at yahoo.com (David) Date: Sat, 29 Jun 2002 01:00:22 GMT Subject: I'm an idiot Message-ID: OK, I am the first to admit it. I am an idiot. I have RTFM on this over and over, and I can still not figure out what I am doing wrong. I think the intent of the code is obvious, but just to clarify, I want to read every line in a file and write those lines back out to another file, but with leading and training space removed. I also want to have some elegant way to determine that I have reached the end of the file and break out of the loop. And just to explain my stupidity, my reference langauge is BASIC. I could have written this in BASIC in a minute, but I need to learn something new. Any help would be appreciated. David f=open('c:\\temp\\temp.txt', 'r') g=open('c:\\temp\\temp1.txt', 'w') while 1: try: s=f.readline g.write(s.split()) except IOError: break g.close f.close From phd at phd.pp.ru Thu Jun 20 04:02:52 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Thu, 20 Jun 2002 12:02:52 +0400 Subject: procmail replacement in Python In-Reply-To: <20020620014021.A4575@lifebook>; from dmitri.gouliaev@telkel.net on Thu, Jun 20, 2002 at 01:40:22AM -0500 References: <20020619181953.E4127@phd.pp.ru> <20020619150411.GB11789@lilith.my-fqdn.de> <20020620014021.A4575@lifebook> Message-ID: <20020620120252.G22899@phd.pp.ru> On Thu, Jun 20, 2002 at 01:40:22AM -0500, Dmitri I GOULIAEV wrote: > > > On Wed, Jun 19, 2002 at 09:08:53AM -0500, Mark McEahern wrote: > > > > http://www.qcc.sk.ca/~charlesc/software/getmail-2.0/ > > > > > > "A POP3 mail retriever..." Hence, it is not fetchmail replacement, as > > > fetchamil also does IMAP, and does it very well. > > > > I don't need to retrieve emails from an IMAP server [...] > > CMIIamW, I thought Oleg was talking about the description of getmail, not about your particular needs. Exactly. Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From whisper at oz.net Wed Jun 19 19:56:05 2002 From: whisper at oz.net (David LeBlanc) Date: Wed, 19 Jun 2002 16:56:05 -0700 Subject: Dispatching a Win32 COM in the background? In-Reply-To: <3D1117D8.9AAEF2F4@engcorp.com> Message-ID: Hmmm... and the run method of Background could be sitting on one end of a Queue (Queue is thread-safe: see your python doc for details) that's buffering the asyncronous calls on the speacher. The main task then just stuffs a talk request into the queue and the Background processes it when it gets to it. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Peter Hansen > Sent: Wednesday, June 19, 2002 16:47 > To: python-list at python.org > Subject: Re: Dispatching a Win32 COM in the background? > > > "Steven M. Castellotti" wrote: > > > > 2) Make the call inside a thread which produces the same effect. > > This might work (I don't know anything about COM though). Try putting > your own code inside the run method of a thread: > > import threading > class Background(threading.Thread): > def __init__(self): > threading.Thread.__init__(self) > > def run(self): > print 'Starting' > pass # your own code goes here > print 'Done' > > >>> b = Background() > >>> b.start() > Starting > > Done > > If at this point you get a >>> prompt back right away, but the > speech generation is carrying on "in the background" then you're > all set. Make sure you do this with code you've already tested > outside of the thread, so you'll know that any failure is not > the fault of your own code... > > -Peter > -- > http://mail.python.org/mailman/listinfo/python-list From jones at jones.jones Fri Jun 14 08:44:14 2002 From: jones at jones.jones (Jones) Date: Fri, 14 Jun 2002 12:44:14 GMT Subject: Writing a simple linux daemon type thing... References: Message-ID: "Radovan Garabik" wrote in message news:rn3cea.rt4.ln at 127.0.0.1... > Jones wrote: > : Hi everyone, > : I hope this is a simple question for you guys. I'm new to Python and Linux. > : I'm wondering if Python (and this group) can help me. > : I want a program to always be running in the background that, connects to > : PostgreSQL every few seconds, queries a table, and for each record it finds, > : shells out to the system to execute program. > > : My research indicates that "nohup" might do the trick? So would it be as > : simple as writing the program in Python and then puting something like > : "nohup python myprog" in the Linux startup sequence (wherever that may be)? > > yes > (python myprog & > would be probably better) Thank you for you reply. Just one more question. Doing what you suggest was my first thought. But I thought I read somewhere last night that using "&" was not a good idea..... I have no idea why (it sounds good to me), but I guess I just want to understand the difference between running it as a "daemon" and just running it the background... if there is one. Or maybe someone has a URL with a good discussion on this someone could point me to. Thanks. From ianb at colorstudy.com Wed Jun 12 18:59:24 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 12 Jun 2002 17:59:24 -0500 Subject: Wanted: Potential Python Authors In-Reply-To: References: Message-ID: <1023922764.511.29.camel@lothlorien.colorstudy.net> On Wed, 2002-06-12 at 17:27, Lothar Scholz wrote: > >- Expert programmer > No, definitely not. Most programmers are not trained on writing > tutorials or books - and normally they are really bad. > Look more for someone trained as technical writer. I don't think programmers deserve that reputation -- at least when it comes to writing for an audience they can sympathize with (people who want to learn to program). An expert programmer has already created an effective internal model and metaphor for programming, which is not shared by technical writers who are not experienced programmers (or experienced in the appropriate domain). Also, a good writer will not just tell how to write an effective program, but how to write a *good* program. In order to do that, you have to be able to write good programs. You also should have something to say that's not just a rephrasing of the documentation -- new content, new perspective, something. Ian From quinn at lira.ugcs.caltech.edu Sat Jun 8 23:51:12 2002 From: quinn at lira.ugcs.caltech.edu (Quinn Dunkan) Date: 9 Jun 2002 03:51:12 GMT Subject: libpython as a shared library? References: <20020604143402.GB22993@hal.mediasupervision.de> Message-ID: On 06 Jun 2002 10:37:42 +0200, Martin v. L?wis wrote: >Gregor Hoffleit writes: > >> If I compile the sources with -fPIC, but put them in a static library, >> there's nearly no speed difference to non-PIC code in a static library. >> My best guess is that the speed penalty is caused by the indirection >> step that's necessary when calling routines from a shared lib; but then, >> that's no real explanation for a loss of 30% speed! > >Can you elaborate a bit what you measured to get that speed difference? > >If it involves startup time, the time for locating libpython surely >involves part of startup time. Also, it might be necessary to perform >many relocations to libpython at run time that might not be necessary >for the application. I hope 2.3 doesn't dynamicly link libpython by default. Not really because of the performance issue, if there is one, but that it seems silly to introduce the annoyance and fragility of shared libraries when all it would do is save a few K for programs which embed python (and I have yet to see any of those). From schorsch at schorsch.com Mon Jun 17 20:13:22 2002 From: schorsch at schorsch.com (Georg Mischler) Date: Tue, 18 Jun 2002 02:13:22 +0200 Subject: If you use Python -OO is it a permanent condition?? References: Message-ID: Jeff Sasmor wrote: > 'Fascinating' > I'm sure there's a logical reason... somehow. Anyway, I found > that if I renamed all the .pyo files to .pyc everything works fine. > I guess that's because there's little difference between them. It's > too bad that there's no way to switch optimized mode on and > off programmatically - would be useful for apps that use compile(). It would be enough to simply look for the respective "other" bytecode file type as well, if nothing else has been found when trying to import a module. The -O setting only has any real relevance when freshly compiling from *.py, after all. Some small amount of added convenience from the side of the interpreter would be highly appreciated in this point. -schorsch -- Georg Mischler -- simulations developer -- schorsch at schorsch.com +schorsch.com+ -- Lighting Design Tools -- http://www.schorsch.com/ From russblau at hotmail.com Wed Jun 19 17:50:00 2002 From: russblau at hotmail.com (Russell Blau) Date: Wed, 19 Jun 2002 17:50:00 -0400 Subject: Extending long References: <69310ed7.0206191220.3bbf68d8@posting.google.com> Message-ID: "Martin v. Loewis" wrote in message news:m3ofe7q902.fsf at mira.informatik.hu-berlin.de... > estama at dblab.ntua.gr (Freeman Stopjohn) writes: > > > class bitnum(long): > > def getbit(self,bitn): > > if self & (1 << bitn) >0: > > return 1 > > else: > > return 0 > > def setbit(self,bitn): > > self=self ^ ( 1 << bitn ) > > ----- > > > > The getbit method works ok. > > The setbit doesn't (it doesn't change the number). > > > > What am i doing wrong? > > You are assigning to self. self is a parameter of setbit, just like > bitn. Assignments to formal parameters have no effect. > > What you want to do cannot be done; long objects are immutable. I > recommend you implement a wrapper, rather than inheriting. How about: def setbit(self,bitn): return bitnum(self ^ ( 1 << bitn )) This will not modify the bitnum() instance in place, since (as you pointed out) such an instance is immutable, but it will return a new instance with the desired value. -- I don't actually have a hotmail account; but I do have one on excite.com if you really want to get in touch with me. From sholden at holdenweb.com Fri Jun 28 08:41:25 2002 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 28 Jun 2002 08:41:25 -0400 Subject: Pythoniac: Thoughts on a hardware Python processor References: Message-ID: "David LeBlanc" wrote in message news:mailman.1025206656.12053.python-list at python.org... [...] > > Ahh! Haven't you heard? Forth came in Fifth and the Forth chip is dead. In > fact I don't think anyone is still offering a stack based computer (only HP > did AFAIK, the HP 3000). > Well, there was the English Electric KDF9, circa 1960. Even though it did have instructions to load and store stack elements from/to memory, all operations were performed on the hardware stack. nothing-new-under-the-HP-ly y'rs - steve ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From djc at object-craft.com.au Tue Jun 25 06:51:07 2002 From: djc at object-craft.com.au (Dave Cole) Date: 25 Jun 2002 20:51:07 +1000 Subject: Web templating/db tool with best designer/coder separation? References: <3D159696.9010209@mxm.dk> <23891c90.0206240735.3395d1f1@posting.google.com> Message-ID: >>>>> "Paul" == Paul Boddie writes: >> Whenever you build any toolkit you have to decide on the set of >> problems that you wish to solve with the toolkit. The smaller the >> problem domain the more useful you can make the toolkit. Paul> Indeed. Some kinds of applications may be addressed well by a Paul> particular toolkit, and since you might spend most of your time Paul> constructing those applications for customers, for example, it Paul> would definitely be worthwhile abandoning "complete freedom of Paul> expression" for something which gets the job done quickly, Paul> effectively and cheaply. This is arguably where many Paul> toolkits/frameworks fall down - by trying to be everything to Paul> everyone, they become as complicated as the language they're Paul> written in and don't always offer much more than the bare Paul> language in doing a particular job. Consequently, people get the Paul> temptation to write "rival frameworks" from scratch. Touche. :-) - Dave -- http://www.object-craft.com.au From deltapigz at telocity.com Wed Jun 26 16:00:59 2002 From: deltapigz at telocity.com (Adonis) Date: Wed, 26 Jun 2002 16:00:59 -0400 Subject: printing (again!!) References: Message-ID: <3d1a1d77$1_5@nopics.sjc> or if your using windows NT/2K/XP you can remap your printer using the NET command given the user access to the lpt port and can simply call it as: x = open("lpt1:", "w") x.write("blah" x.close() etc. that way it would be easier to corss platform. if on win95/98/ME then go as stated on other posts resort to either win32all or a gui toolkit. hope this helps. Adonis also, if your interested in the remapping the DOS lpt port google "DOS printing" "Geoff Tarrant" wrote in message news:afcusp$66r$1 at newsg2.svr.pol.co.uk... > I want to use Python as the language in a Computing course that I teach. > However, I can't find a way that is relatively straightforward to send data > to a printer in a Windows environment. If I can't find a way around this, I > will have to revert to Delphi or VB. Please help. I like the idea of > sending 20 or so Python programmers to University each year. > > Geoff Tarrant > > From catunda at pobox.com Tue Jun 25 10:54:25 2002 From: catunda at pobox.com (Marco Catunda) Date: Tue, 25 Jun 2002 11:54:25 -0300 Subject: Thread Memory Leak References: Message-ID: The second line "listThread = []" in the loop do it., don't it? -- Marco Catunda On Tue, 25 Jun 2002 10:11:08 -0300, Skip Montanaro wrote: > Marco> while 1: > Marco> listThread = [] > > Marco> for i in range(50): > Marco> listThread.append( threading.Thread( None, runthread > You never remove any thread objects from your listThread list. It fills > up with completed threads. From syver-en+usenet at online.no Thu Jun 27 14:17:45 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Thu, 27 Jun 2002 18:17:45 GMT Subject: How to find out operating system References: <3D1B1A37.CF516C4C@engcorp.com> Message-ID: Peter Hansen writes: > David LeBlanc wrote: > > > > You might try os.environ: > > > > os.environ['WINOS'] -> WIN2000 > > > > I don't know if WINOS is defined on '98 or ME, but it should be good > for NT, > > > 2K and XP > > It is not. Neither is it defined on win2k pro: KeyError: WINOS -- Vennlig hilsen Syver Enstad From michael at damaru.com Mon Jun 10 23:16:36 2002 From: michael at damaru.com (Michael Davis) Date: Mon, 10 Jun 2002 23:16:36 -0400 Subject: newbie question - python blocking on int()? References: <4LaN8.2488$Vr2.586019@news20.bellglobal.com> Message-ID: Chris Liechti wrote: > Michael Davis wrote in > news:4LaN8.2488$Vr2.586019 at news20.bellglobal.com: >> I'm writing a specialized ftp client. I'm parsing the output of ftp.dir, >> which gives me a string like this (call it str): >> >> -rw-r--r-- 1 fred 527 Jun 4 22:58 report.php >> >> and I'm getting the various parts like this: >> >> details = string.split( str ) >> permissions = details[0] >> size = details[3] >> name = details[7] >> debug( "added remote file size %5d: %s" % (int(size), name) ) >> >> This works. But when I replace the 3rd line with this: >> >> size = int( details[3] ) >> >> python hangs on that line. Why? > > not when i try it... what do you mean by "hangs" does it takes forever or > do you see an error message? if its the later, then you might have > assigned something to "int" somewhere else, hiding the builtin function. Thanks for replying. Actually, it's the former - when I say 'hangs', I mean that the program appears to stop running at that point. If I write: print "one" size = int( details[3] ) print "two" it prints "one" but not "two". As far as the other points go, luckily I'm in control of all the file names, and I can ensure that none has spaces. Spaces in filenames were always a terrible idea, I think. And I didn't call the string 'str', I called it 'line', which I don't think is a reserved word or function name. Cheers, Michael > > note that you should not use "str" as a name as that is a builtin > object/function that can be very handy. e.g. in python 2.2+ you could have > written "details = str.split(line)" > (or even "details = line.split()" which i prefer) > > also note that split() might not be safe for every case. e.g when the user > name contains a space (if possible) and surely when the filename has a > space in it. > > chris > -- Michael Davis Damaru Custom Programming - Web Development - Database Design http://www.damaru.com 416-540-1284 From hst at empolis.co.uk Fri Jun 7 06:06:58 2002 From: hst at empolis.co.uk (Harvey Thomas) Date: Fri, 7 Jun 2002 11:06:58 +0100 Subject: question on pattern Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220BF0@hendrix.empolisuk.com> Ulrich Pfisterer wrote: > > I want to do a pattern match on a string that spans multiple > lines (c++ > style comments, re.match('(/\*.*?\*/)', filestring) > If I use the re.findall(pattern, string) method it only finds those > matches that are on a single line. If I use re.match(pattern, string, > DOTALL) it spans multiple lines but only finds the first match. > Any help on this one would be greatly appreciated. > This works: >>> import re >>> r = re.compile('/\*.*?\*/', re.DOTALL) >>> t = '/* a \nmulti-line\ncomment*/ /*another comment*/' >>> r.findall(t) ['/* a \nmulti-line\ncomment*/', '/*another comment*/'] >>> HTH Harvey _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From whisper at oz.net Thu Jun 13 00:37:30 2002 From: whisper at oz.net (David LeBlanc) Date: Wed, 12 Jun 2002 21:37:30 -0700 Subject: Python GUI In-Reply-To: <9ddd154e.0206122021.1b06f89a@posting.google.com> Message-ID: Fox and FLTK are other options. http://www.fox-toolkit.org/ http://www.fltk.org/ Neither of these has as wide a following as the GUI's you've already evaluated. I would stick with Tkinter if disk and memory usage are that critical to you - it's look is pretty close to that of the platform it's running on. For additional widgets, check out the Python Megawidgets. http://pmw.sourceforge.net/ David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of H. Safarzadeh > Sent: Wednesday, June 12, 2002 21:21 > To: python-list at python.org > Subject: Python GUI > > > Hi all, > I know that this subject is discussed in many other places, but I don't > think it is harmful to talk about it more! > > I want to what library I should use to make GUI for my Python apps? > I have examined many of them, but I couldn't find what I need. Here is > the result of some of my examinations: > > -Tkinter: A nice simple lib, but really simple! It dosn't have enough > widgets, and I do not like its look in addition! > -wxPython: Really perfect. It has many widgets, and do many works(not > only in GUI). But it is toooo big!(both on disk and in memory). I need a > smaller one. > -pyGTK and pyQt: I do not know enough about them. But I know that I do > not like GTK look on Windows and Qt for Windows has some problems with > its lisence(and it is tooo big, too!) > -Jython/Swing: ....it's Jython, after all! > -Win32 extensions: It is not portable!!! > > Any comments? Other possibilities? > > Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list From trentm at ActiveState.com Fri Jun 21 14:19:53 2002 From: trentm at ActiveState.com (Trent Mick) Date: Fri, 21 Jun 2002 11:19:53 -0700 Subject: Windows versions of Python---pros and cons? In-Reply-To: <60FB8BB7F0EFC7409B75EEEC13E201922151A8@admin56.narex.com>; from BPettersen@NAREX.com on Thu, Jun 20, 2002 at 04:52:35PM -0600 References: <60FB8BB7F0EFC7409B75EEEC13E201922151A8@admin56.narex.com> Message-ID: <20020621111953.B29506@ActiveState.com> [Bjorn Pettersen wrote] > > From: Chris Barker [mailto:Chris.Barker at noaa.gov] > [snip] > > > > On that note: does anyone know if there is a way to turn a > > Python script into something that acts like an application on > > Windows...without resorting to Py2exe and the like. What I > > want is something just like: > > > > chmod +x scriptname > > and a #! line at the top > > > > on Unix. I want it to work on the windows command line. > > If you use the ActiveState version (not sure about the python.org > version) this should work out-of-the-box. Just type the name of the > script, you can even leave out the .py extension. Someone else will > probably tell you how it works, I just know it's got something to do > with registering the .py extension as an executable extension in the > registry... As Mark Hammond mentioned, this is done by adding .py to your PATHEXT env. var. ActivePython does that (and .pyc, .pyo, .pyw, .pys as well). Trent -- Trent Mick TrentM at ActiveState.com From jadestar at idiom.com Sun Jun 16 14:59:43 2002 From: jadestar at idiom.com (James T. Dennis) Date: 16 Jun 2002 18:59:43 GMT Subject: getgrouplist() ? References: Message-ID: Mark McEahern wrote: >> I need a way to get a back a list of supplemental group ids for a >> specified uid. Something like getgrouplist() in my C standard lib. I >> don't see a convenient method for this, have I missed it? >> >> The os module contains getgroups(), but that doesn't allow me to >> specify a uid; it uses only the uid of the current process. > For what it's worth, the grp module is getting some improvements for 2.3: > http://www.python.org/dev/doc/devel/whatsnew/node8.html Here's a simple function to build a dictionary of lists, keyed by username and containing groupnames for primary GID and any supplemental group memberships: #!/usr/bin/env python2.2 import grp,pwd def usersgroups(): results = {} # dict of results groups = grp.getgrall() # list of group entries for i in pwd.getpwall(): # for each user account user = i[0]; gid = i[3] # start each user's group list with his/her primary group: results[user] = [grp.getgrgid(gid)[0]] # scan groups for this user: for g in groups: if user in g[3]: results[user].append(g[0]) return results if __name__=='__main__': for i,j in usersgroups().items(): print i, ":", for x in j: print x, print It's deliberately simplistic. I probably could have done something fancy with list comprehensions or maps or something, but this should be easy to read. From tim.one at comcast.net Fri Jun 21 12:18:18 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 21 Jun 2002 12:18:18 -0400 Subject: RE strings (was: Variable Interpolation - status of PEP 215) In-Reply-To: <3D132ADC.D04B52EA@engcorp.com> Message-ID: [unattributed] > The implementation could choose to cache the result of > re.compile at module level, thus > - speeding up the 'naive' re usage > - freeing the programmer from doing the caching in code [Peter Hansen] > Any reason the re.match() method could not do the same, internally? It already does, and always has. sre increased the internal cache size over pre, and introduced separate caches for "search" and "replace" uses of regexp literals. From gcordova at hebmex.com Thu Jun 27 15:53:49 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Thu, 27 Jun 2002 14:53:49 -0500 Subject: Pythoniac: Thoughts on a hardware Python processor Message-ID: > > Ahh! Haven't you heard? Forth came in Fifth and the Forth > chip is dead. In fact I don't think anyone is still offering > a stack based computer (only HP did AFAIK, the HP 3000). > > Dave LeBlanc > Seattle, WA USA > Which is truly a shame; it's more because of commercial and market pressures, and nothing to do with true throughput or technical merit. Let's see if Python can be ported to Forth, like it was to Java. If it can, *then* python'll run at hardware speed, don't you think? Anyhow, as I said, it's a shame that Forth has been lambasted so much that it's not really possible to find much info and code on the net. It's actually a quite nice tool. :-/ -gus From kragen at pobox.com Wed Jun 26 14:14:32 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 26 Jun 2002 14:14:32 -0400 Subject: M2Crypto: select() behaves weird on SSL sockets References: <3D04ED17.5070606@NOSPAMREMOVETHISxs4all.nl> <3D066E77.4070901@NOSPAMREMOVETHISxs4all.nl> <3D0790E1.9080904@NOSPAMREMOVETHISxs4all.nl> <831ybavprx.fsf@panacea.canonical.org> <3D0919AF.7050903@NOSPAMREMOVETHISxs4all.nl> Message-ID: <83it45lxfb.fsf@panacea.canonical.org> Irmen de Jong writes: > Kragen Sitaker wrote: > > Irmen, why aren't you using asyncore? > > My system (Pyro) is built around threads all the way. > Switching to asyncore/medusa requires a big restructuring of > my code, and that wasn't part of the plan for the next release of Pyro. There are many pieces of middle ground between complete threading (two threads per connection) and complete event-loop-drivenness with just one thread --- as you're obviously aware, since you're using select() in a threaded program. What I guess you're not aware of is that asyncore supports the middle ground (middle colors?) as well as the event-loop-driven end of the spectrum. For example, Zope has an asyncore thread that handles I/O, but actually processes requests and produces results in some child threads. From garrett at bgb.cc Wed Jun 19 01:11:22 2002 From: garrett at bgb.cc (Don Garrett) Date: Wed, 19 Jun 2002 05:11:22 GMT Subject: What If..... Strong Types References: <3D0C0F0D.4030900@bgb.cc> <3D0E8C26.7BF0772D@engcorp.com> Message-ID: <3D1011F1.3060205@bgb.cc> Peter Hansen wrote: > Don Garrett wrote: > > > It takes work to define those interfaces. In my opinion, unnecessary, > inconvenient, and unreadable work... And Python does have private > members, of course, for the right definition of private. I don't think it would take MUCH work to define those interfaces. The only addition work would be a line per member variable. However, any extra work is some extra work. The other limitation (can't delete, add or change out methods) limits what you can do, but doesn't require you to do any more work. Unless, of course, it's working around the limitations. > Preventing modifying methods on an instance would make some of my > automated testing really difficult, if not impossible. Hum... that's the only specific example I've ever run across where someone would need to switch out a method implementation at run time in production code. Depickling and several other very nice features probably depend on it, but they are core libraries, not general code. I draw a distinction there. I suggest that you could create a testing subclass that overrides the methods in questions with testing versions of the methods. Would that work as well? As easily? In C++ or Java I'd have said that a testing class would be to much trouble, in Python it means one line plus the new methods that you would have to write anyway. You also have to be smart about how class instantiation is done (the bigger problem). Another possibility is to say that all methods are function pointers and can be replaced with another function pointer, as long as the signiture matches up well enough. That would still leave a fixed interface and make the main change that I think is needed for compilation. I think. > I don't understand the "must be declared to exist" part. If they are declared > but not defined, they don't exist anyway. If they are defined, then they > already exist and a declaration is redundant. Or were you using some other > definitions of "define" and "declare"? I mean that the class definition specifies all members that instances of that class would contain. All instances would contain all of those members, and only those members until they are destroyed, even if they only hold a value of None. > Fork a branch of Python and experiment! Eventually, I may to exactly that! Unfortunatly, I'm spening most of my time trying to pay the morgage (and Python helps me do that, so I feel that I do owe time to the Python community), so I spend time trying to decide what I would be doing if I really had the time. ;> > I suppose, since Python is flexible and adding all these things to the > language would tend to make it more restrictive and, well, brittle, you > could probably call the language "Stick". :-) > > -Peter From fcorneti at libero.it Tue Jun 11 08:45:09 2002 From: fcorneti at libero.it (Fabio Corneti) Date: Tue, 11 Jun 2002 12:45:09 GMT Subject: Defining a method final References: <6glN8.35376$86.884025@twister1.libero.it> Message-ID: I would like to define a method for a class which has not to be overriden. Of course, since the developer of this project are two, this could be established by convention, but if the project will grow consistently another developer could override the method by mistake, causing unpleasant side effects. -- Fabio Corneti From sholden at holdenweb.com Wed Jun 19 12:18:09 2002 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 19 Jun 2002 12:18:09 -0400 Subject: python version? References: <3D0E8AC8.6C5C96EE@engcorp.com> Message-ID: "George Hester" bad-temperedly top-posted in reply to sensible advice from Peter Hansen... > Listen you aren't my daddy. If you do not want to help constructively then > please get off my boat. > Sound advice, since it is clearly about to sink. You were advised to get to know Python locally before trying to write ASP scripts in it. If you choose to ignore that advice you are making a rod for your own back. still-i-suppose-it-*is*-your-back-ly y'rs - steve ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From phd at phd.pp.ru Wed Jun 19 08:03:49 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Wed, 19 Jun 2002 16:03:49 +0400 Subject: procmail replacement in Python In-Reply-To: ; from pinard@iro.umontreal.ca on Tue, Jun 18, 2002 at 09:55:40PM -0400 References: <20020618235901.GA2197@lilith.my-fqdn.de> Message-ID: <20020619160349.L4127@phd.pp.ru> On Tue, Jun 18, 2002 at 09:55:40PM -0400, Fran?ois Pinard wrote: > [Gerhard H?ring] > > > I've recently looked into the procmail sources and run away screaming. > > ROTFL! If I remember well, the original author knew he had a peculiar > writing style, and was writing in some prominent file (either an FAQ or > the README, or something like) that his style was not to be discussed! :-) When I first saw the procmail code, I thought it was generated by some code obfuscator :) Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From shalehperry at attbi.com Thu Jun 27 15:45:24 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Thu, 27 Jun 2002 12:45:24 -0700 (PDT) Subject: squared functions--most Pythonic way? In-Reply-To: Message-ID: > > functional programming: > > # with an internal named function > def fsquare(f): > def f2(x): > return f(x)**2 > return f2 > this seems to be the most pythonic (lambda is not the preferred approach usually). Of course someone will mention taking this to the next step with a compose() function which take f(x) and g(x). From peter at engcorp.com Thu Jun 27 10:00:22 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 27 Jun 2002 10:00:22 -0400 Subject: How to get rid the new line References: <3D1AD534.A74EC9F4@ipm.fhg.de> Message-ID: <3D1B1A76.563E5394@engcorp.com> Markus von Ehr wrote: > > f = open(filename, 'r') > lines = f.readlines() > line1 = lines[0] # exemplarily for first line > line1 = line1[0:len(line1)-1] > > or: > f = open(filename, 'r') > lines = f.readlines() > line1 = lines[0][0:len(line1)-1] # exemplarily for first line I believe this is unsafe. The final line may not be terminated with \n. -Peter From gleki at gol.ge Thu Jun 13 04:22:20 2002 From: gleki at gol.ge (Giorgi Lekishvili) Date: Thu, 13 Jun 2002 10:22:20 +0200 Subject: py2exe 4 linux? Message-ID: <3D08563C.33D041E3@gol.ge> Hi all! Is there anything like py2exe for Linux? I have never tried to find such a tool as chmod +x with the 1st line of #!/usr/bin/python suffices for POSIX systems. Anyway, maybe there's the tool for linux? Thx, Giorgi From ods at fep.ru Thu Jun 20 07:06:34 2002 From: ods at fep.ru (Denis S. Otkidach) Date: Thu, 20 Jun 2002 15:06:34 +0400 (MSD) Subject: Useful RE patterns (was: Variable Interpolation - status of PEP 215) In-Reply-To: <20020620145453.B25214@phd.pp.ru> Message-ID: On Thu, 20 Jun 2002, Oleg Broytmann wrote: OB> > If I were to add a dozen (or so) patterns to the (S)RE OB> module, OB> > what should I pick? What patterns do you find yourself OB> using OB> > over and over again? OB> OB> IP address (but it is required to test that every nibble OB> is < 256) This can be achieved in regex, try '.'.join(['(1?\d\d|2[0-4]\d|25[0-5])']*4) OB> URL OB> e-mail address (yes, I know very good how hard it is) OB> identificator (letters+digits, starting with a letter) OB> empty line OB> line consisted only with whitespaces OB> comment line, starting with #, may have whitespaces OB> before # Last three are too simple to be a pattern, IMO. From maxm at mxm.dk Mon Jun 24 05:48:47 2002 From: maxm at mxm.dk (Max M) Date: Mon, 24 Jun 2002 11:48:47 +0200 Subject: Generic Python References: <3D16E465.F0D2509E@ifib.uni-karlsruhe.de> Message-ID: <3D16EAFF.9010709@mxm.dk> Uwe Mayer wrote: > The problem is that I've got a base class and there should be many > subclasses of it. Each subclass just overwriting an output method and > serving as a template: > > class base1: > def __init__(self): > ... > def output(self): > ... > > class template1(base1): > def output(self): > ... > > class template2(base1): > def ouptut(self): > ... > > I need many, many of these "template" classes, so a sorter way would be > to accustom the base class to take another argument which then outputs > the right thing: This problems begs for you to create a factory function:: def factory(objType, initValue): classTable = { 'template1':template1 'template2':template2 } return classTable[objType](initValue) This way you don't have to know the specifics anout the class that your create. you would then just have to:: import templates newObj = templates.factory('template2', 'Initial text') regards Max M From phr-n2002b at NOSPAMnightsong.com Fri Jun 28 02:14:40 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 27 Jun 2002 23:14:40 -0700 Subject: crypt for windows? References: Message-ID: <7x6604vsj3.fsf@ruckus.brouhaha.com> Klaus Reinhardt writes: > No, I dont like cygwin. I tried pgp, but it's to > complicated. So I decided to aks me for > password each session. For this I can use > python in 'the next script'. I don't understand your question then. When you asked about crypt and passwords, I thought you meant something compatible with the Unix crypt(3) function that hashes the passwords in Unix password files. Do you mean you just want to encrypt stuff? There's plenty of modules around for that. From peter at engcorp.com Sun Jun 2 02:08:09 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 02 Jun 2002 02:08:09 -0400 Subject: system variables References: Message-ID: <3CF9B649.39F4D6D5@engcorp.com> Daniel Powell wrote: > > hi guys, > I'm new to python and I'm teaching myself from a website. I'm stumped on one > thing this is the exact wording > > "You will need to cause the directory containing the file named python.exe > to be listed in your system environment variable named path." > the website is > http://softwaredev.earthweb.com/sdopen/article/0,,12077_626311,00.html > it says when you do this if you type something like > "python junk.py" it will run the "junk.py" scipt > if anyone can help me do this i would grealty appreciate it. > My OS is Win 98SE Hi Daniel. Edit the file c:\autoexec.bat to modify the PATH statement that is there so it has the python directory listed in it. For example, if it reads SET PATH=c:\windows;c:\windows\command then you should make it this (substituting the appropriate folder in place of c:\python22 for your own system, depending on where you installed Python): SET PATH=c:\windows;c:\windows\command;c:\python22 Test this out manually by typing the above line at a DOS prompt, then typing just "python" (when you are not already in the Python folder). If you type "SET" by itself you'll see the current PATH setting and can adjust the above lines appropriately. After changing AUTOEXEC.BAT you need to reboot, and then the changes should be permanent. -Peter From cliechti at gmx.net Fri Jun 7 17:43:05 2002 From: cliechti at gmx.net (Chris Liechti) Date: 7 Jun 2002 23:43:05 +0200 Subject: direct output to printer References: Message-ID: Uwe Schmitt wrote in news:adr815$e6m39$2 at hades.rz.uni-sb.de: > I'd like to print barcodes with a special barcode printer. > Therefore I have to send raw ASCII data to the printer. > How can I do this using Python under Windows ??? there is a raw print function in win32all, but i haven't used that. for the barcode-printer i used, i sent a bitmap with the barcode. that way you can print the same barcode on paper or preview on the screen (i used wxPython). there are some free barcode fonts around. i use this one: http://www.squaregear.net/fonts/ chris -- Chris From m2 at plusseven.com Fri Jun 14 23:35:06 2002 From: m2 at plusseven.com (Alex Polite) Date: Sat, 15 Jun 2002 05:35:06 +0200 Subject: Python and SQL Server 2000 In-Reply-To: References: Message-ID: <20020615033506.GA8821@matijek.plusseven.com> I tried to do this a couple of years ago. I think MS SQL Server was version 6.x We used ADO connections via the win32com module. It worked but it was kind of sluggish. Then to speed things up I wrote a wrapper around bpc (bulk something something, look it up in the MS SQL manual). I think we couldn't use mxODBC due to licensing issues. Then in the end we moved to MySql. -- Alex Polite http://plusseven.com/gpg/ From jepler at unpythonic.net Thu Jun 6 14:30:38 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 6 Jun 2002 13:30:38 -0500 Subject: Compiling Python In-Reply-To: <838z5sgx7w.fsf@panacea.canonical.org> References: <3CFDF148.AA2035FF@info.unicaen.fr> <3CFE49CA.46A5FEE1@tds.net> <838z5sgx7w.fsf@panacea.canonical.org> Message-ID: <20020606183033.GA12501@unpythonic.net> On Thu, Jun 06, 2002 at 12:58:59PM -0400, Kragen Sitaker wrote: > "Edward K. Ream" writes: > > BTW, a compiled version of a Python program would be valuable > > commercially, as it would allow companies to protect their source code, > > as well as (possibly) improve performance. > > I'm worried about this myself; perhaps the compiler could include the > source code in the resulting executable to prevent this. Your sarcasm is lost on me. Jeff From jadestar at idiom.com Tue Jun 11 05:07:38 2002 From: jadestar at idiom.com (James T. Dennis) Date: 11 Jun 2002 09:07:38 GMT Subject: How to play a .wav sound? References: Message-ID: Erlend J. Leiknes wrote: > Think this should work... not tested. I doesn't. I doesn't in principle (cat foo.wav > /dev/dsp doesn't work for me) and the code is wrong in at least one spot: ... > sdata = f.read(1024) > while sdata: > d.write(sdata) ... that would only copy 1K of data > "Bruno Bellamy" wrote in message > news:ad8jo7$ohl$1 at wanadoo.fr... >> I guess the question has probably been asked many times, sorry for >> bothering... >> But I searched here and there, and I couldn't find how to do that, simply >> play a .wav sound from a python program using Tkinter. >> Moreover, I need to do that in a program that would run similarly under >> Linux and Windows. >> I saw there's a python module called wave, but it seems it can only read >> .wav files. I coulnd't find a way to actually play the sound. Maybe it's >> hidden somewhere? >> If anybody can help me, that would be cool. :) I was stumped for a little while last night as well. Unfortunately I don't have a simple working example, yet; but it looks like pysolsoundserver.so and the PySol (Python Solitaire) sources might be a good start. Apparently PyGame also has some sophisticated sound handling. There doesn't seem to be a way to do it (easily) with the standard libraries, though. From dalke at dalkescientific.com Sun Jun 2 17:24:40 2002 From: dalke at dalkescientific.com (Andrew Dalke) Date: Sun, 2 Jun 2002 15:24:40 -0600 Subject: convert string to a method of a class at runtime? References: <5YvK8.285$Vm3.130161@news.uswest.net> Message-ID: Kevin Altis: >I would like to be able to take a string containing the definition of a >method, compile the method and then add it to an instance variable at >runtime, so that the method defined in the string is part of the class just >as if it had actually been in the class definition to begin with when the >module was first used. I am wary about using such tricks. Still, try this approach instead >>> class H: ... def hello(self, s): ... print s ... >>> h = H() >>> h.hello('world') world >>> s = """def world(self, s): ... print s ... ... """ >>> d = {} >>> exec s in d >>> H.world = d["world"] >>> h.world('new world') new world >>> Andrew dalke at dalkescientific.com From marklists at mceahern.com Thu Jun 20 08:24:59 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 20 Jun 2002 07:24:59 -0500 Subject: module string.py In-Reply-To: <3d11bd6a.11177520@news.polito.it> Message-ID: > 1) looking at the module "string.py" I have seen that are described > some functions like "lower", "rjust", etc. Ther problem is that it > seems not to describe exactly how this functions are made, but there > is only a comment about their properties. So in which file are these > functions described? Just so you know, those functions are also attributes of strings: >>> s = "foo" >>> s.upper() FOO For documentation, rely on the __doc__ strings: >>> print s.upper.__doc__ S.upper() -> string Return a copy of the ... Or, use help(): >>> help(s.upper) (press q to close the resulting screen) > 2) I tried to cancel the file "string.py". After that, the Python > Interpreter doesn't work anymore (it can't even start working). Why? What do you mean by "cancel"? Did you delete it? // m - From martin at came.sbg.ac.at Tue Jun 11 12:02:10 2002 From: martin at came.sbg.ac.at (Martin Krallinger) Date: 11 Jun 2002 09:02:10 -0700 Subject: tk gui for python Message-ID: Dear all, I would appreciate any sample code to generate tk gui for python. i just need to load a file, of past instead a text (protein sequence) and run on it a c programm and return the content of it's output any sample code is welcomed, thanks Martin From Sascha.Ferley at infineon.net Sun Jun 23 22:51:32 2002 From: Sascha.Ferley at infineon.net (Sascha Ferley) Date: Sun, 23 Jun 2002 20:51:32 -0600 (MDT) Subject: PIL, Python and CGI In-Reply-To: <200206241204.16542.rjones@ekit-inc.com> Message-ID: I actually got some nice little traceback that might be of use .. Traceback (most recent call last): File "/export/server/web/CPSC461/cgi-bin/test4.py", line 10, in ? import _imaging ImportError: ld.so.1: /usr/local/bin/python: fatal: libjpeg.so.6: open failed: No such file or directory though: infinity:/usr/local/lib->ls -ld libjpeg* lrwxrwxrwx 1 root other 12 Jun 16 18:58 libjpeg.so -> libjpeg.so.6* lrwxrwxrwx 1 root other 12 Jun 16 18:58 libjpeg.so.1 -> libjpeg.so.6* -rwxr-xr-x 1 root bin 137924 May 21 2001 libjpeg.so.6 infinity:/usr/local/lib-> Which is interesting ... :) Thanks Sascha From boud at valdyas.org Sat Jun 1 15:04:23 2002 From: boud at valdyas.org (Boudewijn Rempt) Date: Sat, 01 Jun 2002 21:04:23 +0200 Subject: Copying a database References: Message-ID: <3cf91e14$0$3864$e4fe514c@dreader4.news.xs4all.nl> Billy Ng wrote: > I need you guys help on mysql again. I need to push my python program to > production now, but I don't want to recreate the mysql database on the > production box. I want to copy the database from the development box to > production box.. Would anybody please tell me how to do it, thanks! > Investigate mysqldump -- it dumps your entire database to a file that you can then install on another mysql server using the basic mysql command line client. It's also one of the better options for doing backups -- backing up the database files themselves is not future-proof, as I've found to my detriment. -- Boudewijn Rempt | http://www.valdyas.org From sean.mcgrath at propylon.com Mon Jun 24 06:08:15 2002 From: sean.mcgrath at propylon.com (Sean McGrath) Date: Mon, 24 Jun 2002 11:08:15 +0100 Subject: a Tree data-structure class? In-Reply-To: <20020623160005.4179.75165.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20020624110603.00b09450@mail.digitome.com> >On 21 Jun 2002 06:10:30 -0700, steve at ferg.org (Stephen Ferg) wrote: > > >I do a lot of processing of tree-structured data, so I'm thinking it > >would be useful to develop a generic Tree class that I could adapt to > >various applications. Or perhaps a Tree class and a generic Node > >class. > > > >But before I start trying to re-invent the wheel, I thought I'd ask if > >anybody knows of something like this that has already been developed. I'd suggest looking at Python's XML libraries. DOM and Pyxie in partic. are basically tree data structures suitable for directed acyclic graph use. regards, Sean From tim.one at comcast.net Fri Jun 28 12:22:01 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 28 Jun 2002 12:22:01 -0400 Subject: doctest for java In-Reply-To: Message-ID: [Janto Dreijer] > Are there any attempts to port the "doctest" module to Java? (All > I can find using google is some testing class for the JavaDoc program > calling itself "DocTest".) > > At a glance it looks like a worthwhile effort...extracting Jython > "examples" > from /**...*/ comments also seems simple to implement. Last I heard, Python's std doctest.py worked fine under Jython. If anything else simple is needed, you're elected . From shalehperry at attbi.com Fri Jun 7 10:22:46 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 07 Jun 2002 07:22:46 -0700 (PDT) Subject: Detecting OS and Window Manager In-Reply-To: <3d00bfb5$1_2@hpb10302.boi.hp.com> Message-ID: > > Of course, this will probably not do what you want in this case, as kdecore > will probably load if it is installed, without regard to whether the current > user is running KDE. I don't have much experience with this particular > topic yet. > correct, especially on a developers box who has GNOME, KDE, ROX, etc installed. From mal at lemburg.com Tue Jun 11 10:26:13 2002 From: mal at lemburg.com (M.-A. Lemburg) Date: Tue, 11 Jun 2002 16:26:13 +0200 Subject: 'for every' and 'for any' References: <20020526135944.A32690@hishome.net> <20020526091742.A987@unpythonic.net> Message-ID: <3D060885.2010504@lemburg.com> James T. Dennis wrote: > Oren Tirosh wrote: > > >>>Then drop those functions into your personal utility library and use 'em >>>as often as you want :) >> > >>I don't have a personal utility library. It's on purpose. I don't have >>personalized key bindings. I try to avoid customization. Customization is >>a big part of what makes one programmer's code difficult to maintain by >>another programmer, what makes on programmers's workstation unusable by >>another and makes combining code from several sources difficult. > > > ... > > >>One of the things I like about Python is that it comes with everything in >>the box. > > >> Oren > > > Yet, this very discussion proves that "everything" is not already in > the box. I'll grant that Python includes a very large set of batteries > --- but I'd still say that there are many useful functions and classes > that can still be added. > > Those should start as personal "utility" libraries, be discussed here > and in PEPs, and (when their general utility is established) added to > appropriate (standard or optional) libraries. > > Obviously you don't re-invent the wheel for each project that you join; > you are re-using some code that you've used before, even if it's from > "finger macros." I can see the argument in favor of adapting your > functions to conform to local conventions and every programming team has > to collaborate to find compatible conventions and standards for their > projects. Any non-trivial project (non-trivial, in this case meaning > "requires a *team* of programmers (> 3)) is going to find some elements > of their project that go beyond established coding conventions. The > alternative to "building a (domain/application specific) library" is > to eschew code re-use. > > In this particular case the all() and every() functions that were > presented are elegant and seem useful. As others have pointed out the > implementations are trivial; so the questions become: "does it 'pollute > the namespace' to add them to the core library?" and (if so) "where would > we put them?" You might want to check out mxTools which has quite a few of these gimmicks implemented in C. -- Marc-Andre Lemburg CEO eGenix.com Software GmbH ______________________________________________________________________ Company & Consulting: http://www.egenix.com/ Python Software: http://www.egenix.com/files/python/ Meet us at EuroPython 2002: http://www.europython.org/ From karczma at info.unicaen.fr Wed Jun 19 05:21:57 2002 From: karczma at info.unicaen.fr (Jerzy Karczmarczuk) Date: Wed, 19 Jun 2002 11:21:57 +0200 Subject: Pedagogic advice needed Message-ID: <3D104D35.E0932297@info.unicaen.fr> Dear Snake Charmers, I am going to teach to some biology students (a branch called here "neurosciences"; you may speculate yourself what kind of computation proficiency they need...) - - a comp. sci. course under a buzzword title "Scientific programming". The plan was to use Matlab as the main vehicle. Then after a while it was clear that in order to give to *all* students the possibility to work at home, we need a free programming package, so the idea was to use SciLab. Then I began to digest all that, and the obvious question was: why not Python? == My questions are: 1. Does anybody here have some teaching experience in a similar context? 2. Assuming that the visualisation issues, all kind of plots, graphs *and animations* are very important, how would you organize with Python such a work? Of course I know Numeric Python, Scientific Python modules, and other standard stuff permitting to do all kind of graphic exercices and demonstrations (eg., all the wx bazar). But I *must* avoid the low-level programming, we won't have time for that. We will need a reasonable complete scientific 3D plotting package usable by people without too much experience. I plan to do some non-trivial prog- ramming with rich data structures (otherwise I would stick to Scilab), but a decent *integrated* scientific library, I mean: a framework, not just a set of - powerful but rather atomic - procedures, would be quite useful. (I checked the Obvious Suspects, the Vault of Parnassus, etc., I am veryfing all that stuff, but perhaps some of you know something really succulent and full of vitamines. I need *your experience*, NOT just standard Web links.) Thank you in advance. Jerzy Karczmarczuk Caen, France From hwcowan at hotmail.com Fri Jun 14 15:47:32 2002 From: hwcowan at hotmail.com (Hugh Cowan) Date: 14 Jun 2002 12:47:32 -0700 Subject: Creating Dynamic Web Pages (ZOPE) References: <46ca81a0.0206062016.789d3af6@posting.google.com> <46ca81a0.0206070654.787ac0f7@posting.google.com> Message-ID: <46ca81a0.0206141147.1a0d164@posting.google.com> Hello, > Now, I would slow down a bit. Surely Zope is a good Web tool, and the most > known in the Python world, but it's not the only one. > > Based on your requirements it is likely the best choice for you, but it's > *my* opinion, so you could do worse than to give a look to a few alternative > options: > > Webware (the most J2EE-like, and quite featureful) > http://webware.sourceforge.net/ > > SkunkWeb (smaller, but well endowed) > http://skunkweb.sourceforge.net/ > > Quixote (the smallest, a little jewel, PTLs are a charm) > http://www.mems-exchange.org/software/quixote/ > > All of them within the reach of the Snake, of course. :^) And there's also > Paul Boddie's description of some of them, to save another little bit of > your time: > > http://www.boddie.org.uk/python/web_frameworks.html Wow -- thanks for the additional information and links. It certainly doesn't hurt to look at other solutions, although I am quite happy with what I have seen so far with Zope. I actually didn't think that there were many *other* options out there that were available! Is this sort / type of software what one would classify as "Web Framework"? (as in the above link) I am having difficulty looking for a description or class for this type of software. I haven't had time to try Zope yet, but for instance I am assuming (not always a good thing mind you) that you could create Static web pages (either coding or WYSIWYG). In those terms Zope is an HTML editor -- but I know that it offers a lot more functionality that just creating web-pages. Someone else has mentioned using programs such as Dreamweaver -- but I didn't think that they were in the same class / category of software? Now that you have introduced me to some other software packages (which I will look at) I am just trying to sort out the different types of software (for myself and so that I can better explain why we need more than MS-FrontPage) between Zope (Web Framework), HTML Editors / Coders, and RAD Web development tools. I am sure that there is some overlap between them all but I am just trying to figure out the main differences between them. Thanks again for the help and answers. Hugh, From mutsuura at mutsuura.com Thu Jun 13 09:36:06 2002 From: mutsuura at mutsuura.com (Attila Horvath) Date: Thu, 13 Jun 2002 09:36:06 -0400 (EDT) Subject: Poll: Readable languages In-Reply-To: <3D08810B.2040707@gmx.de> Message-ID: Ingo Though I subscribe to PYTHON and am new to the language, I've programmed for 25+ years and know various languages to varying degrees. At the risk of stirring up everyone's ire [although not my intention], I notice 'assembler' [of any kind] is not on your list of languages. Let me explain... While it sounds ludicrous to include assembler, and I'll not defend assembler as being inherently 'readable', I want to point out that MANY attempts have been made in the past to specify and design 'natural-readable' computer languages - COBOL being among early ones. Since you're polling for opinions I suggest that there is no truth that ANY language has succeeded in being 'readable'. My absurd suggestion that 'assembler' is missing from your list is my attempt at offering an opinion that the 'best' of languages can be made horrifically unreadable while the 'worst' of languages can be made reasonably readable. For proof, see: http://www.ioccc.org/ In my years of experience I have come across VERY readable assembler and very unreadable COBOL, PASCAL, FORTRAN, ADA, C/C++, JAVA, etc. So I suggest that a langauge does not inherently make resultant code readable. Rather the discipline applied by the programmer/author to the work is what inherently makes any piece of work easily understood. I'm sure that even with PYTHON's strict indentation rules, obfuscated contests can easily be held with very clever winning entries! So why 'assembler'? Because, [1]with the plethera of high level languages in existance today none can teach programmers more about the inner workings of both the language and the machine on which it's executed - inner workings like memory usage, CPU cycles, efficiencies, performances, etc.; and [2]ultimately ALL languages executed on ALL machines have to be translated (converted) minimally down to one comman denominator, assembler [even if it's simply for debugging purposes]. Before I'm accused of missing the point, I AM NOT SUGGESTING THAT PEOPLE MUST PROGRAM IN ASSEMBLER. "THAT" would be ludicrous! I am suggesting however that assembler also qualifies for the specific questions you asked! only my opinion, attila PS: My reference to http://www.ioccc.org/ does not imply that "C" is a readable language. On Thu, 13 Jun 2002, Ingo Linkweiler wrote: > Date: Thu, 13 Jun 2002 13:24:59 +0200 > From: Ingo Linkweiler > Reply-To: i.linkweiler at gmx.net > To: python-list at python.org > Subject: Re: Poll: Readable languages > > Poll: > How readable is the code of this languages? > > I do not want to give an exact definition of "readable", but it should > include each of this questions with ~25%: > > - Can someone who has never seen the language before understand what the > program is doing without reference material? > - Can a developer write code that they can return to after six months > and still understand it? > - Can you use this language for teaching basics of programming and for > showing, how an easy algorithm works? > - What is your general optionion about his language? > > 1.) > ----- > ABC: > ADA: > APL: > BETA: > C++: > COBOL: > DELPHI: > EIFFEL: > FORTH: > FORTRAN: > JAVA: > LISP: > MODULA: > PASCAL: > PERL: > PROLOG: > PYTHON: > SML: > SCHEME: > SMALLTALK: > TCL: > VISUAL BASIC: > other ( *name of language * ): > ----- > 2.) > My most used language is: > ----- > > Please vote.... > 1 = Easy to read, like pseudocode :-) > 2 = Good > 3 = Average > 4 = difficult > 5 = nearly impossible, when not knowing the language :-( > blank = I do not know this language or have no opinion. > > Please only vote, if you know at lease 2 languages. > Please reply to : i.linkweiler at gmx.net > > This poll is done for my diploma paper at university of dortmund, germany. > I will not use your e-mail for any purpose. > > Thanks for your help. > Ingo Linkweiler > > PS: I know, that a NG is not the best place for a poll, and some people > do not like questions like this in a NG. > But as I want to get opinions of many programmers, including users of > NGs, I hope you can accept it. > > _ Mutsuura Associates, Inc. /\ \ P.O. Box 1238 / \ \ Vienna, VA 22183 / /\ \ \ / / /\ \ \ E-MAIL: contact at mutsuura.com / /_/ \ \ \ WEB: http://www.mutsuura.com / \ \ / \ \ / /\ \ \/ /\ \ \ MAIN:(703)281-9722 / / /\ \/ / /\ \ \ CELL:(703)863-1933 / / / \ / / \ \ \ FAX :(703)281-9744 / / / \/_/ \ \_\ SBA/SDB CERTIFIED \/_/ \/_/ From schliep at Octopussy.MI.Uni-Koeln.DE Mon Jun 10 06:11:57 2002 From: schliep at Octopussy.MI.Uni-Koeln.DE (Alexander Schliep) Date: 10 Jun 2002 12:11:57 +0200 Subject: Screen resolution again References: <3D039794.9549C54@bellatlantic.net> Message-ID: The following snippet centers a splash screen dialog on the screen. class SplashScreen(Toplevel): ... def CenterOnScreen(self): self.update_idletasks() xmax = self.winfo_screenwidth() ymax = self.winfo_screenheight() x0 = (xmax - self.winfo_reqwidth()) / 2 y0 = (ymax - self.winfo_reqheight()) / 2 self.geometry("+%d+%d" % (x0, y0)) This works on Windows, Linux, MacOS X ... Cheers, Alexander -- Alexander Schliep schliep at zpr.uni-koeln.de From not.this at seebelow.org Thu Jun 13 09:42:57 2002 From: not.this at seebelow.org (Grant Griffin) Date: Thu, 13 Jun 2002 08:42:57 -0500 Subject: why not "'in' in 'in'"? References: <3D080482.7A7FD514@alcyone.com> <3D082A62.CF800C75@seebelow.org> <3D083298.470850D0@alcyone.com> Message-ID: <3D08A161.A9F3136F@seebelow.org> Erik Max Francis wrote: > > Grant Griffin wrote: > > > In that case, perhaps I should have thought of a better one . > > In > > any event, in the case of strings, I think one might stretch the > > concept > > of "membership" to include substrings. In fact, note that since > > Python > > has no actual character type (because a character is adequately > > represented as a string of length one) the "in" operator actually > > _does_ > > test membership of strings in strings. But for some reason, it's > > limited to testing strings of length one. Go figure! > > A string is a sequence of one-character strings. It's not a sequence of > all the subsequences of a string. > > > Honest answer: although I can't see much use for that construct, I > > can't > > see much harm in it either. So although it's probably not worth > > adding > > to Python, I'm sure _somebody_ would find a use for it. > > But that's exactly the problem; if you want [1, 2] in [1, 2, 3, 4] to > return true (i.e., for the `in' operator to test substrings, not just > membership), then you have an ambiguity problem. A list can contain > sublists as elements, after all. > > > But anyway, let's "just say no" to the tuple case rather than confuse > > ourselves; let's just make the string version of "in" a special case. > > Why make a special case for it when string.find and S.find already exist > and are included expressly for that purpose? Again, it has to do with the fact that the illegal multi-character "in" is intuitive and reads better. Compare the following: if 'mortgage' in email_subject: ... to: if email_subject.find('mortgage') >= 0: ... I consider the former to be highly practical, if not highly pure. As to the latter, I frequently made this mistake at first: if email_subject.find('mortage'): ... which is fairly intutitive, but doesn't work, of course, because "find" returns -1 (logical true) in the failure case! That in itself is counter-intuitive--though it makes sense in the context of "find" being intended as a position detector, not a substring tester. (Maybe it should have been called "position" instead...) But the very fact that a failed "find" returns true suggests that we're on the wrong path--at least as far as intuition/readability goes. Originally, I would find myself automatically typing the illegal "in" form (because it's highly intuitive, though illegal), but by now I've nearly trained myself to type the "find" form. But even so, I find it somewhat hard to read. if-i-were-highly-trainable-i'd-be-using-perl--ly y'rs, =g2 -- _____________________________________________________________________ Grant R. Griffin g2 at dspguru.com Publisher of dspGuru http://www.dspguru.com Iowegian International Corporation http://www.iowegian.com From pyth at devel.trillke.net Wed Jun 5 11:48:14 2002 From: pyth at devel.trillke.net (holger krekel) Date: Wed, 5 Jun 2002 17:48:14 +0200 Subject: self In-Reply-To: ; from NKluge@optonline.net on Wed, Jun 05, 2002 at 05:45:01AM +0000 References: Message-ID: <20020605174814.C30696@prim.han.de> Nicola Kluge wrote: > This is an interesting idea. However, your approach doesn't handle the dot > notation. > For example, > If object.x was = to 3 and g was = to 4 I need that > e.f='object.x*g' gives 12. > Just having e=Evaluator({'a':'3', 'b':'a*17', 'c': > 'b*a','object.x':'3','g':'4'}) > doesn't work. While parsing, 'object.x' is not taken as one symbol in your > approach. > I need to have object capabilities in the equations. i think i have to dig deeper into the python sources to see how and if your task could be done cleanly. One of the main problems seems to be that you can't pass your own 'dictish' object to 'eval' or 'exec'. (Actually you can, but the interception points like '__getattr__' don't get called. smells like a bug to me though this might be arguable). And yes, i think that having an explicit 'self' is a very good pythonic idea (tm). i know because i have done some pretty weird stuff like transfering 'locals()' into the self-dict and back but it often isn't worse it. have fun, holger From skip at pobox.com Sun Jun 16 20:28:12 2002 From: skip at pobox.com (Skip Montanaro) Date: Sun, 16 Jun 2002 19:28:12 -0500 Subject: xmlrpclib/python and fault codes In-Reply-To: <20020616220103.85789.qmail@web20801.mail.yahoo.com> References: <20020616220103.85789.qmail@web20801.mail.yahoo.com> Message-ID: <15629.11548.588323.859686@12-248-41-177.client.attbi.com> Derek> Can anyone out there tell me how to check for a fault Derek> response from an xml-rpc server using the xmlrpclib Derek> python module? Does something like this work? try: server.method(args) except xmlrpclib.Fault, f: print "code:", f.faultCode print "string:", f.faultString If the faultCode isn't helpful, you can pick apart the faultString. -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From cliechti at gmx.net Sat Jun 29 16:38:17 2002 From: cliechti at gmx.net (Chris Liechti) Date: 29 Jun 2002 22:38:17 +0200 Subject: Win32/Python serial port event character problem References: Message-ID: Derek Basch wrote in news:mailman.1025380000.22796.python-list at python.org: > Sorry to post this again but it didn't get any > responses. Maybe better luck this time. well 14hrs isn't that much time on a weekend... some people only look into news once per week. > I use the following code to read data from the serial > port when a certain event character ('\n') is > received: ... > Has anyone ever dealt with this? Is using the event > character not a reliable method in windows? no sorry, i haven't used the event mode. .... > This is driving me batty so any help is greatly > appreciated. my tip is: use http://pyserial.sf.net and read the characters in a separate receiver thread. that thread can then trigger on any character or sequence (e.g. using a Queue to communicate with other threads) -- http://pyserial.sf.net Chris From maxm at mxm.dk Tue Jun 25 17:45:39 2002 From: maxm at mxm.dk (Max M) Date: Tue, 25 Jun 2002 23:45:39 +0200 Subject: ASP only runs once References: <3842735a.0206251112.25609e37@posting.google.com> Message-ID: <3D18E483.3040808@mxm.dk> Michael Anderson wrote: > I've been using python in my asp pages for over a year now with no > problems, and just ran into a problem I can't figure out. I installed > it on a new machine and my pages only run the first time you hit them. > After that they do nothing. Pages in VBScript and JavaScript run fine. I am short of time so short answer. It's a known problem with a workaround. Please search Google for answer. regards Max M From peter at engcorp.com Tue Jun 25 08:15:39 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 25 Jun 2002 08:15:39 -0400 Subject: ntohl/htonl socket transfer between c and python References: Message-ID: <3D185EEB.107547E@engcorp.com> "Eivind B. Nilssen" wrote: > > I have a bit of a problem I cant seem to solve. I am new at > programming python, > and my task is to make a client in python for fetching data from a > remote server written in c. > > The buffer sendt to me from the server is generated as follows: > > *(int*)&bfr[bix] = htonl(*(int*)&f); #where f is a float value > > The buffer received in my python program is a lot of strange asciis > I am not able to cast this buffer to an int or a long and this again > makes > me unable to apply the ntohl command. > > Does anybody have an idea how to extract the data from this buffer? > Do I have to write this part in C? No, you don't have to write it in C. But please, always, post code snippets from your own code showing the problem. If possible, use the interactive console to execute a few of your methods and show the resulting data, or add some print statements to the code to make it clear what's happening. Without code to look at, we're going to waste a lot of time providing answers "shotgun" fashion, only some of which will hit the mark... -Peter From feldspar at ix.netcom.com Sun Jun 30 18:37:55 2002 From: feldspar at ix.netcom.com (Antaeus Feldspar) Date: Sun, 30 Jun 2002 19:37:55 -0300 Subject: Python needs to explain parsing? was Re: Python needs better error reporting References: Message-ID: <3D1F8843.8080602@ix.netcom.com> After reading the thread spun out of all of this, this brings up an idea that I've had for quite some time: can the Python interpreter be made to report more information about *how* it is parsing the syntax it finds? For instance, given the valid line "if s == ' ':" it might return something like the following (or at least this might be what is displayed to the user based on information the parser displays): if : ---- [next 8 lines of code] | == / \ / \ s ' ' thus confirming that what was meant to be a condition is being parsed as a condition. Clearly if the user sees that the parser is putting the block of code to be conditionally executed in where the condition should be, that's a very visual sign of trouble... It's not quite the solution David seems to be looking for, but I think it would address the same problem; is it possible? David LeBlanc wrote: > "Syntax Error: invalid syntax" isn't very informative, yet it's tossed out > frequently. HOW is the syntax invalid? For example: > if s == ' ' > > David LeBlanc > Seattle, WA USA > > > > From r_proietti at yahoo.com Thu Jun 20 11:17:15 2002 From: r_proietti at yahoo.com (NOPollution) Date: Thu, 20 Jun 2002 15:17:15 GMT Subject: module string.py References: <3d11bd6a.11177520@news.polito.it> Message-ID: <3d11f18b.24524431@news.polito.it> On Thu, 20 Jun 2002 14:15:06 +0200, Gerhard =?iso-8859-15?Q?H=E4ring?= wrote: >Hi "Nop", > >* NOPollution [2002-06-20 11:38 +0000]: >> I have two trouble: >> >> 1) looking at the module "string.py" I have seen that are described >> some functions like "lower", "rjust", etc. Ther problem is that it >> seems not to describe exactly how this functions are made, but there >> is only a comment about their properties. So in which file are these >> functions described? > >The behaviour of these functions is described in the documentation, for >example in http://www.python.org/doc/current/lib/module-string.html: > >lower(s) >Return a copy of s, but with upper case letters converted to lower case. > >In this particular case, the docstring of the function has just as much >info: > >>>> string.lower.__doc__ >'lower(s) -> string\n\n Return a copy of the string s converted to >lowercase.\n\n ' > >If you're looking at additional info for _how_ exactactly these >functions are implemented, then the source code is the only info there >is. Where could I find the source code of the functions implemented in "string.py"? > Btw. in current Python versions the string module just delegetages >to the string methods, which are the preferred option. So you could just >as well use. > >> 2) I tried to cancel the file "string.py". After that, the Python >> Interpreter doesn't work anymore (it can't even start working). Why? > >You're not supposed to delete modules from the standard library. If you >don't want your Python to fail in obscure ways, you'd better get that >file back into place. Btw. my Python 2.1.3 and 2.2.1 starts up fine >even without the string module. > >Gerhard >-- >mail: gerhard bigfoot de registered Linux user #64239 >web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 >public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 >reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) > > From mgerrans at mindspring.com Fri Jun 7 05:08:38 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Fri, 7 Jun 2002 02:08:38 -0700 Subject: How do you read unicode files? References: Message-ID: Thanks Mike, Francis and Martin for the quick replies! My mistake was using readlines() to read the text file, instead of read(). (I should have posted a snippet of code in the first place and probably you all would have noticed that immediately). - Matt From marklists at mceahern.com Wed Jun 12 17:19:19 2002 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 12 Jun 2002 16:19:19 -0500 Subject: get a list of classes in this module In-Reply-To: Message-ID: [Terry Reedy] > I believe the name of a modulue is the same inside as out. I do not > know inspect or whether it can work on a module under construction. > However, if the subclasses are too numerous to build the dict by hand, > or the set so dynamic that you do not trust yourself to update it > properly... Yeah, it's not so much that I don't trust myself--there's that. ;-) But it's also the simple DRY principle at work. Why should I have to list the classes in that factory-like dictionary when Python can do that for me? Thankfully, I didn't have to resort to globals()--but took advantage of Python 2.2's __subclasses__ (which requires subclassing the base class from object). That worked smoov. Thanks, // mark - From jiri at baum.com.au Sat Jun 1 06:35:07 2002 From: jiri at baum.com.au (Jiri Baum) Date: Sat, 1 Jun 2002 20:35:07 +1000 Subject: Python and HTML frames References: Message-ID: Ken: > How do I output HTML onto frames? This code below doesn't work. Can > someone help me? This isn't really a python question, it's a HTML question (or possibly HTTP; are you ouputting the right headers?). However, I should note that setting scrolling to "no" is a really, really bad idea unless the frame contains just an image, because not all people have the same-sized fonts. I trust you've read the guidelines for using frames at www.useit.com ? Briefly: don't, and if you have to, make all links TARGET="_top". > == > def mainpagelayout(): > print """ > Languages Dictionary > > > > > > > You're missing a here, and your <body> tags are in the wrong place, but in any case this message is so useless that it beggars belief. The basic point of the web is to communicate: to get information from one person to another. Design of web pages should be guided by this goal. If it isn't, then it becomes an impediment and the whole exercise pointless. In any case, anyone who is shown this image will go away in disgust. You might as well not have it. If your page really, really needs frames (and I doubt it), at least apologise here and explain why. > <body>This page doesn't work without a frames-enabled > browser.</body> > > """ Jiri -- Jiri Baum http://www.csse.monash.edu.au/~jirib MAT LinuxPLC project --- http://mat.sf.net --- Machine Automation Tools From logiplexsoftware at earthlink.net Wed Jun 19 13:01:36 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Wed, 19 Jun 2002 10:01:36 -0700 Subject: python version? In-Reply-To: References: Message-ID: <20020619100136.27e40780.logiplexsoftware@earthlink.net> On Wed, 19 Jun 2002 09:20:44 -0500 Mark McEahern wrote: > Instead, you've probably got people wondering whether we will yet > Rue the day. ;-) You realize that if Rue's name is mentioned one more time, he'll reappear in a puff of autocoding to berate us for preventing him from writing software. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From gerhard at bigfoot.de Fri Jun 28 08:10:21 2002 From: gerhard at bigfoot.de (Gerhard Haering) Date: 28 Jun 2002 12:10:21 GMT Subject: GUI-Control for HTML References: <3D1C4B40.6090803@thomas-guettler.de> Message-ID: In article <3D1C4B40.6090803 at thomas-guettler.de>, Thomas Guettler wrote: > Hi! > > Is there are GUI-control which can display HTML? > > The HTML that will be used will be simple, no javascript or > form support is needed. > > Is there are cross-plattform solution? (Unix + Win32) Yes, wxPython is available on these platforms, and has a HTML component. There might be a HTML viewer add-on for Tkinter, too. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From phlip_cpp at yahoo.com Mon Jun 17 22:26:55 2002 From: phlip_cpp at yahoo.com (Phlip) Date: 18 Jun 2002 02:26:55 GMT Subject: ANN: PyUnitTestBrowser 006 Message-ID: PyUnit Enthusiasts: The latest feature is integrated grep. This means if your editor does not have multi-file search, we do. http://flea.sourceforge.net/BrowseMe.html http://flea.sourceforge.net/browser006.zip http://www.c2.com/cgi/wiki?PyUnitTestBrowser PyUnitTestBrowser is a GUI TestRunner for PyUnit that integrates, round-trip, with Kate, Idle or Vim. The ChangeLog: 005 bonds with PyChecker 004 arbitrarily complex command lines 003 does not require test suites 002 does Windows 001 exists -- Phlip http://www.greencheese.org/ParodyMode -- Appears that VIM is internationalized... May I ask what's the point? -- From kragen at pobox.com Sat Jun 15 14:59:28 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 15 Jun 2002 14:59:28 -0400 Subject: Args not set in extension class References: Message-ID: <83sn3otlkf.fsf@panacea.canonical.org> "Gorny" writes: > I've already dealt with the problem... Just create a function like: > > static PyObject * > wrap_pkt_object(PyObject *self, PyObject *args) > { > PyObject * return_object; > return_object = new_pkt_object(args); > return return_object; > } > > But it would be very nice if someone can explain to me, why this > is happening and it isn't possible to *directly* call new_pkt_object even > if you prototype the latter function with two arguments like > wrap_pkt_object! If you prototype new_pkt_object with two args, make sure you're using the second one. From eager at eagercon.com Mon Jun 10 11:22:57 2002 From: eager at eagercon.com (Michael Eager) Date: Mon, 10 Jun 2002 08:22:57 -0700 Subject: import problem References: <2se7guc3kkmm3bgooj776j55igpkmgpst4@4ax.com> Message-ID: Thanks. It was trying to open libsip.so, not looking for libsip.so.*. Adding the link makes this problem go away (and another show up). On Sun, 09 Jun 2002 21:56:28 GMT, "Erlend J. Leiknes" wrote: >if you have the debugging application strace (its most likely you have it) > >write a small application who only does: from qt import * > >save it, run it like this: strace python your_app.py 1> log1.txt 2>log2.txt >wait for it to finnish, and edit log2 (or log1).txt, scroll to the bottom, >and look for io signales that tries to open libsub.so.* >now you should find out what your filename should be. > >"Michael Eager" wrote in message >news:2se7guc3kkmm3bgooj776j55igpkmgpst4 at 4ax.com... >> I'm trying to use Python 2.2 and PyQt on a RedHat-7.2 system. >> >> I get an error when I execute "from qt import *" -- there is a failure >> in qt.py when it executes "import libsup". The error is "No module >> named libsup". >> >> libsup.so.9 is a link to libsup.so.9.0.3 and is in >> /usr/lib/python2.2/site-packages. If I enter "import libsup", I get >> the same error message. >> >> Any suggestions? >> >> -- Mike Eager, eager at eagercon.com > From inkedmn at earthlink.net Fri Jun 7 22:52:28 2002 From: inkedmn at earthlink.net (inkedmn at earthlink.net) Date: Sat, 08 Jun 2002 02:52:28 GMT Subject: Working with directory References: <20020526.145248.1350573793.20446@iprimus.com.au> <83lma3udjf.fsf@panacea.canonical.org> Message-ID: <3d016fbf.529655106@news.earthlink.net> On 28 May 2002 18:13:08 -0400, Kragen Sitaker wrote: >"Occean" writes: >> I have to write the function that read in to the existing directory and >> display some files according to their date for example, in my PyExample >> directory i got >> >> practice1.py Thu Mar 16 11:54:21 2002 >> practice2.py Thu Mar 17 10:25:22 2002 >> .. >> practice7.py Friday Apr 28 1:20:22 2002 >> >> i want to just get 2 files from that directory which are from Mar or >> specific time only. How can i do that, and which built in function allow >> me to view all the file in directory with time. By looking the reference >> os.time.stat but i can't work out the solution for this problem. > >os.listdir(dirname) lists the directory. > >os.stat(pathname)[stat.ST_MTIME] is the modification time of the file, >as a number of seconds since 1969 GMT. > >time.localtime(nsecs) converts a number of seconds since 1969 GMT into >a tuple giving year, month, day, etc. > >os.path.join(dirname, filename) will be useful in combining the stuff >you get back from os.listdir into full pathnames you can pass to >os.stat. > >So you want a loop something like this: >import os, time, stat >dirname = '.' >for filename in os.listdir(dirname): > date = time.localtime(os.stat(os.path.join(dirname, filename))[stat.ST_MTIME]) > if date[1] == 3: # element 1 is month > print filename, time.asctime(date) > >HTH. > hello... formatting the date/time is pretty easy if you use the asctime method in the time module. like this: >>> import time >>> x = time.asctime() >>> print x Fri Jun 07 19:46:18 2002 one of my personal favorites :) hope this helps ink From pixie888 at hotmail.com Thu Jun 20 03:11:01 2002 From: pixie888 at hotmail.com (pixie888 at hotmail.com) Date: Thu, 20 Jun 2002 07:11:01 GMT Subject: SafeArray problem References: <3d105710.83643750@news.skynet.be> <3d108014$1@news.mhogaming.com> <3d108545.95472593@news.skynet.be> <3d10a3fa$1@news.mhogaming.com> Message-ID: <3d117f5f.159498312@news.skynet.be> On Wed, 19 Jun 2002 11:28:36 -0400, "Michael Weiss" wrote: > >> I have not written an idl-file myself, I just used the classwizard in >> Visual Studio to write my method on the automation object (using MFC). >> What do you really want to know? (I looked for idl-files in my project >> but did not find any) > >How about an ODL file? not found too, I guess that when you use MFC in combination with the Classwizard things are handled hidden for the programmer. Nonetheless: I give you the following information for the better of it: im my .h file afx_msg LPDISPATCH GetRelationQuerierEx(const VARIANT FAR& vaIDs,long lDummy); the first argument is the safearray, the second the long in my .cpp file DISP_PROPERTY_PARAM(CDispCore, "RelationQuerierEx", GetRelationQuerierEx, SetNotSupported, VT_DISPATCH, VTS_VARIANT VTS_I4) > >I was just wondering if the in, in/out, retval, pointer vs. non-pointer >symantics of the parameter were wrong. I was guessing by adding a new >parameter (the long) that the safearray's properties were changed for the >better. But I guess with a pure Dispatch interface (dispinterface) that this >kind of stuff isn't done, or at least its done differently. > >Still, I wonder if this still isn't the problem of the function not being >declared correctly before you made the change and then when you added that >long the declaration of the safearray was changed. > > > > > From plugin at supercable.es Mon Jun 24 11:38:46 2002 From: plugin at supercable.es (Ugo García) Date: Mon, 24 Jun 2002 17:38:46 +0200 Subject: Redirecting StdOut References: <1024856420.145085@seux119> <1024860416.580309@seux119> <3D163550.E525D840@engcorp.com> <1024873013.652528@seux119> <3D1678F3.AD9B059B@engcorp.com> Message-ID: <1024933181.665516@seux119> > You'll doubtless get other replies on this, including pointers to PyGame. > What makes you think a game implemented in Python will not have > enough speed? You certainly would not be writing the low level > graphics routines in Python, but then you aren't about to do that > in C, either (I sincerely hope). Python can call on libraries > which have already been written *in C* (usually) to do the grunt > work, so it is quite fast enough. I've seen PyGame but It still doesn't like. The idea of making a game in a interpreted language doesn't like very much. (Is like making a game in Visual Basic). Perhaps I'm used to make games with C (and of course, asm) or, perhaps this is the right way to do it. Do u know many games that are made with an interpreted languaged? I don't. (I'm talking about GAMES, not little demos). Well, I known one: BLADE. It use Python to define the world, the behavour of the characters, and other things like the save games... If u have test it u could agree that it's extremely sloowly when loading (don't know if it's because it use Python or because the coders as Spanish, like me.... :-) ). > As for reliable, I have to most vigorously object to anyone > characterizing C as "reliable". C code is notoriously difficult > to make reliable, generally being strewn with pointer bugs, > memory allocation problems, and so forth. C was really written > only as a somewhat more human-readable Assembly language substitute > and has been supplanted by many more suitable alternatives for > something as sophisticated as the engine of a game. (ufff. very difficult to understand by my poor English... Let see...) I agree that C is more complicated than other languages; more complicated to code and more complicated to debug. But... What engines do u know are written in another language instead of C? (Perhaps we're are naming 'engine' to different thing) > Or to put it another way: don't knock it till you've tried it! > Python is quite possibly a far more suitable solution for > the entire application, not just for the scripting language. I agree again. I've to try other alternatives before deciding.... but I have already try another.... and I'm still see Python as a script language for a engine, not for the whole engine (it depend, of course, in the kind of the engine). Don't know, perhaps most people who write engines are wrong (i think they're written in C), or perhaps I'm wrong. This is the goal of the forums... to get the right way!!! :-) Thanks, --ugo From dmitri.gouliaev at telkel.net Thu Jun 6 20:18:27 2002 From: dmitri.gouliaev at telkel.net (Dmitri I GOULIAEV) Date: Thu, 6 Jun 2002 19:18:27 -0500 Subject: urllib, urllib2, httplib -- Begging for consolidation? In-Reply-To: ; from "John J. Lee" on Thu, Jun 06, 2002 at 10:55:07PM References: Message-ID: <20020606191826.A17584@lifebook> Hi, John J. Lee ! On Thu, Jun 06, 2002 at 10:55:07PM +0100, John J. Lee wrote: > On Wed, 5 Jun 2002 brueckd at tbye.com wrote: > > Problem #1 is what makes me throw my hands up in frustration when we talk > > about, e.g., expanding the urllib APIs to have some way to do a HEAD > > request: it doesn't belong on that level of functionality. > I think you mean "it doesn't belong in a module named 'urllib2'"... or at > least you should mean that ;) In my opinion, he means that. And, by the way, "it doesn't belong in a module named 'urllib2'" because I would assume, that module named urllib* works with URLs. Am I wrong ? [...] > > That generic > > interface is for making it trivially easy to fetch the contents associated > > with a URL, independent as much as possible from protocol. > Only part of urllib2 (OpenerDirector &c) is a generic any-old-url-scheme > API. The rest (eg. AbstractHTTPHandler, HTTPRedirectHandler) is > HTTP-specific, and can be used on its own, without going through the > generic stuff. What does HTTP-specific stuff inside urllib-module ? Why is it there ? Why not in httplib ? Best regards, -- DIG (Dmitri I GOULIAEV) All below this line is added by my e-mail provider. From ark at research.att.com Fri Jun 7 13:28:48 2002 From: ark at research.att.com (Andrew Koenig) Date: Fri, 7 Jun 2002 17:28:48 GMT Subject: Python 2.2.1 vs. gcc 3.1? References: Message-ID: Incidentally, there is something suspicious here: gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -I. -I/tmp/build-gnu913/Python-2.2.1/./Include -I/usr/local/include -IInclude/ -c /tmp/build-gnu913/Python-2.2.1/Modules/structmodule.c -o build/temp.solaris-2.8-sun4u-2.2/structmodule.o creating build/lib.solaris-2.8-sun4u-2.2 gcc -shared build/temp.solaris-2.8-sun4u-2.2/structmodule.o -L/usr/local/lib -o build/lib.solaris-2.8-sun4u-2.2/struct.so WARNING: removing "struct" since importing it failed That -L/usr/local/lib does not look right, because /usr/local/lib does not exist on my machine. In particular, I began the whole process by saying configure --prefix=/usr/gnu The /tmp/build-gnu913 directory is where I'm actually building everything, so that's as it should be. -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From spammers.do.not.bother at void.bogus Sat Jun 1 14:38:37 2002 From: spammers.do.not.bother at void.bogus (Magnus) Date: Sat, 01 Jun 2002 18:38:37 GMT Subject: Copying a database References: Message-ID: Billy Ng wrote: > I need you guys help on mysql again. I need to push my python program to > production now, but I don't want to recreate the mysql database on the > production box. I want to copy the database from the development box to > production box.. Would anybody please tell me how to do it, thanks! > > Billy Ng Maybe this is what you are looking after: http://www.mysql.org/documentation/mysql/bychapter/manual_MySQL_Database_Administration.html#mysqldump http://www.mysql.org/documentation/mysql/bychapter/manual_MySQL_Database_Administration.html#mysqlhotcopy http://www.mysql.org/documentation/mysql/bychapter/manual_MySQL_Database_Administration.html#mysqlimport /Magnus From martin.oberhuber at windriver.com Thu Jun 20 07:58:47 2002 From: martin.oberhuber at windriver.com (Martin Oberhuber) Date: Thu, 20 Jun 2002 13:58:47 +0200 Subject: Java to Python converter? Message-ID: Hi all, I've got some Java source code that I would like to convert into Python. Does anybody know of a converter that can do this? Thanks, Martin From trentm at ActiveState.com Wed Jun 26 13:55:17 2002 From: trentm at ActiveState.com (Trent Mick) Date: Wed, 26 Jun 2002 10:55:17 -0700 Subject: question od default args In-Reply-To: ; from shalehperry@attbi.com on Wed, Jun 26, 2002 at 10:48:56AM -0700 References: Message-ID: <20020626105517.B28810@ActiveState.com> On 26-Jun-2002 Gon?alo Rodrigues wrote: > Hi, > > When I want default args I usually do > > def (arg = None): > ... > > But what if I want to make None a reasonable argument too? That is, I > want to know if the user has in fact passed an argument, and if not to > do something special, with None (or whatever object) being a reasonable > arg to be passed. You could try something like this: >>> class _NoArgSpecified: ... pass ... >>> def foo(arg=_NoArgSpecified): ... if arg is _NoArgSpecified: ... print "no arg specified" ... else: ... print "arg:", repr(arg) ... >>> foo() no arg specified >>> foo(None) arg: None >>> foo(1) arg: 1 Mind you, the user *can* still cheat, but you shouldn't have to worry about that. >>> foo(_NoArgSpecified) no arg specified >>> Trent -- Trent Mick TrentM at ActiveState.com From dyoo at hkn.eecs.berkeley.edu Fri Jun 28 17:02:17 2002 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Fri, 28 Jun 2002 21:02:17 +0000 (UTC) Subject: get word base References: Message-ID: John Hunter wrote: : I would like to be able to get the root/base of a word by stripping : off plurals, gerund endings, participle endings etc... Hi John, PyWordNet has a function in it called wntools.morphy() which tries to take the morphological root of a word. For example: ### >>> import wntools >>> words = ['hello', 'taxes', 'thoughts', 'walked', 'rakes'] >>> for w in words: print wntools.morphy(w) ... hello tax thought None rake ### morphy() doesn't quite work out of the box, but just because it doesn't guess the part of speech --- morphy() assumes that we want the noun root by default. But then, we can do something like this: ### >>> def root(w): ... return wntools.morphy(w, "noun") or wntools.morphy(w, "verb") ... >>> root("walked") 'walk' >>> root("sent") 'send' >>> root("woke") 'wake' ### So PyWordNet is a really useful tool if you're doing this sort of stuff. PyWordNet and Wordnet can be found here: http://pywordnet.sourceforge.net/ http://www.cogsci.princeton.edu/~wn/ Best of wishes to you! From garrett at bgb.cc Thu Jun 6 16:31:58 2002 From: garrett at bgb.cc (Don Garrett) Date: Thu, 06 Jun 2002 20:31:58 GMT Subject: Using AT on XP to run python script References: Message-ID: <3CFFC694.9000501@bgb.cc> Change "c:\python21\python.exe c:\scripts\script.py" to "c:\python21\python.exe" "c:\scripts\script.py" otherwise it's trying to turn that whole thing into a single file name. However, I would have expected the last thing you tried to work. Try using /interactive just for testing. It may be trying to open a command window or something. Maybe name the script .pyw Chris Stromberger wrote: > I'm having trouble getting AT on XP to run a python script for me. > Have tried: > > at xx:xx "c:\python21\python.exe c:\scripts\script.py" > at xx:xx "start c:\scripts\script.py" > at xx:xx "c:\scripts\script.py" > > and get "the system cannot find the file specified" for the first two. > The last version does nothing apparently--no error indication or > anything. > > I imagine it is related to user accounts and such. Anyone have any > pointers? > From peter at engcorp.com Mon Jun 17 20:45:02 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 17 Jun 2002 20:45:02 -0400 Subject: Python 2.2.1 References: Message-ID: <3D0E828D.B930932A@engcorp.com> > Dave wrote: > > Hi, I am 12 years old and would like to begin learning Python > over the summer. Hi Dave! I sure wish I'd discovered Python when I was twelve... of course, it didn't exist yet. :-( Other replies have already covered the core question, so I'll add two off-topic comments. 1. Please try to turn off "HTML" mode when posting messages here. The messages are mirrored to the ASCII-based Usenet newsgroup comp.lang.python (in case you're using the mailing list) and non-ASCII messages are a problem for many readers. In Outlook you can do this under the menu Tools -> Options -> Mail Format. 2. Please reply to let people know you've succeeded in following their advice. The payback for all the folks who spend their time replying to questions comes when they know their efforts paid off for the original poster! Good luck, :-) -Peter From aahz at pythoncraft.com Wed Jun 26 12:57:12 2002 From: aahz at pythoncraft.com (Aahz) Date: 26 Jun 2002 12:57:12 -0400 Subject: Python 2.2 __slots__ Bug? References: Message-ID: In article , Glyph Lefkowitz wrote: > >I get "I'm fine" and then a segmentation fault. This only happens when >__slots__ is defined on a new-style class. Seriously, i'm not making >those numbers up -- reliably, 43551 objects will crash the interpreter; >fewer will not. Interesting. Using Python 2.2.1 on Mandrake 8.1, I get a segfault without printing "I'm fine". Go ahead and file a bug. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From Norman_Shelley-RRDN60 at email.sps.mot.com Thu Jun 20 12:32:34 2002 From: Norman_Shelley-RRDN60 at email.sps.mot.com (Norman Shelley) Date: Thu, 20 Jun 2002 09:32:34 -0700 Subject: Useful RE patterns (was: Variable Interpolation - status of PEP 215) References: <4PfQ8.44245$n4.10307683@newsc.telia.net> Message-ID: <3D1203A2.B2A3AD9@email.sps.mot.com> Fredrik Lundh wrote: > ... > If I were to add a dozen (or so) patterns to the (S)RE module, > what should I pick? What patterns do you find yourself using > over and over again? All kinds of numerics, e.g. scientific (1e-6, 2e6, ...) and engineering (1u, 2M and/or 2MEG, ...) notation. Python identifiers as previously mentioned. > > > From steve.bond at btinternet.com Wed Jun 19 11:11:22 2002 From: steve.bond at btinternet.com (Steve) Date: Wed, 19 Jun 2002 15:11:22 +0000 (UTC) Subject: newbie: help please! References: Message-ID: Cheers Chris it was exactly as you said i'm so happy now! i just installed the two RPM's X11R6-contrib & XFree86-devel and updated my setup file and it worked!, thanks again Steve From boud at valdyas.org Tue Jun 4 01:12:10 2002 From: boud at valdyas.org (Boudewijn Rempt) Date: Tue, 04 Jun 2002 07:12:10 +0200 Subject: different gui-toolkits pros/cons... References: <_rLK8.12$fd2.979@news.ecrc.de> <3cfbc67b$0$52024$e4fe514c@dreader3.news.xs4all.nl> Message-ID: <3cfc4c59$0$52032$e4fe514c@dreader3.news.xs4all.nl> Uwe Schmitt wrote: > Boudewijn Rempt wrote: > | Uwe Schmitt wrote: > > |> Markus Jais wrote: > |> | with pyQT there might be problems with the license > |> | if you want to make your programm freely available > |> | (but I am not a lawyer, so I might be wrong) > |> > |> That's a very important point: what do I have to pay if I used pyQt > |> for development ??? I did not find any explicit prices at the > |> trolltec-page... > > | Trolltech doesn't sell PyQt: you need to go to http://www.thekompany.com > | for BlackAdder. > > O.K. But what if I only want pyQt ??? I suppose I have to pay Qt... > Buying Qt for Windows and then compiling your own PyQt from source is more expensive than buying BlackAdder, but it can be done -- order the Qt from TrollTech, download your own PyQt, and make sure you've got a supported C++ compiler. -- Boudewijn Rempt | http://www.valdyas.org From bobx at linuxmail.org Thu Jun 13 12:33:45 2002 From: bobx at linuxmail.org (Bob X) Date: Thu, 13 Jun 2002 16:33:45 GMT Subject: Wanted: Potential Python Authors References: Message-ID: <3D08C96B.1020509@linuxmail.org> Sheesh...and all he wanted was some potential authors and we debate it to death! : ) Jeff Donahoo wrote: > I'm looking for somebody to author a short book on Python in my programming > technology series. Who do you think would make a great author that hasn't > already written a book on Python? Candidates include: > > - Competent and frequent posters to this newsgroup > - Author of articles in the various trade magazines > - Expert programmer > > From ken at hotmail.com Sat Jun 1 02:43:01 2002 From: ken at hotmail.com (Ken) Date: Sat, 1 Jun 2002 16:43:01 +1000 Subject: How to open a HTML file when the python cgi program is executing? Message-ID: How do I open a HTML file when the cgi program is executing? The only method I can think of, which doesn't work is this: From garrett at bgb.cc Mon Jun 10 12:12:10 2002 From: garrett at bgb.cc (Don Garrett) Date: Mon, 10 Jun 2002 16:12:10 GMT Subject: wxPython performance References: Message-ID: <3D04CF8D.4050407@bgb.cc> RPM1 wrote: > "Andrei Kulakov" wrote > >>Hello, >> >> "hello world" type program from wxPython tutorial takes 6 >>seconds to start on my cel 366 128mb system (running Debian). Is >>this typical? Why is it so slow? I'm looking for a graphic >>toolkit that'd be fairly quick. I don't want to use Tk because of >>the looks. This whole thread is somewhat strange.... one of the things I liked about wxWindows was that it seemed like one of the snappier cross plateform libraries I've worked with. I'm on a relatively fast machine (1 Ghz with 512M) with Windows (which has been mentioned here as having a faster start). The first start up has touch of delay (less than most commercial apps), but after that it's instant. I guess it's hard to really remember just how much faster computers have gotten over time. -- Don Garrett http://www.bgb.cc/garrett/ BGB Consulting garrett at bgb.cc From kragen at pobox.com Thu Jun 13 17:21:06 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 13 Jun 2002 17:21:06 -0400 Subject: M2Crypto: select() behaves weird on SSL sockets References: <3D04ED17.5070606@NOSPAMREMOVETHISxs4all.nl> <3D066E77.4070901@NOSPAMREMOVETHISxs4all.nl> <3D0790E1.9080904@NOSPAMREMOVETHISxs4all.nl> Message-ID: <831ybavprx.fsf@panacea.canonical.org> Irmen de Jong writes: > Ng Pheng Siong wrote: > Well, I would appreciate a wrapper around select.select, one that > acts on SSL sockets the way I expected (from the man page of select). > That means: a select() wrapper that > 1) works on regular files and sockets > 2) works on SSL sockets > 3) in the case of SSL sockets, honors the pending bytes that might still > be available after a recv() (or send): don't block but return the > socket in the 'read' or 'write' list if bytes are pending... > > This would greatly simplify my socket reading/writing functions... Irmen, why aren't you using asyncore? For those of us who use asyncore, an asyncore.dispatcher-compatible wrapper around an M2Crypto socket that you could hand to asyncore and hang handlers on would probably be sufficient. From bokr at oz.net Mon Jun 17 22:58:38 2002 From: bokr at oz.net (Bengt Richter) Date: 18 Jun 2002 02:58:38 GMT Subject: Divorce property objects from attribute access dependency? References: Message-ID: On Mon, 17 Jun 2002 12:49:06 -0500, Gustavo Cordova wrote: >> >> >>> class C(object): >> ... def __init__(self,v): >> ... self._v = v >> ... def get_v(self): return self._v >> ... def set_v(self,v): self._v = v >> ... v=property(get_v,set_v) >> ... vlist = [v,v] >> ... >> >>> c=C('something') >> >>> c.v >> 'something' >> >>> c.v='other' >> >>> c.v >> 'other' >> >>> c.vlist >> [, ] >> >>> c.vlist[0] >> >> >> Why not trigger get_v() in these accesses too, and have >> single mechanism to suppress it instead of a single >> mechanism to effect it? >> > >You mean that you don't recognize the difference between >evaluating "c.v" and "c.vlist"? > No, I don't mean that ;-) Also notice that I accessed c.vlist[0] to make a more direct analogue to c.v: (BTW, disev below is just a handy thing to compile and disassemble an expression) >>> from miscutil import disev >>> c.v 'something' >>> c.vlist[0] >>> disev('c.v') 0 SET_LINENO 0 3 LOAD_NAME 0 (c) 6 LOAD_ATTR 1 (v) 9 RETURN_VALUE >>> disev('cvlist[0]') 0 SET_LINENO 0 3 LOAD_NAME 0 (cvlist) 6 LOAD_CONST 0 (0) 9 BINARY_SUBSCR 10 RETURN_VALUE The byte code itself is apparently not what makes the difference between property or other attribute access. Apparently LOAD_ATTR checks to see if the attribute-referenced object is a property or not (and I suspect as far as LOAD_ATTR is concerned, any class attribute that dereferences to an instance of a class that has a __GET__ method might do). What I'm saying is that (e.g.) BINARY_SUBSCR etc. could potentially also check on whether what it was retrieving has a __GET__ method, if there were a different mechanism tying a property to an object than via the attribute mechanism, so that object's "self" could be passed to the __GET__ method of the property object. >Well, for one: > >"c.v" is evaluated at runtime, and it's recognized as >an instance's access to a class' property attribute, >so all the background magic happens (which is what >you expected). Just a note: get_v and set_v are >methods, which take "self", and all that. Ok. > >On the other hand, "vlist" is created at compile >time, and it's a list, not a property attribute; >it's only a list with two objects. When you're >evaluating "c.vlist", the items in the list are not >in the correct context to be evaluated as property >attributes, so the background magic does not happen. IMO "correct context" refers to the current state fo affairs, not a technical limitation. I am trying to suggest "divorcing" properties from that "correct context" -- for the sake of discussion;-) The reason vlist items are printed is that they *are* accessed. UIAM, first as objects, and then normally the '__repr__' attribute is accessed to get a method to convert the object to a string representation (or __STR__ if exlicit str() or '%s'% is involved). However, in the case of a property-jiggered class attribute access, something apparently discovers that the object is a property object, and instead of looking for a __repr__ attribute immediately, attribute access is coded to evaluate the property's __GET__ first (with the attribute-search's associated object 'self' as argument), and *then* with the result of that - not the property object any more -- proceed to look for __repr__ to get the string to print. Note that it's a matter of attribute access per se looking at an object, not looking for a particular name. If we bind an alternate attribute name to C.v's property object as well as using a list, the new name will trigger the property action: >>> class C(object): ... def __init__(self,v): ... self._v = v ... def get_v(self): return self._v ... def set_v(self,v): self._v = v ... v=property(get_v,set_v) ... vlist = [v,v] ... a=v ... >>> c=C('something') >>> c.v 'something' >>> c.a 'something' >>> c.vlist[0] >For one, there is no "self" to pass to the methods There are two "selves" in the list. They would work fine if those property selves had closure-style bindings to the object they were a property of. Note that we can transfer the "property" to another class and have its instances see it: >>> class X(object): ... def __init__(self,v): ... self._v = v ... >>> x=X('initial x') >>> x._v 'initial x' >>> X.z = c.vlist[1] >>> x.z 'initial x' because the jiggered access passes the 'self' (as you point out) of the instance involved in the attribute access. >get_v and set_v; another, they're "property attributes", >not "magical list items". :-) No, they are not "property attributes," they are property _objects_ in a list. That is my point. They don't _have_ to have anything to do with getting accessed via a class attribute name. That's just one conventional and handy use that provides an opportunity to pass the associated self, which could as well be part of a property closure. >>> c.vlist [, ] Property object, not property attribute. > >> ISTM kind of a hack to rig access via instance attribute as a >> mechanism for controlling referenced-object behavior (this is >> my impression, I haven't checked code ;-). IMO default behavior >> of an object in lhs or rhs context should not depend on how a >> reference to it was acquired and dereferenced. >> >> (Obviously, if property objects always acted as they now do >> through instance attribute access, "vlist=[v,v]" in this >> example would have to have some kind of access override like >> "vlist = [obj(v),obj(v)]", or else it would generate >> ['something','something'] right there. Using obj(p) a property >> object could be passed around without evaluation and the >> potential side effects thereof). Sorry, that's not quite right. The vlist assignment would not find a _v attribute from the get_v function, if the property was bound to the class itself. I was/am thinking of the property assignment happening in the __init__ function like self.v=property(get_v,set_v), followed by self.vlist=[v,v]. Currently you can do that, but not with live property effect. My generalized property factory function would have to be passed an object to attach to, e.g., self.v=attach_property(self, self.get_v, self.set_v) inside an __init__. Doing it for class variables would also be valid, but of course if you used the class itself as the attachee of the property, you would have to have get/set methods that operated validly in that environment. > >A property object *can* be passed around without side effects, >it's only when accesed as an attribute of an instance of a >class which defines them, that the expected behaviour >triggers. I know that. My post suggests a divorce, alternate ways of getting hitched, and an alternate implementation of triggering, and I'm talking about object-property realtionships ;-) > >For example, try this: > >>>> class klass(object): pass >... >>>> ob = klass() >>>> ob._blah = 10 >>>> def _get_blah(self): return self._blah >>>> def _set_blah(self, b): self._blah = b >>>> ob.blah = property(_get_blah, _set_blah) > >What behaviour do you expect from this? Give it a try. :-) I expect it to work as currently implemented. I am trying to suggest an alternative implementation of property objects. > >> BTW, it would be nice to be able to define a property at >> global module scope also, and perhaps this would tie in nicely. >> >> Just musing ;-) Thoughts? Am I missing a big gotcha? >> One thing is that it will effectively make possible a ()-less >> function call, which will upset some people ;-) > >You can do that without properties: I know interactive use triggers __repr__ and __str__ in various useful ways. I don't want to (ab)use that. I'd like a generalized property object that you can attach to any object and store anywhere. The normal use would be to attach to class instances, and do that by storing as attributes of the same instances during __init__. (Not as class attributes, note. The class would be the normal place to define the get/set/del methods). > >>>> class Caller: >... def __init__(self, func, *args, **kw): >... self.func, self.args, self.kw = func, args, kw >... def __str__(self): return self.func(*args, **kw) >... __repr__ = __str__ >... That depends on access via __str__ or __repr__, which is not what I want. That's a worse context dependency than depending on access via class attribute name. >>>> def PrintTen(): print 10 >... >>>> ten = Caller(PrintTen) >>>> ten >10 > >Another thing, you *can* create "magical list items" >with this class; since __repr__ is also defined, >then when the list which contains them is rendered, >the __repr__ method of the items is called. Neat. :-) > Neat for what it's neat for, but that's the kind of "magic" I'm trying totalk about ;-) All those __repr__/__str__-based ways are beside the point. I'm not looking for help with that, thanks ;-) >I Know, it's a simple-minded example, but you know >what I mean. You can use this Caller class to execute >a function when you type the name of the object that's >related to the function. > >Good luck :-) > Thanks. I was hoping for comments on the idea. I probably didn't make it sufficiently clear, but maybe the above helps? I just wanted to explore the idea of property objects as related to what they function as properties of, potentially associated by means other than being stored as attributes of the instances' classes, and triggered by any access (except a special one designed to inhibit it), not just class attribute access. Regards, Bengt Richter From fredrik at pythonware.com Thu Jun 20 06:39:38 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 20 Jun 2002 10:39:38 GMT Subject: RE strings (was: Variable Interpolation - status of PEP 215) References: <4PfQ8.44245$n4.10307683@newsc.telia.net> Message-ID: and while I'm at it: > # match $$ and $var and ${var} > _dosub = sre.compile(r'\$(?:\$|(\w+)|\{([^}]*)\})').sub how about adding "re" strings (where the "e" tells Python to run the string through the RE compiler): re"[-+]\d+" re"(\d+)\.(\d+)\.(\d+)\.(\d+)" _dosub = re'\$(?:\$|(\w+)|\{([^}]*)\})'.sub ishex = re'0[xX][\dA-Fa-f]'.match # etc (or maybe a ".re" method that does the same thing, but with an optional flag argument ?) From emile at fenx.com Tue Jun 25 10:44:58 2002 From: emile at fenx.com (Emile van Sebille) Date: Tue, 25 Jun 2002 14:44:58 GMT Subject: GOTO w/ Python? References: Message-ID: Delaney, Timothy > I hope you're not serious ... :) > > COME FROM is a joke. Literally. It is a parody of GOTO whose only redeeming > feature is that it is not GOTO. > Having programmed extensively using GOTOs, I'll say the redeeming feature of _COME FROM_ is that it makes GOTO look good! ;-) So-much-spaghetti-so-little-space-ly y'rs, -- Emile van Sebille emile at fenx.com --------- From peter at engcorp.com Sun Jun 23 12:09:15 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 23 Jun 2002 12:09:15 -0400 Subject: (Newbie) Counting Instances ("Hits") with Regular Expressions References: <3d15e215.43448155@news.texas.net> Message-ID: <3D15F2AB.95E01A13@engcorp.com> Ben Fairbank wrote: > > I am new both to Python and to regular expressions, which may account > for my difficulty. I must count the frequenies of certain words in > files of moderate length (about150 k bytes). I have been reading > files and then using count(s,sub), which is fast and easy. I now have > to allow for punctuation and eliminate words within words, etc, and so > am trying to use regular expressions instead of simple words as > targets. I do not, however, find a similarly easy to use count > function in the re module. Yet this is such common operation it must > be there, or easy to implement. What is the usual way of simply > counting "hits" in the re module? (And what have I missed in the > documentation; where is this to be found? I have looked through Lutz > and Ascher) I don't think this sort of thing is really so common as you believe. I'm also not certain using the re module is the typical way to handle something like this. I suspect writing some kind of parser/tokenizer is more common, when you talk about having to take punctuation and such into account. In any case, if you find re's are suitable for you, you can easily count the number found by using "findall" from the re module and len() to find the count. -Peter From sholden at holdenweb.com Mon Jun 17 16:17:42 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 17 Jun 2002 16:17:42 -0400 Subject: Creating Dynamic Web Pages (ZOPE) References: <46ca81a0.0206062016.789d3af6@posting.google.com> <46ca81a0.0206141201.23db4a8c@posting.google.com> Message-ID: <2srP8.127337$Fp1.45878@atlpnn01.usenetserver.com> "Hugh Cowan" wrote ... > Steve, > > Thanks for the suggestion and sample web-site, I will definetly > check-it out. Does DreamWaver support ASP then, or rather provide > support? I mean, I know that you could just add the ASP code mixed in > with the HTML manually, but does it offer any RAD type tools to help > make using ASP easier? > DW does indeed support ASP, though it will also generate code for Cold Fusion or Java Server Pages. The new DW MX product apprently adds PHP and some others. The reason I suggested DW is its ability to quickly build reasonably exact web page layouts, coupled with the ability to define templates whose layout characteristics can quickly be applied to some or all of the pages in a site. It's different from FrontPage in making it easy to define your own templates rather than mostly using pre-built and somewhat clunky "themes" that scream "this is a FrontPage site". > Also, I thought that Dreamweaver was more of just a HTML Editor, while > something like Zope provided extra functionality, tools, wizards, > etc.. to allow you to create Dynamic Web-Sites quicker and easier? I > am just trying to figure out where to concentrate my search for > software and tools. > Zope's acquisition features can indeed be very helpful in propagating useful behaviours to all necessary portions of a site. I'm not aware of wizards, but I wouldn't be the first person to ask about Zope, since although I've run it a couple of times I'm planning to wait until v3 to really try to get to grips with it. > I originally looked through the various *Freeware* web-sites for HTML > editors -- but there are so many of them out there (hard to pick one > from the other -- almost makes you want to go back to a plain old text > editor). While some offer advantages over others, they all seem to > basically assist you in generating the HTML code for web-pages (either > by coding or using a WYSIWYG type interface)? > DW UltraDev comes wtih Fireworks, which is extremely capable at building spiffy graphics like rollovers. DreamWeaver appears to generate reasonably lightweight HTML (though the JavaScript tends to burgeon a bit when you start to polish up your interface with dynamic graphics). It's also fairly liberal at letting you edit the resulting HTML without stopping you from using WYSIWYG mode. I think probably anything further should be done by email, as we are drifting well away from this NG's topic. I would still like to understand what would be involved in adding another back-end to DreamWeaver, as it would make a great addition to something like WebWare (one of the more interesting Python web frameworks). regards -- ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From calves at coelce.com.br Thu Jun 20 08:20:08 2002 From: calves at coelce.com.br (Alves, Carlos Alberto - Coelce) Date: Thu, 20 Jun 2002 09:20:08 -0300 Subject: RES: latex-tex-packages Message-ID: <29A97D00F387D411AC7900902770E148058F93D5@lcoeexc01.coelce.net> Thanks, Pardon me, but I forgot to say it's to install in my linux box at home. So I appreciate packages for linux box based on debian distribuition (I use kernel series 2.4). > -----Mensagem original----- > De: Michael Hudson [mailto:mwh at python.net] > Enviada em: quinta-feira, 20 de junho de 2002 08:55 > Para: Alves, Carlos Alberto - Coelce > Assunto: Re: latex-tex-packages > > > "Alves, Carlos Alberto - Coelce" writes: > > > Hi all, > > You forgive me, c'os I know this issue it's not to this > list; But, anybody > > can tell me where can I get tex/latex packages to install. > I just browse > > some url but can't find'em. > > Depends on OS. I'm making a tentative guess at windows from headers, > so miktex is a reasonable choice: > > http://www.miktex.org > > Cheers, > M. > > -- > Those who have deviant punctuation desires should take care of their > own perverted needs. -- Erik Naggum, comp.lang.lisp > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bt98 at doc.ic.ac.uk Sun Jun 2 06:03:50 2002 From: bt98 at doc.ic.ac.uk (Benjamin Tai) Date: Sun, 02 Jun 2002 11:03:50 +0100 Subject: passing large arrays from C to Python as arguments References: Message-ID: <3CF9ED86.F9EF898A@doc.ic.ac.uk> Chris Fonnesbeck wrote: > I am looking for a way of passing relatively large arrays to python as > an argument to a method call, without hard-coding the length of the > array using Py_BuildValue. Is there an obvious solution to this, like > passing it in a dictionary, or something? At any rate, it is very > awkward to have to pass each element of each array into the argument > individually. > > Thanks, > cjf Hi, Not too sure if the suggestion would work out for you: implementing an extension function which return a list to Python. If so, please read on. Assuming you have an array "a" of length "size": PyObject* p_list_ret; p_list_ret = PyList_New(size); assert(p_list_ret!=NULL); for (ix=0; ix; from jepler@unpythonic.net on Thu, Jun 13, 2002 at 11:06:02AM -0500 References: <20020613160557.GC25416@unpythonic.net> Message-ID: <20020613182751.D6609@prim.han.de> Jeff Epler wrote: > If you're benchmarking, try a solution like this in the mix. It only > has one map/filter call, not map+2*filter. (uses nested scopes and the > new bool() builtin, but this can be avoided if necessary) > > def filter2(test, list): > l1 = [] > l2 = [] > funcs = [l2.append, l1.append] > map(lambda x: funcs[bool(test(x))](x), list) > return l1, l2 nice! holger From rapskat at hotmail.com Sun Jun 9 21:43:58 2002 From: rapskat at hotmail.com (rapskat) Date: Sun, 09 Jun 2002 21:43:58 -0400 Subject: Help with Black Adder... References: <3d025e96$0$3887$e4fe514c@dreader4.news.xs4all.nl> Message-ID: Error Log for Sat, 08 Jun 2002 15:29:00 -0400: segfault in module "Boudewijn Rempt" - dump details are as follows... > rapskat wrote: > >> Greetings All. I'm just getting started with python and I chose Black >> Adder as a RAD IDE. Since my background is (ugh!) VB, I'm used to the >> whole Top Down IDE thing. > > Well, before I started using Python a few years ago, I was a VB > programmer, too. (And Oracle before that -- I've come a long way, I > think). Currently, I use XEmacs for everything, so the transition can be > made, but you need a strong incentive. For me that incentive was to have > to write a book on PyQt and BlackAdder in docbook sgml. And from using > XEmacs for docbook to using it for everything else (except mail and > news) was an insidiuous process. I've now redefined KDE to accept ctrl-s > for search, and ctrl-x-s for save :-). > > >> My questions are: >> >> 1) I am having problems with BA not finding the PyQT libs. I installed >> both from the rpm's (I'm using RH 7.3). But when I start BA it gives >> me an error that it couldn't find the PyQT modules and that they won't >> be available for the session. I've tried removing them and >> reinstalling to no avail. I've run ldconfig as well. Has anyone ele >> seen anything like this and any ideas on how to resolve it? > > I'm not sure that the current version of BlackAdder includes the PyQt > library -- the commercial version does, I think, but the demo version > doesn't. Or something like that. Check whether all libs are really > there; then check whether LD_LIBRARY_PATH includes the location of the > relevant .so's, whether BLACKADDERDIR is correct, and whether > BLACKADDERPYTHON is set correctly. > > (There's a layouto in my book on page 39: the second export ought to be > on the next line.) Thank you for all of your responses. I will look for your publication, Boudewijn, I think it may provide the answers to both my current and future issues. I will also check those variables and see if perhaps they aren't properly set. Thanks again! -- rapskat - 9:35pm up 6 days, 35 min, 6 users, load average: 10.00, 10.03, 10.06 drop the hot to mail me Friends should be preferred to kings. -- Voltaire From kragen at pobox.com Sun Jun 2 22:53:46 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 02 Jun 2002 22:53:46 -0400 Subject: HTML links in a GUI tkinter References: Message-ID: <83elfprs1x.fsf@panacea.canonical.org> aurel-le-gnou writes: > How can I put in a frame or in any widget (?) an html link so that the > browser opens at the url indicated when the user clicks ? > Just simply as if it were an HTML link in an HTML document but in a > tkinter GUI ? Sorry about the empty reply --- in Python 2.x, the webbrowser module has a webbrowser.open() method that does what you want. From vjovanov at stevens-tech.edu Thu Jun 6 10:40:39 2002 From: vjovanov at stevens-tech.edu (Vojin Jovanovic) Date: Thu, 6 Jun 2002 10:40:39 -0400 Subject: self References: <0%hL8.22575$tK.5490038@news02.optonline.net> <_zpL8.81$pq2.4342892@newnews.cc.stevens-tech.edu> Message-ID: > So ':=' variables would first try to evaluate their expressions in their > normal namespace (that of the class, the problem you're dealing with now) and > would then look for 'normal' variable names to resolve. Only if a name > wasnt't found in either would a NameError be raised. Your idea is good. It would be exactly what I need. It would bring a lot to python; a kind of symbolic manipulation capability. Unfortunately, I don't think that my current knowledge of Python is sufficient to implement this in a general way you are suggesting. V.J. From jubafre at zipmail.com.br Fri Jun 21 13:37:59 2002 From: jubafre at zipmail.com.br (jubafre at zipmail.com.br) Date: Fri, 21 Jun 2002 14:37:59 -0300 Subject: =?iso-8859-1?Q?text=20search=20again=3F=3F=3F=3F=3F=3F=3F=3F=3F=3F?= Message-ID: <3D135BCE00000186@www.zipmail.com.br> self.text.search(st, 0.0, regexp='true') is it correct??? i?m not a exact string, i?m searchin for winzip, but in the text appears WinZip and the search doesn?t work, how use regexp flag????? Juliano Freitas www.gebrasil.hpg.com.br ------------------------------------------ Use o melhor sistema de busca da Internet Radar UOL - http://www.radaruol.com.br From edream at tds.net Sun Jun 23 06:05:17 2002 From: edream at tds.net (Edward K. Ream) Date: Sun, 23 Jun 2002 10:05:17 GMT Subject: ConfigParser & converting strings to lists References: <3D152A28.2177B054@tds.net> Message-ID: <3D159D5C.2972C263@tds.net> JohnJacob wrote: > You just want to get your list back from it's string representaion, right? > Try eval: > > files = eval(config.get("recent files", "recentFiles")) Brilliant! As Paul Erdos would say, this is the way it is written in "The Book". Thank you! Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From lmbrtmarc at aol.comlaissermoi Tue Jun 25 23:38:42 2002 From: lmbrtmarc at aol.comlaissermoi (Marc) Date: 26 Jun 2002 03:38:42 GMT Subject: Python and Windows XP Message-ID: <20020625233842.29966.00000386@mb-ma.aol.com> Hello all, I apologise for this newbie question, but I use Windows XP and wonder how I can open a shell session to use Python? There used to be the DOS command option, but now... -- Marc if we can't benefit from an error by making jokes, what's the point of being here? From catunda at pobox.com Wed Jun 26 18:48:58 2002 From: catunda at pobox.com (Marco Catunda) Date: Wed, 26 Jun 2002 19:48:58 -0300 Subject: geting python files for use on web References: Message-ID: To use ASP and Python I suggest you to download activepython from www.activestate.com Activepython is an distribution of python with all modules for windows and much other things. -- Marco Catunda On Wed, 26 Jun 2002 16:39:06 -0300, Chris Liechti wrote: > "Ali K" wrote in > news:k6oS8.191997$6m5.159601 at rwcrnsc51.ops.asp.att.net: >> I would like to know where I can download the nessecary files for usin >> python in ASP and/or CGI. > > the standard python distro from python.org should do for CGI. > >> Please reply. > > what do you mean? by email? > > chris From tjreedy at udel.edu Wed Jun 5 17:02:04 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 05 Jun 2002 21:02:04 GMT Subject: writing a text in hyphenless justification References: <32d0f89.0206042221.1910798c@posting.google.com> Message-ID: "Backflip" wrote in message news:32d0f89.0206042221.1910798c at posting.google.com... > Hi everybody, > i?ve got a little problem again...... > i want to take a raw_input and makes it to a hyphenless justification output..... > how is this possible????? > The most beautiful solution would be the one, that i can define the width.... > has got smb a idee??? it would be very nice, if smb can help me with my problem..... Go to http://mail.python.org/pipermail/python-dev/2002-June/thread.html and check the thread 'Where to put wrap_text' (Ie, where in the standard library, for 2.3). Terry J. Reedy From skip at pobox.com Wed Jun 26 13:25:21 2002 From: skip at pobox.com (Skip Montanaro) Date: Wed, 26 Jun 2002 12:25:21 -0500 Subject: Python 2.2 __slots__ Bug? In-Reply-To: <20020626.060323.78699939.glyph@twistedmatrix.com> References: <20020626.060323.78699939.glyph@twistedmatrix.com> Message-ID: <15641.63745.509965.708519@12-248-8-148.client.attbi.com> Glyph> I think I have discovered a weird bug in the Python interpreter. Glyph> Under Python2.2, when I run this script: ... Glyph, This looks like a new bug to me. A quick scan for __slots__ in the SF bug tracker didn't turn up anything. If you are unable to get ahold of the SF site, I'll file a bug report for you, just let me know. -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From blomquist_scott at hotmail.com Mon Jun 10 16:34:47 2002 From: blomquist_scott at hotmail.com (Scott Blomquist) Date: 10 Jun 2002 13:34:47 -0700 Subject: False Queue.Empty exception ? Message-ID: <4a53cb75.0206101234.179ba0fd@posting.google.com> I use the Queue class to maintain a threadpool of threads which currently have no task, rather than creating/reaping threads as they are needed. When I have a task, I grab one out of the queue and assign the task to it. To add complexity :) I have made the threadpool able to have a min and a max number of threads created, and if the queue of free threads is Empty, then I (potentially) create more threads (up to the max), and drop them into the free queue. The problem is that the Empty exception appears to be raised even when the queue is in fact not empty - causing me to create threads when I don't really need to - some sort of race condition in the following code from the Queue class? def get(self, block=1): """Remove and return an item from the queue. If optional arg 'block' is 1 (the default), block if necessary until an item is available. Otherwise (block is 0), return an item if one is immediately available, else raise the Empty exception. """ if block: self.esema.acquire() elif not self.esema.acquire(0): raise Empty self.mutex.acquire() was_full = self._full() item = self._get() if was_full: self.fsema.release() if not self._empty(): self.esema.release() self.mutex.release() return item Keeping in mind that I am doing a non-blocking get, it seems as though if there is a thread between the self.esema.acquire(0) and the self.esema.release(), and it gets switched out and another thread is switched in and comes through the get call, it will fail on the self.esema.acquire(0), even though the queue is not neccessarily emtpy. Can someone help me out here? Am I just misusing/misunderstanding the capabilities of Queue class? Thanks, --ScottB From glyph at twistedmatrix.com Wed Jun 26 11:23:45 2002 From: glyph at twistedmatrix.com (Glyph Lefkowitz) Date: Wed, 26 Jun 2002 10:23:45 -0500 (CDT) Subject: Python 2.2 __slots__ Bug? In-Reply-To: References: Message-ID: <20020626.102345.59647403.glyph@twistedmatrix.com> From: Jonathan Hogg Subject: Re: Python 2.2 __slots__ Bug? Date: Wed, 26 Jun 2002 14:00:48 +0100 > On 26/6/2002 12:03, in article > mailman.1025089474.17780.python-list at python.org, "Glyph Lefkowitz" > wrote: > > > I get "I'm fine" and then a segmentation fault. This only happens when > > __slots__ is defined on a new-style class. Seriously, i'm not making those > > numbers up -- reliably, 43551 objects will crash the interpreter; fewer will > > not. > > Interestingly I get the construction working fine, but the 'del' crashes the > interpreter with (on Mac OS X): Hmm. Sprinkling print statements about shows it dying on the 'del' (this is how I encountered the bug originally, I was trying to time the [de]allocation of large numbers of objects under 2.1 vs. 2.2), but the stacktrace is still the same; is there some difference between the way allocation works on OS X vs. Linux? (I assume if you can run OS X we're using the same hardware.) > This seems to fail for me at 5430 objects. I couldn't get the allocation to > crash at all (or at least up to a million objects, after which I got bored). Yep, same here. Allocation is no problem. -- | <`'> | Glyph Lefkowitz: Traveling Sorcerer | | < _/ > | Lead Developer, the Twisted project | | < ___/ > | http://www.twistedmatrix.com | -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From whisper at oz.net Fri Jun 21 02:50:58 2002 From: whisper at oz.net (David LeBlanc) Date: Thu, 20 Jun 2002 23:50:58 -0700 Subject: Dispatching a Win32 COM in the background? In-Reply-To: <9OpQ8.90552$ks6.8015@nwrddc02.gnilink.net> Message-ID: Hmmm... if this is working for you, that's great - it just looks strange to me. If Background_TTS is the background speacher thread, shouldn't it have the queue.get() in it and the foreground have the queue.put()? It's also worth noting that self isn't used or needed at the global level, so self.speech is kind of different ;-) Actually... tell me how this works :) : import threading # Private class class _speech_processor(threading.Thread): def __init__(self, speech_queue, talker): threading.Thread.__init__(self) self._talk_queue = speech_queue self._talker = talker def run(self): tq = self._talk_queue # tiny speed up? talker = self._talker while 1: # the main thread will kill us. talker.Speak(tq.get()) # end of _speech_processor class BackgroundSpeaker(): def __init__(self, debug_mode): self._debug_mode = debug_mode self._bg = None self._speech_queue = None self._talker = None self._statusOK = 1 # Must be before try/excepts. Success unless failure! try: from win32com.client import constants # I think this is redundant import win32com.client # since you'll get the constants here too except ImportError: if (self._debug_mode): print "Unable to import Win32COM extensions - are they installed?" self._statusOK = 0 try: self._talker = win32com.client.Dispatch("SAPI.SpVoice") except: if (self._debug_mode): print "Error Initializing Microsoft Speech API." self._statusOK = 0 # leading '_' means private method (by agreement only - not enforced) def _start_bg(self): import Queue self._speech_queue = Queue.Queue() self._bg = _speech_processor(self._speech_queue, self._talker) self._bg.start() def say(self, speech): if not self._statusOK: if self._debug_mode: print "Unable to say: %s." % speech, "Components not installed." return if self._bg is None: self._start_bg() self._speech_queue.put(speech) # end of BackgroundSpeaker if __name__ == '__main__' import time import sys debug_mode = 1 Speaker = BackgroundSpeaker(debug_mode) # It always creates, even if it can't talk. while 1: speech = raw_input("Enter a phrase to speak, then hit Enter") if speech == "": Speaker.say("All done") time.sleep(20) # give some time for finishing up. sys.exit() Speaker.say(speech) I would be interested in hearing if this works! It may have typos since I did it all manually. Don't have the speech kit to test with. HTH, David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Steven M. Castellotti > Sent: Thursday, June 20, 2002 12:12 > To: python-list at python.org > Subject: RE: Dispatching a Win32 COM in the background? > > > Thanks a lot guys, your suggestions have worked perfectly! > > Just for the record, here's what the full implementation looks like. > > This code allows text to be piped to Microsoft's Text-To-Speech > sythesizer, spoken in the background, in a thread-safe manner: > > ##################################################################### > > import threading > > class Background_TTS(threading.Thread): > > def __init__(self, debug_mode): > threading.Thread.__init__(self) > > self.debug_mode = debug_mode > self.loop = 1 > > import Queue > self.text_queue = Queue.Queue() > > > ##################################################################### > > def Speak(self, text): > self.text_queue.put(text) > > > ##################################################################### > > def stop(self): > > self.loop = 0 > > > ##################################################################### > > def run(self): > from win32com.client import constants > import win32com.client > import time > > speech = win32com.client.Dispatch("SAPI.SpVoice") > > while self.loop: > > if not(self.text_queue.empty()): > text = self.text_queue.get() > speech.Speak(text) > time.sleep(.001) > > ##################################################################### > > initialization looks like this: > > try: > self.speech = Background_TTS(self.gameInformation.debug_mode) > self.speech.start() > except: > if (self.gameInformation.debug_mode): > print "Error Initializing Microsoft Speech API." > else: > self.text_to_speech_enabled = 1 > > ##################################################################### > > calling the synthesizer: > > self.speech.Speak(text) > > ##################################################################### > > and finally, stopping the process: > > self.speech.stop() > > > > Once again guys, thanks! > > -Steve Castellotti > SteveC (at) innocent.com > http://cogengine.sourceforge.net/ > > > > On Wed, 19 Jun 2002 18:56:05 -0500, David LeBlanc wrote: > > > Hmmm... and the run method of Background could be sitting on one end of > > a Queue (Queue is thread-safe: see your python doc for details) that's > > buffering the asyncronous calls on the speacher. The main task then just > > stuffs a talk request into the queue and the Background processes it > > when it gets to it. > > > > David LeBlanc > > Seattle, WA USA > > > >> -----Original Message----- > >> From: python-list-admin at python.org > >> [mailto:python-list-admin at python.org]On Behalf Of Peter Hansen Sent: > >> Wednesday, June 19, 2002 16:47 > >> To: python-list at python.org > >> Subject: Re: Dispatching a Win32 COM in the background? > >> > >> > >> "Steven M. Castellotti" wrote: > >> > > >> > 2) Make the call inside a thread which produces the same effect. > >> > >> This might work (I don't know anything about COM though). Try putting > >> your own code inside the run method of a thread: > >> > >> import threading > >> class Background(threading.Thread): > >> def __init__(self): > >> threading.Thread.__init__(self) > >> > >> def run(self): > >> print 'Starting' > >> pass # your own code goes here > >> print 'Done' > >> > >> >>> b = Background() > >> >>> b.start() > >> Starting > >> > >> Done > >> > >> If at this point you get a >>> prompt back right away, but the speech > >> generation is carrying on "in the background" then you're all set. Make > >> sure you do this with code you've already tested outside of the thread, > >> so you'll know that any failure is not the fault of your own code... > >> > >> -Peter > >> -- > >> http://mail.python.org/mailman/listinfo/python-list > -- > http://mail.python.org/mailman/listinfo/python-list From geoff at gerrietts.net Wed Jun 5 16:04:31 2002 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Wed, 5 Jun 2002 13:04:31 -0700 Subject: htmllib examples? In-Reply-To: References: Message-ID: <20020605200431.GB1455@isis.gerrietts.net> Quoting Giulio Cespuglio (giulio.agostini.remove.this at libero.it): > Hi there, > > I'm trying to use htmllib, but I can't find any examples in the > documentation > (http://www.python.org/doc/current/lib/module-htmllib.html). > Is there a (very well hidden) example codebase in www.python.org? > Where else can I look? I sent this out the other day -- it's probably not exactly what you're looking for, but it's a step in the direction: http://groups.google.com/groups?hl=en&lr=&selm=mailman.1022875851.20681.python-list%40python.org -- Geoff Gerrietts "Don't get suckered in by the comments-- they can be terribly misleading. www.gerrietts.net/geoff/ Debug only code." --Dave Storer From pinard at iro.umontreal.ca Sat Jun 15 14:53:03 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 15 Jun 2002 14:53:03 -0400 Subject: Pronouncing '__init__' In-Reply-To: <20020615165915.A17174@hishome.net> References: <20020615132519.A14452@hishome.net> <20020615134410.A15079@prim.han.de> <20020615165915.A17174@hishome.net> Message-ID: [Oren Tirosh] > I used __init__ just as an example. I meant how do you pronounce names > with leading and trailing double underscore in general. The magic name > __init__ may be by far the one most commonly encountered in everyday > programming but __there__ __are__ __many__ __others__. I sometimes said "special" as a prefix (suffix in French!). So, "special init", "special mul", etc. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From osuchw at ecn.ab.ca Fri Jun 14 17:36:01 2002 From: osuchw at ecn.ab.ca (waldekO) Date: 14 Jun 2002 14:36:01 -0700 Subject: Help with ADO and dynamic insert statement... References: <3d0826ec.240888125@netnews.attbi.com> <3d09c924.347952062@netnews.attbi.com> Message-ID: candiazoo at attbi.com wrote in message > I am still having problems using dynamic sql statements to perform lookups and > inserts into a MS Access database and an Oracle database. --DELETED-- I can not to answer you question directly but I may show you mine approach to querying using ADO. To retrive information from database from win32com.client import Dispatch conn = Dispatch('ADODB.Connection') conn.Open(db_source, db_user, db_passwd) sql = """ select id, fname, lname, address from contacts where contact_id = %s """ %(contactid) flag, rs = conn.Execute(sql) # function name is GetRows but really it returns columns # so one has to swing the results around uzing zip() cols = rs.GetRows() if rows: rows = zip(*cols) # To insert I would similarily first construct sql statemnt using string # formatting and then call conn.Execute(sql) # For example: sql = """ insert into other_contacts (id, fname, lname, address) values (%s, '%s', '%s', '%s') """ for row in rows: conn.Execute(sql %row) Of course this approach is very simple and does not take into account escaping single quotes or exotic data types but it is sufficient for my needs in most cases. waldekO From jon+usenet at unequivocal.co.uk Tue Jun 25 11:36:03 2002 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: Tue, 25 Jun 2002 15:36:03 -0000 Subject: Python hits the spot References: Message-ID: In article , Tim Peters wrote: > [Andrew Koenig] >> Don't some implementations of malloc offer a way to ask the operating >> system to commit to the memory being available when you allocate it? >> If so, I can imagine testing for that facility at config time and >> using it if available. > > SourceForge remains open 24 hours a day for patches. My bet is that nobody > cares enough to bother -- the barrier for complaining on Usenet is one an > ant can hurdle with ease . It wouldn't be a good idea anyway. It is not Python's job to second-guess the operating system's memory management policies. From irmen at NOSPAMREMOVETHISxs4all.nl Sat Jun 15 17:37:33 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Sat, 15 Jun 2002 23:37:33 +0200 Subject: type(socket) != SocketType References: <3D0BAD4D.5050105@NOSPAMREMOVETHISxs4all.nl> Message-ID: <3D0BB39D.1010802@NOSPAMREMOVETHISxs4all.nl> Chris Liechti wrote in a prompt response: > what happens to people with timoutsocket? that module repaces the > socket.socket class with a custom one and your check will fail.... Heh, you're probably right. I hereby declare socket.SocketType useless. > maybe there is a cleverer solution that typechecking. the SSL socket has > other/additional attributes etc right?. check for them with has_attr(). or > use the __name__ attribute of the class. Thanks for these suggestions. I will probably go check for the 'pending' attribute, because that is what the SSL sockets have and regular sockets don't. This will likely fix things.... Irmen. From phd at phd.pp.ru Tue Jun 4 04:45:40 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Tue, 4 Jun 2002 12:45:40 +0400 Subject: libpython as a shared library? In-Reply-To: ; from grisha@ispol.com on Mon, Jun 03, 2002 at 08:24:28PM +0000 References: Message-ID: <20020604124540.E9162@phd.pp.ru> On Mon, Jun 03, 2002 at 08:24:28PM +0000, Gregory (Grisha) Trubetskoy wrote: > Has there been any progress in making an option of building libpython as a > shared lib (.so)? I saw some feature requests, but couldn't quite figure > out the ultimate status of this. Implemeneted in Python 2.3. Download CVS version or nightly tarball. Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From rayed at saudi.net.sa Sun Jun 2 00:42:44 2002 From: rayed at saudi.net.sa (Rayed Al-Rashed) Date: Sun, 02 Jun 2002 07:42:44 +0300 Subject: Interactive socket connection References: <3CF88F9B.1080308@saudi.net.sa> <3CF8BA2E.A8C42539@engcorp.com> Message-ID: <3CF9A244.6040505@saudi.net.sa> Thanks for the response, flush() helped a little, but I faced another problem, waiting for input. I built another version it work great using "select" module to poll both the socket and stdin. The finished program is a POP proxy that accept the connection from the user and depending on the user name it forward the connection to the proper POP3 server (configured by getuserserver function): for example user "rayed" go to server "r.pop.mydomain.com" Thanks a lot for your advice, any ideas on how to improve it? :) ------------------------------------ #!/usr/local/bin/python import sys import string import socket import select def getuserserver(user): server = "%s.pop.mydomain.com" % (user[0], ) return (user, server) print "+OK POP3 server ready" sys.stdout.flush() # GET USER NAME while 1: s = sys.stdin.readline() s = string.strip(s) s = string.lower(s) try: (command, username) = string.split(s, " ", 2) except: command = s if command == "user": break elif command == "quit": print "+OK Sayonara" sys.exit() else: print "-ERR Unknown AUTHORIZATION state command" sys.stdout.flush() (id,server) = getuserserver(username) s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect((server, 110)) buf = s.recv(8000) s.send("USER %s\r\n" % (id,)) while 1: r,w,e = select.select ([sys.stdin,s], [], [sys.stdin,s]) if s in r: buf = s.recv(8000) if not buf: # Connection closed break sys.stdout.write(buf) sys.stdout.flush() if sys.stdin in r: buf = sys.stdin.readline() s.send(buf) ------------------------------------ Peter Hansen wrote: > Rayed Al-Rashed wrote: > >>Hello, >> >>I am trying to build POP3 proxy, I want it to run from "inetd" so it should >>communicate with the user using regular stdin, stdout. >>I built a small code that should run as general proxy for any protocol, but >>I faced the following problem, it doesn't show any output from the server >>until I pass it a command [...] > > > Are you maybe in need of a sys.stdout.flush() to get the output to > be sent after the sys.stdout.write()? > > -Peter From sholden at holdenweb.com Mon Jun 3 08:11:25 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 3 Jun 2002 08:11:25 -0400 Subject: win32com under Cygwin References: <3CF9846B.579606ED@wiencko.com> Message-ID: <%5JK8.180011$%u2.88943@atlpnn01.usenetserver.com> "Chris Liechti" wrote in message news:Xns9221CB7B32FDcliechtigmxnet at 62.2.16.82... > Tom Wiencko wrote in news:3CF9846B.579606ED at wiencko.com: > > > There may be an easy answer for this, but I have not yet found it... > > > > I noticed that the Python distribution with Cygwin does not include the > > win32 extensions. The only distribution I can find for them is a > > Windows executible, which does not seem to know about Cygwin. > > thats the official page of win32all: > http://starship.python.net/crew/mhammond/ > > the binary version is compiled for the official python.org interpreter. > > > Can these libraries be loaded under Cygwin? Do they even work under > > Cygwin? Can somebody point me toward how to load them if it is > > possible? > > the sources are available from the page above. maybe you can manage to > compile it with cygwin for cygwin python. don't know if that is easy... > I'm guessing that it would be easier to compile the win32all extensions under mingw32 than under cygwin, because the former (IIRC) uses Microsoft libraries, whereas the latter uses special libraries to give a modicum of Posix compatibility. It probably won't be impossible. I have compiled simpler extensions like mxODBC and MySQLdb under cygwin with minor problems (that should go away, as results were fed back to package authors). But don't expect a cygwin port to be a simple recompile... regards Steve -- ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From gbien at intekom.co.za Tue Jun 11 11:14:33 2002 From: gbien at intekom.co.za (Geoff Bien) Date: Tue, 11 Jun 2002 17:14:33 +0200 Subject: unknown opcode Exception then AV Message-ID: I have one script out of many (python 2.1 activestate on win32) which gives an "invalid opcode" exception and then also sometimes causes an AV. This script uses intebase with the gvib or kinterbasdb extension modules. since using gvib or kinterbasedb makes no difference to the problem they are probably not the cause this is the only script I have problems with. it is too long to post here. Traceback (most recent call last): File "", line 452, in ? File "", line 446, in go File "", line 425, in doPeriod File "", line 341, in doMonth SystemError: unknown opcode the interpreter seems quite confused with this script, in other places simple statements like x=x+1 are giving the wrong results From emile at fenx.com Sun Jun 23 12:06:50 2002 From: emile at fenx.com (Emile van Sebille) Date: Sun, 23 Jun 2002 16:06:50 GMT Subject: Newbie question (anyone programming with curses?) References: Message-ID: hellboy > I'm quite new to Python, but I'm positive that version 2.2 (for Windows) > comes without curses module, though documentation states it is included. > import curses gives me "Import Error: no module named curses" message. > Anyone knows where to download curses module (for Windows)? > from http://py-howto.sourceforge.net/curses/node2.html No one has made a Windows port of the curses module. On a Windows platform, try the Console module written by Fredrik Lundh. The Console module provides cursor-addressable text output, plus full support for mouse and keyboard input, and is available from http://effbot.org/efflib/console. Hope this is current and helps, -- Emile van Sebille emile at fenx.com --------- From ark at research.att.com Thu Jun 6 13:14:24 2002 From: ark at research.att.com (Andrew Koenig) Date: Thu, 6 Jun 2002 17:14:24 GMT Subject: for , ordering References: Message-ID: gabor> hi, gabor> i have a list and i want to create a copy of it with a bit different gabor> objects... by now i have something like this: gabor> objects1 = [] gabor> objects2 = [] gabor> . gabor> . gabor> . gabor> for obj1 in objects1: gabor> objects2.append(obj2(obj1.x)) gabor> 1. isn't there a more elegant way to do this? Isn't this the same as saying objects2 = objects1[:] ? Am I missing something obvious? -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From mcfletch at rogers.com Fri Jun 28 15:33:24 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 28 Jun 2002 15:33:24 -0400 Subject: wxpython threads help needed References: <6bd9f01b.0206281055.2b01a2a6@posting.google.com> Message-ID: <3D1CBA04.2080201@rogers.com> http://wiki.wxpython.org/index.cgi/LongRunningTasks HTH, Mike ps: better place to ask for wxPython specific advice is the wxPython users list... http://lists.wxwindows.org/mailman/listinfo/wxpython-users sameer wrote: > Does anyone have an example of wxpython threads in action? I am > trying to create an application with several (tabbed) panels, each of > which is being updated on its on thread. Basically, I don't want the > application to freeze up, or to have long startup times as all the > panels are being updated. I want the startup to happen as soon as the > main panel is built. I would appreciate it if someone can give an > example either from their own app or code, or a simple example cooked > up on the fly. > > Thanks! -- _______________________________________ Mike C. Fletcher http://members.rogers.com/mcfletch/ From huaiyu at gauss.almadan.ibm.com Mon Jun 3 22:01:04 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Tue, 4 Jun 2002 02:01:04 +0000 (UTC) Subject: Behavior of += (was Re: [Python-Dev] Customization docs) References: Message-ID: Gustavo Cordova wrote: >So, it's not actually a bug, but an artifact of the hoops >Python needs to jump through in order to maintain total >dynamism in data types. > >Instead of this: > > a = ([1],[2],[3]) > a[0] += [3] > >do this: > > a = ([1],[2],[3]) > t = a[0] > t += [3] > >there won't be any exception, because 't' *can* be rebinded >to the value emmited by the += operation; *and* 'a' will >also contain the same reference. > >It's not *totally* equivalent, because it's missing a >single, last step: > > a[0] = t > >*that* is what's raising the exception, which is what >the += operator is trying to do in you're original version. > Great explanation! The problem stems from the fact that the current += operator implements two semantically distinct operations, chosen according to some properties of the operands. This is not unlike the situation of the division operator with distinct behaviors on floats and ints. I'd imagine that at some future time there would be a desire to split += to two distinct operators, one for true in-place operator and one for the fake one currently implemented for immutables. That would remove the spurious exceptions for mutable members of immutable structures. A main hindrance to the change at that time would be the difficulty to disambiguate the true intention of existing code with the += operator. That's not unlike the difficulty involved with the division operator change. Maybe it's better to change earlier? Huaiyu From skip at pobox.com Mon Jun 10 11:17:09 2002 From: skip at pobox.com (Skip Montanaro) Date: Mon, 10 Jun 2002 10:17:09 -0500 Subject: Newbie OOP Question.(diff between function, module and class) In-Reply-To: References: Message-ID: <15620.49909.679355.726113@12-248-41-177.client.attbi.com> SA> I'm still trying to grasp this OOP concept in Python. Can someone SA> tell me the difference between a function, a module, and a class? SA> Since Python defines them all as objects, how do they differ outside SA> of being called from inside the script or outside the script? You posted this midday Saturday and here it's Monday morning but you still have no replies to this question? I would have thought people would jump all over the opportunity to respond to a question like this. Here's my take on things: * A function is an action to perform using a set of input arguments and returning a set of output arguments. For example: >>> print sin(47) 0.123573122745 * A class associates a chunk of data with a set of functions which operate on that data. The first argument to each function in a class (typically called a "method" in Python) is a reference to the data stored in that instance of the class. For example: import math class Point: def __init__(self, x, y): self.x = x self.y = y def polar(self): return math.sqrt(self.x**2+self.y**2), math.atan2(self.y, self.x) * A module is an object that partitions the namespace in a hierarchy. For example, you can have a function named "sin" which is distinct from the sin function in the math module ("math.sin"). Modules used in a straightforward way only add a single extra level of hierarchy to the namespace. Packages generalize this concept to multiple levels (modules inside modules). -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) Boycott Netflix - they spam - http://www.musi-cal.com/~skip/netflix.html From dysfate at gmx.de Fri Jun 14 09:35:42 2002 From: dysfate at gmx.de (Johannes Stiehler) Date: 14 Jun 2002 15:35:42 +0200 Subject: Writing a simple linux daemon type thing... References: Message-ID: I suppose you would have to redirect all output to stdout and log directly to a specified log file. That's usually in the code for all daemonizing processes. The point is to completely unconnect the process from the console where it was started. Johannes -- Johannes Stiehler CIS der LMU M?nchen From dyoo at hkn.eecs.berkeley.edu Sat Jun 1 03:38:02 2002 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Sat, 1 Jun 2002 07:38:02 +0000 (UTC) Subject: Internat References: <69QJ8.68711$ux5.82517@rwcrnsc51.ops.asp.att.net> Message-ID: Ali K wrote: : Can one use Python as a language for ASP or CGI or something? Hi Ali, Sure! There's some good resources on introductory CGI stuff with Python on the "Web Programming" topic guide: http://www.python.org/topics/web/ Devshed.com has a bunch of articles on doing CGI programming with Python a while back, and they seemed prety useful: http://zope1.devshed.com/zope.devshed.com/Server_Side/Python/CGI/page1.html What programming background are you coming from? We might be able to point you toward more relevant resources if you tell us more about what you'd like to do. I have to admit complete ignorance about ASP, but there are resources out there that talk about how to drive ASP with Python. Chris Tismer has a site about this: http://starship.python.net/crew/pirx/asp/py_asp.html Good luck to you! From Chris.Barker at noaa.gov Wed Jun 5 15:49:25 2002 From: Chris.Barker at noaa.gov (Chris Barker) Date: Wed, 05 Jun 2002 12:49:25 -0700 Subject: Behavior of += (was Re: [Python-Dev] Customization docs) References: Message-ID: <3CFE6B13.79CA4A8C@noaa.gov> John Roth wrote: > I don't see a compatability issue here, because > the current behavior raises an exception. Unless someone did the perverse thing I proposed in a earlier post, and took advantage of the fact that the operation did, in fact, work, even though it raised an exception! While I completely agree with Huaiyu's argument (though I'm not sure the "increment with re-binding" is really all that useful for mutables), and I think the current semantics is a minor wart, I am convinced that the original behavior that started this thread is a MAJOR WART (I'd call it a bug). I think I have a pretty good understanding now of why it happens, and why it isn't trivial to change, but I think it is a very bad idea for an operation to raise an exception, but also be successful! Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From david.abrahams at rcn.com Mon Jun 17 21:13:22 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Mon, 17 Jun 2002 21:13:22 -0400 Subject: ImageMagick for Python incl. Source References: Message-ID: "Achim Domma" wrote in message news:aelmhc$35m$03$1 at news.t-online.com... > Hi, > > I have just updated http://www.procoders.net/imagemagick with some > documentation and small examples. There is also source code to compile > ImageMagick for Python on non-windows plattforms, but this might be a bit > tricky. Feel free to ask, if you have problems. > > greetings > Achim Heh, you might want to fix the link to point at www.boost.org, or possibly http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/*checkout*/boost/boost/libs/p ython/doc/v2/reference.html, if you know what I mean ;-) -Dave From msoulier at nortelnetworks.com_.nospam Mon Jun 24 13:12:17 2002 From: msoulier at nortelnetworks.com_.nospam (Michael P. Soulier) Date: 24 Jun 2002 17:12:17 GMT Subject: I'd give up Perl tomorrow if only... References: <3D12F6FC.3000608@wedgetail.com> Message-ID: On Fri, 21 Jun 2002 09:50:54 GMT, Derek Thomson wrote: > > Among other things, it's one of the reasons I'm tinkering with a Perl ORB. There's also XMLRPC, and SOAP, something already supported by both languages. Mike -- Michael P. Soulier, QX41, SKY Tel: 613-765-4699 (ESN: 39-54699) Optical Networks, Nortel Networks, SDE Pegasus "...the word HACK is used as a verb to indicate a massive amount of nerd-like effort." -Harley Hahn, A Student's Guide to Unix From rhymes at myself.com Sat Jun 29 11:39:10 2002 From: rhymes at myself.com (Rhymes) Date: Sat, 29 Jun 2002 17:39:10 +0200 Subject: private Message-ID: Is there any possibility to build up a _real_ private attribute? Such as C++ private data members... I know that with double-underscore prefix (and the name mangling related) I can " hide " data members but I think it's not a so crafty trick... Is there any PEP about it? Will Guido insert a private keyword in a future release of Python ? -- Rhymes rhymes at myself.com " ride or die " From opengeometry at NOSPAM.yahoo.ca Thu Jun 27 14:24:05 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 27 Jun 2002 18:24:05 GMT Subject: Help with an algorithm wanted References: Message-ID: Russell E. Owen wrote: > In article , William Park > wrote: >>If pairing (ie. mapping between 2 objects) occurs randomly, then it's >>virtually impossible, because you don't know which direction to go from any >>one object. It would be travelling from city to city, without knowing >>which state or county. > > Fortunately the pairings (conversion functions) are completely fixed. So > the graph never varies, and it even has a fairly simple shape (basically > a fork with 3 tines and a long handle, if that makes any sense). > > The problem is that the graph has 10 nodes. Rather than hand code 10 > different objects, I'm trying to create a factory that will generate the > required object based on which node (data representation) is a given > from which the others are derived. In your previous example, C is the central "hub" for A, B, and D. If you have hub = {'A': 'C', 'B': 'C', 'D': 'C'} then, you can find the node to which A, B, and D are attached, ie. >>> hub['D'] 'C' Can you organize other objects around hubs? After that, organize the hubs into central hub of their own? If so, then the traversal will be much easier. It's difficult to get our teeth into without knowing what the big picture looks like... :-) -- William Park, Open Geometry Consulting, 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin From dom at edgereport.put_a_c_o_m_here Thu Jun 6 15:36:03 2002 From: dom at edgereport.put_a_c_o_m_here (Domenic R. Merenda) Date: Thu, 06 Jun 2002 19:36:03 GMT Subject: Medium to Large Scale Python Deployments References: <833cw0gvg3.fsf@panacea.canonical.org> Message-ID: Exactly. We plan to upgrade as soon as we test the new version. -- Domenic R. Merenda Editor, The Edge Report http://www.edgereport.com "Fredrik Lundh" wrote in message news:FbOL8.42027$n4.9527047 at newsc.telia.net... > Kragen Sitaker wrote: > > > Are you running Python natively on the AS/400? How hard was that? > > chances are he's using Per Gummedals port: > > http://home.no.net/pgummeda/ From Christopher.Saunter at durham.ac.uk Wed Jun 26 06:29:52 2002 From: Christopher.Saunter at durham.ac.uk (Christopher Saunter) Date: Wed, 26 Jun 2002 10:29:52 +0000 (UTC) Subject: Pythoniac: Thoughts on a hardware Python processor Message-ID: Dear All, I have seen the occasional post about creating a specific hardware 'Python Processor', that could then be built and used in programmable logic or the like (Valves, relays, core memory - Pythoniac ;-) - in other words, create a processor that executes Python bytecode directly. There would be various different reasons for doing this (the 'neat' factor etc...) Replies to these questions have been a bit scant, so I though I would chuck something in. Due to Lazy Typing Syndrome I've used a couple of abbreviations: PVM - Python Virtual Machine / Python Interpreter PBC - Python Byte Code This has been done for Java, for example http://www.xilinx.com/prs_rls/0134lavacore.htm and I have seen a partially complete open source core out there somewhere, but I can't find it right now. I have recently been looking at doing this for Python, and it seems like a rather odd task. From playing with the 'dis' module and reading some docs, it seems that Python Interpreter (PVM), which would be translated into a processor, has these properties: o Operates on sequential bytecode with branching / jump instructions. o Entirely stack based (no concept of registers / memory) So far, so good - a processor could be built to do these functions of the interpreter. However, we go on.... o Rather than operating on 8/16/xxx bit words, as most hardware processors do, the PVM processes objects (via pointers on the stack), which are treated in a 'black box' fashion - i.e. they have add, subtract, compare etc. methods that are called by the PVM, and that return a result. These methods of objects may not actually be coded for in Python, but in the machine language (x86, alpha etc, derived from C etc.) of the underlying processor. Here, the PVM is very different from a 'typical' hardware processor, as the later has a strictly limited number of data types, which it is able to manipulate, whereas Python has many, built out of the basic types, and although some may be coded in Python, they themselves are built on top of C code (or Fortran etc.) that are all translated to native (x86 etc) bytecode outside of Python. The upshot of this is that the PVM is unaware, in the majority of cases, of what actually needs to be done to manipulate objects, it just makes calls to non Python code. So, how to go about dealing with this in a Python processor? a) Create a stack based Python bytecode processor to replace the PVM, and have this interact with another processor (x86 etc.) which stores the objects and executes their methods. Ick. b) Create a stack based bytecode processor that interfaces to custom hardware processors for each Python object. Ick. Neither of these are particularly nice (or for b, workable) solutions. The one I prefer is the following: c) Create a processor that understands Python bytecode, using a stack for the object pointers. However, the processor would execute a sort of superset of PBC, call it P+. This would be fully compatible with Python, but would include several built in types (32bit integers, 8bit integers for strings etc,) and would have access to a memory space. The basic Python types(1) would then be implemented using P+, and stored in the memory available to P+. c Should present a processor that executes Python bytecode, manipulating the Python stack. Then, when a method of an object is called, the appropriate piece of P+ is called, executed by the same processor, and it modifies the data structures of the objects, and the Python stack as necessary, before returning seamlessly to the PBC execution. Python extensions would then be directly executable on this processor, if coded in Python. If they are coded in C or some other language, a C->P+ compiler would be needed... The level of abstraction caused by having to chase down function and object pointers will be higher than for the execution of code on a more conventional hardware processor, but this is also the case for executing PBC with an interpreter. One advanced idea (not really thought about it yet!) is to store the Python stack in main memory, but to store the top x (e.g. 32) items of the stack in a register file to allow bytecode parallelism. I gather that IA-64 may do something sort of similar. --- So, Pythoniac: a hardware (well, FPGA(2)...) processor that directly executes Python bytecode. What do people think about the idea? Is it really feasible? I have doubts it would be particularly quick (in the same way I have my doubts about anti-gravity generators... ;-), but it should be fun! I would like to try and implement this, initially in a simulation environment, then in a real FPGA, with hooks back to a PC allowing the loading, execution, single step execution and monitoring etc of PBC. Ideally I would like to reach a state where an interactive interpreter runs over a serial port... So, anyone else interested in this? Comments, suggestions, gaping holes in my understanding of things as outlined above etc are welcome! Regards, Chris Saunter (1) Now we have increasing type<->object integration, should we refer to numbers, strings, lists etc as types or objects? (2) FPGA - Field Programmable Gate Array - a chip that consists of a 'logic fabric' than can be configured to produce arbitrary circuit designs. If this sounds new to you, try www.fpgacpu.org From jjl at pobox.com Thu Jun 6 17:55:07 2002 From: jjl at pobox.com (John J. Lee) Date: Thu, 6 Jun 2002 22:55:07 +0100 Subject: urllib, urllib2, httplib -- Begging for consolidation? In-Reply-To: References: Message-ID: On Wed, 5 Jun 2002 brueckd at tbye.com wrote: > On Wed, 5 Jun 2002, John J. Lee wrote: [...] > Before I jump in I do want to emphasize that I'm not trying to be too > critical of httplib/urllib/urllib2 - the OP asked if they should be > consolidated, and my short response is "yes, and reorganized too". :-) OK -- but no reason for consolidation of the implementation, yes. I don't really think there is any reason for consolidation of the interface either (which I suppose is what you mean by reorganisation), but the documentation for httplib might include a pointer to urllib{2,}, since as you point out below it's probably not obvious that that's where the HTTP redirection stuff is. [...] > So, depending on your specific needs, you'd "plug in" to this hierarchy at > the appropriate level. If all you need is to go fetch some object, you'd [...] > The key though is that each level you'd have to reinvent as little as > possible - you'd build on related work from lower levels. Almost goes without saying. But again, I think that's what we've got already. [...] > functionality instead of enforced layering). The approach we have today is > *sort of* like this, except that richer and smarter functionality is being > added at the *top* of the hierarchy. The redirection stuff was added between httplib and the OpenerDirector / urlopen stuff. That's not at the top. > Problem #1 is what makes me throw my hands up in frustration when we talk > about, e.g., expanding the urllib APIs to have some way to do a HEAD > request: it doesn't belong on that level of functionality. I think you mean "it doesn't belong in a module named 'urllib2'"... or at least you should mean that ;) > That generic > interface is for making it trivially easy to fetch the contents associated > with a URL, independent as much as possible from protocol. Only part of urllib2 (OpenerDirector &c) is a generic any-old-url-scheme API. The rest (eg. AbstractHTTPHandler, HTTPRedirectHandler) is HTTP-specific, and can be used on its own, without going through the generic stuff. [...] > Probably 90% of the problem is naming and/or module organization - urllib, > a module to retrieve the contents given a generic URL, should be just that > and little else, and protocol-specific knowledge should be accessible from > protocol-specific modules. Given how it is now and need for backwards-compat., what do you suggest to do? I think putting a pointer in httplib docs (if there's not one there already) is the best that can be done now. John From twister at raplounge.de Tue Jun 11 15:16:46 2002 From: twister at raplounge.de (Ben Thursfield) Date: Tue, 11 Jun 2002 21:16:46 +0200 Subject: Newbie question communicating between 2 progs References: <3D046BF0.DC36542C@raplounge.de> <3D04A938.627EE705@engcorp.com> <3D04E8ED.C0708C2B@raplounge.de> <3D04F4EF.9040800@bgb.cc> Message-ID: <3D064C9E.FF9B4DAE@raplounge.de> Don Garrett schrieb: > The two programs are only running while the frame they handle is being > generated. The one programm is running as long as i want it to, because i am using a while loop, so that is no problem. So only the one that prints needs to be refreshed. I want it to behave in a chat window manner, where it frequently prints out the last 25 lines. > I'm assuming you aren't using some form of server push, which has it's own > problems. I actually don't know what a server push is, so I don't think I am using one ;-). > However, the best answer to your question is to use cookies. The contents > should be visible to all pages on the local site (you can control this) so > they will allow you scripts to communicate with themselves and each other. You > can store a fair amount in one (I'm not sure what the size limit is), and it > can be binary. I thougth that there must be a way of declaring data structers or whatever as extern in a C manner. This does not seem to be the case, i suppose.... > A few warnings. > > Some people disable cookies. This can totally break your site. > > All cookies are always uploaded as part of every page request everywhere > they are visible. This means that you shouldn't make them too large or you > will slow your site. If they are big, try to restrict cookie visibility to > just the pages that really need them. You can specify where the cookies are > visible when you create them. You can even store the state info in a database > and use the cookie as a key to retreive it. > > When it comes to security, you cannot trust the contents of the cookie. The > contents need to be validated the same way the values from a form would be. A > tricky black hat can force the cookie contents to be anything they want. > I was thinking about sth. like that actually. Only that I wanted to write the output into an html file and then let the frame refresh that one. I then thought that there must be a way to access the data some other way, as i didn't want to make a directore one can write into, because of security reasons... The cookies way seems better then. I don't know, but how do normal internet chat programms handle this? Do they use cookies, too? > Two last bits of advice from an old web developer (well as old as a web > developer can be). > > Try to avoid frames. They cause a lot of problems for both you and for your > users. For example, they often break cross-browser, they can break bookmarks, > and they can break printing. > I know, on the other hand I didn't know how to do the program in another way :-( . > Try to avoid refreshes, especially frequent ones. Someone with a poor link > will spend more time looking at an empty page that hasn't loaded than they > will looking at your content. > Good point, too. Thanks for all your help! > -- > Don Garrett http://www.bgb.cc/garrett/ > BGB Consulting garrett at bgb.cc From chris.gonnerman at newcenturycomputers.net Wed Jun 19 23:55:47 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Wed, 19 Jun 2002 22:55:47 -0500 Subject: python version? References: <3D1138EE.FDDCE5DF@engcorp.com> Message-ID: <00e201c2180e$61910d20$0101010a@local> ----- Original Message ----- From: "Peter Hansen" > "Delaney, Timothy" wrote: > > > > > From: George Hester [mailto:hesterloli at hotmail.com] > > > > > > All fixed > > > > > [snip questionnaire] > > > > Now I'm confused. What does that mean??? > > I interpreted it as "I got the point, please leave it alone now." Huh. I got "I don't want to see your point, go away." Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From stephen at xemacs.org Mon Jun 3 02:35:45 2002 From: stephen at xemacs.org (Stephen J. Turnbull) Date: 03 Jun 2002 15:35:45 +0900 Subject: 'for every' and 'for any' References: <20020526135944.A32690@hishome.net> <20020526091742.A987@unpythonic.net> Message-ID: <87wutglvi6.fsf@tleepslib.sk.tsukuba.ac.jp> >>>>> "Quinn" == Quinn Dunkan writes: Quinn> To me, that's "abstraction". Logging debugging information Quinn> is a very common task, but python doesn't have it built in. Quinn> I don't write 'if debug >= whatever: print blah' all the Quinn> time and blame python for forcing me to jump through hoops, Quinn> I write util.dprint(). I don't have to complain about its Quinn> not being built in or wait for 2.3 or 2.2.2 or whatever, Quinn> since I can have exactly what I want right now. Picking an example that suits the point: this is exactly what PEP-something-or-other (282, in this case) is about. Understood, _you_ don't have to wait, and you maybe don't want to. As I understand it, Oren's point is precisely that you rarely have to wait very long (at the current stage of Python development) for the appropriate PEP-something-or-other to show up -- and it's usually pretty well thought out and will work for most people. Furthermore, PEPs are strongly encouraged (maybe required?) to provide an implementation early. This means that you can use them now, with a pretty good shot at forward compatibility. -- Institute of Policy and Planning Sciences http://turnbull.sk.tsukuba.ac.jp University of Tsukuba Tennodai 1-1-1 Tsukuba 305-8573 JAPAN My nostalgia for Icon makes me forget about any of the bad things. I don't have much nostalgia for Perl, so its faults I remember. Scott Gilbert c.l.py From jwilhelm at outsourcefinancial.com Fri Jun 14 13:07:32 2002 From: jwilhelm at outsourcefinancial.com (Joseph Wilhelm) Date: 14 Jun 2002 10:07:32 -0700 Subject: I feel stoopid ... this code is to verbose In-Reply-To: <3D0A1791.3060307@mxm.dk> References: <3D0A1791.3060307@mxm.dk> Message-ID: <1024074452.1015.12.camel@jwilhelm.ofsloans.com> On Fri, 2002-06-14 at 09:19, Max M wrote: > def stringSlicer(string, chunkSize=3): > chunkList = [] > reverseString = list(string) > reverseString.reverse() > for i in range(0, len(string), chunkSize): > chunk = reverseString[i:i+chunkSize] > chunk.reverse() > chunk = ''.join(chunk) > chunkList.append(chunk) > chunkList.reverse() > return '.'.join(chunkList) > > > print stringSlicer('42000000') > > >>> 40.000.000 > > I just find that it's a lot of code for such a little function an it > annoys my sense of aestetics. I have tried a lot of different approaches > including using zip on a list like ['','','.'], and other weird stuff :-) > > I just cannot seem to find the nice 3-liner I expected from the > beginning. Has anybody got a better solution ? I thought somebody might > find it a fun exercise. Well I have... How about this: import string def stringSlicer( str, chunkSize=3 ): parts = list( str ) for x in range( ( len( parts ) - chunkSize ), 0, -chunkSize ): parts.insert( x, "." ) return string.join( parts, "" ) print stringSlicer( '42000000' ) >>> 42.000.000 --Joseph Wilhelm From marklists at mceahern.com Sat Jun 15 10:00:03 2002 From: marklists at mceahern.com (Mark McEahern) Date: Sat, 15 Jun 2002 09:00:03 -0500 Subject: getgrouplist() ? In-Reply-To: <20020615001750.94759.qmail@web10304.mail.yahoo.com> Message-ID: > I need a way to get a back a list of supplemental group ids for a > specified uid. Something like getgrouplist() in my C standard lib. I > don't see a convenient method for this, have I missed it? > > The os module contains getgroups(), but that doesn't allow me to > specify a uid; it uses only the uid of the current process. For what it's worth, the grp module is getting some improvements for 2.3: http://www.python.org/dev/doc/devel/whatsnew/node8.html // m - From cbbrowne at acm.org Sat Jun 1 02:32:48 2002 From: cbbrowne at acm.org (Christopher Browne) Date: 1 Jun 2002 06:32:48 GMT Subject: Generating unique numbers? References: <3CF7EBC8.4080802@verio.net> <79b2b0bb.0205312136.5365df9c@posting.google.com> Message-ID: A long time ago, in a galaxy far, far away, xscottgjunk at yahoo.com (Scott Gilbert) wrote: > VanL wrote in message news:<3CF7EBC8.4080802 at verio.net>... >> Is there a good algorithm for generating unique numbers >> (ints, specifically) that can be used as object identifiers? >> >> I am discounding the obvious newid += 1 because I will need >> to merge different sets, and while I may have some number >> overlap, using a simple count for each object would >> guarantee that I have the maximum number of clashes. >> >> Specifically, I will be using these numbers as dictionary keys. >> > > If you're on windows, you could use the pythoncom module CreateGuid > function. > > Basically GUIDs are 128 bit numbers that are pretty much going to be > unique no matter where or when you call the function. And GUIDs are basically DCE UUIDs. I think this is all C stuff; it oughtn't be _too_ difficult to wrap it into a Python library... -- (concatenate 'string "cbbrowne" "@ntlug.org") http://www.ntlug.org/~cbbrowne/oses.html All things are possible except skiing through a revolving door. -- DeMara Cabrera From whisper at oz.net Sat Jun 15 03:00:50 2002 From: whisper at oz.net (David LeBlanc) Date: Sat, 15 Jun 2002 00:00:50 -0700 Subject: MS Word -- finding text In-Reply-To: Message-ID: Please post some snippets. That's always more likely to get useful assistance then stating a general problem. Where are you encountering the unicode decoding problem? Regards, David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Prema > Sent: Friday, June 14, 2002 23:50 > To: python-list at python.org > Subject: MS Word -- finding text > > > Hi All ! > Just wondering if anyone has some sample code around how to open a > document, find a string and return the paragraph(s) containing the > string. > > I have got a good part of the way but running up against Unicode > decoding > > Can post some snippets if needed > Thanks very much in advance > > Kind regards > Mike > -- > http://mail.python.org/mailman/listinfo/python-list From john at jrmstudios.com Sat Jun 15 05:50:53 2002 From: john at jrmstudios.com (John R. Marshall) Date: Sat, 15 Jun 2002 04:50:53 -0500 Subject: IDE recommendations?? References: <3d0b06bd$0$52043$e4fe514c@dreader3.news.xs4all.nl> Message-ID: On Saturday 15 June 2002 04:18 am, Boudewijn Rempt wrote: > At one > point there was a version of KDevelop that supported Python development, > but that has disappeared, it seems. It's (Gideon) still there :-). Instructions for getting it from CVS can be found here http://www.kdevelop.org/index.html?filename=branches_compiling.html -- John R. Marshall - Web Developer JRM Studios - http://www.jrmstudios.com The Hotrodding Network - http://www.hotrodding.net From gcordova at hebmex.com Mon Jun 3 16:48:46 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Mon, 3 Jun 2002 15:48:46 -0500 Subject: Which is fastest dict or list.index() ? Message-ID: > > I need a structure to hold a correspondence between toons and id like > > {'Bugs' : 0, 'Mickey' : 1, 'Babs' : 2, 'Jerry' : 3, 'Tom' : > 4, 'Babs' : 5} > > I must be able to alpha sort these toons (without loosing > their id), and access a toon from an id or an id from a toon. > > By now a use a dict and a list : the dict gives index from a > toon, and the list gives me a toon from an index. > > {'Bugs' : 0, 'Mickey' : 1, 'Babs' : 2, 'Jerry' : 3, 'Tom : 4, 'Babs' : 5} > ['Bugs', 'Mickey', 'Babs', 'Jerry', 'Tom', 'Babs'] > > (the id is used somewhere else a key to a collection of elements) > > My question is which is the best way (best = quickest and > memory safe) to handle this ? > Should i subclasse from dict or list ? > Should i consider using only one list with toons (and use > their index as id) > ? > Should i use 2 dicts ? > > Many thanks to you for helping > > s13. > Hmmm... OK, first, let's analyze your data domain: "Toon names", which are character strings; "Toon Name Indexes", which are integer numbers. That gives us an insight: You'll never have a clash between a "ToonName" and a "ToonNameIndex". In such a case (I've used this technique before, with good results). I'd really recommend you use a single object, a dictionary, subclassed if you like, to store all the information. So, you can say "toondict[5]" and obtain "Babs", and say "toondict['Babs']" and obtain 5. Since, now, keys and values are transposed, you need special methods to obtain all toons and indexes, so it's trivial to separate all contained data to find what you need. This will give you the piece of mind (hah!) that you're not duplicating functionality. I'd subclass 'dict' like this: class ToonDict(dict): # All stays the same, except: def __setitem__(self, key, value): # Special-case item insertion. dict.__setitem__(self, key, value) dict.__setitem__(self, value, key) # Obtain list of data of a certain type. def __typed_data(self, *types): items = self.values() items = filter(lambda i:type(i) in types, items) items.sort() return items # Retrieve a sorted list of toon names. def toons(self): return self.__typed_data(str) # Retrieve a sorted list of toon name indexes. def toon_name_indexes(self): return self.__typed_data(int) Good luck :-) -gus From jepler at unpythonic.net Sat Jun 29 22:20:57 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Sat, 29 Jun 2002 21:20:57 -0500 Subject: possibly a dumb question In-Reply-To: <3d1e6251$1_3@nopics.sjc> References: <3d1e5eff$1_7@nopics.sjc> <3D1E6415.8128F3F8@engcorp.com> <3d1e6251$1_3@nopics.sjc> Message-ID: <20020629212050.A2822@unpythonic.net> class foo(object): def __new__(*args): return 0 x = foo(0) print x, type(x) But if you want the constructor for "foo" to return a value that is not an instance of "foo", why not let "foo" be a function? Since both functions and classes are callables, it's no problem allowing both anywhere a callable object can be used... Jeff From olc at ninti.com Sat Jun 8 20:38:44 2002 From: olc at ninti.com (Michael Hall) Date: Sun, 9 Jun 2002 10:08:44 +0930 (CST) Subject: Removing ^M Message-ID: I am trying remove ^M characters (some kind of newline character) from an HTML file. I've tried all sorts of string.replace and sed possibilities but the things just won't go away. Does anyone have a way of removing such characters? TIA Mick From peter at engcorp.com Sat Jun 29 16:25:52 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 29 Jun 2002 16:25:52 -0400 Subject: Most efficient way to write data out to a text file? References: <3d1a6993.248534625@netnews.attbi.com> <3d1dc547.468619140@netnews.attbi.com> Message-ID: <3D1E17D0.5581791E@engcorp.com> James Kew wrote: > > "Dave Kuhlman" wrote in message > news:afkv73$f2274$1 at ID-139865.news.dfncis.de... > > > candiazoo at attbi.com wrote: > > > 4) I localized constants I was using in boolean > > > tests (there were declared at the beginning of the module, I moved > > > them to the function call just before the loop). > > > > Is finding things in globals slower than finding them in locals? > > Yes: you have to look, and fail to find, in the locals before you look in > the globals. I'm no expert in this, but that doesn't sound right. Locals are indexed, not searched in a dictionary. The compiler decides if something is local, not the runtime. I think you're confusing the two-level lookup with the fact that for non-locals, first it looks in globals, then in the builtins. (Hope I got that right.) -Peter From gustafl at algonet.se Mon Jun 10 17:25:06 2002 From: gustafl at algonet.se (Gustaf Liljegren) Date: Mon, 10 Jun 2002 21:25:06 +0000 (UTC) Subject: if number is 1-2, 4 or 6-8 or 12-28, 30, 32... Message-ID: I'm making a function that takes one integer and returns a boolean that says if the integer matches a number in a certain group of numbers. This group consists of single numbers aswell as ranges spanning thousands of numbers. I'm looking for an elegant way to write this function. Thanks in advance! Gustaf From aahz at pythoncraft.com Tue Jun 11 16:50:47 2002 From: aahz at pythoncraft.com (Aahz) Date: 11 Jun 2002 16:50:47 -0400 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 10) References: Message-ID: In article , Oleg Broytmann wrote: >On Tue, Jun 11, 2002 at 01:35:10PM -0400, Aahz wrote: >>> >>> Oleg BroytMann posted glue that automatically moves vim users to >> >> Broytman > > It is arguable :) This is transliteration from Russian, so there are too >many way to do it. When my sister moved to Israel, they wrote in her >passport "Brojtman"! > When I was considering my way of the transliteration I decided to use >German-like "mann" instead of English-like "man"; after all these are >German-like surnames. And in programs I am almost always do >DoubleCapitalization and write "BroytMann"! :) Oops. I was pretty sure StudlyCaps was wrong, and I misread what I searched for on Gooja. My bad. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I had lots of reasonable theories about children myself, until I had some." --Michael Rios From sholden at holdenweb.com Tue Jun 4 12:01:56 2002 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 4 Jun 2002 12:01:56 -0400 Subject: Behavior of += (was Re: [Python-Dev] Customization docs) References: Message-ID: <9A5L8.232032$%u2.84870@atlpnn01.usenetserver.com> "John Roth" wrote in message news:ufpb3sn6332ub4 at news.supernews.com... > > "Huaiyu Zhu" wrote in message > news:slrnafo7qv.37c.huaiyu at gauss.almadan.ibm.com... > > Gustavo Cordova wrote: > > > > > Great explanation! The problem stems from the fact that the current > += > > operator implements two semantically distinct operations, chosen > according > > to some properties of the operands. This is not unlike the situation > of the > > division operator with distinct behaviors on floats and ints. > > This is not an issue with '+='. It's an issue with assignment, > regardless > of whether it is standalone or combined with some other operation. > > And I disagree that assignment implements two distinct operations. > Assignment always rebinds. Always. In the examples cited, it > attempted to rebind into a tuple, because that's what was asked > for when the left hand side had a subscript. > >>> a = b = [1,2,3] >>> a += [4] >>> a, id(a), b, id(b) ([1, 2, 3, 4], 269472088, [1, 2, 3, 4], 269472088) >>> Where did the rebinding take place? ISTM that "a" is still bound to the same list, which has been modified in place. > The reason that the examples given at the top of the thread fail > in such strange ways is simply that '+=' does not check whether > the assignment is possible before doing the addition (or concatination, > in the specific cases cited.) > That's because a type's implementation of augmented operations is allowed to decide whether to rebind or update in place. Seems to me the exception is caused because the tuple's hash would be changed, though I'm not familiar with the implementation detail. That seemed reasonable to me. > To see this, you could try the first example, using explicit '+' and > '='. I suspect it would fail in exactly the same way, with exactly > the same side effect. > Clearly an explicit assignment to a tuple element is always going to fail, so I don't really see what this would tell you. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From fredrik at pythonware.com Thu Jun 20 11:49:05 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 20 Jun 2002 15:49:05 GMT Subject: Access to XML dataBase References: Message-ID: Marta Gutierre wrote: > I tried sothing like: > > import xmlrpclib > client=xmlrpclib.Server("http://localhost:4080") > try: > client.listCollections("db") > except xmlrpclib.Fault,faultobj: > print "ERROR", faultobj > ERROR found for "listCollections": no default handler registered.'> > > Any idea of what does it mean ??? the Java server is trying to tell you that there is no "listCollection" handler. > I can't find good documentation of XML-RPC in Python it's not a Python problem, really... From kseehof at neuralintegrator.com Sat Jun 8 20:18:25 2002 From: kseehof at neuralintegrator.com (Ken Seehof) Date: Sat, 08 Jun 2002 17:18:25 -0700 Subject: How could i get execution times ? In-Reply-To: Message-ID: > I'm looking for a way to get execution time at different points > of a program, by now i use the > code below, but i've seen in some post that time.clock() could be > a better way to measure this, > > So my question, is how you pythoners do it ??? and to understand _why_ ? >>> for x in range(10): ... print time.time() 1023578958.14 1023578958.14 1023578958.14 1023578958.14 1023578958.14 1023578958.14 1023578958.14 1023578958.14 1023578958.14 1023578958.14 >>> for x in range(10): ... print time.clock() 88.9835171558 88.9849477866 88.9862024171 88.9876648955 88.9889245546 88.9901624231 88.9913986155 88.9926339697 88.9938701621 88.9951130592 >>> for x in range(10): ... time.sleep(.01) ... print time.time() 1023579557.1 1023579557.1 1023579557.16 1023579557.16 1023579557.16 1023579557.16 1023579557.16 1023579557.21 1023579557.21 1023579557.21 >>> pprint.pprint([time.clock() for i in range(10)]) [12.151166630349151, 12.151180877989908, 12.151191773244607, 12.151202668499304, 12.151213563754002, 12.151224459008699, 12.151235354263397, 12.151246249518094, 12.151258820965822, 12.15126971622052] In other words, time.clock() is far more precise for elapsed time (the above example demonstrates precision on the order of microseconds -- more than adequate for profiling python code). But time.time() apparently has a granularity on the order of a tenth of a second (on windows), which is fine for profiling slower applications like Microsoft Outlook :-) I believe that the difference between the corresponding C library functions is due to there being two different clocks in the hardware. One clock is very precise, and drives the CPU but only knows about elapsed time, (this clock is only on when the CPU is on). The other clock is essential a digital watch plugged into your computer (it runs on a battery, just like a watch, when the CPU is off). I hope this answers your questions. - Ken Seehof From shalehperry at attbi.com Fri Jun 7 10:41:28 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 07 Jun 2002 07:41:28 -0700 (PDT) Subject: question on pattern In-Reply-To: <3D007E96.3010505@rmb.co.za> Message-ID: On 07-Jun-2002 Ulrich Pfisterer wrote: > I want to do a pattern match on a string that spans multiple lines (c++ > style comments, re.match('(/\*.*?\*/)', filestring) > If I use the re.findall(pattern, string) method it only finds those > matches that are on a single line. If I use re.match(pattern, string, > DOTALL) it spans multiple lines but only finds the first match. > Any help on this one would be greatly appreciated. > match only matches once you can either use a loop or use I believe findall() or something similar. From romberg at smaug.fsl.noaa.gov Fri Jun 7 13:26:48 2002 From: romberg at smaug.fsl.noaa.gov (Mike Romberg) Date: 07 Jun 2002 11:26:48 -0600 Subject: Medium to Large Scale Python Deployments References: Message-ID: >>>>> " " == Michael Chermside writes: > Folks, I think this is a pretty useful thing to collect. In > fact, it might be really nice to collect a list of large > (successful) Python projects and post it somewhere so the > Python community could use it for advocacy. > So do me a favor... if you have (or know of) a large Python > project which you think our community ought to be bragging > about, please either post it to this thread or email it to > me. I'm working on a project which is is a mix of C++ and python. Currntly the python part of it is: python ~/pycount.py -R "*.py" lines code doc comment blank file 35 6 0 20 9 ./data/textFiles/GFECONFIG/Gweight.py 1390 264 0 937 189 ./data/textFiles/GFECONFIG/gfeConfig.py [snip] 134062 88680 3160 24281 17941 total The code is for a weather forecast system being developed for the national weather service: http://www-md.fsl.noaa.gov/eft/ Mike Romberg (romberg at fsl.noaa.gov) From thehaas at binary.net Mon Jun 10 19:10:35 2002 From: thehaas at binary.net (thehaas at binary.net) Date: Mon, 10 Jun 2002 23:10:35 GMT Subject: wxPlotCanvas documentation? References: Message-ID: > 3. How do I find anything in the documentation? > My inability to find my wxButt in the wxDark with both > wxHands (with or without a wxFlashlight) is not > limited to PlotCanvas, so I'm hoping that the problem > is on my end. The wxPython website, as far as I can > tell, only has one documentation link, and it's a link > to wxWindows, not the wxPython objects that wrapper > it. There's a sample code section, but every last one > of the examples is marked "To Be Written When I Have > More Time." The wxPython documentation link really does goto the official wxWindows docs, but it has notes where wxWindows and wxPython (and wxPerl, for that matter) differ. Not ideal, mind you, but it is there. Did you try the wxWiki? I've found it the best place to look first (though it isn't complete) http://wiki.wxpython.org/ Also, the wxPython users mailing list is a great place . . . Robin Dunn, the man in charge of wxPython, is great about answering questions, treating people with respect, and being honest about wx's short comings. I love wxPython, but the initial learning curve is quite steep. Once you get past the very initial stage, though, it grows on you. -- mikeh From op73418 at mail.telepac.pt Wed Jun 26 14:06:13 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Wed, 26 Jun 2002 19:06:13 +0100 Subject: question on properties References: Message-ID: On Wed, 26 Jun 2002 17:04:32 +0100, Gon?alo Rodrigues wrote: >Hi, > >Suppose in a class Klass I have a property prop. Suppose also that I >have > >class AnotherKlass(Klass): > ... > >I can override property prop in AnotherKlass by just redefining it, but >what if I want to acess the base class prop how do I do it? > >TIA and all the best, >Gon?alo Rodrigues Got it! Use (for getting): Klass.prop.__get__(self) All the best, Gon?alo Rodrigues From bkelley at wi.mit.edu Mon Jun 3 11:02:50 2002 From: bkelley at wi.mit.edu (Brian Kelley) Date: Mon, 03 Jun 2002 11:02:50 -0400 Subject: Graph distances, how can I speed it up? References: <33803989.0206030235.4134d33e@posting.google.com> Message-ID: <3CFB851A.80102@wi.mit.edu> While a C or C++ implementation would be prefereable, there are more efficient algorithms for shortest distance between nodes. Floyd-Warshall comes to mind. (I think Andrew Dalke helped me with this one a while ago just to give appropriate credit) import Numeric # Finds the all-pairs minimum distance between two points. # # Initial matrix must be a symmetric "weight" matrix w[i][j] where # w[i][i] == 0 and w[i][j] is the direct distance between i and j. # This is usually 1 but can be weighted for importance. # # Must have a symmetric matrix for this implementation def floyd_warshall(w): assert(len(w.shape) == 2) # must be a 2D array N = w.shape[0] assert(N == w.shape[1]) # must be a square 2D array k = 0 dold = w # destroys contents of w # (Use this if you don't want to destroy) #dold = Numeric.array(w) dnew = Numeric.zeros((N,N)) for k in range(1, N): for i in range(N): # We can do this simplification because of symmetry for j in range(i+1, N): x = min(dold[i][j], dold[i][k] + dold[k][j]) dnew[i][j] = x dnew[j][i] = x dnew, dold = dold, dnew return dold Brian Kelley Whitehead Institute for Biomedical Research From jadestar at idiom.com Mon Jun 17 04:29:30 2002 From: jadestar at idiom.com (James T. Dennis) Date: 17 Jun 2002 08:29:30 GMT Subject: Which is fastest dict or list.index() ? References: Message-ID: Shagshag13 wrote: > Thanks !!! (i use some tricks i find in seqdict) >> If you want a skiplist version, let me know and I'll send it. >> Raymond Hettinger > I'm sorry, but i don't understand what you mean by a "skiplist version" > So here is how i do it now, i think i miss to explain that i must keep some > kind of id (which i use as a key in another table, and i want to keep > this other table indexed by integer instead of words to save mermory). > <- thoug i don't know if this is a real saving... I'd probably use a simple list of tuples in a class. The class would be responsible for maintaining the sorted order of the list via the "bisect" module's insort function and it would provide a short binary search function to find and return any element of the list. Actually almost any technique is likely to be overkill for this particular problem domain. There are max. a few thousand toons and any modern computer could could simply brute force them using x=dictionaries.items(); x.sort(). > i'm huge newbie but i feel python really pleasant, great, etc... (even if i > had lots of trouble > with memory run out... on a solaris system with 1024mo...) > i post for comments or advices as i'm not a skilled pythoner... > thanks in advance for reading and helping > class IKeys: > def __init__(self): > self._size = 0 > self._term = {} # element -> int key - ex: {a : 0, b : 2, c : 1} > self._iKeys = [] # contains elements, int key -> element - ex: [a, c, b] > def __str__(self): > s = 'iKey (' + "\n" > s += str(self._term) + "\n" > s += str(self._iKeys) + "\n" > s += str(self._size) + " # size)\n" > return s > def __len__(self): > return self._size > def __getitem__(self, pos): > return self._iKeys[pos] > def index(self, element): > return self._term[element] > def add(self, element): > if self._term.has_key(element): > return self._term[element] > self._iKeys.append(element) > self._term[element] = self._size > self._size += 1 > return (self._size - 1) > def keys(self): > return self._iKeys > def get_size(self): > return self._size > which i use like this : >>>> toons = IKeys() >>>> for t in ['Bugs', 'Mickey', 'Babs', 'Jerry', 'Tom', 'Babs']: > toons.add(t) > 0 > 1 > 2 > 3 > 4 > 2 # already in toons so we don't had it, we get id >>>> print toons > iKey ( > {'Mickey': 1, 'Babs': 2, 'Tom': 4, 'Bugs': 0, 'Jerry': 3} > ['Babs', 'Bugs', 'Jerry', 'Mickey', 'Tom'] > 5 # size) >>>> t[2] > 'b' >>>> toons[2] > 'Babs' >>>> toons.index('Jerry') > 3 >>>> tmp = toons.keys() >>>> tmp.sort() >>>> for t in tmp: # here it's sorted > i = toons.index(t) > print "Toons [%s] has id [%s]" % (t, i) > Toons [Babs] has id [2] > Toons [Bugs] has id [0] > Toons [Jerry] has id [3] > Toons [Mickey] has id [1] > Toons [Tom] has id [4] From aahz at pythoncraft.com Mon Jun 17 14:44:29 2002 From: aahz at pythoncraft.com (Aahz) Date: 17 Jun 2002 14:44:29 -0400 Subject: If you use Python -OO is it a permanent condition?? References: Message-ID: In article , Jeff Sasmor wrote: > >So I tried: > >python -OO P1.pyo > >and it works just fine. Does this mean that the interpreter must >always be started with -OO to execute files compiled with -OO? I can't >imagine why this would be the case, but it seems to be -- at least as >far as I can see from my little bit of experimentation. Python doesn't search for .pyo files unless it is running in optimized mode. Try setting the PYTHONOPTIMIZE env var. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From daves_spam_dodging_account at yahoo.com Mon Jun 10 14:22:31 2002 From: daves_spam_dodging_account at yahoo.com (David Brady) Date: Mon, 10 Jun 2002 11:22:31 -0700 (PDT) Subject: wxPlotCanvas documentation? Message-ID: <20020610182231.26180.qmail@web21108.mail.yahoo.com> I have searched the wxPython and wxWindows documentation, peered through the wxdemo files, and searched the web in the hopes of finding the answers to my questions, but to no avail. I would like to write a simple graphing calculator program with wxPython. 1. How do I create a wxPlotCanvas in a wxFrame window? I can see in wxPython/demo/wxPlotCanvas.py how to create a PlotCanvas object if I wanted, say, to run my graphing calculator inside the wxDemo framework, but I don't. How do I instantiate this guy and stick him in a wxFrame class of my own deriving? 2. How do I manipulate wxPlotCanvas? >From the demo code I see there are PolyMarker and PolyLine objects, as well as a PlotGraphics function. However, since I can find exactly zero documentation on PlotCanvas, this is all I know about this object. 3. How do I find anything in the documentation? My inability to find my wxButt in the wxDark with both wxHands (with or without a wxFlashlight) is not limited to PlotCanvas, so I'm hoping that the problem is on my end. The wxPython website, as far as I can tell, only has one documentation link, and it's a link to wxWindows, not the wxPython objects that wrapper it. There's a sample code section, but every last one of the examples is marked "To Be Written When I Have More Time." The wxPython homepage proudly shows a long list of people who claim that wxPython is a Java and/or TkInter killer. All I want to know is, how the hell did these people figure out how to use it? I'm not complaining about wxPython, mind you. What I've gotten to work makes me believe that it really is wonderful. But I'm at wit's end here trying to find out how to do anything that isn't already in a tutorial. Like get the client rect of a wxFrame object. Like find out what events EVT_PAINT might throw. Like use a wxBitmap to double-buffer a wxDC. Like do anything beyond the first four tutorial pages. HELLLLLP! (thanks) -dB ===== David Brady daves_spam_dodging_account at yahoo.com I'm feeling very surreal today... or *AM* I? __________________________________________________ Do You Yahoo!? Yahoo! - Official partner of 2002 FIFA World Cup http://fifaworldcup.yahoo.com From aoeu at go.com Mon Jun 17 06:32:32 2002 From: aoeu at go.com (Thinkit) Date: 17 Jun 2002 03:32:32 -0700 Subject: you guys needs a logo References: <7fe97cc4.0206142325.4df3a174@posting.google.com> Message-ID: <3eeda89d.0206170232.675596b8@posting.google.com> xah at xahlee.org (Xah Lee) wrote in message news:<7fe97cc4.0206142325.4df3a174 at posting.google.com>... > you guys need a logo. > > the light-bulb is quite lame as far as logo goes. > > I suggest that the O'Reilly's python book cover a good choice. It > should not be something funny and cute. > > The MacPython's some 16 Ton weight block is also a good logo. > > Perhaps you guys can run a logo competition. > > Xah > xah at xahlee.org > http://xahlee.org/UnixResource_dir/complang.html#python How about a penguin masturbating? To show what else besides python linux males do. From jepler at unpythonic.net Fri Jun 14 14:15:54 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 14 Jun 2002 13:15:54 -0500 Subject: I feel stoopid ... this code is to verbose In-Reply-To: <3D0A1791.3060307@mxm.dk> References: <3D0A1791.3060307@mxm.dk> Message-ID: <20020614181549.GF30070@unpythonic.net> On Fri, Jun 14, 2002 at 06:19:29PM +0200, Max M wrote: > Hmm ... I am working on a problem. In Danish we have a number format > that looks like: > > 42.000.000,00 which is 42 millions See the 'locale' module, functions 'format' and (internal) _group. If you can call locale.setlocale() to one which requires these separators, it should take care of the rest on calls to .format(). >>> locale.setlocale(locale.LC_ALL, "da_DK") 'da_DK' >>> locale.format("%.2f", 42000000.0, 1) '42.000.000,00' Jeff From geoff at gerrietts.net Sat Jun 1 00:55:08 2002 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Fri, 31 May 2002 21:55:08 -0700 Subject: Extracting data from HTML In-Reply-To: <1022883953.6150.5802.camel@localhost> References: <82096df4.0205311152.5891a17b@posting.google.com> <1022883953.6150.5802.camel@localhost> Message-ID: <20020601045508.GF13794@isis.gerrietts.net> Quoting Ian Bicking (ianb at colorstudy.com): > On Fri, 2002-05-31 at 14:52, Hazel wrote: > > how do i write a program that > > will extract info from an HTML and print > > of a list of TV programmes, its Time, and Duration > > using urllib? > > You can get the page with urllib. You can use htmllib to parse it, but > I often find that regular expressions (the re module) are an easier way > -- since you aren't looking for specific markup, but specific > expressions. You'll get lots of false negatives (and positives), but > when you are parsing a page that isn't meant to be parsed (like most web > pages) no technique is perfect. Definitely agree with this sentiment. I'll go a step farther, and do a little compare/contrast. Once upon a time, I wanted to grab data from the weatherunderground.com website. I know there are lots of better ways to go about getting this information, these days, but I was not so well-informed back then. So I wanted to grab this information, and I tried using regular expressions to mangle the page. But truthfully, it was just too hard to do. I could guess about where in the file the table with all the info would appear, but getting a regular expression that was inclusive enough to catch all the quirks, yet exclusionary enough to filter out all the other embedded tables, proved a very large challenge. That's when the idea of a parser made a lot of sense. I could push the whole page through a parser, looking for one particular phrase in a element, and from that point forward, map elements to elements effectively. It became a very simple exercise, because I knew how to find that info. But as Ian rightly points out, htmllib and a real parser can be very heavy if you're just looking to grab unformatted info -- or if you can't rely on the formatting to be reliable. Both techniques are worth knowing -- but better than either would be finding a way to get the information you're after via XML-RPC or some other protocol that's designed to carry data rather than rendering instructions. Best of luck, --G. -- Geoff Gerrietts "If life were measured by accomplishments, most of us would die in infancy." http://www.gerrietts.net/ --A.P. Gouthey From phd at phd.pp.ru Thu Jun 6 09:08:47 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Thu, 6 Jun 2002 17:08:47 +0400 Subject: vim, compile python Message-ID: <20020606170847.A7683@phd.pp.ru> Hello! For those who use vim editor. Put this into your .vimrc: " Set options for python files autocmd FileType python set autoindent smartindent \ cinwords=class,def,elif,else,except,finally,for,if,try,while \ makeprg=compyle4vim.py \ errorformat=%E\ \ File\ \"%f\"\\,\ line\ %l\\,\ column\ %c,%C%m | \ execute "autocmd BufWritePost " . expand("%") . " call DoPython()" " Compile (clearing *.cgi[co] files after compilation) " and if it is script, make it executable function DoPython() !compyle % if expand("%:e") != "py" !rm -f %[co] endif if getline(1) =~ "^#!" !chmod +x % endif endfunction The compyle and compyle4vim.py programs are attached. Now comments. The first line (autocmd) does not need any explanation. In the second line there are listed keywords after which not only opens new line but also does indent. The third and fourth lines give the name of makeprg (the program for the :make command) and the format of its error output. If you have a python program with syntax errors open the program in vim and execute the command :make % vim will run makeprg (compyle4vim.py) and parse its output, then put cursor to the line and column with the error and report the error on the status line. The fifth line teaches vim to call DoPython function upon saving the file. The function runs compyle (shell script that uses py_compile.py), and if the file is a script (starts with #!) makes it executable. The compyle script is useful for all users, not only for the users of vim, and probably those who use Emacs could use compyle4vim.py :) Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. -------------- next part -------------- #! /usr/local/bin/python -O import sys filename = sys.argv[1] infile = open(filename, 'r') codestring = infile.read() infile.close() try: compile(codestring, filename, "exec") except SyntaxError, detail: pass else: sys.exit() msg, (_fname, lineno, offset, line) = detail sys.stderr.write(""" File "%s", line %d, column %d SyntaxError: %s """ % (filename, lineno, offset, msg)) -------------- next part -------------- #! /bin/sh if [ "$1" = "-1" ]; then only_one=1 shift fi if [ -z "$1" ]; then echo "Usage: compyle [-1] file.py..." exit 1 fi TEMPLATE="from py_compile import compile; compile('" if [ "$only_one" = "1" ]; then pgm=$TEMPLATE$1"')" python -c "$pgm" || exit 1 else for file in "$@"; do pgm=$TEMPLATE$file"')" python -c "$pgm" || exit 1 python -OOc "$pgm" || exit 1 done fi #pgm="$HOME/lib/python/com.py" #python $pgm "$@" && python -O $pgm "$@" From peter at engcorp.com Sat Jun 29 22:30:27 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 29 Jun 2002 22:30:27 -0400 Subject: possibly a dumb question References: <3d1e5eff$1_7@nopics.sjc> <3D1E6415.8128F3F8@engcorp.com> <3d1e6251$1_3@nopics.sjc> Message-ID: <3D1E6D43.75D2820D@engcorp.com> Adonis wrote: > > sure: > > class foo: > def __init__(self, value): > return value > x = foo(0) > print x ;yeilds 0 > > i know the code provided is wrong, but its the general idea. Ahh, you simply cannot do that. The __init__() method is defined to return a reference to the object which it initializes and you can't change that. Note the error message given: TypeError: __init__() should return None Anyway, you really don't need to do this, since in your other post you give your goal (sort of). I'll paste the message here: """an addition: why not use a function blah blah, yes, but this is going to be a modularized project, essentially i want to load some user made modules which will be classes and will be loaded into python dynamically. like a memory resident cgi server skipping the use of pipes.""" Okay, trying again: The above is still not quite correct, because "modules which will be classes" is wrong. I guess you mean the modules will contain class definitions? In that case, you still need to create instances of the classes (like the "x = foo()" part above) and then call methods of the classes. Can you clarify further? What you're trying to accomplish is not hard (I believe... once we figure out exactly what it is) but you are starting off on the wrong foot. -Peter From gh_pythonlist at gmx.de Tue Jun 18 18:10:51 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Wed, 19 Jun 2002 00:10:51 +0200 Subject: how tranform in String?? In-Reply-To: <3D0F9DAE000002DE@www.zipmail.com.br> References: <3D0F9DAE000002DE@www.zipmail.com.br> Message-ID: <20020618221051.GA1879@lilith.my-fqdn.de> * jubafre at zipmail.com.br [2002-06-18 18:49 -0300]: > i have s='xavante brasil', i want to transform in > > s='xavante', 'brasil' with two indexes > > how i make this??????????? Check out the split method of strings in the docs. Using it works like: s = 'xavante brasil'.split() Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 25.0 ?C Wind: 1.0 m/s From sholden at holdenweb.com Mon Jun 3 16:03:30 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 3 Jun 2002 16:03:30 -0400 Subject: thread module under Windows References: <59d8a5f6.0206030730.1be14ffb@posting.google.com> <3CFB9030.4030802@attbi.com> Message-ID: "Pete Shinners" wrote in message news:3CFB9030.4030802 at attbi.com... > Dmitri wrote: > > I have been searching the conference for the simple question like " > > where the thread module is " and got the answer that it's inside the > > python if the threading support is on. > > Thread support defaults to "on" for all python compiles. all windows users > will have thread support, unless they have specifically compiled there own > without. an easy way to test is to just try it.. > [ ... ] > Erm, isn't cygwin the exception here, due to an occasional buglet which Jason hasn't yet finally squashed? I semm to remember I had to explicitly rebuild my cygwin python to get threading. regards -- ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From emile at fenx.com Tue Jun 4 00:54:09 2002 From: emile at fenx.com (Emile van Sebille) Date: Tue, 04 Jun 2002 04:54:09 GMT Subject: Please help with script... References: Message-ID: "Topy" wrote in message news:adheqc$nhn$1 at netnews.upenn.edu... > Hey all, > I'm having trouble with a problem I have with this python program. It's > kind of long, so if anyone has the patience, I would gladly appreciate your > time(the programming is fairly simple I think.) Anyway, the problem I need s/problem I nees/homework assignment/ Ask again when you've addressed the problem and have a specific implementation issue or question. Learning to ask != learning. -- Emile van Sebille emile at fenx.com --------- From pyth at devel.trillke.net Wed Jun 19 16:20:56 2002 From: pyth at devel.trillke.net (holger krekel) Date: Wed, 19 Jun 2002 22:20:56 +0200 Subject: python version? In-Reply-To: ; from huaiyu@gauss.almadan.ibm.com.trillke.net on Wed, Jun 19, 2002 at 06:57:22PM +0000 References: <3D0E8AC8.6C5C96EE@engcorp.com> <37TP8.47886$GY.15021139@twister.nyroc.rr.com> <3D1010C3.C321F8B0@engcorp.com> <3D107948.B3FEE4BB@engcorp.com> Message-ID: <20020619222056.K15079@prim.han.de> Huaiyu Zhu wrote: > Being able to communicate effectively in Usenet may be an important skill > for your students to master. You may want to teach them some lessons you > have learned yourself. Here's a mini multiple choice questionair to get you > started: > ... wow! this monster-thread begins to be quite amusing (hopefully for everybody!) holger From fperez528 at yahoo.com Wed Jun 19 15:35:35 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Wed, 19 Jun 2002 13:35:35 -0600 Subject: Problems with mayavi, pyvtk References: <7396d2b2.0206191025.3351a888@posting.google.com> Message-ID: Lemniscate wrote: > > I just downloaded and installed the latest versions of pyvtk and > mayavi.??However,?when?I?try?to?follow?the?instructions?at > http://mayavi.sourceforge.net/docs/guide/c827.html#VIZ-DATA for using > mayavi, I get the ImportError as below.??For?the?like?of?me,?I?can't > seem to figure out why I don't have any vtkpython modules anywhere > (doing searches on the internet for the module hasn't been a big help > so far Well, google's second hit on 'vtkpython' is http://basic.netmeg.net/godzilla/, which sounds like what you want. At least it should be a good start. Cheers, f From uwe at rocksport.de Fri Jun 7 05:56:22 2002 From: uwe at rocksport.de (Uwe Schmitt) Date: 7 Jun 2002 09:56:22 GMT Subject: problem with distutil.... Message-ID: Hi, I use the following setup.py for generating a distribution: from distutils.core import setup setup(name="graph", version="1.0", author="Uwe Schmitt", author_email="uwe.schmitt at procoders.net", url="http://www.procoders.net", py_modules=["graph"]) The module to distribute is graph.py and is located in the same directory as setup.py. When I do "python setup.py sdist" a dist-folder and a .tar.gz-file are generated. But when I unpack this tar.gz, I cant find the module graph.py... Greetings, Uwe -- Dr. rer. nat. Uwe Schmitt ICQ# 159647634 Uwe.Schmitt at num.uni-sb.de From jdhunter at nitace.bsd.uchicago.edu Fri Jun 28 16:14:50 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Fri, 28 Jun 2002 15:14:50 -0500 Subject: get word base Message-ID: I would like to be able to get the root/base of a word by stripping off plurals, gerund endings, participle endings etc... Here is a totally naive first attempt that gets it right sometimes: import re rgx = re.compile( '(\w+?)(?:ing|ed|es|s)') def get_base(word): m = rgx.match(word) if m: return m.group(1) else: return word words = ['hello', 'taxes', 'thoughts', 'walked', 'rakes'] for word in words: print word, get_base(word) Produces the following output > python get_baseword.py hello hello taxes tax thoughts thought walked walk rakes rak I can think of a few things to do to refine this, but before I forge ahead, I wanted to solicit advice. Thanks, John Hunter From candiazoo at attbi.com Sat Jun 29 21:32:03 2002 From: candiazoo at attbi.com (candiazoo at attbi.com) Date: Sun, 30 Jun 2002 01:32:03 GMT Subject: Most efficient way to write data out to a text file? References: <3d1a6993.248534625@netnews.attbi.com> <3d1dc547.468619140@netnews.attbi.com> Message-ID: <3d1e5f28.508011921@netnews.attbi.com> Oops! Mental typo. :) Either way, the few changes I made really made a difference. There is no escaping the hit I am taking with my awkward queries to the Oracle database that are gathering additional data... but the other changes which affected the code in the loop really paid off! Mike On Sat, 29 Jun 2002 19:05:18 GMT, "Fredrik Lundh" wrote: >Dave Kuhlman wrote: > >"from time import asctime", I hope. From kalle at lysator.liu.se Thu Jun 27 16:31:19 2002 From: kalle at lysator.liu.se (Kalle Svensson) Date: Thu, 27 Jun 2002 22:31:19 +0200 Subject: self destruction :) In-Reply-To: References: Message-ID: <20020627203119.GH11208@i92.ryd.student.liu.se> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [Guyon Mor?e] > > i've tried: 'del self', but somehow it didn't work. afterwards it should > > also _not_ be in the list anymore. [Sean 'Shaleh' Perry] > mylist = [obj1, obj2, ....] > del obj1 # mylist still has a reference to obj1 so > # the del simply decrements the ref count By the way, this program - ----- 8< ----- import sys allobjects = [] class C: def __init__(self): print "Before append, RC: %s." % (sys.getrefcount(self) - 2) allobjects.append(self) print "After append, RC: %s." % (sys.getrefcount(self) - 2) def __del__(self): print "In __del__, RC: %s." % (sys.getrefcount(self) - 2) def delete(self): print "Before remove, RC: %s." % (sys.getrefcount(self) - 2) allobjects.remove(self) print "After remove, RC: %s." % (sys.getrefcount(self) - 2) print "Creating..." C() print print "Deleting..." allobjects[0].delete() print print "Exiting..." - ----- >8 ----- prints - ----- 8< ----- Creating... Before append, RC: 3. After append, RC: 4. Deleting... Before remove, RC: 2. After remove, RC: 1. In __del__, RC: 3. Exiting... - ----- >8 ----- when run. Where do the extra references in __init__ and __del__ come from? Peace, Kalle - -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.7 (GNU/Linux) Comment: Processed by Mailcrypt 3.5.6 iD8DBQE9G3YMdNeA1787sd0RAqHiAJ9Fmja/KUvq08+qls9OZEEHLWrEbACfXWIW URLMCDEABgB1pkvj1eYxV6Q= =APuL -----END PGP SIGNATURE----- From shalehperry at attbi.com Fri Jun 28 12:10:24 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 28 Jun 2002 09:10:24 -0700 (PDT) Subject: Can i write chating system using python In-Reply-To: <3d1c8661$1_1@news.iprimus.com.au> Message-ID: On 28-Jun-2002 tritran wrote: > Can anyone provide me the website or resource to create the chating system > or instance messeger using python. > just go to google and do some searching. There are irc clients, jabber clients, talk clients, etc in python. Plus there is a full network implementation so you can invent your own protocol and client/servers as well. From christophe.delord at free.fr Fri Jun 14 13:05:35 2002 From: christophe.delord at free.fr (Christophe Delord) Date: Fri, 14 Jun 2002 19:05:35 +0200 Subject: I feel stoopid ... this code is to verbose References: <3D0A1791.3060307@mxm.dk> <20020614183945.17cc73f7.christophe.delord@free.fr> <20020614184908.5a174d7a.christophe.delord@free.fr> Message-ID: <20020614190535.62ae384c.christophe.delord@free.fr> On Fri, 14 Jun 2002 18:49:08 +0200 Christophe Delord wrote: > > Here is a 3-liner ;-) > > > > > I just cannot seem to find the nice 3-liner I expected from the > > > beginning. Has anybody got a better solution ? I thought somebody might > > > find it a fun exercise. Well I have... > > def stringSlicer(st, chunkSize=3): > def slc(st): return st and slc(st[:-chunkSize])+[st[-chunkSize:]] or [] > return ".".join(slc(st)) > > > Or maybe this 1-liner: def stringSlicer(st, sz=3, d=''): return st and stringSlicer(st[:-sz],sz,'.')+st[-sz:]+d or "" From gbreed at cix.compulink.co.uk Mon Jun 24 05:56:48 2002 From: gbreed at cix.compulink.co.uk (gbreed at cix.compulink.co.uk) Date: Mon, 24 Jun 2002 09:56:48 +0000 (UTC) Subject: Python HTML Data Collection References: Message-ID: Paul Barrett wrote: > I'm fairly new to Python but I do have a little bit of experience > from > a class I took which taught some Python. I'm working at a job where I > query a CGI script, collect the data and then post it to another CGI > script. My main question is whether I could write a python script which > would automate this process. Both of these scripts are on external > websites and I only need a select amount of the data. I thought that if > any language would do this job, then it would be Python, but I haven't > been able to find any information for something like this. Do you folks > have any suggestions? See urllib[2].urlopen Graham From cliechti at gmx.net Fri Jun 21 17:46:32 2002 From: cliechti at gmx.net (Chris Liechti) Date: 21 Jun 2002 23:46:32 +0200 Subject: TimeoutQueue.py Message-ID: Anyone ever needed a Queue with timeout? I have some external hardware, talking over pyserial to my app. The app uses threads, i.e one is listening on the serial port, any thread can send data but receives answers from the listening one using a Queue. Now sometimes the hardware does not respond (e.g. switched off etc.) and the sending thread would be waiting forever in a Queue.get(). Therefore i needed a get(timeout) so that i can raise an exception in cas of a hardware failure. I hacked up a version of Queue to TimeoutQueue and attached it for everyone who's interested. Its basicaly a merge between Queue.py and threading.py's _Event.wait(). have fun, chris ----- file: TimeoutQueue.py ------------- """A multi-producer, multi-consumer queue. now with timeout value for get(). it waits up to 'timeout' seconds and return the item if one is available within that time or it raises an Empty exception otherwise. cliechti at gmx.net """ >from time import time as _time, sleep as _sleep class Empty(Exception): "Exception raised by Queue.get(block=0)/get_nowait()." pass class Full(Exception): "Exception raised by Queue.put(block=0)/put_nowait()." pass class Queue: def __init__(self, maxsize=0): """Initialize a queue object with a given maximum size. If maxsize is <= 0, the queue size is infinite. """ import thread self._init(maxsize) self.mutex = thread.allocate_lock() self.esema = thread.allocate_lock() self.esema.acquire() self.fsema = thread.allocate_lock() def qsize(self): """Return the approximate size of the queue (not reliable!).""" self.mutex.acquire() n = self._qsize() self.mutex.release() return n def empty(self): """Return 1 if the queue is empty, 0 otherwise (not reliable!).""" self.mutex.acquire() n = self._empty() self.mutex.release() return n def full(self): """Return 1 if the queue is full, 0 otherwise (not reliable!).""" self.mutex.acquire() n = self._full() self.mutex.release() return n def put(self, item, block=1): """Put an item into the queue. If optional arg 'block' is 1 (the default), block if necessary until a free slot is available. Otherwise (block is 0), put an item on the queue if a free slot is immediately available, else raise the Full exception. """ if block: self.fsema.acquire() elif not self.fsema.acquire(0): raise Full self.mutex.acquire() was_empty = self._empty() self._put(item) if was_empty: self.esema.release() if not self._full(): self.fsema.release() self.mutex.release() def put_nowait(self, item): """Put an item into the queue without blocking. Only enqueue the item if a free slot is immediately available. Otherwise raise the Full exception. """ return self.put(item, 0) def get(self, timeout=None): """Remove and return an item from the queue. If optional arg 'timout' is None (the default), block if necessary until an item is available. Otherwise (timout is a number), return an item if one is available within the specified time, else raise the Empty exception. """ if timeout is None: self.esema.acquire() else: # code from threading.py: _Event.wait() # Balancing act: We can't afford a pure busy loop, so we # have to sleep; but if we sleep the whole timeout time, # we'll be unresponsive. The scheme here sleeps very # little at first, longer as time goes on, but never longer # than 20 times per second (or the timeout time remaining). delay = 0.0005 # 500 us -> initial delay of 1 ms endtime = _time() + timeout while 1: if self.esema.acquire(0): break remaining = endtime - _time() if remaining <= 0: #time is over and no element arrived raise Empty delay = min(delay * 2, remaining, .05) _sleep(delay) #reduce CPU usage by using a sleep self.mutex.acquire() was_full = self._full() item = self._get() if was_full: self.fsema.release() if not self._empty(): self.esema.release() self.mutex.release() return item def get_nowait(self): """Remove and return an item from the queue without blocking. Only get an item if one is immediately available. Otherwise raise the Empty exception. """ return self.get(0) # Override these methods to implement other queue organizations # (e.g. stack or priority queue). # These will only be called with appropriate locks held # Initialize the queue representation def _init(self, maxsize): self.maxsize = maxsize self.queue = [] def _qsize(self): return len(self.queue) # Check whether the queue is empty def _empty(self): return not self.queue # Check whether the queue is full def _full(self): return self.maxsize > 0 and len(self.queue) == self.maxsize # Put a new item in the queue def _put(self, item): self.queue.append(item) # Get an item from the queue def _get(self): item = self.queue[0] del self.queue[0] return item ------------------- -- Chris From fperez528 at yahoo.com Tue Jun 25 15:24:41 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Tue, 25 Jun 2002 13:24:41 -0600 Subject: Creating an execution environment References: Message-ID: Juan M. Casillas wrote: > It's?posible?to?have?multiple?environments?with?a?single?python > interpreter???its?posible?to?have?multiple?interpreters?in?a > C?program???Also,?I?want?to?load?chunks?of?code?for?multiple > files,?and?then?add?the?symbols?to?the?right?environment... > Hola Juan, You can use IPython if you want (http://www-hep.colorado.edu/~fperez/ipython) which is set up for exactly that. A single call (documented in the manual and supplied examples) will start an environment which looks similar to the normal interpreter (actually with many enhancements) but with a completely independent namespace. Multiple such environments can coexist either in parallel or embedded within one another. Since they are all python programs, I imagine you can just make the call from within your C code. So far I've only tested the embedding facilities by calling them from within other python programs, but I don't see any reason why making the calls from within C would be a problem. Suerte! f. From tdelaney at avaya.com Thu Jun 13 22:55:52 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Fri, 14 Jun 2002 12:55:52 +1000 Subject: filter2 Message-ID: > From: Delaney, Timothy [mailto:tdelaney at avaya.com] > > Python 1.5.2 ... > > filter2: 5.0598633013 > filter3t: 4.76191299505 > filter3l: 4.37944378728 > > Python 2.2.1 ... > > filter2: 5.40253108615 > filter2t: 4.38322776899 > filter2l: 4.40173851257 > filter3t: 4.32153526376 > filter3l: 4.26489291133 Jython 2.1.2 C:\python\modules\test10.py:6:[SyntaxWarning]: local name 'funcs' in 'filter2t' shadows use as global in nested scopes C:\python\modules\test10.py:6:[SyntaxWarning]: local name 'test' in 'filter2t' shadows use as global in nested scopes C:\python\modules\test10.py:13:[SyntaxWarning]: local name 'funcs' in 'filter2l' shadows use as global in nested scopes C:\python\modules\test10.py:13:[SyntaxWarning]: local name 'test' in 'filter2l' shadows use as global in nested scopes filter2: 5.827999949455261 filter3t: 5.078000068664551 filter3l: 4.983999967575073 Tim Delaney From eric.brunel at pragmadev.com Tue Jun 11 06:15:28 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Tue, 11 Jun 2002 10:15:28 +0000 Subject: python, shell, environment variable References: Message-ID: oliver wrote: > hi, folks, > > I am trying to get a set of python and bash scripts to work, and I > constantly run into trouble with environment variables: > > First, my python script need to modify environment variable, say, > PATH, and want to keep the modification even after the script is done. > os.environ["PATH"]= ... doesn't seem to work, any idea? Modifying environment variables this way is simply impossible: a process run by another process cannot change the environment of its parent, so your Python script will not be able to change environment variables in a persistent way. > Second, it would be better if my python script can call bash shell and > still keep the environment variable modification done by bash. I tried > os.popen("source some_shell"), it doesn't work. ? Same answer: this is impossible. os.popen runs the command in a subshell, and the environment variable changes made by the "source" will only be visible in that sub-shell. One way to achieve what you want to do is to describe the environment variables you want to change in a file created by the sub-process. That file will then be used by the parent to do the actual variable settings. Here is an example: ---------foo.sh--------------------- cat > /tmp/envvars <<. MYVAR1=value1 MYVAR2=value2 . ------------------------------------ ---------foo.py--------------------- import os os.system('foo.sh') for l in open('/tmp/envvars').readlines(): var, val = l.strip().split('=') os.environ[var] = val # ... print os.environ['MYVAR1'] ------------------------------------ This works from a bash child to a Python parent. The reverse is also possible using the same mechanism: the Python script may simply create a file containing "setenv" commands that will be source'd by the parent bash script. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From michael at damaru.com Mon Jun 10 19:39:55 2002 From: michael at damaru.com (Michael Davis) Date: Mon, 10 Jun 2002 19:39:55 -0400 Subject: newbie question - python blocking on int()? Message-ID: <4LaN8.2488$Vr2.586019@news20.bellglobal.com> Hi, I'm writing a specialized ftp client. I'm parsing the output of ftp.dir, which gives me a string like this (call it str): -rw-r--r-- 1 fred 527 Jun 4 22:58 report.php and I'm getting the various parts like this: details = string.split( str ) permissions = details[0] size = details[3] name = details[7] debug( "added remote file size %5d: %s" % (int(size), name) ) This works. But when I replace the 3rd line with this: size = int( details[3] ) python hangs on that line. Why? Thanks a lot! -- Michael Davis Damaru Custom Programming - Web Development - Database Design http://www.damaru.com 416-540-1284 From stefnin.nospam at yahoo.fr Wed Jun 19 12:23:34 2002 From: stefnin.nospam at yahoo.fr (Stephane Ninin) Date: 19 Jun 2002 16:23:34 GMT Subject: tkinter menu (newbie question) References: Message-ID: Eric Brunel a tapote dans news:aeq0cv$p5g$1 at wanadoo.fr: > >> If I want to use several of these windows, >> can still use for base class Tk, instead of Frame ? > > Nope: the instance of Tk is your main window. There should only be > one, and closing it will end your application. If you want to create > other windows, you should create instances of Toplevel. > So, what would be the easiest way to attach a menu to a window which is not the main window ? (that is which doesnot inherit from Tk class) It seems that Frame class has no menu key, so I cannot use config(menu=...) for a class that would inherit for Frame... -- Stephane Ninin stefnin.nospam at yahoo.fr Les cons, ca ose tout... C'est meme a ca qu'on les reconnait. From imbosol at vt.edu Tue Jun 25 15:49:04 2002 From: imbosol at vt.edu (Carl Banks) Date: Tue, 25 Jun 2002 15:49:04 -0400 Subject: Suggestions for good programming practices? References: Message-ID: brueckd at tbye.com wrote: > On 25 Jun 2002, Donn Cave wrote: > >> | So... rather than teaching "avoid W!", let's say "be careful with W >> | because of X, Y, and Z". I still wouldn't use eval/exec on code posted >> | through a web form, for example, but there are times when they are very >> | useful and I can use them in good confidence because I understand their >> | risks. >> >> But you weren't going to be deterred by that pronouncement anyway. >> >> "Avoid exec, execfile, eval, and input" is good advice. Taken at face >> value, it doesn't necessarily absolutely prohibit their use - if I said >> "avoid walking in the road", you could reasonably reasonably assume I'm >> saying something like "walk on the sidewalk when possible". > > If you mean the latter, say the latter. Neither newbies nor veterans have > to do any reading between the lines. Even better, say "walk on the > sidewalk when possible because ___". Fair enough. * Avoid using exec, execfile, eval, and input unless you are deliberately asking your user to supply Python code, and take serious precautions if the program is running at a higher privledge level than the user. All other uses of them should be thoroughly thought out, and the implications understood. >> Someone whose software engineering skills have been honed by years >> of wrestling with ugly code monsters will apply a different perspective >> to that advice. A 1-week newbie could do worse than to follow that >> advice religiously. > > I understand your point, but the OP is new to Python, not programming. > This isn't a big deal; I was simply pointing out that just saying "don't > use those!" (Why? Are they broken? Deprecated? What?) isn't as helpful as > explaining the risks. > > In the specific case of exec/eval, people are quick to strike them down, > often citing the untrusted input example (what about os.system, .fork, > etc.?), but that's a pretty narrow and uncommon usage scenario. I completely disagree. I've seen at least two potentially security-compromizing uses of eval posted here in the last few days as "good" ways to do something. I imagine most people see eval and think, "what a cool, easy way to turn a string into a list!" without stopping to consider that it could also turn a string into a syntax error, or an object that erases your whole filesystem when its __getitem__ method is called. > When I > first learned Python I used them in some of the "forbidden" ways because I > hadn't learned getattr/setattr yet. So what? My programs worked fine (a > little slow) and later I learned better ways and now use those instead. You were lucky that your forbidden uses of eval and exec weren't dangerous in that case. (Or maybe you weren't lucky but were already aware that eval could be dangerous, but that's not the case for all newbies.) > If a person is new to programming altogether then what kind of a teacher > will draw attention to exec/eval in the first place anyway? A good one. Realizing that one does not need to call attention to eval for a newbie to find it, a good teacher explains that it is dangerous before the newbie has a chance to hurt himself with it. > Besides, the > people who understand the potential for problems with something tend to be > the ones that don't mishandle it (whether it be streets, guns, or Python > functions). Which is why it is important to tell people who don't understand the potential for problems to not use eval until they do. You seem to have this idea, based on this last paragraph, that a good way to keep newbies from misusing eval and exec is to keep them in ignorance. I think that's absurd. I don't know if you're just grasping for arguments, because you previously seemed to think it's best to explain WHY, as opposed to simply saying, "Don't do it." -- CARL BANKS http://www.aerojockey.com "Nullum mihi placet tamquam provocatio magna. Hoc ex eis non est." From shalehperry at attbi.com Tue Jun 18 20:04:37 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Tue, 18 Jun 2002 17:04:37 -0700 (PDT) Subject: procmail replacement in Python In-Reply-To: <20020618235901.GA2197@lilith.my-fqdn.de> Message-ID: On 18-Jun-2002 Gerhard H?ring wrote: > Does such a thing exist? I've recently looked into the procmail sources > and run away screaming. I'd very much prefer a Python replacement to > such badly written C code. > > Does anything exist that I can start from? I've even contemplated not > inventing yet another filter language, but just using plain Python > functions. > there is also a nice filter language from CMU called Sieve (I think). You could implement a python based Sieve interpreter. From info at mjais.de Tue Jun 4 17:07:16 2002 From: info at mjais.de (Markus Jais) Date: Tue, 04 Jun 2002 23:07:16 +0200 Subject: property in Py2.2 References: <3CFC9814.4761F3CB@gol.ge> Message-ID: hi this is an example I am using: ############ class Address(object): __slots__ = ('firstname', 'lastname', 'street', 'zipcode', ' city', 'country', '_email', 'phone_private', 'phone_work', 'phone_mobile', 'birthday', 'comment') def __init__(self): self.firstname = "" self.lastname = "" self.street = "" self.zipcode = "" self.city = "" self.country = "" self._email = "" self.phone_private = "" self.phone_work = "" self.phone_mobile = "" self.birthday = "" self.comment = "" def set_email(self, email): if re.match(".*@.*\..*", email): # must contain '@' and a '.' self._email = email else: print "wrong" # TODO raise Exceptionm def get_email(self): return self._email email = property(get_email, set_email, None, 'Setting the email adress') ############ markus Giorgi Lekishvili wrote: > Hi all! > > I wonder if someone finds time to send me a real code of how to use > properties in Py2.2 > > I would be much obliged, if you also send me a version of the code for > Py2.1, with __setattr__ and __getattr__. > > Thx, > Giorgi > > PS. Prior to post here, I have read the materials on www.python.org. I > find them very helpful. From fcolaco at demnet.ubi.pt Sat Jun 22 05:44:17 2002 From: fcolaco at demnet.ubi.pt (=?iso-8859-1?q?Francisco_Miguel_Cola=E7o?=) Date: Sat, 22 Jun 2002 10:44:17 +0100 Subject: =?iso-8859-1?b?RWxlaef1ZXM=?= Brasileiras/Brasilian Election References: Message-ID: On Sat, 22 Jun 2002 01:40:12 +0100, KEVIN MITNICK wrote: > PORTUGU?S > O que um governo corrupto ? capaz de fazer pra manter-se no poder?! > TUDO:manipula??o da imprensa, da economia, das pesquisas eleitorais, > mentiras e falsas acusa??es s?o apenas alguns dos expedientes usados > por FHC e sua equipe (de corruptos) pra manter-se no poder. > Acordem brasileiros. N?o podemos deixar que esse terrorista social > volte a eleger os seus. Basta!Vamos dar uma resposta nas urnas! Vamos > dar uma chance a esquerda. Vamos eleger LULA pra presidente!!! > > ENGLISH > What a corrupt goverment is capable to make to keep the power itself?! > EVERYTHING:manipulation of press, of economy, of electoral research, > lies and false accusation are just some resources used > by FHC and his team (of corrupts) to keep the power themselves. > Brasilians wake up. We can't let this social terrorist elect his > friends again. That's enough!Let's give an answer in the elections. > Let's give a chance to Left Hand. Let's elect LULA for president of Brazil. I think this is the function you want: if government_is corrupt: manipulate (press, economy, poles) say (lies, false_accusations) def rotate_corrupts (scoundrel, color): elect (scroundel, color) rotate_corrupts ('Lula da Silva', 'red') Thanks for recurring to the python help desk. FHC (Francisco Hon?rio Cola?o, actually) From m2 at plusseven.com Wed Jun 12 17:34:37 2002 From: m2 at plusseven.com (Alex Polite) Date: Wed, 12 Jun 2002 23:34:37 +0200 Subject: Something faster then sgmllib for sucking out URLs In-Reply-To: References: <20020612202828.GB16934@matijek.plusseven.com> Message-ID: <20020612213437.GC16934@matijek.plusseven.com> On Wed, Jun 12, 2002 at 03:15:45PM -0700, brueckd at tbye.com wrote: > How fast do you need it to be? Using regular expressions + other junk (see > below) I get about 1 MB/sec on a 900 MHz Pentium III - that's a lot I think this will be fast enough. Thanks a lot. -- Alex Polite http://plusseven.com/gpg/ From mhammond at skippinet.com.au Sun Jun 2 19:12:46 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sun, 02 Jun 2002 23:12:46 GMT Subject: windows install put short path names to win register References: <61f6bfa8.0206021304.2abedc3c@posting.google.com> Message-ID: <3CFAA6E0.5010806@skippinet.com.au> Toni Gaya wrote: > Windows python 2.2.1 installation program puts short file names to > some path values in windows register. > > This makes that programs that read python path or some other > information as python path from windows register crash > -i'm using NTFS (maybe with FAT32, due that FAT system works with > short file names and long file names, works, but as NTFS only works > with long file names, some other installation programs just crash)-. > Examples: try to install mysqldb (mysql connection) or py2exe on > windows with a NTFS disk, and these programs crash. NTFS supports both long and short file names. The short file name can be opened in exactly the same way as the long file name - ie, the 2 names are exactly equivilent. I can't see a good reason for the Python installer to convert to short names (my guess is code generated by the Wise "Wizard"), but I can also see no reason it would not work, and I can assure you that the simple fact that Python writes short names is not enough to prevent mysql from working :) Mark. From tebeka at cs.bgu.ac.il Wed Jun 19 04:41:22 2002 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 19 Jun 2002 01:41:22 -0700 Subject: Help: win32gui & threads References: <33803989.0206170318.9d3a225@posting.google.com> <3D0E6849.3050909@skippinet.com.au> Message-ID: <33803989.0206190041.43b788ac@posting.google.com> Hello Mark, > * Is the DestroyWindow() call being made? Yes and OnDestroy is also called. > * Does the main thread ever appear to end - ie, if you put a print > statement after the PumpMessages(), will it appear. Yes. The OS is winnt4 BTW: I'm sure you recognize the code copy from win32gui_taskbar demo, 10x :-) From eric.brunel at pragmadev.com Mon Jun 3 06:33:10 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Mon, 3 Jun 2002 10:33:10 +0000 Subject: How to suspend execution for at least x seconds in python ? (ie does "sleep" exist in Python ?) References: Message-ID: Nicolas Torzec wrote: > Dear all, > I was wondering if an utility like "sleep x" exist in python ? > Under Unix-like operating systems, the sleep utility suspends execution > for at least x seconds under... Of course it does: import time time.sleep(x) HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From bokr at oz.net Sun Jun 16 14:39:44 2002 From: bokr at oz.net (Bengt Richter) Date: 16 Jun 2002 18:39:44 GMT Subject: Divorce property objects from attribute access dependency? Message-ID: >>> class C(object): ... def __init__(self,v): ... self._v = v ... def get_v(self): return self._v ... def set_v(self,v): self._v = v ... v=property(get_v,set_v) ... vlist = [v,v] ... >>> c=C('something') >>> c.v 'something' >>> c.v='other' >>> c.v 'other' >>> c.vlist [, ] >>> c.vlist[0] Why not trigger get_v() in these accesses too, and have single mechanism to suppress it instead of a single mechanism to effect it? ISTM kind of a hack to rig access via instance attribute as a mechanism for controlling referenced-object behavior (this is my impression, I haven't checked code ;-). IMO default behavior of an object in lhs or rhs context should not depend on how a reference to it was acquired and dereferenced. (Obviously, if property objects always acted as they now do through instance attribute access, "vlist=[v,v]" in this example would have to have some kind of access override like "vlist = [obj(v),obj(v)]", or else it would generate ['something','something'] right there. Using obj(p) a property object could be passed around without evaluation and the potential side effects thereof). BTW, it would be nice to be able to define a property at global module scope also, and perhaps this would tie in nicely. Just musing ;-) Thoughts? Am I missing a big gotcha? One thing is that it will effectively make possible a ()-less function call, which will upset some people ;-) Regards, Bengt Richter From jepler at unpythonic.net Tue Jun 11 12:20:40 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 11 Jun 2002 11:20:40 -0500 Subject: Defining a method final In-Reply-To: <6glN8.35376$86.884025@twister1.libero.it> References: <6glN8.35376$86.884025@twister1.libero.it> Message-ID: <20020611162039.GA2348@unpythonic.net> The following code uses a metaclass to attempt to enforce "final" methods. Warning: Use of metaclasses has exploded brains. Accessing directly through __dict__ or object.__setattr__ can bypass these protections. def finalmethod(f): """Marks a method as a final method. Use like classmethod(), etc. Only works in subclasses of FinalMethods: class C(FinalMethods): def f(x): ... f = finalmethod(f)""" f.__final__ = 1 return f class FinalMethodsMeta(type): """Metatype for FinalMethods""" def __init__(cls, name, bases, dict): super(FinalMethodsMeta, cls).__init__(name, bases, dict) for base in cls.__mro__: if base is cls: continue for attrname in base.__dict__: attr = base.__dict__[attrname] if hasattr(attr, "__final__") and attr.__final__: func = getattr(cls, attrname).im_func print attrname, attr, func if func is not attr: raise ValueError, \ "Subclasses of %s may not override the method %s" \ % (base.__name__, attrname) def __setattr__(cls, name, attr): oldval = getattr(cls, name, None) if hasattr(oldval, "__final__") and oldval.__final__: raise ValueError, "final methods may not be overridden by assignment to class" super(FinalMethodsMeta, cls).__setattr__(name, attr) class FinalMethods: """Subclasses of FinalMethods may define a method to be a finalmethod(). This probably only works with instancemethods, not classmethods or staticmethods. A subclass may not override a finalmethod""" __metaclass__ = FinalMethodsMeta def __setattr__(self, name, attr): oldval = getattr(self, name, None) if hasattr(oldval, "__final__") and oldval.__final__: raise ValueError, "final methods may not be overridden by assignment to instance" super(FinalMethods, self).__setattr__(name, attr) def _test(): class c1(FinalMethods): def f(x): pass f = finalmethod(f) def g(x): pass class c2(FinalMethods): def g(x): pass g = finalmethod(g) # Test that FinalMethods classes can be subclassed when they don't # interfere with each others' final methods class c3(c2, c1): pass assert c3.f.im_func is c1.f.im_func # Test that a FinalMethods class can be subclassed when the added # methods do not interfere with the super's final methods class c4(c1): def g(x): pass # Test that when a final method is concealed by a non-final method, # it blows up try: class c5(c1, c2): pass except ValueError, detail: print "Caught expected ValueError:", detail else: print "Did not catch expected error" print c5.g, c1.g, c2.g raise RuntimeError # Test that when a final method is overridden in the subclass, it # blows up try: class c5(c1): def f(x): pass except ValueError, detail: print "Caught expected ValueError:", detail else: print c5.f, c1.f print "Did not catch expected error" raise RuntimeError # Test that when a final method is overridden in the sub-subclass, # it blows up try: class c6(c3): def f(x): pass except ValueError, detail: print "Caught expected ValueError:", detail else: print c6.f, c3.f print "Did not catch expected error" raise RuntimeError # Test that assigning to non-final attributes works (class) class c7(c1): pass c7.g = lambda: None # Test that assigning to final attributes fails (class) try: class c7(c3): pass c7.f = None except ValueError, detail: print "Caught expected ValueError:", detail else: print "Did not catch expected error" raise RuntimeError # Test that assigning to non-final attributes works (instance) i = c1() i.g = None # Test that assigning to final attributes fails (instance) try: i = c1(); i.f = None except ValueError, detail: print "Caught expected ValueError:", detail else: print "Did not catch expected error" raise RuntimeError print "seems ta work" if __name__ == '__main__': _test() From Sascha.Ferley at infineon.net Sun Jun 23 23:43:56 2002 From: Sascha.Ferley at infineon.net (Sascha Ferley) Date: Sun, 23 Jun 2002 21:43:56 -0600 (MDT) Subject: Resolution PIL, Python and CGI In-Reply-To: <200206241308.33270.rjones@ekit-inc.com> Message-ID: On Mon, 24 Jun 2002, Richard Jones wrote: > On Mon, 24 Jun 2002 13:02, Sascha Ferley wrote: > > On Mon, 24 Jun 2002, Richard Jones wrote: > > > Your web server environment most likely doesn't have /usr/local/lib in > > > its LD_LIBRARY_PATH. > > > > You probly mean Apache... I'll take a look for at the conf files for it.. > > Any ideas where to statically define the lib paths for apache.. i doubt in > > the httpd.conf file.. > > You've basically got three choices as I see it: > > 1. recompile PIL to statically link libjpeg etc. > 2. recompile PIL to use -R (or whatever the flag is) so it remembers where the > dynamic libs are > 3. modify your apache start script to set the environment var appropriately. > > 1 or 2 are going to be the easiest, and safest options. Thanks to Richard, this problem is resolved. The issue: Apache didn't have all the library path's that it needed. to fix. set in httpd.conf the SetEnv LD_LIBRARY_PATH env-variable. Thanks to everyone.. Sascha From d_blade8 at hotmail.com Wed Jun 19 14:25:25 2002 From: d_blade8 at hotmail.com (Lemniscate) Date: 19 Jun 2002 11:25:25 -0700 Subject: Problems with mayavi, pyvtk Message-ID: <7396d2b2.0206191025.3351a888@posting.google.com> Hi everybody, I just downloaded and installed the latest versions of pyvtk and mayavi. However, when I try to follow the instructions at http://mayavi.sourceforge.net/docs/guide/c827.html#VIZ-DATA for using mayavi, I get the ImportError as below. For the like of me, I can't seem to figure out why I don't have any vtkpython modules anywhere (doing searches on the internet for the module hasn't been a big help so far, and it isn't ANYWHERE on my harddrive). Am I missing something simple (the fact that other people don't seem to be having this problem makes me think I am). Please let me know. Thanks a bunch. Lem >>> import mayavi Traceback (most recent call last): File "", line 1, in ? File "C:\Python22\Lib\site-packages\mayavi\__init__.py", line 5, in ? import Common, Base.Objects File "C:\Python22\Lib\site-packages\mayavi\Base\__init__.py", line 19, in ? import Objects File "C:\Python22\Lib\site-packages\mayavi\Base\Objects.py", line 20, in ? import Tkinter, vtkpython, math, tkColorChooser ImportError: No module named vtkpython >>> From jeff at sasmor.com Tue Jun 18 21:40:08 2002 From: jeff at sasmor.com (Jeff Sasmor) Date: Wed, 19 Jun 2002 01:40:08 GMT Subject: If you use Python -OO is it a permanent condition?? References: Message-ID: Actually, once you use Python it's a permanent condition :-) -- #-------------------------------- Jeff Sasmor jeff at sasmor.com "Delaney, Timothy" wrote in message news:mailman.1024445663.26965.python-list at python.org... > For some reason, I parse the subject line as "If you use Python in an > object-oriented way, is it a permanent condition?" > > I'm not sure if that's a philosophical question, but it confused the hell > out of me ;) > > Tim Delaney > > From jtt at hnc.com Tue Jun 4 15:39:18 2002 From: jtt at hnc.com (Jim) Date: 4 Jun 2002 12:39:18 -0700 Subject: DCOracle2 - Can't get cursor.execute to return data when SQL query involves datetimes. Message-ID: Hello, I am trying to write a simple program to retrieve 2 colums from a table. I am running on Solaris 2.8, Python 2.1.1, DCOracle2 and Oracle 8.1.7.3. The columns are: acct_number ( one char long) transaction_datestamp (oracle datetimestamp) Here is my program: import DCOracle2 trandt = '19970110121212' db = DCOracle2.connect("uid/pwd") c = db.cursor() dt = DCOracle2.Timestamp(int(tran_date[0:4]), int(tran_date[4:6]), int(tran_date[6:8]), int(tran_date[8:10]), int(tran_date[10:12]), int(tran_date[12:14])) results = c.execute,('select acct_nbr, trn_dt from testtable where ACCT_NBR = :1 and TRN_DT = :2',"1",dt) aaa = c.fetchone() print aaa The execute never return any thing from query when the date timestamp is part of the query. If I only query on the acct_nbr it returns the expected row. What am I missing ??? Thanks, jim. From joe+usenet at sunstarsys.com Sat Jun 1 10:14:39 2002 From: joe+usenet at sunstarsys.com (Joe Schaefer) Date: 01 Jun 2002 10:14:39 -0400 Subject: Migrating from PHP to Python... References: Message-ID: Gerhard =?iso-8859-15?Q?H=E4ring?= writes: [f'ups disobeyed] [...] > X-Post and F'up to appropriate group. Please continue trolling over > there. Please don't spam clp.misc with garbage like this. IMO you've done a disservice to both communities. -- Joe Schaefer "What a waste it is to lose one's mind. Or not to have a mind is being very wasteful. How true that is." -- Dan Quayle From kragen at pobox.com Sat Jun 1 16:12:02 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 01 Jun 2002 16:12:02 -0400 Subject: How to open a HTML file when the python cgi program is executing? References: <9m6ada.31b.ln@10.0.0.1> Message-ID: <83n0uevjvx.fsf@panacea.canonical.org> Sheila King writes: > print "Location: http://replacement-url\n" > > You should have nothing before this, and there's no point in having > anything after it, since the page is being redirected. Some browsers (in particular old versions of Opera) have problems with redirects every once in a while; that's why redirects traditionally contain HTML, in case the browser is broken. From chris_mk at hotmail.com Tue Jun 4 01:28:14 2002 From: chris_mk at hotmail.com (Christopher) Date: 3 Jun 2002 22:28:14 -0700 Subject: Problem with urllib.urlopen() References: Message-ID: There were some problem with posting the whole link so I'll break each one up... 1st Link: http://www.ncbi.nlm.nih.gov/entrez/query.fcgi? cmd=PureSearch&db=PubMed&details_term=%28%28%28%22organization%20and% 20administration%22%5BMeSH%20Subheading%5D%20OR%20organ%5BText%20Word%5D%29% 20AND%20%28%22diabetes%20mellitus%22%5BMeSH%20Terms%5D%20OR%20diabetes%5BText% 20Word%5D%29%29%20AND%20%28%28%22glucagon%22%5BMeSH%20Terms%5D%20OR%20glucagon% 5BText%20Word%5D%29%20AND%20%28%22insulin%22%5BMeSH%20Terms%5D%20OR%20insulin% 5BText%20Word%5D%29%29%29 2nd Link: http://www.ncbi.nlm.nih.gov/entrez/query.fcgi? cmd=Display&db=PubMed&details_term=%28%28%28%22organization%20and% 20administration%22%5BMeSH%20Subheading%5D%20OR%20organ%5BText%20Word%5D%29% 20AND%20%28%22diabetes%20mellitus%22%5BMeSH%20Terms%5D%20OR%20diabetes%5BText% 20Word%5D%29%29%20AND%20%28%28%22glucagon%22%5BMeSH%20Terms%5D%20OR%20glucagon% 5BText%20Word%5D%29%20AND%20%28%22insulin%22%5BMeSH%20Terms%5D%20OR%20insulin% 5BText%20Word%5D%29%29%29&dopt=XML&query_key=1 Sorry about that. Chris chris_mk at hotmail.com (Christopher) wrote in message news:... > Hi all, > > I'm having a bit of a problem and I'm not sure what I should do. I've > tried a couple of things and I'm running out of ideas. > > Basically, I want to be able to access, directly, the XML versions of > the NCBI results of a search. There is a default display of 'Summary' > and then there are numberous other displays, one of which is 'XML' You > can view the following link in XML (sort of) merely by changing the > display option (that was just some backgroud info, nothing spectacular > that really matters). > Here is a link to an example page (do a search, then click details, > then the URL button and PubMed gives the actual url it uses (otherwise > it is just a cgi url; got that from O'Reilly's "Developing > Bioinformatics Computer Skills": > http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=PureSearch&db=PubMed&details_term=%28%28%28%22organization%20and%20administration%22%5BMeSH%20Subheading%5D%20OR%20organ%5BText%20Word%5D%29%20AND%20%28%22diabetes%20mellitus%22%5BMeSH%20Terms%5D%20OR%20diabetes%5BText%20Word%5D%29%29%20AND%20%28%28%22glucagon%22%5BMeSH%20Terms%5D%20OR%20glucagon%5BText%20Word%5D%29%20AND%20%28%22insulin%22%5BMeS % > 0Terms%5D%20OR%20insulin%5BText%20Word%5D%29%29%29 > > > Now, try this url in your webbrowser and see what you get (you should > see the actual xml version of the page above): > http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=Display&db=PubMed&details_term=%28%28%28%22organization%20and%20administration%22%5BMeSH%20Subheading%5D%20OR%20organ%5BText%20Word%5D%29%20AND%20%28%22diabetes%20mellitus%22%5BMeSH%20Terms%5D%20OR%20diabetes%5BText%20Word%5D%29%29%20AND%20%28%28%22glucagon%22%5BMeSH%20Terms%5D%20OR%20glucagon%5BText%20Word%5D%29%20AND%20%28%22insulin%22%5BMeSH%2 T > rms%5D%20OR%20insulin%5BText%20Word%5D%29%29%29&dopt=XML&query_key=1 > > You should, like I said, get the XML version of the original links > (with some extra information, which is why I want to interface with > the XML site, btw). Now, if you do an interface with Python instead > of your browser you get a response of an error page instead. Why is > that and what can I do to change it? If you have any information, I > would appreciate it ver much. Thanks. > > Chris From garth at deadlybloodyserious.com Mon Jun 17 01:49:32 2002 From: garth at deadlybloodyserious.com (Garth T Kidd) Date: 16 Jun 2002 22:49:32 -0700 Subject: a possibly foolish question about slices References: Message-ID: <4c877253.0206162149.bff3ae3@posting.google.com> > x[p:][:n] Does the parser take the appropriate short-cut, here, or do we end up with a temporary list? Regards, Garth. From cliechti at gmx.net Mon Jun 3 16:17:46 2002 From: cliechti at gmx.net (Chris Liechti) Date: 3 Jun 2002 22:17:46 +0200 Subject: Created a "file" like command in python (see man 4 magic) and face a showstoper bug References: <359e75aa.0206031113.6a8bfed1@posting.google.com> Message-ID: thomas.mangin at free.fr (Thomas Mangin) wrote in news:359e75aa.0206031113.6a8bfed1 at posting.google.com: > I wrote some code perform "file" like operation and I am facing a > nasty bug. > > the files can be found at : ftp://www.slhan.org/source/circle/ > > It produce the same output that "file": > > # ./magic.py core > core: ELF 32-bit LSB core file of 'vi' (signal 11), Intel 80386, > version 1 (SYSV) > > # ./magic.py jpg_good.jpg > jpg_good.jpg: JPEG image data, JFIF standard 1.01, resolution (DPI), > 50 x 50 > > # ./magic.py jpg_bad.jpg > jpg_bad.jpg: JPEG image data, EXIF standard %d.73, 10752 x 2048 > > Note the %d ! > > The code causing problem is : > 1. initialize replace with None > if replace: use this instead: if replace is not None: and have fun progamming python! chris > try: > mime = mime % replace > except: > pass > > In both case mime is containing the string "%d." and replace is in > both case of type int and valued 1 and 0. > > Any idea ? > > Thomas Mangin > -- Chris From neal at metaslash.com Thu Jun 13 22:36:25 2002 From: neal at metaslash.com (Neal Norwitz) Date: Fri, 14 Jun 2002 02:36:25 GMT Subject: Shrinking Python References: Message-ID: On Thu, 13 Jun 2002 16:15:39 -0400, Mahrt, Dallas wrote: > I am looking into using Python in a small device with limited space for > binaries. Due to this, I am both investigating creating a shared library > with the interpreter and shrinking the footprint of this library. I have > found many threads talking bout shared libraries, so I am not too > concerned about that aspect. > > I am concerned about shrinking the library's binary footprint. I did > find several links to a "Deeply Embedded Python" based on 1.5.1 which > has since vanished. I have stripped the library to improve size some (to > ~1.13 MB) but would like to reduce it further. Has anyone tackled this > or even attempted? Are there any links to resources that may help me > that I haven't found? How small do you want it to go? My stripped sizes on Linux are: -rw-r--r-- 1 neal cvs 702902 Jun 13 22:10 libpython2.3.a -rwxr-xr-x 1 neal cvs 682428 Jun 13 22:13 python* This is with the latest CVS version and passing --without-doc-strings to ./configure. You should be able to easily drop the library down by 90k, by removing: unicode, regular expressions, and posix. Without too much work, ie. by defining -DWITHOUT_COMPLEX, and ./configure --without-doc-strings --without-unicode \ --without-signal-module --disable-shared I get this: [neal at epoch src]$ ls -l libpython2.3.a python -rw-r--r-- 1 neal cvs 686126 Jun 13 22:29 libpython2.3.a -rwxr-xr-x 1 neal cvs 664828 Jun 13 22:29 python* Neal From jbublitzNO at SPAMnwinternet.com Tue Jun 18 14:48:36 2002 From: jbublitzNO at SPAMnwinternet.com (Jim) Date: Tue, 18 Jun 2002 18:48:36 GMT Subject: SWIG and Callbacks References: <3d0a8b6e@nntp.server.uni-frankfurt.de> <3d0b4fd6@nntp.server.uni-frankfurt.de> <3d0c6d67@nntp.server.uni-frankfurt.de> <3D0CE698.1050806@SPAMnwinternet.com> <3D0D3223.5070500@SPAMnwinternet.com> <3D0E2606.5050001@SPAMnwinternet.com> Message-ID: <3D0F807A.40203@SPAMnwinternet.com> David Abrahams wrote: > "Jim" wrote in message >>Template-based code does require special treatment with sip. >>In most cases where I've wrapped template-based types or >>classes, I manually write C++ code for conversion C++ <-> Py >>(sip has some functions that make that easier) and implement >>it as a sip 'mapped type', which lets me refer to the same >>conversion code from any return value or arg. > That's a given with Boost.Python; with v2 conversions are automatically > registered in a global repository so they can be re-used automatically > across extension modules. For C++ code with a lot of templates Boost.Python has an advantage, particularly if you're early on the learning curve. >>I generally >>assign a new name (eg QList -> IntList) but wouldn't >>have to (sip will parse QList and look for a mapped >>type definition corresponding). >>sip won't handle all possible C++ syntax, and it sometimes >>takes some creativity to shoehorn something in, but something >>well over 80% of h file code translates directly (after >>removing variable names), and only 1 or 2% really takes >>major effort. > .../your/ h file code... Sure - you can extend sip in almost any way you want also (the bindings generated are C++ code), but it may be a little trickier fitting things in the binding's framework. It's also possible to embed custom Python or C++ code in sip description files and I do that when appropriate (rarely). It kind of goes against the design philosophy of sip IMHO, so I try to avoid it personally. >>The real problem wouldn't seem to be C++ types as such, but >>finding a useful (to the Python programmer) representation >>via PyObject, and still maintaining the range of abilities >>built into the C++ code (esp things like subclassing). > That's built-in to Boost.Python. V1 had to implement a complicated Python > class look-alike itself; V2 uses Python's new-style classes so subclassing > "just works". Making virtual functions overridable in Python requires a > small amount of boilerplate on the part of the programmer. I often wish I > had a good C++ parser front-end which I could use to automate that part. New-style classes lock you into Python 2.2+ though - I've got users still at 1.5.2 and place a lot of emphasis on long term version support. sip does the virtual code boilerplate' automatically, unless the method requires handwritten code for some other reason (rare). On the stuff I do, I see a lot more virtual code than templates, but that obviously varies a lot. >>>>The other features that are helpful on large projects are the >>>>built-in support for versioning >>>How so? Can you say more about this? >>sip uses directives: %If (A - B) ... %End to wrap a block >>of code for versioning over a range. It could also be >>%If (A - ) (>= A) or %If ( - B) (< B). Acceptable values >>for A and B are defined in a %Timeline declaration; actual >>values for A and B are passed to sip via the command line, >>usually derived from a version #define in the C++ source >>code via configure (at least on Linux). Evaluation is by >>lexical ordering of the A and B values. A and B are >>strings like 'KDE_3_0_0'. >>Not very different from #ifdefs, but maybe a little >>easier. > OK. The C++ code you're wrapping still has to get by with #ifdef, I > suppose... Depends on the code I suppose. Qt and KDE just issue all new files - no versioning in the C++ code. >>>Do you mean docstring generation? >> >>No - similar, but sip provides %ExportDoc ... %End directives >>inside which you could place just about anything you want I >>suppose. For PyQt/PyKDE the directives wrap SGML marked-up text. >>You can construct an input file which along with the proper sip >>command line switch, will collect and concatenate all of the >>doc blocks distributed over the description files. The >>concatenated file can be processed (in the case of SGML) to >>provide HTML docs, or whatever you require. > Oh, there are plenty of automated tools for extracting doc from C++. Lots of > people use Doxygen with Boost.Python. No need to invent a new way to do it! It's basically no different than Python - just %ExportDoc instead of """, and SGML and tools are hardly new. You could use doxygen if you wanted to (sip supports comments - I'm guessing sip files are sufficiently parseable for doxygen) and you don't have to use %ExportDoc. You have to generate markup either way if you want HTML or other formats. >>My guess is that Boost does at least some of this a little more >>naturally. I'm not sure the extent that Boost can modify things >>like return values or args without resorting to C++ > There is no "resorting to C++" with Boost.Python -- Boost.Python *embraces* > C++! Since you're coding the wrappers in C++ anyway, it's trivial to make a > "thin wrapper function" which calls the function being wrapped if you want > to change the interface somehow. Then you just wrap the thin wrapper. I finally went back to your website - I took your 'like an IDL' comments a little too literally. IMHO, the fact that Boost.Python *is* C++ is a big advantage for people who want/need that. Personally, I don't want to write C++, which is how I got into this in the first place. Thin wrappers are easily implementable with sip too. In contrast to the very large packages like PyQt and PyKDE, they tend to be very lightweight and quick to build. I can see ways though that I might use Boost.Python to avoid having to choose between writing my own thin wrapper and having to bind an entire C++ fileset. OTOH, I've written C++ wrappers where the only difference betwen the h file and the sip file is the addition of a %HeaderCode block for sip, and I could write a simple py script to do that. Doesn't happen often, but normally isn't a lot more work than that. >>Yes, but I don't write it - I just edit it mostly to correct >>mistakes my description file generator creates and to handwrite >>code where the generator has flagged that. Crude but effective (TM) >>Even without automation, the process is easiest if you start by >>saving the h file with a .sip extension and then (mostly) delete >>the things that sip doesn't want/need, so it's still mostly >>editing (sometimes A LOT of editing). > That seems to be the key difference. It's not clear wether it's really an > advantage, but I suppose that time will tell. I doubt that it's ever clearly an advantage. It works very well for PyQt and PyKDE because of the C++ style those projects use generally - very consistent, relatively small amount of template usage, lots of enums and of course sip has features to support Qt. sip has been used outside of the Qt/KDE area, but perhaps not on anything available publicly yet. There's certainly plenty of opportunities for something like "benchmarketing". Either one of us could contrive examples to make one or the other look clearly better, but like most things it's probably more rational to look at what the user actually needs to accomplish. I've avoided actual code comparisons, because the simple cases tend to be one-sided one way or the other. >>I should probably go back and review Boost. I had thought that >>with Boost it was possible to wrap as much or as little of a >>C++ library as you want to. > That's true. Big selling point IMHO. >>I had the impression SWIG was supposed to do most of that in a single >>step. Just wondering if I could implement something like that with Boost, >>or need to code a line manually for each method/class/whatever. > If you have something which can mostly parse your headers, you can generate > much of the wrapping code automatically. Yes - it looks like that should be possible. Virtual code might require a little more work in generating Boost.Python code automatically, but the tradeoff is probably less things flagged as requiring handwritten code. > Yep. BTW, Boost is much more than just my Python binding library, so please, > for the sake of the other authors: "Boost.Python" when discussing my lib. Noted - I've tried to do better in this post. > Not sure that you'll find much to steal; they're so different in approach... I can be very creative when stealing other people's code :) Actually "under the hood" sip and Boost.Python have similarities. Jim From aahz at pythoncraft.com Thu Jun 13 09:43:31 2002 From: aahz at pythoncraft.com (Aahz) Date: 13 Jun 2002 09:43:31 -0400 Subject: Threading tutorial wanted. References: Message-ID: In article , Alex Polite wrote: > >I few minutes of googling on python + threads doesn't yield a >lot. Maybe someone here can point me to a good primer. Maybe someone >here can write a good primer. Take a look at my web page, but look at the OSCON 2001 tutorial, not the one from 2000 suggested by Anoop. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I had lots of reasonable theories about children myself, until I had some." --Michael Rios From phlip_cpp at yahoo.com Thu Jun 13 01:07:31 2002 From: phlip_cpp at yahoo.com (Phlip) Date: 13 Jun 2002 05:07:31 GMT Subject: Python GUI References: <9ddd154e.0206122021.1b06f89a@posting.google.com> Message-ID: H. Safarzadeh wrote: > -Tkinter: A nice simple lib, but really simple! It dosn't have enough > widgets, and I do not like its look in addition! Look closer. The other ones you listed are fine, and you might end up productively going with them, but do not judge Tkinter based only on its lone /tkinter page on the python.org site. Firstly, you probably overlooked Python MegaWidgets. Tkinter is not simple, it's primitive. That means you must assemble it to get things like a list box WITH a scrollbar. Pmw puts together all the pieces into a fat framework with splitter bars, canned dialog boxes, combo boxes, spinners, sliders, formatted entry fields; the works. And because it comes with a framework for this assembly, new assemblages are just an extension away. Secondly, whenever anyone thinks of a new kind of canvas, such as Visualization Toolkit, the first thing they do is make sure it bonds with Tcl/Tk. Hence the second thing it bonds with is Tkinter. Search the web for these Widgets; they are all over the place. I have found several for flat charting (including Blt), and for R3 and R4 presentations like OpenGL. Thirdly, Tkinter's Canvas widget is essentially a mini-UI kit within a kit. You can float a wide number of kinds of graphic objects (shapes, images, lines, text, etc.), all represented in memory as objects, not pixels. You can bind UI events directly to these objects instead of perform manual hit detection outside the black box. They come with a full set of properties so you don't need to manage their state and representation for them. And you can float primitive windows >and< other Tkinter widgets inside the canvas, down among the graphic primitives. Hence you can roll elaborate super-widgets yourself with very few lines of code. Just last week, over a couple of hours, I implemented visual feedback (a drop shadow) under graphics that were clickable, then granted the user the ability to click and drag these graphics around, with a bungee line connecting dynamically back to their origin. This canvas gave me all that in a very few lines of code, and prevented me from wasting many days performing primitive graphic manipulations within a hand-made framework. Just because other libraries make rolling your own widgets hard don't look at raw Tkinter's low widget count as any sign of weakness; it is in fact a strength. A very nice example of the Canvas in action is TreeBox.py by Arpad Kiss, featured here: http://c2.com/cgi/wiki?PyUnitTestBrowser Fourth, Tkinter has been around a very long time, and any UI question you could think to ask (such as idle timer functions, multi-level callbacks, elaborate key chord detection, mousewheel support) has been added to the system. Put them all together, and you have a >lot< of widgets, a lot of abilities under the hood, and a lot of potential for very facile coding. End of zealotry. The next time someone floats this question I'l passionately recommend Fltk or PyAmulet or something. -- Phlip http://www.greencheese.org/LucidScheming -- In business always remember: The customer is always funny! -- From peter at engcorp.com Fri Jun 28 18:45:56 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 28 Jun 2002 18:45:56 -0400 Subject: Dialing out on MODEM References: Message-ID: <3D1CE724.1B204E88@engcorp.com> Chris Liechti wrote: > > "David McInnis" wrote in > news:mailman.1025270142.10532.python-list at python.org: > > > This is my object > > > >>>> import serial > >>>> modem = serial.Serial > >>>> modem = serial.Serial(2) > >>>> modem.write("atdt3120992\n") > > somtimes it it's a '\r\n' and maybe you need to send the escape sequence > first, to enter the command mode. if i remember correctly thats 3 times ESC > and then wait 100ms or so. either google or your modem manual should help. > i had to do somthing like that to dial with pyserial, but unfortunately the > code is on an other machine... Most often, it's three plusses "+++" preceded and followed by a one-second delay (if I recall correctly... I'm amazed I know longer know this with certainty, given the number of times I've had to do it). In addition, it's always a wise thing to write an empty line (just the terminate, whether it's \n or \r\n or \r) before doing anything after you open the serial port a modem, since a previous application could have sent a few characters without a terminator and they're still sitting in the modem's buffer. It might look to your modem as though you had actually sent "ATDT31ATDT3120992\n" for example, which wouldn't help much. By the way, the need for \r\n has nothing to do with Windows. It's entirely up to your modem what termination strings it wants. Some can handle just \n I think, and I'm pretty sure others will automatically adapt to \r\n as well, even if they don't normally take it. Check the manual for the modem. -Peter From whisper at oz.net Wed Jun 19 13:40:25 2002 From: whisper at oz.net (David LeBlanc) Date: Wed, 19 Jun 2002 10:40:25 -0700 Subject: newbie: help please! In-Reply-To: <002b01c2178e$3e6693e0$0101010a@local> Message-ID: Errr... since that's tk.h doing the include, I am pretty sure that it's trying to include tcl/include/x11/xlib.h and not one from a X11 distro. You just need to add tcl/include to your include path. These files do have some minor differences to add support for Tcl. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Chris Gonnerman > Sent: Wednesday, June 19, 2002 5:38 > To: Steve > Cc: python-list at python.org > Subject: Re: newbie: help please! > > > ----- Original Message ----- > From: "Steve" > Newsgroups: comp.lang.python > To: > Sent: Wednesday, June 19, 2002 5:20 AM > Subject: newbie: help please! > > > > hello, > > > > i have python 2.2.1 installed on my mandrake 8.1 system, which seems to > > work fine. > > > > The problem is im trying to install Tk exstensions, i have > downloaded both > > tcl8.3.4 and tk8.3.4 files and installed using the ./configure, make and > > then make install commands. I then when into the setup file in the > > Python-2.2.1/Modules directory where i understand i have to enable the > > tkinter extension module, by uncommenting the approritae lines. > > > > Lastly i run 'make' at the top of my Python-2.2.1 directory but > i get this > > error: > > > > gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include > > -DHAVE_CONFIG_H -DWITH_APPINIT -I/usr/local/include > -I/usr/X11R6/bin -c > > ./Modules/_tkinter.c -o Modules/_tkinter.o > > In file included from ./Modules/_tkinter.c:49: > > /usr/include/tk.h:83:29: X11/Xlib.h: No such file or directory > > > > i have the Xlib.h in the Python-2.2.1/Include directory > > > > the tkinter part of my setup file looks like this and everything was > > installed in the default places > > The standard Python 2.2 configuration system should automatically add tk > support if all components are there. Your error is because you don't have > the X11 development RPM(s) installed. Get out your Mandrake install set > and add any RPM's which are specifically for X11 development (I run SuSE > so I don't know what RPM's you need for Mandrake). > > The Xlib.h in the Python-2.2.1/Include directory isn't the right one. You > need the X11 version. > > > > > # *** Always uncomment this (leave the leading underscore in!): > > _tkinter _tkinter.c tkappinit.c -DWITH_APPINIT \ > > # *** Uncomment and edit to reflect where your Tcl/Tk libraries are: > > -L/usr/local/lib \ > > # *** Uncomment and edit to reflect where your Tcl/Tk headers are: > > -I/usr/local/include \ > > # *** Uncomment and edit to reflect where your X11 header files are: > > -I/usr/X11R6/bin \ > > X11 header files are conventionally in /usr/X11R6/include or in > /usr/include/X11, and on many distro's both exist, one being a link to the > other. /usr/X11R6/bin is almost certainly NOT the right location. > > > # *** Or uncomment this for Solaris: > > # -I/usr/openwin/include \ > > # *** Uncomment and edit for Tix extension only: > > # -DWITH_TIX -ltix8.1.8.2 \ > > # *** Uncomment and edit for BLT extension only: > > # -DWITH_BLT -I/usr/local/blt/blt8.0-unoff/include -lBLT8.0 \ > > # *** Uncomment and edit for PIL (TkImaging) extension only: > > # (See http://www.pythonware.com/products/pil/ for more info) > > # -DWITH_PIL -I../Extensions/Imaging/libImaging tkImaging.c \ > > # *** Uncomment and edit for TOGL extension only: > > # -DWITH_TOGL togl.c \ > > # *** Uncomment and edit to reflect your Tcl/Tk versions: > > -ltk8.3 -ltcl8.3 \ > > # *** Uncomment and edit to reflect where your X11 libraries are: > > -L/usr/X11R6/lib \ > > # *** Or uncomment this for Solaris: > > # -L/usr/openwin/lib \ > > # *** Uncomment these for TOGL extension only: > > # -lGL -lGLU -lXext -lXmu \ > > # *** Uncomment for AIX: > > # -lld \ > > # *** Always uncomment this; X11 libraries to link with: > > -lX11 > > > > Any help would be much appreciated! > > Install the missing RPM's and correct your setup file as noted, and > all should build fine. > > > Thanks > > You're welcome. Hope this helps. > > Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net > http://newcenturycomputers.net > > > > -- > http://mail.python.org/mailman/listinfo/python-list From kragen at pobox.com Sat Jun 15 15:05:34 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 15 Jun 2002 15:05:34 -0400 Subject: IDE recommendations?? References: <3d0b06bd$0$52043$e4fe514c@dreader3.news.xs4all.nl> Message-ID: <83lm9gtla9.fsf@panacea.canonical.org> Boudewijn Rempt writes: > I've tried to use most IDE's out there -- from Pythonwin to Pythonworks. > None was really comfortable, except for Wing IDE, which is really powerful. > It doesn't include integration of a GUI designer, though, which makes it > little more than a glorified editor/debugger (but _very_ glorified). At one > point there was a version of KDevelop that supported Python development, but > that has disappeared, it seems. > > I use bash & XEmacs & Designer nowadays, and that gives me a fair > productivity. I'd like to improve XEmacs to be a better Python IDE. What kind of integration does it need with Designer? I haven't used GUI-designer IDEs much, so I don't really know what features I'm missing. From jubafre at zipmail.com.br Wed Jun 26 15:41:41 2002 From: jubafre at zipmail.com.br (jubafre at zipmail.com.br) Date: Wed, 26 Jun 2002 16:41:41 -0300 Subject: =?iso-8859-1?Q?py2exe=20erro=20message=3F=3F=3F?= Message-ID: <3D19FB0A000002A8@www.zipmail.com.br> C:\Python22\Lib\SITE-P~1\py2exe>c:\python22\python setup.py py2exe usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: setup.py --help [cmd1 cmd2 ...] or: setup.py --help-commands or: setup.py cmd --help error: invalid command 'py2exe' (no module named 'distutils.command.py2exe') what does mean this error?? Juliano Freitas www.gebrasil.hpg.com.br ------------------------------------------ Use o melhor sistema de busca da Internet Radar UOL - http://www.radaruol.com.br From gabor at realtime.sk Thu Jun 6 17:36:05 2002 From: gabor at realtime.sk (gabor) Date: 06 Jun 2002 17:36:05 -0400 Subject: for , ordering Message-ID: <1023399365.7322.50.camel@wintermute.atriaky.sk> hi, i have a list and i want to create a copy of it with a bit different objects... by now i have something like this: objects1 = [] objects2 = [] . . . for obj1 in objects1: objects2.append(obj2(obj1.x)) 1. isn't there a more elegant way to do this? 2. is that guaranteed that the for cycle iterates over the elemenst of the list in the correct order ( 0,1,2,3,4,....)? thanks, gabor From candiazoo at attbi.com Thu Jun 27 13:36:13 2002 From: candiazoo at attbi.com (candiazoo at attbi.com) Date: Thu, 27 Jun 2002 17:36:13 GMT Subject: Most efficient way to write data out to a text file? References: <3d1a6993.248534625@netnews.attbi.com> Message-ID: <3d1b4d09.306764359@netnews.attbi.com> Completed at Thu Jun 27 10:50:13 2002 11623 function calls in 152.079 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.001 0.001 151.962 151.962 :1(?) 429 0.140 0.000 0.279 0.001 catalog_model.py:109(__init__) 429 0.148 0.000 0.148 0.000 catalog_model.py:114(set_base_fee) 429 0.014 0.000 0.014 0.000 catalog_model.py:118(set_page_fee) 429 0.015 0.000 0.015 0.000 catalog_model.py:121(to_string) 1703 0.104 0.000 0.104 0.000 catalog_model.py:509(fix_date_rang e) 848 0.157 0.000 0.157 0.000 catalog_model.py:57(__init__) 1 150.396 150.396 151.961 151.961 catalog_model.py:573(generate_cata log) 848 0.027 0.000 0.027 0.000 catalog_model.py:66(set_wrk_inst) 848 0.020 0.000 0.020 0.000 catalog_model.py:69(set_title) 848 0.017 0.000 0.017 0.000 catalog_model.py:72(set_pub_name) 848 0.017 0.000 0.017 0.000 catalog_model.py:75(set_std_num) 848 0.016 0.000 0.016 0.000 catalog_model.py:78(set_date_range ) 848 0.137 0.000 0.137 0.000 catalog_model.py:81(set_source_id) 33 0.000 0.000 0.000 0.000 catalog_model.py:820(test_refresh) 36 0.353 0.010 0.353 0.010 catalog_model.py:823(test_echo) 1 0.000 0.000 0.000 0.000 catalog_model.py:826(test_cancel) 419 0.015 0.000 0.033 0.000 catalog_model.py:89(__init__) 419 0.136 0.000 0.136 0.000 catalog_model.py:92(to_string) 1 0.000 0.000 0.000 0.000 connections.py:85(cursor) 1 0.011 0.011 0.189 0.189 cursors.py:108(__do_query) 1 0.022 0.022 0.022 0.022 cursors.py:135(_fetch_row) 1 0.000 0.000 0.000 0.000 cursors.py:145(_check_for_warnings ) 1 0.178 0.178 0.178 0.178 cursors.py:160(_get_result) 2 0.002 0.001 0.002 0.001 cursors.py:162(close) 1 0.000 0.000 0.212 0.212 cursors.py:167(_query) 671 0.027 0.000 0.036 0.000 cursors.py:174(fetchone) 1 0.000 0.000 0.000 0.000 cursors.py:21(__init__) 1 0.000 0.000 0.000 0.000 cursors.py:28(__del__) 2 0.000 0.000 0.000 0.000 cursors.py:31(close) 671 0.009 0.000 0.009 0.000 cursors.py:36(_check_executed) 2 0.000 0.000 0.000 0.000 cursors.py:46(_get_db) 1 0.000 0.000 0.212 0.212 cursors.py:51(execute) 0 0.000 0.000 profile:0(profiler) 1 0.117 0.117 152.079 152.079 profile:0(test.generate_catalog()) From Sascha.Ferley at infineon.net Sun Jun 23 23:02:51 2002 From: Sascha.Ferley at infineon.net (Sascha Ferley) Date: Sun, 23 Jun 2002 21:02:51 -0600 (MDT) Subject: PIL, Python and CGI In-Reply-To: <200206241258.04096.rjones@ekit-inc.com> Message-ID: On Mon, 24 Jun 2002, Richard Jones wrote: > On Mon, 24 Jun 2002 12:51, Sascha Ferley wrote: > > I actually got some nice little traceback that might be of use .. > > > > Traceback (most recent call last): > > File "/export/server/web/CPSC461/cgi-bin/test4.py", line 10, in ? > > import _imaging > > ImportError: ld.so.1: /usr/local/bin/python: fatal: libjpeg.so.6: open > > failed: No such file or directory > > > > though: > > > > infinity:/usr/local/lib->ls -ld libjpeg* > > lrwxrwxrwx 1 root other 12 Jun 16 18:58 libjpeg.so -> > > libjpeg.so.6* > > lrwxrwxrwx 1 root other 12 Jun 16 18:58 libjpeg.so.1 -> > > libjpeg.so.6* > > -rwxr-xr-x 1 root bin 137924 May 21 2001 libjpeg.so.6 > > infinity:/usr/local/lib-> > > > > Which is interesting ... :) > > Your web server environment most likely doesn't have /usr/local/lib in its > LD_LIBRARY_PATH. You probly mean Apache... I'll take a look for at the conf files for it.. Any ideas where to statically define the lib paths for apache.. i doubt in the httpd.conf file.. Sascha From jjl at pobox.com Tue Jun 4 17:38:27 2002 From: jjl at pobox.com (John J. Lee) Date: Tue, 4 Jun 2002 22:38:27 +0100 Subject: Login Authentication with cookies... In-Reply-To: References: Message-ID: On 3 Jun 2002, chandan wrote: [...] > import ClientCookie [...usage snipped...] > Error message: > Traceback (innermost last) > File "c:\python22\programs\demos\trial", line 7, in ? > result = ClientCookie.urlopen(request) > NameError: global name 'types' is not defined [...] This was fixed a few days ago -- please either download 0.0.7b, or just add the line 'import types' at the top of ClientCookie/_ClientCookie.py. Sorry about that -- this will (/should) teach me not to make a 'small change' without retesting. BTW, please send bug reports / questions to me rather than the Python list in the 1st instance -- I may not always notice them here immediately. John From whisper at oz.net Wed Jun 26 03:27:12 2002 From: whisper at oz.net (David LeBlanc) Date: Wed, 26 Jun 2002 00:27:12 -0700 Subject: autocoder redux (was Re: Reminder of a python Project.) In-Reply-To: <3D1941BA.7AFF5C92@engcorp.com> Message-ID: > Timothy Rue wrote: > > > > On 25-Jun-02 22:38:16 Peter Hansen wrote: > > >I'm afraid there is no longer any need for an autocoder. > > > > Geee, maybe you should tell that to NIST > > No need. They called me the other day and I let them know, but > it was too late to get it into the Computerworld article. > > Seriously, there's really no issue with software development any > more. The problems are solved. I guess if you've invented the > world's first autocoder, it kinda sux to be you then, eh? > > -Peter > -- Yes, software development techniques have gotten so good, they're now going to have Windows XP running atomic Reactors, Air Traffic Control and the Space Shuttle. I expect they where encouraged by US Navy tests of a warship being run on Windows NT where the ship (conventional fueled carrier) ended up laying dead in the water and tugs had to be summoned to bring her into port (source: Procedings of the United States Naval Institute). Gives "blue screen of death" a whole new meaning. Dave LeBlanc Seattle, WA USA From skip at pobox.com Fri Jun 7 14:00:10 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 7 Jun 2002 13:00:10 -0500 Subject: Python 2.2.1 vs. gcc 3.1? In-Reply-To: <200206071747.g57HlbH01057@europa.research.att.com> References: <15616.57963.519636.730290@12-248-41-177.client.attbi.com> <200206071747.g57HlbH01057@europa.research.att.com> Message-ID: <15616.62634.635544.905055@12-248-41-177.client.attbi.com> Andrew> PPS: I tried building one of the .so files by hand, essentially Andrew> by snarfing the output from the Makefile log and executing it Andrew> manually: ... Andrew> So apparently it is building a .so file with references Andrew> correctly resolved. That's good to hear Andrew> How do I go about finding out the cause of the failure? Try running the just built python executable and then manually execute "import struct". What error message(s) do you see? -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) Boycott Netflix - they spam - http://www.musi-cal.com/~skip/netflix.html From max at alcyone.com Wed Jun 12 00:43:30 2002 From: max at alcyone.com (Erik Max Francis) Date: Tue, 11 Jun 2002 21:43:30 -0700 Subject: newbie: copying dictionaries References: Message-ID: <3D06D172.FE5F7A23@alcyone.com> "Jon J. Morin" wrote: > Hi. I'm a newbie to python and have a question about copying > dictionary > objects. I'm working out of Learning Python by Mark Lutz & David > Ascher > (O'Reilly). The following bit of code was an exercise in the book and > it > works, but what I'm asking is why? I see where the dictionary keys > get > copied from one object to the other, but how do the values get copied > over > as well? With the assignment statement: newDict[key] = aDict[key] This assigns the key in the new dictionary to the value of the old. Note you could shorten the function using the .update method: def copyDict(aDict): newDict = {} newDict.update(aDict) return newDict -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Who'd ever think it / Such a squalid little ending \__/ The American and Florence, _Chess_ Church / http://www.alcyone.com/pyos/church/ A lambda calculus explorer in Python. From wurmy at earthlink.net Sat Jun 8 11:35:32 2002 From: wurmy at earthlink.net (Hans Nowak) Date: Sat, 08 Jun 2002 15:35:32 GMT Subject: RE Module How to escape $ References: Message-ID: <3D0223D5.4050900@earthlink.net> Prema wrote: > Hi People ! > I'm trying to use the re.sub function to replace several instances of a > PHP Variable eg "$Amount". Could someone please help with an example > Thanks very much > Mike Sure... >>> import re >>> s = "I have $amount dollars" >>> re.sub("\$\S+", "foo", s) 'I have foo dollars' >>> HTH, -- Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) # decode for email address ;-) The Pythonic Quarter:: http://www.awaretek.com/nowak/ From marc.spoorendonk at pretection.com Wed Jun 19 07:05:08 2002 From: marc.spoorendonk at pretection.com (Marc Spoorendonk) Date: Wed, 19 Jun 2002 13:05:08 +0200 Subject: connect to running internet explorer (IE) via shdocvw.dll Message-ID: <3D106564.4040602@pretection.com> This is how my problem can be handled in VB: Dim SWs As New SHDocVw.ShellWindows Dim IE As SHDocVw.InternetExplorer For Each IE In SWs Set Doc = IE.document If TypeOf Doc Is HTMLDocument Then List3.AddItem Doc.url End If Next The question is simple: How can I accomplish this same thing in Python? Mark Hammond answered me this by email: "I think you will find SHDocVw is a vtable interface, and therefore not supported by Python." I've read up about vtable, COM etc. but I am fairly new to this. (I was born as a Unix programmer.) I've played with the interfaces and makepy.py. Should I write a python-plugin in C++ or can it be done by native pytoncode? Regards, Marc From cliechti at gmx.net Thu Jun 13 17:24:09 2002 From: cliechti at gmx.net (Chris Liechti) Date: 13 Jun 2002 23:24:09 +0200 Subject: Type subclassing: bug or feature References: Message-ID: aahz at pythoncraft.com (Aahz) wrote in news:aeau48$111$1 at panix1.panix.com: > Consider the following code: > > class MyStr(str): > def contains(self, value): > return self.find(value) >= 0 > > s = MyStr("hello, world!") > s = s.capitalize() > if s.contains('Hello'): > print "Found it!" > > It fails with an AttributeError when it calls s.contains(), because > s.capitalize() returned a str instead of a MyStr. Anyone want to take a > whack at defending this as the correct behavior? solving this at the C level would require patching many stingobject factory functions... e.g. PyString_FromStringAndSize for capitalize(). but it would indeed be desireable. i think it would like to have a even more genral mechanism. i would like to have a possibility to replace the builtin type. e.g. i could replace the builtin "str" and all strings from now on would be instaces of my class. but that's clearly impossible in the current implementation. like Bengt already sugested just automated ;-) ... >>> class mstr(str): ... for name,m in str.__dict__.items(): ... if type(m) == type(str.find): ... exec """def %s(*args, **kwargs): ... q = str.%s(*args, **kwargs) ... if type(q) is str: return mstr(q) ... else: return q\n""" % (name, name) ... def __contains__(self, other): ... return str.find(self, other) >= 0 ... >>> s = mstr("hello") >>> type(s.capitalize()) >>> 'll' in s.capitalize() 1 chris -- Chris From emile at fenx.com Thu Jun 27 10:14:35 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 27 Jun 2002 14:14:35 GMT Subject: Difference between HTMLParser and htmllib.HTMLParser References: Message-ID: "Dave Swegen" wrote in message news:mailman.1025178934.31606.python-list at python.org... > I've just started playing with these, and I'm curious which is the > better of the two (I noticed the HTMLParser module only came in in 2.2). > And is there any reason why the names are so confusingly similiar? I > tried searching in google for info on this, but the daft naming made it > rather hard ;) > A quick look at the code shows that HTMLParser is part of a family that subclasses markupbase.ParserBase and doesn't need to specify each of the individual tags it understands, allowing it to adapt more easily. >From the initial cvs checkin just over a year ago: (ref http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Li b/HTMLParser.py ) """ A much improved HTML parser -- a replacement for sgmllib. The API is derived from but not quite compatible with that of sgmllib, so it's a new file. I suppose it needs documentation, and htmllib needs to be changed to use this instead of sgmllib, and sgmllib needs to be declared obsolete. But that can all be done later. This code was first published as part of TAL (part of Zope Page Templates), but that was strongly based on sgmllib anyway. Authors are Fred drake and Guido van Rossum. """ HTH, -- Emile van Sebille emile at fenx.com --------- From look at sig.invalid Mon Jun 24 04:57:47 2002 From: look at sig.invalid (Simo Salminen) Date: Mon, 24 Jun 2002 08:57:47 +0000 (UTC) Subject: HTTP authentication References: <3D166ED4.FBE9E2C8@alcyone.com> <3D1679BF.7F2D3A1@engcorp.com> Message-ID: * Peter Hansen [Sun, 23 Jun 2002 21:45:35 -0400] > I think another solution is just to specify the username and > password in the URL like so: > > ref = urllib.urlopen("http://username:password at host.domain/path/file") > and if this does not work, the site might be using digest-authentication instead of basic. then one can use urllib2 and HTTPDigestAuthHandler (look urllib2.py __doc__ for mor info). -- simo salminen iki fi From goodger at users.sourceforge.net Thu Jun 27 21:53:33 2002 From: goodger at users.sourceforge.net (David Goodger) Date: Fri, 28 Jun 2002 01:53:33 GMT Subject: Python Documentation generation In-Reply-To: References: Message-ID: Mahrt, Dallas wrote: > I have found several systems for generating documentation of Python modules > (HappyDoc, pythondoc, pydoc) but I don't believe any of them fulfill all of > these desires. Any suggestions from the group? I'd say that HappyDoc is the best there is right now. If you're looking for something better, and have ideas as to what could make it better, how about helping out with Docutils (http://docutils.sourceforge.net/)? We're working on generating docs from Python modules, but we've a long way to go yet. Input and participation is welcome! -- David Goodger Open-source projects: - Python Docutils: http://docutils.sourceforge.net/ (includes reStructuredText: http://docutils.sf.net/rst.html) - The Go Tools Project: http://gotools.sourceforge.net/ From opengeometry at NOSPAM.yahoo.ca Thu Jun 27 14:45:16 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 27 Jun 2002 18:45:16 GMT Subject: Pythoniac: Thoughts on a hardware Python processor References: Message-ID: Christopher Saunter wrote: > Dear All, > > I have seen the occasional post about creating a specific hardware 'Python > Processor', that could then be built and used in programmable logic or the > like (Valves, relays, core memory - Pythoniac ;-) - in other words, create > a processor that executes Python bytecode directly. There would be > various different reasons for doing this (the 'neat' factor etc...) The only route that has any chance of success is Python -> Forth -> stack engine which leverage works that has already gone into Forth area. But, my days of hand assembling 68000 or programming HP calculators are long gone... :-) -- William Park, Open Geometry Consulting, 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin From K.Rdt at TU-Berlin.DE Thu Jun 27 03:46:38 2002 From: K.Rdt at TU-Berlin.DE (Klaus Reinhardt) Date: Thu, 27 Jun 2002 09:46:38 +0200 Subject: system-output to wxpython-window In-Reply-To: <7647A9F4B298E74DB6793865DA67285004AD94@exchange.adrembi.com> Message-ID: <963VF032VR76ARQMHDC93ZX61WT32VS.3d1ac2de@FRITZweb> Am 26.06.02 15:27:51, schrieb "Roman Yakovenko" : >Also I think after a few minutes of running this code you will want to write multi threading. >It is also simple. I have working example. I think exactly what you need. --------------------------------------------------------------------- Hi Can you give me an example. I read the doc and tried this .. import sys,os,thread # y=thread.start_new_thread("c:\\windows\\netstat.exe","-a -n tcp 20") y=thread.start_new_thread("dir","-a -n tcp 20") sys.exit() but it naturally -) doesn't work. K at Rdt --------------------------------------------------------------------- From pyth at devel.trillke.net Sun Jun 30 03:58:30 2002 From: pyth at devel.trillke.net (holger krekel) Date: Sun, 30 Jun 2002 09:58:30 +0200 Subject: Python needs better error reporting In-Reply-To: <3D1E5376.32716.DF5C94@localhost>; from opus@value.net on Sun, Jun 30, 2002 at 12:40:22AM -0700 References: <3D1EAF12.84CE5914@cascade-sys.com> <3D1E5376.32716.DF5C94@localhost> Message-ID: <20020630095830.C20310@prim.han.de> Opus wrote: > At the most, I might suggest that there be an option to run just the parser, > with more verbose output. Maybe even a different parser would be in order. > Idea for anyone???? i'd suggest a heuristic approach. Compute statistics for which token usually comes after a group of others. Just look at AST-structures not values. This way you can suggest a hint to the user what he might have done wrong. I think it's not feasible and too verbose to tell the user what is actually correct. A simple "Maybe you forgot ..." would cover 90% of the cases, i guess. holger From hesterloli at hotmail.com Mon Jun 17 04:21:31 2002 From: hesterloli at hotmail.com (George Hester) Date: Mon, 17 Jun 2002 08:21:31 GMT Subject: python version? References: Message-ID: Probably not. Where do I import that from and how do it? I am trying to put a script in ASP using Python as the script language to give me the version of Python that I am running when I call the ASP. The more the script works out of the box the better I'll be able to catch on to this language. Thanks. -- George Hester _________________________________ "Gerhard H?ring" wrote in message news:mailman.1024182500.12788.python-list at python.org... > * George Hester [2002-06-15 22:58 +0000]: > > Python ActiveX Scripting Engine error '80020009' > > > > Traceback (innermost last): File " LOOK AT ME! Sign my guestbook:
-- Kragen Sitaker The Internet stock bubble didn't burst on 1999-11-08. Hurrah! The power didn't go out on 2000-01-01 either. :) From hesterloli at hotmail.com Tue Jun 18 17:55:32 2002 From: hesterloli at hotmail.com (George Hester) Date: Tue, 18 Jun 2002 21:55:32 GMT Subject: python version? References: <3tingu8psfmefoab93pl8gips8hg7sgpvp@4ax.com><9YBP8.44418$GY.13865843@twister.nyroc.rr.com> Message-ID: No George was asking for a script he could put in a ASP to determine his version of Python. -- George Hester _________________________________ "Cliff Wells" wrote in message news:mailman.1024435149.22322.python-list at python.org... > On Tue, 18 Jun 2002 20:48:14 GMT > George Hester wrote: > > > Bah humbug. > > Ah, the Christmas spirit, all year round ;) > > -- > Cliff Wells, Software Engineer > Logiplex Corporation (www.logiplex.net) > (503) 978-6726 x308 (800) 735-0555 x308 > > From bernie at 3captus.com Tue Jun 11 11:50:37 2002 From: bernie at 3captus.com (Bernard Yue) Date: Tue, 11 Jun 2002 15:50:37 GMT Subject: getopt Message-ID: <3D061A9F.7CDC7132@3captus.com> Hi, I was expecting an exception from the following getopt.getopt() called, but didn't. Is it normal? I've try with Python 2.1 and 2.2 as well. Result starts the same. Python 2.3a0 (#1, Jun 7 2002, 14:47:32) [GCC 2.95.3 20010315 (SuSE)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import getopt >>> args = '-a -b -c -d bar a1 a2'.split() >>> args ['-a', '-b', '-c', '-d', 'bar', 'a1', 'a2'] >>> optlist, args = getopt.getopt(args, 'abc:d:') >>> optlist [('-a', ''), ('-b', ''), ('-c', '-d')] >>> args ['bar', 'a1', 'a2'] >>> Thanks in advance! Bernie From SBrunning at trisystems.co.uk Thu Jun 13 05:19:36 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Thu, 13 Jun 2002 10:19:36 +0100 Subject: methods to parse big foreign ascii-file? Message-ID: <31575A892FF6D1118F5800600846864DCBD345@intrepid> > From: holger krekel [SMTP:pyth at devel.trillke.net] > Igor Stroh wrote: > > On Wed, 12 Jun 2002 18:05:51 +0200, "holger krekel" > > wrote: > > > > > - come up with a grammar and let a parser do > > > the hard work (which one?) > > > > if the file is structured in a certain form, that is you can describe > the > > data structure with a EBNF, then have a look at 'simpleparse' (I've lost > > the link, but google will certainly have some for you :) )... > > thanks. This might be simple yet powerful enough for the task. I must > try hard to remember EBNF-grammars from my diploma exams, though :-) There is an article about SimpleParse and EBNF here - . Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From amuys at shortech.com.au Mon Jun 24 21:50:49 2002 From: amuys at shortech.com.au (Andrae Muys) Date: 24 Jun 2002 18:50:49 -0700 Subject: Windows versions of Python---pros and cons? References: <3D110B55.4D8AD7FA@astro.cornell.edu> <3D122E79.A189C72E@astro.cornell.edu> <3D124575.2A1393FF@astro.cornell.edu> Message-ID: <7934d084.0206241750.221bbff2@posting.google.com> Tom Loredo wrote in message news:<3D124575.2A1393FF at astro.cornell.edu>... > Fernando P?rez wrote: > > > > Don't know if there's a misunderstanding here: > > Very likely! (On my part!) > > > cygwin is a unix-like > > environment under Windows. > > Okay, my concern was that it wouldn't work with or be able to produce > Windows binaries---like if I had to produce binary extension modules > to ship to others, or a McMillan-ized install that used PythonWin > and Tk or wxWindows. Cygwin is so huge that I got the impression > it was a self-contained "subenvironment" so to speak, so I didn't > realize I could use it to produce stuff that non-cygwin Windows users > could use. > It is important to differentiate between the cygwin environment, and the cygwin platform itself. At its core cygwin is a dll that provides a port of most of the POSIX API to W32. On top of this, cygwin also offers a host of other API's common on various unix platforms ported to the cygwin.dll 'unix platform'. On top of these libraries the cygwin environment is assembled out of all manner of common unix programs, utilities, servers, etc built using these libraries and the cygwin.dll. The environment is huge. Considering that a full install includes ports of XFree86, TeX, gcc & libs, python2.2, perl5.6.1, a full install == a LOT of bytes :). The libraries however are a fraction of this size, consider a ls -l *.dll on /bin (where cygwin keeps the libraries, I assume for windows compat' sake) $ ls -l *.dll | awk 'BEGIN { sum = 0 } { sum = sum + $5 } END { print sum }' 8931012 $ ls -l cygwin1.dll -rwxr-xr-x 1 Administ None 895304 Jun 24 12:33 cygwin1.dll $ ls -l *.dll -rwxr-xr-x 1 Administ None 46592 Jan 21 04:51 cygXpm-X4.dll -rwxr-xr-x 1 Administ None 41984 Jan 21 04:51 cygXpm-noX4.dll -rwxr-xr-x 1 Administ None 58880 May 7 16:36 cygbz2-1.dll -rwxr-xr-x 1 Administ None 635904 May 17 22:25 cygcrypto.dll -rwxr-xr-x 1 Administ None 333824 Jun 19 08:16 cygdb2.dll -rwxr-xr-x 1 Administ None 51200 Mar 17 16:24 cygexslt-0.dll -rwxr-xr-x 1 Administ None 46080 Apr 25 2001 cygform5.dll -rwxr-xr-x 1 Administ None 35328 Jan 9 16:11 cygform6.dll -rwxr-xr-x 1 Administ None 18944 Feb 20 13:06 cyggdbm.dll -rwxr-xr-x 1 Administ None 19968 Jan 13 11:29 cyghistory5.dll -rwxr-xr-x 1 Administ None 22016 Dec 13 2001 cygintl-1.dll -rwxr-xr-x 1 Administ None 21504 Jun 21 2001 cygintl.dll -rwxr-xr-x 1 Administ None 82944 Oct 20 2001 cygitcl30.dll -rwxr-xr-x 1 Administ None 35328 Oct 20 2001 cygitk30.dll -rwxr-xr-x 1 Administ None 45568 Feb 8 10:00 cygjbig1.dll -rwxr-xr-x 1 Administ None 121856 Feb 9 15:21 cygjpeg6b.dll -rwxr-xr-x 1 Administ None 26624 Apr 25 2001 cygmenu5.dll -rwxr-xr-x 1 Administ None 19968 Jan 9 16:11 cygmenu6.dll -rwxr-xr-x 1 Administ None 159232 Apr 25 2001 cygncurses++5.dll -rwxr-xr-x 1 Administ None 179200 Jan 9 16:11 cygncurses++6.dll -rwxr-xr-x 1 Administ None 230912 Apr 25 2001 cygncurses5.dll -rwxr-xr-x 1 Administ None 206848 Jan 9 16:11 cygncurses6.dll -rwxr-xr-x 1 Administ None 15360 Apr 25 2001 cygpanel5.dll -rwxr-xr-x 1 Administ None 11776 Jan 9 16:11 cygpanel6.dll -rwxr-xr-x 1 Administ None 41105 Nov 22 2001 cygpcre.dll -rwxr-xr-x 1 Administ None 40251 Nov 22 2001 cygpcreposix.dll -rwxr-xr-x 1 Administ None 175104 May 8 05:10 cygpng10.dll -rwxr-xr-x 1 Administ None 179200 May 24 12:23 cygpng12.dll -rwxr-xr-x 1 Administ None 174080 Jan 21 11:05 cygpng2.dll -rwxr-xr-x 1 Administ None 22528 Jun 9 15:50 cygpopt-0.dll -rwxr-xr-x 1 Administ None 123904 Jan 13 11:29 cygreadline5.dll -rwxr-xr-x 1 Administ None 68016 Nov 21 2001 cygregex.dll -rwxr-xr-x 1 Administ None 159744 May 17 22:25 cygssl.dll -rwxr-xr-x 1 Administ None 399360 Oct 20 2001 cygtcl80.dll -rwxr-xr-x 1 Administ None 4608 Oct 20 2001 cygtclpip80.dll -rwxr-xr-x 1 Administ None 10240 Oct 20 2001 cygtclreg80.dll -rwxr-xr-x 1 Administ None 258560 Feb 10 18:36 cygtiff3.dll -rwxr-xr-x 1 Administ None 637952 Oct 20 2001 cygtk80.dll -rwxr-xr-x 1 Administ None 895304 Jun 24 12:33 cygwin1.dll -rwxr-xr-x 1 Administ None 1277440 Mar 17 13:56 cygxml2-2.dll -rwxr-xr-x 1 Administ None 155136 Mar 17 16:23 cygxslt-1.dll -rwxr-xr-x 1 Administ None 15360 Mar 17 16:24 cygxsltbreakpoint-1.dll -rwxr-xr-x 1 Administ None 50688 Mar 12 14:38 cygz.dll -rwxr-xr-x 1 Administ None 49664 Feb 25 13:33 libW11.dll -rwxr-xr-x 1 Administ None 749056 Aug 22 2001 libperl5_6_1.dll -rwxr-xr-x 1 Administ None 771584 Jan 1 06:26 libpython2.2.dll -rwxr-xr-x 1 Administ None 204288 Oct 20 2001 tix4180.dll As you can see the cygwin dll is only ~900k, while even the entire porting environment (excluding X11R6) is < 9Mb (X11R6 is just over 4Mb). So in most situations this is not imposing a signifigant overhead. Andrae Muys From kragen at pobox.com Sat Jun 8 20:28:23 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 08 Jun 2002 20:28:23 -0400 Subject: array, list, performance... References: <3CFFB86A.4114459A@accessforall.nl> Message-ID: <83ofel5m8o.fsf@panacea.canonical.org> Ype Kingma writes: > Michael Chermside wrote: > > li.append(x) appending is O(1) > > (actually, it SOMETIMES takes O(len(li)) as it > > resizes the list. But if you grow a list by > > continually appending, the amortized time is > > linear (ie, constant amortized time per element) > > Append is often enough linear in the length of the list > that growing by appending is O(len(li) * len(li)). Not when I try it: Python 2.1.1 (#2, Dec 19 2001, 12:19:22) [GCC 2.95.2 20000220 (Debian GNU/Linux)] on linux2 Type "copyright", "credits" or "license" for more information. >>> import MetaPy.Speed >>> def mklist(n): ... ar = [] ... for ii in xrange(n): ... ar.append(ii) >>> MetaPy.Speed.seconds_per_call(lambda: mklist(0)) 1.7825510264682151e-05 >>> MetaPy.Speed.seconds_per_call(lambda: mklist(1)) 2.862680041153042e-05 >>> MetaPy.Speed.seconds_per_call(lambda: mklist(10)) 7.8054009556034588e-05 >>> MetaPy.Speed.seconds_per_call(lambda: mklist(100)) 0.00057740376706547905 >>> MetaPy.Speed.seconds_per_call(lambda: mklist(1000)) 0.0055893541133707342 >>> MetaPy.Speed.seconds_per_call(lambda: mklist(10000)) 0.055918868174255905 >>> MetaPy.Speed.seconds_per_call(lambda: mklist(100000)) 0.59515897688580466 Looks linear to me. From ark at research.att.com Fri Jun 7 14:15:45 2002 From: ark at research.att.com (Andrew Koenig) Date: Fri, 7 Jun 2002 14:15:45 -0400 (EDT) Subject: Python 2.2.1 vs. gcc 3.1? In-Reply-To: <15616.63342.559215.644086@12-248-41-177.client.attbi.com> (message from Skip Montanaro on Fri, 7 Jun 2002 13:11:58 -0500) References: <15616.57963.519636.730290@12-248-41-177.client.attbi.com> <200206071747.g57HlbH01057@europa.research.att.com> <15616.62634.635544.905055@12-248-41-177.client.attbi.com> <200206071804.g57I4fp01212@europa.research.att.com> <15616.63342.559215.644086@12-248-41-177.client.attbi.com> Message-ID: <200206071815.g57IFjg01303@europa.research.att.com> Skip> Showing that you cd'd to your build directory and executed "./python" would Skip> give me greater faith that you were executing the just-built interpreter and Skip> importing the proper .so file. Note that since the build process renamed Skip> the file, you will probably have to go back and mv it back to struct.so Skip> before trying this... $ ./python Python 2.2.1 (#4, Jun 7 2002, 13:24:38) [GCC 3.1] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> import struct Traceback (most recent call last): File "", line 1, in ? ImportError: No module named struct To what would it have renamed struct.so? From martin at v.loewis.de Thu Jun 6 16:32:00 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 06 Jun 2002 22:32:00 +0200 Subject: 64-bit Python? References: <87elfl3yvu.fsf@mathdogs.com> <83660wgvrm.fsf@panacea.canonical.org> Message-ID: Kragen Sitaker writes: > Yes, this is correct. Even the buffer interface, which my > arrayfrombuffer package[0] uses to provide access to mmapped files as > Numeric arrays inexplicably uses int instead of size_t. It can't use size_t for the object's size, since size_t is unsigned, but some applications put negative numbers into ob_size (see longobject.c for an example). Regards, Martin From gerhard.haering at gmx.de Thu Jun 27 11:37:26 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 27 Jun 2002 15:37:26 GMT Subject: Var substitution References: Message-ID: Guy wrote in comp.lang.python: > Hi > > What i'm wanting to know, is there any way of looking at a variables > value rather than its name. > > Example > > Unix : ${MyVar} > Dos : %MyVar% Python: MyVar > Both of the above will be subtituted with the values. In Python, values are bound to names. By using a name on the left-hand side of =, you bind a value to it. In all other cases, you access the value with its name. x = "foo" Bind the value "foo" to the name x in the current scope (namespace). print x Access the value the name "x" in the current namespace refers to. y.x = "foo" Bind the value x in the namespace y (which might be a class, class instance, module, function, ...) to the value "foo". print y.x Access the value of the name "x" in the namespace y. > Example python script (below causes error): > >>>> guy="name" You bind the value "name" of type string to the name 'guy' in the current namespace. In this case, the global namespace. >>>> import os You import the module os, which does have a namespace of its own. >>>> os.guy You try to access 'guy' in the namespace of the os module, which doesn't exist there. > This is what should happen : > >>>> import os >>>> os.name Sure, the os module has "name" in its namespace, but not "guy". That's why this works. > 'nt' Just for demonstration, as there's no point in it, but you _could_ do the following: import os os.guy = "foo" print os.guy Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From msoulier at nortelnetworks.com_.nospam Thu Jun 20 12:26:35 2002 From: msoulier at nortelnetworks.com_.nospam (Michael P. Soulier) Date: 20 Jun 2002 16:26:35 GMT Subject: do...while Message-ID: Greetings. How do you people handle the lack of a do...while in Python? I find that at times, I must initialize variables for a loop with identical code to the loop, which feels like a waste to me. ie. line = filehandle.readline() while len(line) > 5: line = filehandle.readline() A do...while here would be nice. Just curious. Mike -- Michael P. Soulier, QX41, SKY Tel: 613-765-4699 (ESN: 39-54699) Optical Networks, Nortel Networks, SDE Pegasus "...the word HACK is used as a verb to indicate a massive amount of nerd-like effort." -Harley Hahn, A Student's Guide to Unix From bdesth at nospam.free.fr Tue Jun 25 13:59:03 2002 From: bdesth at nospam.free.fr (laotseu) Date: Tue, 25 Jun 2002 13:59:03 -0400 Subject: 'parent object'? References: <3d18228c$0$221$4d4ebb8e@news.nl.uu.net> <3D182662.CBC925DB@alcyone.com> Message-ID: <3D18AF67.2010207@nospam.free.fr> Erik Max Francis wrote: > "Guyon Mor?e" wrote: > > >>Is there, like 'self, also a 'parent' object of some sort? >> >>The problem i'm having is that i have a class, which contains a list >>of >>instances of another class. How can i let this 'childclass' call a >>function >>which is on the 'parent class'? > > > An instance has access to its class (.__class__ attribute), and a class > has access to its parent classes (.__bases__ attribute). > That's ok for 'parent/child' in the inheritence meaning. But the OP asked about something else : a container instance (the 'parent'), and the instances it contains (the 'childrens'). This has nothing to do with subclassing. You should define a 'container/child' interface. it may be very simple in Python, something like class container: def __init__(self): self.childrens = [] def add_child(self, child): if child not in self.childrens: child.parent = self # create a 'parent' attribute self.childrens.append(child) def remove_child(self, child): if child in self.childrens: del self.childrens[self.childrens.index(child)] del child.parent Now whatever class your child objects is an instance of, it gets a new 'parent' attribute when you add it to the container instance, and looses this attribute when you remove it... Well... it could be safer to check if the 'child' object already has a parent before you add it, but y'll sure improve all this !-) Hope this helps laotseu From merkosh at hadiko.de Fri Jun 14 22:12:22 2002 From: merkosh at hadiko.de (Uwe Mayer) Date: Sat, 15 Jun 2002 04:12:22 +0200 Subject: file.tell() -- obscure IOError Message-ID: hi, i have an object which conforms to the file protocoll. while calling the self.file.tell() method, i get the following error message: >>> s1 == s2 Traceback (most recent call last): File "", line 1, in ? File "riff.py", line 153, in __cmp__ data1 = self.read(self.value.step) File "riff.py", line 205, in read maxsize = len(self) -self.tell() File "riff.py", line 234, in tell return self.file.tell() -self.value.start IOError: (0, 'Error') when does tell() raise an IOError? Thanks for any help! Yours Uwe From jepler at unpythonic.net Mon Jun 24 12:56:21 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 24 Jun 2002 11:56:21 -0500 Subject: converting an array of chars to a string In-Reply-To: <60FB8BB7F0EFC7409B75EEEC13E20192158EF5@admin56.narex.com> References: <60FB8BB7F0EFC7409B75EEEC13E20192158EF5@admin56.narex.com> Message-ID: <20020624165620.GD2142@unpythonic.net> Earlier, JB [mailto:jblazi at hotmail.com] wrote: > > Thank you very much. In principle, this was exactly, for > > what I was looking. But most unforunately if I declare such > > an array a, then > > > > a[0]=210 > > a[0] += 46 > > > > produces an error instead of the correct result 0. Now I am > > a bit desperate. > On Mon, Jun 24, 2002 at 09:59:05AM -0600, Bjorn Pettersen wrote: > Python helpfully gives you an OverflowError since that's technically > what it is. Having the value magically truncated would surprise even > more people. The simple solution is of course: > > def byteAdd(a, b): > return (a + b) % 256 > > a[0] = byteAdd(a[0], 46) > > hth, > -- bjorn It seems like a "modulo arithmetic" array type would be useful. Hypothetically, >>> x = array.array("mB", [210]) >>> x[0] += 47 >>> x[0] 1 Jeff` From cliechti at gmx.net Sat Jun 1 15:54:18 2002 From: cliechti at gmx.net (Chris Liechti) Date: 1 Jun 2002 21:54:18 +0200 Subject: wxPython performance References: <3CF8E382.3A44F0DA@engcorp.com> Message-ID: Andrei Kulakov wrote in news:slrnafhtdv.407.ak at ak.silmarill.org: > In article <3CF8E382.3A44F0DA at engcorp.com>, Peter Hansen wrote: >> Andrei Kulakov wrote: >>> >>> "hello world" type program from wxPython tutorial takes 6 >>> seconds to start on my cel 366 128mb system (running Debian). Is ... > . if not too much trouble, could you please try this one > (from wxpython tutorial)? > > from wxPython.wx import * > > class MyApp(wxApp): > def OnInit(self): > frame = wxFrame(NULL, -1, "Hello from wxPython") > frame.Show(true) > self.SetTopWindow(frame) > return true i changed this to "return false" > app = MyApp(0) > app.MainLoop() (2nd time, P3-600 Win32) $ time python news_wxspeedtest.py OnInit returned FALSE, exiting... ... real 0m1.382s user 0m0.020s sys 0m0.030s here the slowest part is loading and initilaizing the interpreter. i think wx windows slows loading down, especialy the first time, because its loading the wx library. on win32 this is about 4MB. chris -- Chris From pyth at devel.trillke.net Fri Jun 7 11:33:55 2002 From: pyth at devel.trillke.net (holger krekel) Date: Fri, 7 Jun 2002 17:33:55 +0200 Subject: self In-Reply-To: ; from vjovanov@stevens-tech.edu on Fri, Jun 07, 2002 at 10:51:17AM -0400 References: <0%hL8.22575$tK.5490038@news02.optonline.net> <_zpL8.81$pq2.4342892@newnews.cc.stevens-tech.edu> Message-ID: <20020607173355.C6609@prim.han.de> Vojin Jovanovic wrote: > > Why such a > > harsh reaction without bothering to correct the obvious 'typo'? > > No, it is not the 'typo'. I corrected that immediately. ok. sorry for wrong accusations... > However, all that aside, the problems is that your code just din't work > after I corrected those 2 'typos'. Take a look yourself .... > > Python 2.1.2 (#31, Jan 15 2002, 17:28:11) [MSC 32 bit (Intel)] on win32 hmmm. it seems to be a problem with the python version: 'type(value)!=str' comparison doesn't seem to work with python2.1 (works with 2.2). So here goes my python2.1/2.2 version: Python 2.1.3 (#1, Apr 20 2002, 10:14:34) [GCC 2.95.4 20011002 (Debian prerelease)] on linux2 Type "copyright", "credits" or "license" for more information. Welcome to Lazy Python. Type "help LazyPython" for help. >>> class Evaluator: def __init__(self, eqs={}): self.__dict__['equations']=eqs def __getattr__(self, name): value = self.equations[name] if type(value)!=type(''): return value scope={} while 1: try: return eval(value, scope) except NameError, n: var=str(n).split("'")[1] scope[var]=getattr(self, var) def __setattr__(self, name, value): self.equations[name]=value >>> class Berta: a=5 >>> e=Evaluator({'a':3}) >>> e.berta=Berta() >>> e.g='berta.a*a' >>> e.g 15 >>> now i hope we are getting close to discussing the idea, finally :-) regards, holger From larooy at xtar.co.nz Thu Jun 13 03:46:56 2002 From: larooy at xtar.co.nz (John La Rooy) Date: Thu, 13 Jun 2002 19:46:56 +1200 Subject: using m2crypto to encrypt credit card numbers References: Message-ID: <20020613194656.04643b54.larooy@xtar.co.nz> Whatever you use to identify the credit card number has to be guaranteed to be unique for each card number. A hash won't give you that. Perhaps you could use public key encryption. Encrypt the keys right away on the internet connected machine using a key pair. The private key is kept on a separate system and can recover the credit card numbers from the cipher. Every purchase made with the card will encrypt the number to the same ciphertext which you use to identify that card everywhere in your database. The machine with the private key need not be connected to the internet at all if you don't mind using sneakernet to transport the transactions to it. John On Tue, 11 Jun 2002 15:12:00 -0500 "Mark McEahern" wrote: > [Graham Ashton] > > I've not followed the thread, but I'm assuming that your problem is that > > you don't want to store the card number in plain text, and that if you > > encrypt and store it in a manner that will allow automatic decryption by > > your software, then a cracker who gains access to your servers will be > > able to decrypt the card numbers with ease. > > That's it precisely. > > > The only sensible solution to this that I've ever thought of involves > > getting the payment processor (i.e. online transaction processing > > company) to store a hash for each of your customers' credit cards. > > I should have mentioned that solutions which involve getting the payment > processor to do anything different are simply not an option. As far as I > can tell, I either store the credit card number or I can't do recurring > billing. If you know of any payment processors that support recurring > billing, please share them. > > > Consequently you wouldn't need to store the card number at all, just the > > encrypted hash. Job's a good'un; card numbers would be nicked from far > > fewer online web sites with shoddy security. > > Also, another reason I need to store the credit card number is in the case > of chargebacks, which don't go through the payment processor--rather, they > go through the bank. I don't fully understand this part, but I do believe I > need the credit card number in order to link the chargeback to a > transaction. > > Thanks for your comments, > > // mark > > - > > > From shagshag13 at yahoo.fr Thu Jun 6 14:40:15 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Thu, 6 Jun 2002 20:40:15 +0200 Subject: Efficient python programming... Message-ID: I'm looking for any state of art, optimizing techniques, tips, that a python beginner couldn't know by itself, but should learn and would be aware to write "efficient and good looking"python's code... (not the kind of thing which made you an obfuscated python nerd, but that "map" should be preferred to "for in loop" if possible, that dictionary are very well optimized, etc.) Thanks, s13. From sholden at holdenweb.com Fri Jun 28 09:39:25 2002 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 28 Jun 2002 09:39:25 -0400 Subject: SimpleHTTPServer + Multithreading References: <3d1b4010$1_3@nopics.sjc> Message-ID: <_EZS8.107502$mF.30395@atlpnn01.usenetserver.com> "Adonis" wrote ... > i was googling around and was able to come up with cannibalized code, and > was wondering if there was anyway to make it more "clean" looking, or as it > is, is the best way: > > (main idea: a multithreading SimpleHTTPServer) > > import BaseHTTPServer, SimpleHTTPServer, SocketServer, socket, webbrowser > > class XFSPWebServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer): > pass > > class ReqHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): > > def do_POST(self): > data = self.rfile.read(int(self.headers["content-length"])) > data = data.split('&')[0].split('=')[1] > self.wfile.write("HIH") > > PORT = 80 > > httpd = XFSPWebServer((socket.gethostname(), PORT), ReqHandler) > > httpd.serve_forever() > > any help would greatly be appreciated. > Here's the threading CGI server from Chpater 7 of "Python Web Programming". Replacing CGIHTTPServer with SimpleHTTPServer should give you what you want. As you can see, the trick is simply to subclass the server you want, making sure that the ThreadingMixin class is the first base class. import SocketServer import BaseHTTPServer import CGIHTTPServer class ThreadingCGIServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer): pass import sys server = ThreadingCGIServer(('', 8080), CGIHTTPServer.CGIHTTPRequestHandler) # try: while 1: sys.stdout.flush() server.handle_request() except KeyboardInterrupt: print "Finished" You can get this, and lots more, code at the download page of http://pydish.holdenweb.com/pwp/ regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From ark at research.att.com Fri Jun 7 14:04:41 2002 From: ark at research.att.com (Andrew Koenig) Date: Fri, 7 Jun 2002 14:04:41 -0400 (EDT) Subject: Python 2.2.1 vs. gcc 3.1? In-Reply-To: <15616.62634.635544.905055@12-248-41-177.client.attbi.com> (message from Skip Montanaro on Fri, 7 Jun 2002 13:00:10 -0500) References: <15616.57963.519636.730290@12-248-41-177.client.attbi.com> <200206071747.g57HlbH01057@europa.research.att.com> <15616.62634.635544.905055@12-248-41-177.client.attbi.com> Message-ID: <200206071804.g57I4fp01212@europa.research.att.com> Skip> Try running the just built python executable and then manually execute Skip> "import struct". What error message(s) do you see? $ python Python 2.2.1 (#1, Jun 7 2002, 12:06:38) [GCC 3.1] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> import struct Traceback (most recent call last): File "", line 1, in ? ImportError: ld.so.1: python: fatal: relocation error: file /usr/gnu/lib/python2.2/lib-dynload/struct.so: symbol PyString_Type: referenced symbol not found >>> However, please note that /usr/gnu/lib/python2.2/lib-dynload/struct.so is left over from the previous installation, because the new one didn't install a new struct.so at all. Therefore, I do not think that this diagnostic messge is relevant. From gerhard at bigfoot.de Tue Jun 18 13:50:05 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Tue, 18 Jun 2002 19:50:05 +0200 Subject: pychecker + XEmacs In-Reply-To: <20020618165548.GB29257@matijek.plusseven.com> References: <3d0de483$0$3881$e4fe514c@dreader4.news.xs4all.nl> <20020618165548.GB29257@matijek.plusseven.com> Message-ID: <20020618175005.GA613@lilith.my-fqdn.de> * Alex Polite [2002-06-18 18:55 +0200]: > Interesting. Where is the CVS repository for python-mode.el? It's in the Python CVS repository. Directory dist/src/Misc/ Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From hesterloli at hotmail.com Mon Jun 17 04:19:24 2002 From: hesterloli at hotmail.com (George Hester) Date: Mon, 17 Jun 2002 08:19:24 GMT Subject: python version? References: <3tingu8psfmefoab93pl8gips8hg7sgpvp@4ax.com> Message-ID: Well yours I haven't the slightest idea what you are getting at. -- George Hester _________________________________ "Dialtone" wrote in message news:3tingu8psfmefoab93pl8gips8hg7sgpvp at 4ax.com... > On Sat, 15 Jun 2002 22:58:36 GMT, "George Hester" > wrote: > > >I think I need a script to do this. > > >>> import sys > >>> sys.version > '2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)]' > >>> sys.version_info > (2, 2, 1, 'final', 0) > -- > try: troll = "Brain" > except TypeError, data: > troll.plonk() > Co-Responsabile Hardware Information & Technology http://hit.edengames.net From shalehperry at attbi.com Sat Jun 29 17:32:33 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Sat, 29 Jun 2002 14:32:33 -0700 (PDT) Subject: can't import generators In-Reply-To: Message-ID: > > Any other thoughts? The only thing slightly non-standard about by > install is that I compiled python2.2 for large file support with > > OPT= -ggdb -O2 -Wall -Wstrict-prototypes -D_LARGEFILE_SOURCE > -D_FILE_OFFSET_BITS=64 > > but I can't see that making a difference. > the other thing I see different than most is you used gcc 3.1. Not that it should matter either. From frederic.michoulier at prisme.fr Tue Jun 11 12:29:13 2002 From: frederic.michoulier at prisme.fr (=?iso-8859-1?Q?Fr=E9d=E9ric_Michoulier?=) Date: Tue, 11 Jun 2002 18:29:13 +0200 Subject: Hi, this is a test Message-ID: <00bf01c21165$1f32fec0$4064a8c0@pcfm> Hi, this is a test Frederic -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: test.txt URL: From loewis at informatik.hu-berlin.de Thu Jun 6 05:33:47 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 06 Jun 2002 11:33:47 +0200 Subject: 64-bit Python? References: <87elfl3yvu.fsf@mathdogs.com> Message-ID: "Fredrik Lundh" writes: > Python *integer* objects are limited to that size on platforms > where a C long is 32 bits. I believe there is another limit: the maximum length of a string, list, or tuple is 2**31-1 on 64-bit platforms where a C int is 4 bytes. That, in particular, includes mmapped objects as well. Regards, Martin From boud at valdyas.org Sat Jun 8 15:29:00 2002 From: boud at valdyas.org (Boudewijn Rempt) Date: Sat, 08 Jun 2002 21:29:00 +0200 Subject: Help with Black Adder... References: Message-ID: <3d025e96$0$3887$e4fe514c@dreader4.news.xs4all.nl> rapskat wrote: > Greetings All. I'm just getting started with python and I chose Black > Adder as a RAD IDE. Since my background is (ugh!) VB, I'm used to the > whole Top Down IDE thing. Well, before I started using Python a few years ago, I was a VB programmer, too. (And Oracle before that -- I've come a long way, I think). Currently, I use XEmacs for everything, so the transition can be made, but you need a strong incentive. For me that incentive was to have to write a book on PyQt and BlackAdder in docbook sgml. And from using XEmacs for docbook to using it for everything else (except mail and news) was an insidiuous process. I've now redefined KDE to accept ctrl-s for search, and ctrl-x-s for save :-). > > My questions are: > > 1) I am having problems with BA not finding the PyQT libs. I installed > both from the rpm's (I'm using RH 7.3). But when I start BA it gives me > an error that it couldn't find the PyQT modules and that they won't be > available for the session. I've tried removing them and reinstalling to > no avail. I've run ldconfig as well. Has anyone ele seen anything like > this and any ideas on how to resolve it? I'm not sure that the current version of BlackAdder includes the PyQt library -- the commercial version does, I think, but the demo version doesn't. Or something like that. Check whether all libs are really there; then check whether LD_LIBRARY_PATH includes the location of the relevant .so's, whether BLACKADDERDIR is correct, and whether BLACKADDERPYTHON is set correctly. (There's a layouto in my book on page 39: the second export ought to be on the next line.) -- Boudewijn Rempt | http://www.valdyas.org From look at replyto.address.invalid Tue Jun 4 01:31:41 2002 From: look at replyto.address.invalid (Greg Ewing) Date: Tue, 04 Jun 2002 17:31:41 +1200 Subject: Behavior of += (was Re: [Python-Dev] Customization docs) References: <06da01c208f4$d69003c0$6601a8c0@boostconsulting.com> <200206010121.g511LxX19223@pcp742651pcs.reston01.va.comcast.net> <073501c20960$23f367e0$6601a8c0@boostconsulting.com> <200206011334.g51DY1D21669@pcp742651pcs.reston01.va.comcast.net> <07d801c20970$cdebe050$6601a8c0@boostconsulting.com> Message-ID: <3CFC50BD.CB9CB70C@replyto.address.invalid> Jeff Epler wrote: > > Maybe the bytecode for inplace operations like > f[i] += v > should implement the > pseudocode > _temp = f[i] > _new = inplace_add(_temp, v) > if _new is not _temp: > f[i] = _new > del _temp, _new That's a nice idea... > However, this would probably double the bytecode size of the sequence, > and hurt performance similarly.... It needn't, if: (1) the INPLACE_xxx bytecodes leave the first operand on the stack (2) there are new STORE_xxx_IF_UNCHANGED bytecodes that compare the value to be stored with the previous one. The total number of bytecodes should then be the same, and all the new work would be done in C code, which ought to be pretty fast (a pointer comparison and a few extra inc/decrefs). -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From op73418 at mail.telepac.pt Fri Jun 28 08:34:21 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Fri, 28 Jun 2002 13:34:21 +0100 Subject: Pythoniac: Thoughts on a hardware Python processor References: Message-ID: <1plohucs4iist5ss52957klaf9damhj6kt@4ax.com> > >Ahh! Haven't you heard? Forth came in Fifth and the Forth chip is dead. In >fact I don't think anyone is still offering a stack based computer (only HP >did AFAIK, the HP 3000). > >Dave LeBlanc >Seattle, WA USA > Completely OT but there is that J. Joyce line in Ulysses that goes like Lazarus, come forth! And he came fifth and lost the job. best, Gon?alo Rodrigues From opus at value.net Sun Jun 30 03:46:00 2002 From: opus at value.net (Opus) Date: Sun, 30 Jun 2002 00:46:00 -0700 Subject: squared functions--most Pythonic way? In-Reply-To: <3D1EB241.FF7ABD7D@cosc.canterbury.ac.nz> Message-ID: <3D1E54C8.11630.E4859E@localhost> Shouldn't addNumbers(5) equate to 5? In other words, it should evaluate that as addNumbers(5)(0) or is that addNumbers(0)(5)? How would you send a list of numbers (or objects that represent numbers) to this? On 30 Jun 2002 at 19:24, greg wrote: > Janto Dreijer wrote: > > > > def addNumbers(k): > > def f(x): > > a = addNumbers(x + k) > > a.val = x+k > > return a > > return f > > > > >>> addNumbers(9)(5)(2)(4)(6).val > > 26 > > > > Now if only I could figure out how to use __repr__() so I don't > > need that ".val". It also fails when passed only one number. i.e > > addNumbers(5). Help? > > class AddNumbers: > > def __init__(self, x): > self.val = x > > def __call__(self, k): > return AddNumbers(self.val + k) > > def __repr__(self): > return repr(self.val) > > addNumbers = AddNumbers(0) > > >>> print addNumbers(9)(5)(2)(4)(6) > 26 > >>> print addNumbers(5) > 0 > > -- > Greg > -- > http://mail.python.org/mailman/listinfo/python-list --Opus-- Dictatorship (n): a form of government under which everything which is not prohibited is compulsory. -------------------------------------------------------- Get added to my Humor list: mailto:opus at value.net?subject=ADD_HUMOR Get added to my Neat list: mailto:opus at value.net?subject=ADD_NEAT Get my PGP public key: mailto:opus at value.net?subject=PSEND&body=send%20PublicKEY.asc Visit My Home Page: http://value.net/~opus/ From whisper at oz.net Mon Jun 24 18:29:49 2002 From: whisper at oz.net (David LeBlanc) Date: Mon, 24 Jun 2002 15:29:49 -0700 Subject: Suggestions for good programming practices? In-Reply-To: Message-ID: > > * Avoid exec, execfile, eval, and input. Might one ask why? What do you have to know to use them successfully? Does "input" imply that "input-raw" is also to be avoided? Avoid "from foo import *"; this avoids unnecessary namespace pollution and other forms of confusion. > * Use local variables whenever possible. Important in Python because > local variables are much faster than global. In practice, this > means that people will often put their main code in a function, and > call it with the "if __name__=='__main__': main()" cliche. Does code run at global scope pay a global scope lookup cost? And for large loops in defs that use class instance data, copying the data to a local variable to avoid the lookup cost each time through the loop. (Does copying globals to local also give a speed gain?) class myclass(): def __init__(self): self.min = 1 self.max = 1000 def loop(self): min = self.min max = self.max for i in range(min,max): print i > * Learn how references and the object system work as soon as possible. > You should not be surprised when you do this: > > a = [1,2,3] > b = a > b[0] = 100 > print a > > And it prints "[100,2,3]" The one that always gets me is "lat,lon,timezone = getLocation("seattle")". I.E. the ability to return multiple distinct values as opposed to returning multiple values in the form of a struct as in C or C++. I would add to the list: * Learn to think in OO and pattern concepts. > -- > CARL BANKS http://www.aerojockey.com > "Nullum mihi placet tamquam provocatio magna. Hoc ex eis non est." Dave LeBlanc Seattle, WA USA " Curses! self.bdfl will never work! Back to the drawing board Pinky!" From maxm at mxm.dk Tue Jun 25 06:50:12 2002 From: maxm at mxm.dk (Max M) Date: Tue, 25 Jun 2002 12:50:12 +0200 Subject: Web templating/db tool with best designer/coder separation? References: <23891c90.0206250232.249c8488@posting.google.com> Message-ID: <3D184AE4.7070302@mxm.dk> Paul Boddie wrote: > This thread wouldn't end if we all started naming template systems, > though. ;-) For something similar to the jonpy templating, take a look > at http://www.clearsilver.org - a system which I was made aware of > recently. If nothing else, that site gives some very good arguments > against "Python in HTML" systems. Yes but that system os only where Zope is with dtml! Zpt has been written to not have the faults of dtml ... so Zpt is pretty well thought out for what it is intended to do. regards Max m From wurmy at earthlink.net Sun Jun 30 00:19:10 2002 From: wurmy at earthlink.net (Hans Nowak) Date: Sun, 30 Jun 2002 04:19:10 GMT Subject: possibly a dumb question References: <3d1e5eff$1_7@nopics.sjc> <3D1E6415.8128F3F8@engcorp.com> <3d1e6251$1_3@nopics.sjc> Message-ID: <3D1E867F.8090001@earthlink.net> Adonis wrote: > sure: > > class foo: > def __init__(self, value): > return value > x = foo(0) > print x ;yeilds 0 So you want to have an object, but use it like it has a certain value, like 0. This is possible, but only to a certain extent. After x = foo(0), x will always be a reference to the instance of foo (unles you rebind it of course). It will not be a reference to the value you passed to the foo instance. In the case of printing, you can define a __repr__ or __str__ method that return the value rather than the boring <__main__.Foo instance at 0x008F9EC8>: >>> class foo: def __init__(self, value): self.value = value def __repr__(self): return repr(self.value) >>> f = foo(0) >>> f 0 By defining other magic methods, you can do more, e.g. treat it like f was a number, etc. This may, or may not, be what you're looking for. If not, using f.value rather than f may be your best bet... HTH, -- Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) # decode for email address ;-) The Pythonic Quarter:: http://www.awaretek.com/nowak/ From jhndnn at yahoo.com Fri Jun 14 12:00:56 2002 From: jhndnn at yahoo.com (John Dunn) Date: 14 Jun 2002 09:00:56 -0700 Subject: Standalone embedded Win32 Python Message-ID: <2cc96dc7.0206140800.5614a0bd@posting.google.com> I have embedded Python in my C++ Win32 app. What is the recommended way of installation/distribuion? It seems the best would be to statically link to Python - this would also allow me to customized the Python environment that runs with my app. Unfortunately, Python doesn't appear to support static linking on Win32. I really don't want to run the whole Python installed when I install my app. If I can't statically link, is it acceptable to just ship my own local copy of the DLL? I assume I will have to edit some code so it doesn't look to the registry to find the path to Python. Is there any documentation on doing this? This seems to be important to any app that has Python embedded - you can't very well tell your customers to download the latest Python install just to run your program. Thanks for any help- John Dunn -- John Dunn Peak Audio, a division of Cirrus Logic, Inc. http://www.peakaudio.com From whisper at oz.net Mon Jun 24 16:44:04 2002 From: whisper at oz.net (David LeBlanc) Date: Mon, 24 Jun 2002 13:44:04 -0700 Subject: Suggestions for good programming practices? In-Reply-To: Message-ID: David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Mark McEahern > Sent: Monday, June 24, 2002 13:22 > To: python-list at python.org > Subject: RE: Suggestions for good programming practices? > > > Dianne van Dulken wrote: > > I'm fairly new to python, coming from a perl background, and > was wondering > > if anyone has a list of things that they consider as good programming > > practice in Python (I thought this might be an interesting topic for > > discussion, anyway) > > Here's one... > > When evaluating whether a variable is None, don't compare it like this: > > if x == None: > > instead, use: > > if x: > > or: > > if not x: > > The encourages a polymorphic approach. If you must compare to > None, use the > identify operator rather than equality: > > if x is None: > > or: > > if x is not None: > > // mark > I'm curious to know how this encourages polymorphism, and how making a conditional test implicit rather then explicit is good practice? Regards, Dave LeBlanc Seattle, WA USA From donn at u.washington.edu Tue Jun 4 20:06:22 2002 From: donn at u.washington.edu (Donn Cave) Date: 5 Jun 2002 00:06:22 GMT Subject: Behavior of += (was Re: [Python-Dev] Customization docs) References: <3CFCF3E7.AE891EBE@noaa.gov> Message-ID: Quoth bokr at oz.net (Bengt Richter): ... | Here is a contrived case where += lets you use a | mutable-lhs-target-expression-with-side-effect and | get only one side effect. There are obviously other | ways, but at least += is convenient (and presumably | faster in a case like this). | | >>> a=[0] | >>> def foo(): | ... print 'side effect' | ... return a | ... | >>> foo() | side effect | [0] | >>> foo()[0]+=1 | side effect | >>> a | [1] | >>> foo()[0] = foo()[0]+1 | side effect | side effect | >>> a | [2] I imagine you have some actual application for something like this, but the example doesn't seem very compelling - like you say, there are obviously other ways. If they're less convenient, maybe they're easier on the eyes. But it's probably a moot point. Whether the current behavior of += is a wart or not, it's not likely to be removed. Donn Cave, donn at u.washingon.edu From noone at here.invalid Sun Jun 23 01:05:45 2002 From: noone at here.invalid (JohnJacob) Date: Sun, 23 Jun 2002 00:05:45 -0500 Subject: ConfigParser & converting strings to lists References: <3D152A28.2177B054@tds.net> Message-ID: > files = config.get("recent files", "recentFiles") > > sets files to the _string_ "[file1, file2, ...]". I suppose this must > be how get should work; after all, settings could be arbitrary > strings... You just want to get your list back from it's string representaion, right? Try eval: files = eval(config.get("recent files", "recentFiles")) I hope that's what you meant. greg From david.abrahams at rcn.com Tue Jun 18 18:04:08 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Tue, 18 Jun 2002 18:04:08 -0400 Subject: SWIG and Callbacks References: <3d0a8b6e@nntp.server.uni-frankfurt.de> <3d0b4fd6@nntp.server.uni-frankfurt.de> <3d0c6d67@nntp.server.uni-frankfurt.de> <3D0CE698.1050806@SPAMnwinternet.com> <3D0D3223.5070500@SPAMnwinternet.com> <3d0f9f70@nntp.server.uni-frankfurt.de> Message-ID: "Michael 'Mickey' Lauer" wrote in message news:3d0f9f70 at nntp.server.uni-frankfurt.de... > David Abrahams wrote: > > Heh, yeah. Unfortunately, documentation is often harder than coding. Even > > the current official release of Boost.Python is not very well-documented. > > We're working hard to correct that for v2, which is in pre-release. > > Is it completed enough to try it out for wrapping a small library? Absolutely. People are already using it for big projects. http://mail.python.org/pipermail/c++-sig/2002-May/001100.html to get started > If not, > could you estimate when it will be ? I hope to officially retire v1 at the end of the month, replacing it with v2. -Dave From gabor at realtime.sk Thu Jun 6 13:54:47 2002 From: gabor at realtime.sk (gabor) Date: 06 Jun 2002 13:54:47 -0400 Subject: array, list, performance... Message-ID: <1023386087.3833.17.camel@wintermute.atriaky.sk> hi, how fast is list? i mean accessing an item at an arbitrary position is O[n] or O[1]? i need O[1].... are there any suitable classes in python? thanks, gabor From chris.gonnerman at newcenturycomputers.net Tue Jun 25 22:38:54 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Tue, 25 Jun 2002 21:38:54 -0500 Subject: Reminder of a python Project. References: <2218.941T781T12224051threeseas@earthlink.net> Message-ID: <007701c21cba$a4117ee0$0101010a@local> ----- Original Message ----- From: "Timothy Rue" > First off, it's ok that I got such a high level of resistance to my > initial posting here about this project. Thanks to some research that /. > had an article on, regarding the size of GPL project teams. > > But anyway.... Remember the autocoding project I mentioned? Gah. I thought I had this guy in my message rules under "Delete from Server." I will remedy this immediately... Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From peter at engcorp.com Fri Jun 21 09:38:45 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 21 Jun 2002 09:38:45 -0400 Subject: [newbie] import fails first time, then works :-[ References: <3D1379D1.5020705@nospam.free.fr> Message-ID: <3D132C65.34B38F8C@engcorp.com> laotseu wrote: > > Hi Everybody > > I've got this strange problem : > when importing modules that wrap external modules (like socket and > _socket etc), the first time, I get an ImportError > (no module named _[module]). > If i try a second time, it works ok ?-o > > Exemple : > >>> import socket > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/local/lib/python2.2/socket.py", line 41, in ? > from _socket import * > ImportError: No module named _socket > >>> import socket > >>> socket > See recent postings in the archives for explanations about why this is actually _not_ working the second time, but only appears to. In this case, despite that you say the external modules are in the right place, there is probably something wrong with the _socket external module or it cannot be found and that's the root cause of your trouble. -Peter From gerhard at bigfoot.de Fri Jun 21 10:05:53 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 21 Jun 2002 14:05:53 GMT Subject: a Tree data-structure class? References: Message-ID: Stephen Ferg wrote: > I do a lot of processing of tree-structured data, so I'm thinking it > would be useful to develop a generic Tree class that I could adapt to > various applications. Or perhaps a Tree class and a generic Node > class. I've once quickly hacked this as a demonstration (just skip the German): http://starship.python.net/pipermail/python-de/2001q4/003178.html Btw. Zope CVS contains highly optimized BTree classes. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From nessus at mit.edu Tue Jun 4 16:05:19 2002 From: nessus at mit.edu (Douglas Alan) Date: 04 Jun 2002 16:05:19 -0400 Subject: manipulating child processes under Windows References: Message-ID: Syver Enstad writes: > Hmm, my first reaction is to think in terms of window handles in > some way, there's a FindWindow function in win32 (and win32all) that > let's you search for a window by name, I'll have to check the msdn > library to find out how to get the owning process handle from a > window handle. What if there were more than one process with the same name. How would I tell which one is the right one? |>oug From flynt at gmx.ch Fri Jun 7 11:50:18 2002 From: flynt at gmx.ch (flynt) Date: Fri, 07 Jun 2002 17:50:18 +0200 Subject: Session Cookies References: <000d01c20e38$da94fdb0$4100a8c0@KARIMXP1> Message-ID: <3D00D63A.51940D20@gmx.ch> Karim Shehadeh wrote: > > Part 1.1 Type: Plain Text (text/plain) > Encoding: 7bit Hello Karim For an example look into the *New Riders* book: "Python Web Programming" by Steve Holden and David Beazley ISBN: 0-7357-1090-2 you find an example of a web-site framework based on python. They call it *AWeFUL*; chapter 17 in that book. Session handling with cookies is part of it. Greetings Flynt From garrett at bgb.cc Thu Jun 6 16:48:35 2002 From: garrett at bgb.cc (Don Garrett) Date: Thu, 06 Jun 2002 20:48:35 GMT Subject: constructive critisism on pythonwin IDE References: <6bd9f01b.0206050736.f469082@posting.google.com> Message-ID: <3CFFCA79.4050905@bgb.cc> Thomas Heller wrote a wonderful script named 'autoreload' that helps with this problem quite a bit. I don't think this is an official distribution location (and thus not current?), but I found a link to it here: http://starship.python.net/crew/zack/ F. GEIGER wrote: > This a Python issue, not a PythonWin IDE issue. > > Cheers > Franz > > "sameer" schrieb im Newsbeitrag > news:6bd9f01b.0206050736.f469082 at posting.google.com... > >>First of all, let me start of by saying that Pythonwin is a great IDE. >> Now for the constructive critisism. The thing I hate about PythonWin >>is, that despite the fact that it's a development environment, there >>is a lot of caching done of modules, and the cached copy is not >>checked against a potentialy modified copy. Whenever I change the >>contents of a file and try to run a module that depends on that file, >>I always end up with the old copy. I have to then import and then >>reload the changed module in the interactive window for it to refresh. >> It would greatly increase my productivity, if I can specify which >>modules can be cached. I understand that there is a speed and >>development time issue, but I would like a little more fine grained >>control on how caching works on PythonWin, as the way it's currently >>implemented now is not acceptable. >> > > From never at mind.info Sun Jun 2 17:32:43 2002 From: never at mind.info (G. Willoughby) Date: Sun, 2 Jun 2002 22:32:43 +0100 Subject: HTML links in a GUI tkinter References: Message-ID: > How can I put in a frame or in any widget (?) an html link so that the > browser opens at the url indicated when the user clicks ? I think you can use a Tkinter Text widget, and then specify tags around the web address: http://www.pythonware.com/library/tkinter/introduction/x7883-concepts.htm then: import os os.startfile(page.html) to execute the html file. --G. Willoughby From marklists at mceahern.com Mon Jun 24 16:22:01 2002 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 24 Jun 2002 15:22:01 -0500 Subject: Suggestions for good programming practices? In-Reply-To: Message-ID: Dianne van Dulken wrote: > I'm fairly new to python, coming from a perl background, and was wondering > if anyone has a list of things that they consider as good programming > practice in Python (I thought this might be an interesting topic for > discussion, anyway) Here's one... When evaluating whether a variable is None, don't compare it like this: if x == None: instead, use: if x: or: if not x: The encourages a polymorphic approach. If you must compare to None, use the identify operator rather than equality: if x is None: or: if x is not None: // mark - From gh_pythonlist at gmx.de Tue Jun 11 19:37:40 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Wed, 12 Jun 2002 01:37:40 +0200 Subject: RfD: Automagically making a class instance 'synchronized' (draft impl.) In-Reply-To: <20020612000425.U6609@prim.han.de> References: <20020611205423.GA28113@lilith.my-fqdn.de> <20020612000425.U6609@prim.han.de> Message-ID: <20020611233740.GA28544@lilith.my-fqdn.de> * holger krekel [2002-06-12 00:04 +0200]: > Gerhard H?ring wrote: > > For one of my projects, I'll need something not quite unlike the > > following code. It's not tested, yet, but it looks ok and complete to > > me. I thought that it could be useful to other developers who need to > > use multithreading, so I'm posting it here. Maybe something like this > > would even be a useful addition to the Standard Library? > > note that Ian Kjos some weeks ago send a nice module 'morethreading.py' > to the dev-list. IIRC, it still waits for beeing reviewed and extended > with other ideas (like synchronized methods). Sounds interesting, I'll have a look at it. I also just found this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65202 which has a few more interesting additions. It's possible to do without my methodlist, for example. > [...] this can be safely substituted and then even returns the correct value with > try: ... finally: Whoops. I missed that originally, thanks. Btw. I've only recently started to seriously experiment with multithreading. Have you read my recent post Message-ID: with the title "Need advice on multithreading problem" ? I find it really nifty. It's about wrapping a C library function that uses callbacks to Python generators. I'd welcome any comments on the approach I've taken there (Queue.Queue, a deferred producer thread with the generator in the main thread being the consumer). Unfortunately, this opened a whole can of worms, which I think I solved now. Now I'm trying to solve them more elegantly. If anybody wants to try this out in real life, it's in the PySQLite CVS as the alternative IterCursor implementation. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 14.7 ?C Wind: 2.6 m/s From oren-py-l at hishome.net Sun Jun 30 14:01:39 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Sun, 30 Jun 2002 14:01:39 -0400 Subject: yield equivalent in C/JavaScript? In-Reply-To: References: Message-ID: <20020630180139.GA38821@hishome.net> On Sat, Jun 29, 2002 at 07:12:46PM +0100, Robin Becker wrote: > Is there any way to do yielding easily in C? I have a bunch of programs > which are normally connected together using unix pipes. I would like to > merge them and the problem is then how to get them to communicate nicely > using a single process. It's possible to implement this in C using Duff's Device: #define BEGIN_GENERATOR static int _GenState=0; \ switch(_GenState) { \ case 0: #define END_GENERATOR } \ _GenState = 0; #define YIELD(x) _GenState=__line__; return (x); case __line__: int generator(arguments) { static int foo, bar, etc; /* Make all variables static */ BEGIN_GENERATOR for(...) { if(...) { ... YIELD(x) ... } else { ... } ... YIELD(y) ... } END_GENERATOR } If you want this to be reentrant use a struct passed as an argument to the function instead of static variables. Oren From jolsen at mailme.dk Sun Jun 2 08:23:30 2002 From: jolsen at mailme.dk (Jesper Olsen) Date: 2 Jun 2002 05:23:30 -0700 Subject: How to play a .wav sound? References: Message-ID: I see that your question has already been answered. An alternative solution is to install the snack toolkit: http://www.speech.kth.se/snack/ and from python do this: import tkSnack tkSnack.initializeSnack(root) sound=tkSnack.Sound(load="file.wav") sound.play() Cheers Jesper Bruno Bellamy wrote in message news:... > I guess the question has probably been asked many times, sorry for > bothering... > But I searched here and there, and I couldn't find how to do that, simply > play a .wav sound from a python program using Tkinter. > > Moreover, I need to do that in a program that would run similarly under > Linux and Windows. > > I saw there's a python module called wave, but it seems it can only read > .wav files. I coulnd't find a way to actually play the sound. Maybe it's > hidden somewhere? > > If anybody can help me, that would be cool. :) From irmen at NOSPAMREMOVETHISxs4all.nl Mon Jun 10 14:16:55 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Mon, 10 Jun 2002 20:16:55 +0200 Subject: M2Crypto: select() behaves weird on SSL sockets Message-ID: <3D04ED17.5070606@NOSPAMREMOVETHISxs4all.nl> Hi I'm using m2crypto 0.07 snapshot 3 with Python 2.2.1 and I'm experiencing weird behavior when using select(). Basically, it seems that a SSL socket is no longer in ready state when entering select() again, after reading *a part* of the available data on the socket. Using plain sockets, the select() will keep reporting that the socket is ready for reading, until all data has been read. With SSL sockets, the second select() blocks eternally... Any clue? I really need the regular select() behavior, also on SSL sockets... Thanks, Irmen de Jong (test code available on request.) From fcordonier at myrealbox.com Fri Jun 21 04:22:13 2002 From: fcordonier at myrealbox.com (=?ISO-8859-15?Q?Fr=E9d=E9ric_Cordonier?=) Date: Fri, 21 Jun 2002 10:22:13 +0200 Subject: Windows versions of Python---pros and cons? References: <3D110B55.4D8AD7FA@astro.cornell.edu> <20020619154654.C619@ActiveState.com> <20020619225800.GB12907@lilith.my-fqdn.de> Message-ID: <3D12E235.6070304@myrealbox.com> Gerhard H?ring wrote: >* Trent Mick [2002-06-19 15:46 -0700]: > > >>My understanding is that for C extensions to work they must be built >>with the same compiler as that used to build the Python with which they >>will run. (I may be wrong. Someone please correct me if I am.) >> >> > >You are wrong. As long as you link to the python{major}{minor}.dll you >are binary compatible, no matter which compiler you use. It's just a >matter of providing an additional compiler option to distutils, like in: > > python setup.py build --compiler=mingw32 > >Gerhard > > Hello, I am no windows or C++ specialist, but I happened to write extensions for Python in the scope of unitary testing code for embedded systems. I did extensions with both Borland C++ 5.01 and mingw32. Under windows, it is always easier to link the project with a .lib file rather than directly connecting to the .dll. The problem with Borland is that the .lib for Pythonxx.dll is tricky to generate. In fact, Borland adds some '_' to the exported symbols. You have to: > impdef Python22.def Python22.dll modify the Python22.def to add leading '_' to the symbols (I use gvim that is really handy for this kind of tasks). then > implib Python22.lib Python22.def For Mingw32, the .lib file can be generated with 'pexports' and 'dlltool'. Moreover, I wrote extensions with SWIG using Borland. One problem I encountered is that the main module entry is not exported correctly (when importing the module, an exception is raised), because SWIGEXPORT is not adapted (maybe specific to BC++5.01?). You have to redefine it to #define SWIGEXPORT(a) a _export FAR PASCAL Last, using distutil with Borland is certainly possible, but not with version 5.01 (my customer only has this version). Some linker options used with '--compler=bcpp' are not known by 5.01. I had to patch distutils to make it work. If ever someone needs it, I will go back to my notebook to check what was done... Fred. From juanm.casillas at eresmas.com Thu Jun 27 10:06:59 2002 From: juanm.casillas at eresmas.com (Juan M. Casillas) Date: Thu, 27 Jun 2002 16:06:59 +0200 Subject: Module Help In-Reply-To: <3D1B0FA6.9080101@thomas-guettler.de> References: <3D1B0FA6.9080101@thomas-guettler.de> Message-ID: <15643.7171.903855.772185@eresmas.com> >>>>> "Thomas" == Thomas Guettler writes: Thomas> Juan M. Casillas wrote: >> Hello! >> >> I want to create an empty module from C, and then add functions >> and definitions stored in another file, and some code that I >> will create on-the-fly, from C. Thomas> I don't understand you. Want to you mean with "from C"? Thomas> Why not use python for code generating? Hello! I have a C program that gets a file that gets some code from various places; then I want to create different execution environments, and the way I think I can do it is creating various modules on the fly, and executing code from them. Kind Regards, Juan M. Casillas >> The basic problem I have is that I don't know how to create the >> empty module (this module doesn't have any representation in >> the filesystem) and then how can I add the code and save the >> "environment" for this newly created module, how can I manage >> the globals and locals dictionaries ? for each module ? Thomas> Do you want to create a text file containing python code, Thomas> or create it at runtime dynamically? Thomas> thomas Thomas> -- http://mail.python.org/mailman/listinfo/python-list From pyth at devel.trillke.net Tue Jun 11 16:28:44 2002 From: pyth at devel.trillke.net (holger krekel) Date: Tue, 11 Jun 2002 22:28:44 +0200 Subject: Why does Python mix OO concepts and non OO concepts for operation s on basic types? In-Reply-To: ; from rnd@onego.ru on Wed, Jun 12, 2002 at 12:20:00AM +0400 References: <3D054A98.3090708@bgb.cc> Message-ID: <20020611222844.T6609@prim.han.de> Roman Suzi wrote: > I only forgot how will I do this: > > map(string.split, s) > > if GvR will deprecate string module... what about map(str.split, s) :-) holger From op73418 at mail.telepac.pt Wed Jun 26 14:03:08 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Wed, 26 Jun 2002 19:03:08 +0100 Subject: question od default args References: <3D19FEA3.6020804@earthlink.net> Message-ID: On Wed, 26 Jun 2002 17:50:42 GMT, Hans Nowak wrote: >Gon?alo Rodrigues wrote: >> Hi, >> >> When I want default args I usually do >> >> def (arg = None): >> ... >> >> But what if I want to make None a reasonable argument too? That is, I >> want to know if the user has in fact passed an argument, and if not to >> do something special, with None (or whatever object) being a reasonable >> arg to be passed. > >Hmm, so use a default argument that is not reasonable to pass... some weird >string, or a complex number, or even an instance of a (singleton?) class >written especially for this... although that may be a bit overkill. Of course, >the question is what is "reasonable" here and what not... In principle everything is reasonable. But (some variation of) "an instance of a (singleton?) class written especially for this" is worth a try. Thanx, Gon?alo Rodrigues From fredrik at pythonware.com Sat Jun 29 15:05:18 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 29 Jun 2002 19:05:18 GMT Subject: Most efficient way to write data out to a text file? References: <3d1a6993.248534625@netnews.attbi.com> <3d1dc547.468619140@netnews.attbi.com> Message-ID: Dave Kuhlman wrote: > > 1) "import sys" became "import exit from sys" > > 2) "import os" became "import makedires from os" > > Does importing a function from a module (as opposed to importing > the whole module) save a look-up each time the function is called? no. but evaluating "exit" instead of "sys.exit" saves one lookup. (the latter first looks up "sys" in the global namespace, and then "exit" in the sys namespace). (not that it matters for these functions; it didn't sound like his performance problem was that Python couldn't exit fast enough ;-) > > 3) "import time" bacame "import asctime from time" (this one is > > used frequently) "from time import asctime", I hope. > Is finding things in globals slower than finding them in locals? yes. Python assigns integer indices to local names, and stores the corresponding objects in an array. globals (and ordinary object attributes) are stored in a dictionary. if you read enough code, you'll find that "rebinding" is a pretty common pydiom in performance-critical code. some examples: import time def myfunction(...): # bind asctime to a local name asctime = time.asctime for ... in ...: x = asctime(...) this also works for methods: def myotherfunction(...): result = [] append = result.append for .. in ...: append(...) # appends to result return result since arguments are also treated as local variables, and default values are evaluated once (when the function object is created), you'll also find things like: def myfunction(..., asctime=time.asctime): for ... in ...: x = asctime(...) > Did this change in Python 2.2? no. From hst at empolis.co.uk Tue Jun 11 12:05:03 2002 From: hst at empolis.co.uk (Harvey Thomas) Date: Tue, 11 Jun 2002 17:05:03 +0100 Subject: Cross platform spawning Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220BF9@hendrix.empolisuk.com> Peter Scott wrote: > > I am trying to make a script spawn a seperate process, like you would > do like this on unix: > > os.system('python myscript.py myargument &') > > But the & at the end (to make a separate process) doesn't work on > Windows. I want the script to run on both Linux (*BSD, whatever) and > Windows. I didn't want to have to find out the path to the python > interpreter, so os.spawnlp (with no blocking) sounded perfect until I > saw that it wasn't available on Windows. > > Does anyone out there know what I can do in this situation? Not sure if it's exactly what you want but under Win NT you could use os.system('start python myscript.py myargument') (see the NT help for details of the start command) _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From edream at tds.net Fri Jun 21 09:43:26 2002 From: edream at tds.net (Edward K. Ream) Date: Fri, 21 Jun 2002 13:43:26 GMT Subject: Inhibiting duplicate apps in Windows? References: <3D11F9E8.DFFFC8E4@tds.net> Message-ID: <3D132D7E.35CBF952@tds.net> > What I would like is for the second copy of Leo to detect that another > copy of leo.py is already running, send a message to the first copy and > then exit. I wonder if anyone knows how this might be done? This morning I realize that a workaround would be to implement a "Recent Files" menu. This would be especially useful in Leo, as .leo files typically represent many other files. This doesn't solve the stated problem, and will be good enough in practice. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From BPettersen at NAREX.com Mon Jun 10 19:00:30 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Mon, 10 Jun 2002 17:00:30 -0600 Subject: Why does Python mix OO concepts and non OO concepts for operation s on basic types? Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192158EBD@admin56.narex.com> > From: James T. Dennis [mailto:jadestar at idiom.com] > [snip] > > Personally I think it would be generally nice if I could > call most of the list and string methods in both ways: > > list.append(somelist,someitem) would be the same as: > somelist.append(someitem). > > And the obvious: > > string.join('',something) would be as: ''.join(something). Your wish is granted: >>> x = [] >>> list.append(x, 5) >>> x [5] >>> str.join(' ', ['a', 'b', 'c']) 'a b c' >>> not-that-I-would-ever-do-something-like-that'ly y'rs -- bjorn From mjackson at wrc.xerox.com Tue Jun 18 07:49:38 2002 From: mjackson at wrc.xerox.com (Mark Jackson) Date: 18 Jun 2002 11:49:38 GMT Subject: python version? References: <3tingu8psfmefoab93pl8gips8hg7sgpvp@4ax.com> <9YBP8.44418$GY.13865843@twister.nyroc.rr.com> Message-ID: Duncan Booth writes: > "George Hester" wrote in > news:9YBP8.44418$GY.13865843 at twister.nyroc.rr.com: > > > I think you guys don't how to do it. > > And I think you are one of the most impolite posters we have seen around > here. > > Try this: [snip] Slipping George the old "reformats your hard drive" script - that was *mean*. Fair, but mean. -- Mark Jackson - http://www.alumni.caltech.edu/~mjackson Until we test our beliefs, we can't say for sure if we have leeches or we have aspirin. - David Faigman From logiplexsoftware at earthlink.net Thu Jun 13 04:00:51 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: 13 Jun 2002 01:00:51 -0700 Subject: How to call a function using apply with keyword args? In-Reply-To: References: Message-ID: <1023955252.7453.15.camel@localhost.localdomain> On Thu, 2002-06-13 at 00:50, Martin v. L?wis wrote: > "Achim Domma" writes: > > > I have a function like this: > > > > def MyFkt(A,B,C): pass > > > > and some parameters from a config file: > > > > params = {'A':5,'B':8,'C':9} > > > > how can I call MyFkt with this parameters? > > I recommend > > MyFkt(**params) > > > I tried apply(MyFkt,[],params) > > If you want to use apply, it is > > apply(MyFkt, (), params) > > The arguments need to be a tuple. Actually, a list will work as well: Python 2.1.1 (#1, Aug 13 2001, 19:37:40) [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-96)] on linux2 Type "copyright", "credits" or "license" for more information. >>> def MyFkt(A,B,C): ... print A, B, C ... >>> params = {'A':5,'B':8,'C':9} >>> apply(MyFkt,(),params) 5 8 9 >>> apply(MyFkt,[],params) 5 8 9 >>> From ryanmorillo at hotmail.com Tue Jun 18 06:44:59 2002 From: ryanmorillo at hotmail.com (Ryan) Date: 18 Jun 2002 03:44:59 -0700 Subject: tray icon using tkinter References: Message-ID: <4a7fde99.0206180244.11eea205@posting.google.com> john at johnnypops.demon.co.uk (John Popplewell) wrote in message news: > Anoop P B wrote in message news: > > is there a way that i can provide a tray icon ie. next to the clock (on > > win32) for my program (using tkinter) ? i know that there is a way of > > doing this in wxpython but i need to know whether its possible in tkinter. > > > > thanks, > > anoop > > > Have you had a look at "Tray It!" ? > > http://www.teamcti.com/trayit/index.html > > cheers, > John. also look at the win32 extensions, I remember going through all the demo code that there is a way to do it (MFC I think but don't know for sure). It is simple to do a try except block around the import and logic to use it since it will only be for windows. It is used for the windows IDE also. Also check out TKinter3000 at http://www.pythonware.com/products/tkinter/tkinter3000.htm, they may have something (or you can ship the one from win32 extensions with your app) From rpm1deletethis at nospamfrontiernet.net Sun Jun 2 08:19:38 2002 From: rpm1deletethis at nospamfrontiernet.net (RPM1) Date: Sun, 2 Jun 2002 08:19:38 -0400 Subject: wxPython performance References: Message-ID: "Andrei Kulakov" wrote > Hello, > > "hello world" type program from wxPython tutorial takes 6 > seconds to start on my cel 366 128mb system (running Debian). Is > this typical? Why is it so slow? I'm looking for a graphic > toolkit that'd be fairly quick. I don't want to use Tk because of > the looks. I found wxPython to be slow also. I wrote a program to syntax highlight a specific type of log file with Tkinter. I thought wxPython would look better and it has more controls available so I ported it to wxPython. The performance was so bad I went back to Tkinter. For example, loading a 1MB file into the text box and syntax highlighting it in Tkinter takes about 2 seconds. In wxPython it took more than 30 seconds. Patrick M. From marklists at mceahern.com Tue Jun 11 09:05:17 2002 From: marklists at mceahern.com (Mark McEahern) Date: Tue, 11 Jun 2002 08:05:17 -0500 Subject: using m2crypto to encrypt credit card numbers In-Reply-To: <4620daca.0206110429.1417b389@posting.google.com> Message-ID: [gyromagnetic] > Managing keys is a fundamental problem with encryption. I would highly > recommend that you not store the credit card numbers at all. Instead, > store a (SHA, MD5) hash of the number, and then validate against the > hash. I'm not using the credit card number to validate--that's what the password is for. (I don't store the password, but a hash of it.) I'm using the credit card number to collect payment. If I don't store the credit card number, how do I send it to the payment processor to collect payment? // mark - From aahz at pythoncraft.com Thu Jun 27 12:59:53 2002 From: aahz at pythoncraft.com (Aahz) Date: 27 Jun 2002 12:59:53 -0400 Subject: doc for threading? References: Message-ID: In article , Klaus Reinhardt wrote: > >Is there a more elaborated doc (with examples) >for threading than the distribution is providing? See my web page. Still not great, but the examples should be useful. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From pyth at devel.trillke.net Wed Jun 5 20:41:12 2002 From: pyth at devel.trillke.net (holger krekel) Date: Thu, 6 Jun 2002 02:41:12 +0200 Subject: self In-Reply-To: <926F937512224245A616323693D3F16B1C01EF@ctmsg01.corp.fitlinxx.com>; from db3l@fitlinxx.com on Wed, Jun 05, 2002 at 08:19:05PM -0400 References: <926F937512224245A616323693D3F16B1C01EF@ctmsg01.corp.fitlinxx.com> Message-ID: <20020606024112.G30696@prim.han.de> David Bolen wrote: > [me] > > everything is a google-search away if you know the right codewords :-) > > I don't in this case, though ... > > Sorry, I must admit to being temporarily overcome with a fit of laziness. I > had actually fumbled around a bit before finding the posts I mentioned, so I > should really have tried to include a reference. > > Lest the codewords remain secret, I managed to wind my way there with a > search on "eval dictionary instance" in comp.lang.python (which referenced a > post of Tim's on the fourth page of results). > > The messages I had found occurred deep into a "Dictionary from list?" thread > from last October which crossed over into the subject of subclassing > dictionaries: > > http://groups.google.com/groups?th=2338421ec8397bec&seekm=mailman.1004338951 > .27778.python-list%40python.org very nice, thanks! [GvR in the above link] IMO, fixing these internal accesses to always use the overrides would remove much of the attractiveness of subclassing built-in types; I believe it would slow things down too much given the current state of the implementation. If you want a vaguely dictionary-like object, write a class that doesn't derive from dictionary but implements the mapping protocol; if you want a base class that implements most of the operations already, start with UserDict. This seems reasonable except that 'exec' and 'eval' require a real dict-type. Due to the generic nature of these execution statements i guess that fixing it is roughly equivalent to fixing it all over the place unless they could be somehow special-cased. Oh well... holger From tim.one at comcast.net Tue Jun 11 21:32:14 2002 From: tim.one at comcast.net (Tim Peters) Date: Tue, 11 Jun 2002 21:32:14 -0400 Subject: Sorting list (maybe stupid) In-Reply-To: Message-ID: [Delaney, Timothy] > ... > Personally, I think the implementation should be documented to > use a stable sort - presumably mergesort (stable, minimal number of > comparisons which is very important in Python). Write a mergesort as fast and memory-efficient as the sort we've got and we'll consider it. I wasn't able to. Great progress in memory-efficient mergesort algorithms has been made over the last decade (the ancient one in a Knuth Vol 3 exercise achieves memory efficiency at the cost of vastly more comparisons), but I don't know whether they're truly practical yet. Count the # of comparisons the samplesort/binary_insertion hybrid actually does and you'll find that mergesort doesn't have enough of an advantage there to make up for the speed it loses due to greater data movement. From juanm.casillas at eresmas.com Thu Jun 27 04:01:13 2002 From: juanm.casillas at eresmas.com (Juan M. Casillas) Date: Thu, 27 Jun 2002 10:01:13 +0200 Subject: Module Help Message-ID: <15642.50761.524492.167169@eresmas.com> Hello! I want to create an empty module from C, and then add functions and definitions stored in another file, and some code that I will create on-the-fly, from C. The basic problem I have is that I don't know how to create the empty module (this module doesn't have any representation in the filesystem) and then how can I add the code and save the "environment" for this newly created module, how can I manage the globals and locals dictionaries ? for each module ? Thanks in advance Juan M. Casillas From altis at semi-retired.com Sun Jun 2 17:20:25 2002 From: altis at semi-retired.com (Kevin Altis) Date: Sun, 2 Jun 2002 14:20:25 -0700 Subject: convert string to a method of a class at runtime? Message-ID: <5YvK8.285$Vm3.130161@news.uswest.net> I would like to be able to take a string containing the definition of a method, compile the method and then add it to an instance variable at runtime, so that the method defined in the string is part of the class just as if it had actually been in the class definition to begin with when the module was first used. So, instead of a class definition like: class H: def hello(self, s): print s def world(self, s): print s I would like to have just the 'hello' method defined beforehand and add 'world' at runtime. Here's a shell transcript of my attempt to add the 'world' method by compiling it and using the 'new' module to turn the compiled string into a method of the class. As the transcript shows, my attempt failed, so I'm hoping some Python language experts will be able to tell me what steps I got wrong. Perhaps, I need to use a different method to define the argument list or change where the global namespace comes from; I thought the namespace should be the same as that already defined for the instance or class? >>> class H: ... def hello(self, s): ... print s ... >>> h = H() >>> h.hello('world') world >>> s = """def world(self, s): ... print s ... ... """ >>> s 'def world(self, s):\n print s\n\n' >>> c = compile(s, '', 'exec') >>> c >>> import new >>> f = new.function(c, globals()) >>> h.__class__.__dict__['world'] = new.instancemethod(f, None, h.__class__) >>> h.world('new world') Traceback (most recent call last): File "", line 1, in ? TypeError: ?() takes no arguments (2 given) >>> Fingers crossed, that this kind of dynamic method addition is doable. I know I can do it by just typing a function into the shell like this: >>> def world2(self, s): ... print s ... >>> f2 = new.instancemethod(world2, None, h.__class__) >>> f2 >>> h.__class__.__dict__['world2'] = f2 >>> h.world2('yea') yea But I need to be able to do the addition outside the shell, so compiling the string is necessary. In more complex examples, the method needs the namespace to be right so it can make use of whatever imports and other global variables have been setup. Thanks, ka --- Kevin Altis altis at semi-retired.com From msoulier at nortelnetworks.com_.nospam Wed Jun 5 07:29:32 2002 From: msoulier at nortelnetworks.com_.nospam (Michael P. Soulier) Date: 5 Jun 2002 11:29:32 GMT Subject: building on hpux 10.20 Message-ID: Hello. I have Python 1.5.2 and Python 2.0 both built on HP-UX 10.20 with no problems. However, I just tried building 2.2.1, and I got this error immediately in the compile: gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H -o Modules/python.o Modules/python.c In file included from /usr/include/limits.h:6, from /opt/corp/unsupported/lib/gcc-lib/hppa1.1-hp-hpux10.20/2.8.1/include/ limits.h:116, from /opt/corp/unsupported/lib/gcc-lib/hppa1.1-hp-hpux10.20/2.8.1/include/ syslimits.h:7, from /opt/corp/unsupported/lib/gcc-lib/hppa1.1-hp-hpux10.20/2.8.1/include/ limits.h:11, from Include/Python.h:27, from Modules/python.c:3: /usr/include/sys/stdsyms.h:244: #error "Large Files (ILP32) not supported in strict ANSI mode." In file included from Include/Python.h:62, from Modules/python.c:3: Include/pyport.h:480: #error "LONG_BIT definition appears wrong for platform (bad gcc/glibc config?)." gmake: *** [Modules/python.o] Error 1 Has anyone seen this before? We won't be moving away from HP-UX 10.20 for a while yet, so it would be nice to get this working. Mike -- Michael P. Soulier, QX41, SKY Tel: 613-765-4699 (ESN: 39-54699) Optical Networks, Nortel Networks, SDE Pegasus "...the word HACK is used as a verb to indicate a massive amount of nerd-like effort." -Harley Hahn, A Student's Guide to Unix From fperez528 at yahoo.com Wed Jun 19 13:44:48 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Wed, 19 Jun 2002 11:44:48 -0600 Subject: Pedagogic advice needed References: <3D104D35.E0932297@info.unicaen.fr> Message-ID: Jerzy Karczmarczuk wrote: > Then I began to digest all that, and the obvious question was: why not > Python? Indeed :) > 1. Does anybody here have some teaching experience in a similar context? I've been invited to give a talk to a similar group of biology students, at the end of the course, and have also given informal talks on 'python for science' to mathematicians. My topic for the biologists was C/python integration, but the whole course was given to a mix of graduate/undergrads with no computing background. I've spoken a fair bit to the professor and his experience (even though this was his first time teaching it) seems to have been very positive. You can find more about his course at: http://mcdb.colorado.edu/courses/6440/ > 2. Assuming that the visualisation issues, all kind of plots, graphs > *and animations* are very important, how would you organize with > Python such a work? For this kind of work, my current solution is using python/Numeric for the matlab-like numerical work, with Gnuplot for normal 2d/3d plotting (I have available a customized interface for Gnuplot access which runs on top of M. Haggerty's Gnuplot.py -- http://www-heller.harvard.edu/~mhagger/download/). This works very well for all kinds of 'typical' scientific plotting needs. For fancier 3d visualization needs (isosurfaces of functions of 3 variables, volume rendering, etc) I use the amazing MayaVi (http://mayavi.sourceforge.net/). It's a full featured GUI visualizer, but all written in python and scriptable 'from inside'. With it you'll also get ivtk, a very nice system for interactive use of VTK. Here are a few quick examples of what mayavi can do (from my own stuff, there's plenty more out there): http://windom.colorado.edu/~fperez/pub/topo_viz_sample.jpg -> isosurfaces and colormap cut planes (with and without transparency) of a 3-d slice of a 4-d dataset. http://windom.colorado.edu/~fperez/pub/topo_vol_ray.jpg -> a fancy ray-traced volume rendering of one 3-d slice. This kind of rendering is SLOW, but gives pretty pictures :) You have to write your own translucency tables obviously, and that takes some experimenting. You can grab from there the code to make that image if you want to play with it (http://windom.colorado.edu/~fperez/pub/vtk_volume.tgz) http://windom.colorado.edu/~fperez/pub/topo_2412.b585m008.36.1000.slices/ -> the full 4-d dataset sliced into a webpage. The html generation code is about 15-20 lines of very simple python. It's a very convenient way of visualizing complex datasets and automatically sharing the results with ohters: all they need is a web browser. > Of course I know Numeric Python, Scientific Python modules, and other > standard stuff permitting to do all kind of graphic exercices and > demonstrations (eg., all the wx bazar). Do you know about SciPy ()? It is a complete 'framework' that wraps around Numeric to provide very impressive overall functionality. > But I *must* avoid the low-level programming, we won't have time for that. > We will need a reasonable complete scientific 3D plotting package usable > by people without too much experience. If someone is there to do the install for them, I'd say scipy could satisfy your needs. Installing it is a major chore right now, but once up and running it works very well. You need to run off of CVS though, all releaseed code is outdated now. > (I checked the Obvious Suspects, the Vault of Parnassus, etc., I am veryfing > all that stuff, but perhaps some of you know something really succulent and > full of vitamines. I need *your experience*, NOT just standard Web links.) Well, besides the above, I would plug here my own project IPython (http://windom.colorado.edu/~fperez/ipython/). It's a command-line shell much more powerful than the default one, with many features specifically designed for scientific computing work (inspired/stolen from environments like Mathematica and IDL). If you install it and start 'ipython -p numeric' (assuming you have both Numeric and Gnuplot.py installed), you'll have an environnment very much like Matlab. Its gnuplot access functions are enhanced versions of the originals in Gnuplot.py, to make day to day plotting easier (I use it constantly, so I do eat my own dog food :) I use IPython everyday for exactly the kind of thing you have in mind, so I've tuned it to be as convenient as possible in that kind of environment. If you are interested in using it, I'll be glad to help you out with any snags you encounter. Cheers, f. From mhammond at skippinet.com.au Fri Jun 14 19:40:44 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Fri, 14 Jun 2002 23:40:44 GMT Subject: PythonWin Problem! References: <1a52c7f1.0206131455.6df50cf8@posting.google.com> <3D0973C5.60407@skippinet.com.au> <1a52c7f1.0206141158.1c03b3f5@posting.google.com> Message-ID: <3D0A7F8E.3090606@skippinet.com.au> Ethan wrote: > Thanks Mark. It worked like a charm. One thing though, the key I had > to delete was in HKCU rather than in HKLM. The second method would not > work with ME since like I said in my earlier post, I don't have a > right click menu for items in the taskbar. > Yes, I meant HKCU - sorry. I haven't used ME, but I know that Win9x, 2k and XP all have a right-click menu on the taskbar. Mark. From andy47 at halfcooked.com Tue Jun 11 01:57:47 2002 From: andy47 at halfcooked.com (Andy Todd) Date: Tue, 11 Jun 2002 05:57:47 +0000 (UTC) Subject: MySQLdb warnings problem References: Message-ID: Terry Hancock wrote in news:mailman.1023595512.23403.python-list at python.org: > Hi all, > > I'm in the middle of writing a Zope/MySQL project, and > I use a Python/MySQL crawler to do some database > maintenance tasks. > > I'm writing this crawler now, and it's my first > experience with "Python Database API 2.0", which seems > really overblown and complicated compared to the simple > interface described in O'Reilly's MySQL/mSQL book, or > with the ZSQL interface in Zope. I suppose this is > for the benefit of more complicated RDBMs than MySQL. > > Anyway, I hope I'm not making a mistake using it -- > I'm just trying to use the most "standard" Python > interface to MySQL, and I'm under the impression that > this is it. Please advise if I'm wrong. > > I couldn't find a mysqldb specific mailing list, so I > thought I'd try asking my question here: > > The program is fairly long, but what happens is that > it scans the database for entries in a database table > called "user" and calculates some statistics for them > based on other tables. All the retrievals work fine, > but I get a funny traceback when I write the data > back into the user's row in the table: > > Traceback (most recent call last): > File "Styx.py", line 258, in ? > styx.crawl( styx.params['P_Styx'], styx_tasks) > File "Crawler.py", line 193, in crawl > task[1](argval) # Operate on it > File "Styx.py", line 165, in compute_user_stats > dbcursor.execute(sqlcmd) > File > "/usr/local/narya/lib/python2.1/site-packages/MySQLdb/cursors.py", line > 61, in execute > r = self._query(query) > File > "/usr/local/narya/lib/python2.1/site-packages/MySQLdb/cursors.py", line > 168, in _query > rowcount = self._BaseCursor__do_query(q) > File > "/usr/local/narya/lib/python2.1/site-packages/MySQLdb/cursors.py", line > 118, in __do_query > self._check_for_warnings() > File > "/usr/local/narya/lib/python2.1/site-packages/MySQLdb/cursors.py", line > 150, in _check_for_warnings > raise Warning, self._info > _mysql_exceptions.Warning: Rows matched: 1 Changed: 0 Warnings: 1 > > For reference, here's a snippet of the code where this > broke: > sqlcmd= """ > UPDATE user SET nposts=%d, nrecent=%d, keytopic='%s' > WHERE username='%s' > """ % ( n_posts, n_recent, keytopic, user[0] ) > > #print sqlcmd > #try: > dbcursor.execute(sqlcmd) > #except: > # pass > > As the commented-out lines indicate, I tried ignoring this problem. > Doing so seems to make the program work fine, but I can't figure > out why it should be an issue in the first place (and I generally > prefer not to just ignore warnings, especially without understanding > them). > > The thing is, what's the warning message? Nothing was changed > this time, because a previous run already updated the stats (the > first run said "Rows matched: 1 Changed: 1 Warnings: 1"). > > Uncommenting the print statement shows what the actual SQL was: > > UPDATE user SET nposts=7, nrecent=0, keytopic='/' > WHERE username='anonymous' > > which looks legit to me, though I'm not really an SQL expert. > > So maybe it's raising a warning every time I write to the > database? Why? > > Should I just stick the try-except code back in and forget > about it, or am I missing a step somewhere? Any ideas would > be much appreciated. > > Thanks! > Terry > Terry, There isn't (as far as I know) a MySQLdb mailing list, but questions of this type are very welcome at the db-sig mailing list (db-sig at python.org or http://mail.python.org/mailman/listinfo/db-sig). Regards, Andy -- Contents free posts a speciality From hesterloli at hotmail.com Wed Jun 19 04:23:30 2002 From: hesterloli at hotmail.com (George Hester) Date: Wed, 19 Jun 2002 08:23:30 GMT Subject: python version? References: Message-ID: <6cXP8.47927$GY.15261354@twister.nyroc.rr.com> You ought to be -- George Hester _________________________________ "Ganesan R" wrote in message news:ouu1o0djnx.fsf at andlx-anamika.cisco.com... > >>>>> "George" == George Hester writes: > > > Don't worry I won't return here. This is not a group to get help but a > > group of individuals that think the world owes them something when they > > participate here. > > Oh, my! I am simply overcome with grief *sob* > > Ganesan > > -- > Ganesan R (rganesan at debian.org>) | http://www.debian.org/~rganesan/ > 1024D/5D8C12EA, fingerprint F361 84F1 8D82 32E7 1832 6798 15E0 02BA 5D8C 12EA From hancock at anansispaceworks.com Sat Jun 8 12:03:26 2002 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sat, 08 Jun 2002 09:03:26 -0700 Subject: MySQLdb warnings problem Message-ID: <3D022ACE.A545BF98@anansispaceworks.com> Hi all, I'm in the middle of writing a Zope/MySQL project, and I use a Python/MySQL crawler to do some database maintenance tasks. I'm writing this crawler now, and it's my first experience with "Python Database API 2.0", which seems really overblown and complicated compared to the simple interface described in O'Reilly's MySQL/mSQL book, or with the ZSQL interface in Zope. I suppose this is for the benefit of more complicated RDBMs than MySQL. Anyway, I hope I'm not making a mistake using it -- I'm just trying to use the most "standard" Python interface to MySQL, and I'm under the impression that this is it. Please advise if I'm wrong. I couldn't find a mysqldb specific mailing list, so I thought I'd try asking my question here: The program is fairly long, but what happens is that it scans the database for entries in a database table called "user" and calculates some statistics for them based on other tables. All the retrievals work fine, but I get a funny traceback when I write the data back into the user's row in the table: Traceback (most recent call last): File "Styx.py", line 258, in ? styx.crawl( styx.params['P_Styx'], styx_tasks) File "Crawler.py", line 193, in crawl task[1](argval) # Operate on it File "Styx.py", line 165, in compute_user_stats dbcursor.execute(sqlcmd) File "/usr/local/narya/lib/python2.1/site-packages/MySQLdb/cursors.py", line 61, in execute r = self._query(query) File "/usr/local/narya/lib/python2.1/site-packages/MySQLdb/cursors.py", line 168, in _query rowcount = self._BaseCursor__do_query(q) File "/usr/local/narya/lib/python2.1/site-packages/MySQLdb/cursors.py", line 118, in __do_query self._check_for_warnings() File "/usr/local/narya/lib/python2.1/site-packages/MySQLdb/cursors.py", line 150, in _check_for_warnings raise Warning, self._info _mysql_exceptions.Warning: Rows matched: 1 Changed: 0 Warnings: 1 For reference, here's a snippet of the code where this broke: sqlcmd= """ UPDATE user SET nposts=%d, nrecent=%d, keytopic='%s' WHERE username='%s' """ % ( n_posts, n_recent, keytopic, user[0] ) #print sqlcmd #try: dbcursor.execute(sqlcmd) #except: # pass As the commented-out lines indicate, I tried ignoring this problem. Doing so seems to make the program work fine, but I can't figure out why it should be an issue in the first place (and I generally prefer not to just ignore warnings, especially without understanding them). The thing is, what's the warning message? Nothing was changed this time, because a previous run already updated the stats (the first run said "Rows matched: 1 Changed: 1 Warnings: 1"). Uncommenting the print statement shows what the actual SQL was: UPDATE user SET nposts=7, nrecent=0, keytopic='/' WHERE username='anonymous' which looks legit to me, though I'm not really an SQL expert. So maybe it's raising a warning every time I write to the database? Why? Should I just stick the try-except code back in and forget about it, or am I missing a step somewhere? Any ideas would be much appreciated. Thanks! Terry -- ------------------------------------------------------ Terry Hancock hancock at anansispaceworks.com Anansi Spaceworks http://www.anansispaceworks.com ------------------------------------------------------ From egbert at bork.demon.nl Fri Jun 7 04:48:22 2002 From: egbert at bork.demon.nl (Egbert Bouwman) Date: Fri, 7 Jun 2002 10:48:22 +0200 Subject: Program to an interface, not an implementation In-Reply-To: ; from eric.brunel@pragmadev.com on Thu, Jun 06, 2002 at 02:15:41PM +0000 References: Message-ID: <20020607104821.A227@bork.demon.nl> All your comments are crystal clear. Thanks. My next problem is on nearly the same page (17) of the GoF book: class versus interface (== type) inheritance, but in the python context. "In C++ and Eiffel inheritance means both interface and implementation inheritance" and "in Smalltalk inheritance means just implementation inheritance". I don't know any of these languages. Now in my simplistic worldview, if you inherit from a class, you inherit everything, implementation and interface, because the implementation defines the interface as well. Even if all methods of the superclass only contain 'pass'. But I may be wrong. egbert -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From occeanlinux at linuxmail.org Mon Jun 3 02:09:43 2002 From: occeanlinux at linuxmail.org (Gold Fish) Date: Mon, 03 Jun 2002 06:09:43 GMT Subject: List References: <20020602205610.31575.qmail@linuxmail.org> <009b01c20a7e$12a5ad80$0101010a@local> Message-ID: <3cfb07cf_1@news.iprimus.com.au> Mike C. Fletcher wrote: > I don't know if you'll consider this a more elegant way to divide up the > lists, but I think it's a little more beautiful than the index-mucking > approaches IMO: > > def into( source, count=3 ): > source = source[:] > return intoDestructive( source, count ) > > def intoDestructive( source, count=3 ): > if source and not count: > raise ValueError( """Cannot divide into 0-length sub-elements""" > ) > elif not source: > return [] > results = [] > if count > 0: > while source: > results.append( source[:count]) > del source[:count] > else: > while source: > results.append( source[count:]) > del source[count:] > return results > > It will be very slow for very large lists with positive slice values > (something the index-mucking approach doesn't suffer from), but for most > reasonably sized lists, should be fairly good. It handles negative > steps as well, so you can slice up the list from the right _or_ the left > side :) . > > Enjoy all, > Mike > > Chris Gonnerman wrote: > ... >> >> Lists = [] >> N = 2 >> >> adj = 0 >> >> if len(BigList)%N: >> adj = 1 >> >> for i in range(len(BigList)/N+adj): >> Lists.append(BigList[i*N:(i+1)*N]) >> >> (If anyone knows a more elegant solution please post it, >> as I am getting headaches trying to think of one.) > ... > _______________________________________ > Mike C. Fletcher > http://members.rogers.com/mcfletch/ Sorry for the very stupid question but i still don't get my goal, that's is using Mike C. Fletcher method i will generate the list of elements again and don't know what size it is. For example : [['p1','p2','p3'],['p4','p5','p6'],['p7','p8','p9'],['p10']] I want to seperate this list again in order to using them later .It look like you go to the realestate agent website and find the list of property then you just want to display 3 properties per pages. And you can go to other pages which also contain 3 properties as well until the last pages which has only 1 items. For example: Page 1: ['p1','p2','p3'] Page 2: ['p4','p5','p6'] Page 3: ['p7','p8','p9'] Page 4: ['p10'] I didn't sleep well due to this problem Can any help me. From cmkim at shinbiro.com Thu Jun 27 00:17:25 2002 From: cmkim at shinbiro.com (Kim Chul Min) Date: Thu, 27 Jun 2002 13:17:25 +0900 Subject: [Q] How Can I call python function from C source? Message-ID: Hello there, I want to call python function from c source. for example, in file "main.c" -------------------------------------------------------------- int main(void) { /** want to call python function add(a,b) that return a+b **/ } -------------------------------------------------------------- in the file "add.py" -------------------------------------------------------------- def add(a,b): return(a+b) -------------------------------------------------------------- Can I call any function that written by python from C source ? If possible, can anyone show me simple example like above?? Plz,,, Help me....Thankx in advance... Ciao, Farangan Xavio cmkim at shinbiro.com From tdelaney at avaya.com Wed Jun 19 00:01:48 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Wed, 19 Jun 2002 14:01:48 +1000 Subject: python version? Message-ID: > From: George Hester [mailto:hesterloli at hotmail.com] > > The whole issue started from here. I did not deserve to be > told to "crawl > before I walk." I may have responded to that inappropriately Actually, that is a very common phrase which is used to suggest that you probably don't know enough yet to do what you're trying to do, and so should work on something simpler first. So it was indeed very appropriate here. Every time I learn a new programming language I need to crawl before I walk - I can't do something complicated until I understand the syntax and semantics. In any case, this all started when you did not try to understand the useful suggestions you were given right from the very first reply to this thread. I refer you once again to: http://www.tuxedo.org/~esr/faqs/smart-questions.html which contains *very* useful information for *anyone* when asking questions (especially in a technical forum). It is not an attempt to ridicule you - it is an attempt to help you learn what is appropriate and what is expected. I've already spent far too much time on this myself, but I'm still hoping you will help yourself. Tim Delaney From johnroth at ameritech.net Tue Jun 4 08:03:30 2002 From: johnroth at ameritech.net (John Roth) Date: Tue, 4 Jun 2002 08:03:30 -0400 Subject: Behavior of += (was Re: [Python-Dev] Customization docs) References: Message-ID: "Huaiyu Zhu" wrote in message news:slrnafo7qv.37c.huaiyu at gauss.almadan.ibm.com... > Gustavo Cordova wrote: > > Great explanation! The problem stems from the fact that the current += > operator implements two semantically distinct operations, chosen according > to some properties of the operands. This is not unlike the situation of the > division operator with distinct behaviors on floats and ints. This is not an issue with '+='. It's an issue with assignment, regardless of whether it is standalone or combined with some other operation. And I disagree that assignment implements two distinct operations. Assignment always rebinds. Always. In the examples cited, it attempted to rebind into a tuple, because that's what was asked for when the left hand side had a subscript. The reason that the examples given at the top of the thread fail in such strange ways is simply that '+=' does not check whether the assignment is possible before doing the addition (or concatination, in the specific cases cited.) To see this, you could try the first example, using explicit '+' and '='. I suspect it would fail in exactly the same way, with exactly the same side effect. John Roth From peter at engcorp.com Wed Jun 5 10:44:43 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 05 Jun 2002 10:44:43 -0400 Subject: Compiling Python References: Message-ID: <3CFE23DB.994F8A6C@engcorp.com> TuxTrax wrote: > > Hello all > > I am new to this forum, and to Python, please excuse the newbie question. > > I have started reading the o'reilly book, "learning python" and find python > to be an amazing language so far. My first impression of it is a language that > is easier than basic to learn and use, and more powerful than many other > high level languages such as pascal. > > My question is this; I realize that Python compiles to bytecode automatically > as part of the interpreters tokenization run, but is there a way to permanently > compile python code outputting to an executable binary? Why do you want to do that? For presumably increased speed, or because you don't want the hassle of multiple .py files all over the place (in other words, better packaging)? -Peter From whisper at oz.net Mon Jun 24 21:55:22 2002 From: whisper at oz.net (David LeBlanc) Date: Mon, 24 Jun 2002 18:55:22 -0700 Subject: Suggestions for good programming practices? In-Reply-To: <3D17C148.6CC8B3D2@engcorp.com> Message-ID: They may be returned in a tuple, but they're PUT in discrete variables and not kept in a tuple that I have to programmatically unpack. Language lawyer should be shot, _then_ heard. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Peter Hansen > Sent: Monday, June 24, 2002 18:03 > To: python-list at python.org > Subject: Re: Suggestions for good programming practices? > > > David LeBlanc wrote: > > > > The one that always gets me is "lat,lon,timezone = > getLocation("seattle")". > > I.E. the ability to return multiple distinct values as opposed > to returning > > multiple values in the form of a struct as in C or C++. > > You _are_ returning them "in a struct". It's spelled "tuple" > but other than that what's the difference? > > -Peter > -- > http://mail.python.org/mailman/listinfo/python-list From sjmachin at lexicon.net Tue Jun 11 16:20:31 2002 From: sjmachin at lexicon.net (John Machin) Date: 11 Jun 2002 13:20:31 -0700 Subject: if number is 1-2, 4 or 6-8 or 12-28, 30, 32... References: Message-ID: Gustaf Liljegren wrote in message news:... > Cliff Wells wrote: > > Thanks both of you. I tried both solutions. Since some intervals are very > high (1000000+), it takes too long to add them to a list. Cliff's solution > was really fast, but it took a while to understand. :) > Sorry, Mr Customer, I thought I heard you say "thousands & elegant"; now I'm hearing "millions & fast". Let's get serious: How many intervals do you have (a) max (b) average? How many of the intervals are single integers? Between the lowest possible number and the highest possible number, what percentage of integers are in the set? What is the frequency distribution of membership tests? [I.e. is it biassed towards small/large integers or is it "random"?] What is your real speed requirement? With Cliff's solution, what proportion of your app's run-time is spent testing set membership? How many tests per set? From m.faassen at vet.uu.nl Sun Jun 30 16:58:39 2002 From: m.faassen at vet.uu.nl (Martijn Faassen) Date: 30 Jun 2002 20:58:39 GMT Subject: Reminder of a python Project. References: <2218.941T781T12224051threeseas@earthlink.net> Message-ID: Timothy Rue wrote: > First off, it's ok that I got such a high level of resistance to my > initial posting here about this project. Thanks to some research that /. > had an article on, regarding the size of GPL project teams. > But anyway.... Remember the autocoding project I mentioned? FOR IMMIADIATE DISTRIBUTION TO ALL PSU MEMBERS -- ULTRA SECRET The Python Secret Underground does not allow any functional autocoder to exist in this particular timeline at this particular time, outside of the various bots. The ruebot is (obviously) a rogue mutant version of the timbot. The mutation has however wiped out its autocoding ability, deleting any knowledge of the 10th autocoding command, retaining only 9. Detecting this lack in itself but not exactly understanding it, the ruebot is now attempting regain this lost ability. Luckily its post-singularity knowledge is virtually incomprehensible to most humans before the year 2053. All PSU members are instructed to either AVOID or MISLEAD the ruebot in a subtle way. At all costs, do not leak the information of the 10th command necessary for true autocoding. Let it focus on the 9 commands and let it think those are all that are needed for autocoding. From hesterloli at hotmail.com Tue Jun 18 16:41:09 2002 From: hesterloli at hotmail.com (George Hester) Date: Tue, 18 Jun 2002 20:41:09 GMT Subject: python version? References: Message-ID: Thought so. Since I have been treated so nicely I will make it a point to return with the solution. Thanks for all the help. -- George Hester _________________________________ "Ganesan R" wrote in message news:ou8z5cg7ft.fsf at andlx-anamika.cisco.com... > >>>>> "George" == George Hester writes: > > > "If you can't get an answer, please don't take it personally that we don't > > feel we can help you. Sometimes the members of the asked group may simply > > not know the answer." > > Yeah, right. Nobody in the group knows the answer to your question. We would > really appreciate if you do some research and figure it out for yourself. We > would be even more happy when you come back and enlighten us with your > knowledge. Thank you. > > Ganesan > > -- > Ganesan R From egbert at bork.demon.nl Mon Jun 10 06:19:52 2002 From: egbert at bork.demon.nl (Egbert Bouwman) Date: Mon, 10 Jun 2002 12:19:52 +0200 Subject: Program to an interface, not an implementation In-Reply-To: ; from gscott@peregrine.com on Fri, Jun 07, 2002 at 08:43:23AM -0700 References: Message-ID: <20020610121951.B473@bork.demon.nl> Again I learned a lot from both of you, and reading a couple of hours in a C++ book helped as well. But it is not all crystal clear any more. Eric says: > So, as you see, you probably can live without knowing anything about all > this and still be able to do great stuff with whatever language you like You should see my programs already. However I have the impression that assimilating the GoF book will improve things enormously. And for that I have to understand their and other terminology. Compared to the terminologies the basic mechanisms look simple. In Gordon's reply the venom is in the end: > For C++ interface inheritance REQUIRES class inheritance. For > Python/Smalltalk, it does not. This I read as: For Python interface_inheritance does not require class_inheritance. So you can inherit an interface without inheriting the class, but interface_inheritance by way of class_inheritance is possible as well. That means at least two things: - python has interface inheritance (which some people deny), - interface_inheritance without class_inheritance is a kind of cultural (not genetical) inheritance: give it the same name and all is well. But for me that is only polymorphism ! I do all this hair splitting because the GoF say (still page 17) that many patterns depend on the distinction between interface- and implementation inheritance. How do you define in python the interface inheritance the GoF talk about ? egbert -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From ykingma at accessforall.nl Thu Jun 6 15:30:55 2002 From: ykingma at accessforall.nl (Ype Kingma) Date: Thu, 06 Jun 2002 20:30:55 +0100 Subject: array, list, performance... References: Message-ID: <3CFFB86A.4114459A@accessforall.nl> Michael Chermside wrote: > > Here is my understanding of it: > > li = [x0, x1, x2, ...] > > li[n] element access is O(1) > li.append(x) appending is O(1) > (actually, it SOMETIMES takes O(len(li)) as it > resizes the list. But if you grow a list by > continually appending, the amortized time is > linear (ie, constant amortized time per element) Append is often enough linear in the length of the list that growing by appending is O(len(li) * len(li)). You can prevent that by creating a list a large enough list when starting, eg: li = [None] * neededSize > li.insert(0) prepending is O(len(li)) > (so grow the list from the end!) > del li[0] deleting from the front (or middle) is O(len(li)) > li.pop() deleting from the end is O(1) > li[n] = x assignment to the middle is O(len(li)) Assigment to the middle of a list is O(1), ie. same as element access. > len(li) determining length is O(1) > li.index(x) search is O(len(li)) (NOT efficient) > li.sort() sort is O(len(li)*ln(len(li))) > (I believe it uses quicksort, but if a python > function has to be executed for the compare > that may take some time.) > > It's really just your basic auto-growing array, but with a bunch of > clever things done to speed up common cases, and I don't know those well > enough to comment on them. > > -- Michael Chermside Have fun, Ype -- email at xs4all.nl From occeanlinux at linuxmail.org Sun Jun 2 16:35:20 2002 From: occeanlinux at linuxmail.org (Gold Fish) Date: Sun, 02 Jun 2002 20:35:20 GMT Subject: string generator Message-ID: <3cfa8039_1@news.iprimus.com.au> I like to create a list of file automatical based on series. For example user input the number of file say 5. So i want to generate the file according to this range , this mean the generated files could be filename1 filename2 filename3 filename4 filename5 I using the for loop like that for file in range(5): lis = [file] string.join('filename',lis[1:]) how can it didn't work. I am confusing how to do it. From feldspar at ix.netcom.com Sat Jun 22 13:45:21 2002 From: feldspar at ix.netcom.com (Antaeus Feldspar) Date: Sat, 22 Jun 2002 14:45:21 -0300 Subject: Python hits the spot References: <3D1482AE.8FA299D8@kfunigraz.ac.at> Message-ID: <3D14B7B1.7040602@ix.netcom.com> Siegfried Gonzi wrote: [snip] > Thank you Billy Boy for a forgiving user system Windows XP which in turn > relieves Python's "wreak havoc" behavior. [snip] You know, a month or so ago, I was listening to complaints from a webpage builder that of all the Web browsers out there, only Internet Explorer rendered his friend's HTML code "correctly". When he was pressed for what the other browsers did "incorrectly", it turned out that the would-be web-maven wanted to be able to use the digit "0" and the letter "O" interchangeably in hexadecimal values -- not because there was any particular benefit to mixing-and-matching, merely because they were used to be careless about such things. Internet Explorer was the only one that accepted such behavior without even an alert that it was wrong. "Forgiving"? Or enabling? One hard-won piece of wisdom I've learned about computer interfaces over the years is "people learn by doing; if you allow them to do it the wrong way, they learn to do it wrong." Even if you say "In this case, it doesn't make a difference, so why not?" that only builds in bad habits that compound on each other until the time comes that it *does* make a difference. That's the hard lesson that has been learned about safety systems, is that building in six layers of safety to protect workers from the consequences of their actions will in fact train workers to get all six wrong at once. -jc From niemeyer at conectiva.com Thu Jun 27 15:06:39 2002 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Thu, 27 Jun 2002 16:06:39 -0300 Subject: Python crashed on me In-Reply-To: <20020627205042.A18986@phd.pp.ru> References: <20020627205042.A18986@phd.pp.ru> Message-ID: <20020627160639.A23280@ibook.distro.conectiva> Hello Oleg! > Recently Python (one program that I am dbugging) started to crash. > FreeBSD kills it with "Bus error", Linux with "Segmentation fault". > > I think the program crashed in the cPickle.dump(file, 1), because after > the crash the file is corrupted and cannot be load back (upon loading > cPickle complain EOFile). The error is reproduceable. > > How can I debug the situation? May be my data grew too big? The pickle > file is about 800K. [...] Do you have a small testcase? -- Gustavo Niemeyer [ 2AAC 7928 0FBF 0299 5EB5 60E2 2253 B29A 6664 3A0C ] From paoloinvernizzi at dmsware.com Tue Jun 25 13:24:31 2002 From: paoloinvernizzi at dmsware.com (Paolo Invernizzi) Date: Tue, 25 Jun 2002 17:24:31 GMT Subject: Python and Eclipse References: <3D17FAF4.35CC9F1B@earthlink.net> <81CC01E58BF2A99B.DFCD5EC6E4654907.32D731380951B9CA@lp.airnews.net> <3D189A8A.577C8186@earthlink.net> Message-ID: <3D18A6D2.5080404@dmsware.com> > Eclipse is open source, so no matter what > IBM decides, interested parties could pick > it up and run if necessary. I've read the licence, I've understood that I can release product based on Eclipse, either commercially, either compiled, preserving the copyright note and a link to original eclipse source... but I'm a terrible reader of license-style document! Someone can confirm this? > I have not tried JBuilder. I worked with jbuilder 5 for about 6 mnts, and I feel Eclipse is far superior. I love the refactoring tools, but I still whisper for a form builder plugin...(and Borland is a master in this field!) Concerning elipse and python, I think there are 2 roads. The first one is using jpe (http://sourceforge.net/projects/jpe) the python-java framework. I've tried it some time ago... and I managed to execute python code from a java VM (a jython prompt in reality! ;) but I stopped there. Perhaps Frederic Giacometti and jython folks can give some help! The second one is to use socket (is possible?) to connect to a python server application... (with the plus that switching various python versions is very easy)... and move some logic in python (fast development times ;) The problem, as usual It's that I have no time ;( Cya Paolo Invernizzi From never at mind.info Fri Jun 28 08:47:26 2002 From: never at mind.info (G. Willoughby) Date: Fri, 28 Jun 2002 13:47:26 +0100 Subject: Is Python growing? References: <3D1B92FB.59B590A0@pop.ntlworld.com> <7x66042j50.fsf@ruckus.brouhaha.com> Message-ID: > Well, you could have said... Theres always one isn't there? ;-) --G. Willoughby From karczma at info.unicaen.fr Tue Jun 11 08:55:02 2002 From: karczma at info.unicaen.fr (Jerzy Karczmarczuk) Date: Tue, 11 Jun 2002 14:55:02 +0200 Subject: Defining a method final References: <6glN8.35376$86.884025@twister1.libero.it> Message-ID: <3D05F326.478E20B9@info.unicaen.fr> Fabio Corneti wrote: > > I would like to define a method for a class which has > not to be overriden. Of course, since the developer of > this project are two, this could be established by > convention, but if the project will grow consistently > another developer could override the method by mistake, > causing unpleasant side effects. Hm. A classical problem. Will you ask tomorrow for private methods and private inheritance as well? Python, like Smalltalk was never designed for paranoid [*NO* disrespect meant or implied] projects, whose members need to protect themselves from themselves. If such a danger is real, use qualified names. Jerzy Karczmarczuk Caen, France From donn at u.washington.edu Tue Jun 11 20:10:22 2002 From: donn at u.washington.edu (Donn Cave) Date: 12 Jun 2002 00:10:22 GMT Subject: M2Crypto: select() behaves weird on SSL socket References: <3D04ECED.2030202@NOSPAMREMOVETHISxs4all.nl> <3D04FBF5.8090407@NOSPAMREMOVETHISxs4all.nl> <3D04FE2F.6070302@NOSPAMREMOVETHISxs4all.nl> <1023762896.869994@yasure> <3D063356.30200@NOSPAMREMOVETHISxs4all.nl> Message-ID: Quoth Irmen de Jong : | If there is a SSL wrapper for plain sockets, isn't there some | sort of SSL wrapper of select()? I don't know. Probably not, but I don't know what's in M2Crypto. | > I see my reply earlier today followed up a separate thread, after | > you posted your initial question twice. If you haven't seen it, | > a hint: SSL_pending(self->ssl.) (I don't know much more than that, | > anyway.) | | I don't know if this function is exposed in M2Crypto... if it is, | I could probably get my code to work. If it isn't, I don't know | how to fix it :-( Assuming I guessed right about what the function does, you either need it - or you have to redesign your application to use a separate thread here, where the thread will just read and not care whether it blocks or not. (This may be the first time I have ever proposed threads as a solution in c.l.p., which goes to show what a stupid problem this is.) Donn Cave, donn at u.washington.edu From vze3myxh at verizon.net Sun Jun 2 13:37:20 2002 From: vze3myxh at verizon.net (vze) Date: Sun, 02 Jun 2002 17:37:20 GMT Subject: GUI Toolkit! References: <1a52c7f1.0206011720.7c3ac7ea@posting.google.com> Message-ID: If you need to make something very quickly, try pythoncard at pythoncard.sourceforge.net. It is a layer above wxWindows and comes with tons of samples - including an interface builder written in itself. wrote: > Hi, > I need to do some GUI programming with Python. I found that there > are quite a few options available for the toolkits . Apart from TkInter, > I have seen bindings for Qt, wxWindows, FOX and FLTK. I want to pick one > with the best open visual tools available. From what I have looked I am > really impressed with the screen shots of Boa Constructor. Apparently it > even generates the event procs. But I doubt that I have seen everything. > Can anyone please tell me about any other options that I might have. I > am developing on Windows. > > Thanks From gerhard.haering at gmx.de Sun Jun 30 23:33:16 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Mon, 1 Jul 2002 05:33:16 +0200 Subject: Q: Status of MySQL & Python? In-Reply-To: <69hvhu4otkrcncmu0d4vudfhv74o7maiul@4ax.com> References: <69hvhu4otkrcncmu0d4vudfhv74o7maiul@4ax.com> Message-ID: <20020701033316.GA6829@lilith.my-fqdn.de> * John Hall [2002-07-01 03:12 +0000]: > When trying to run the dbBrowser from Samples, MySQLdb/__init__.py > does a traceback in line #27 because _mysql is not found. Sure 'nuff, > I don't have that. I do have souce C source: _mysql.c Obviously you downloaded the source distribution. It's dead simple to build this, if you have Visual C++ installed: - Edit setup.py to point to your MySQL installation - Enter python setup.py install But you can just download the binary installers for Windows, which are available for Python versions from 1.5.2 to 2.2 at the same place as the source tgz: http://sourceforge.net/project/showfiles.php?group_id=22307 If you find any Windows-specific problems with these, complain to me - I built them. The source distribution is still useful, because it contains the fine documentation, which is missing in the binaries. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From rayed at awal.net.sa Sun Jun 30 03:50:04 2002 From: rayed at awal.net.sa (rayed) Date: Sun, 30 Jun 2002 10:50:04 +0300 Subject: Preforked server in Python Message-ID: <3D1EB82C.1000501@awal.net.sa> Hi, I am looking for module similar to SocketServer that prefork chlidren instead of forking on each request. Thanks in advance - rayed From bjarne_christiansen at hotmail.com Wed Jun 26 04:08:26 2002 From: bjarne_christiansen at hotmail.com (Bjarne Christiansen) Date: Wed, 26 Jun 2002 08:08:26 +0000 Subject: Python file upload Message-ID: Hi, I have some problems uploading binary files though the web browser. It seens to work fine when uploading ACII file but but binary files seems to be currupted. The begining of the binary file seems fine, but some data is missing.... Here is my file upload script: #!c:\Python\python -d import cgi print "content-type: text/html\n\n" form = cgi.FieldStorage() if not form: print """

""" elif form.has_key("filename"): item = form["filename"] if item.file: data = item.file.read() print cgi.escape(data) data1 = cgi.escape(data) f = open("file1.jpg","wb") f.write(data1) Any help will be greatly appriciated! Best Regards, Bjarne Christiansen bjarne_christiansen at hotmail.com _________________________________________________________________ MSN Photos is the easiest way to share and print your photos: http://photos.msn.com/support/worldwide.aspx From plugin at supercable.es Mon Jun 24 18:25:51 2002 From: plugin at supercable.es (Ugo García) Date: Tue, 25 Jun 2002 00:25:51 +0200 Subject: Threads on embedded Python References: <1024952585.111238@seux119> Message-ID: <1024957605.771843@seux119> Let see if I get something clear... I don't have any main loop in Python. I only have some functions that 'control' certains object in my operation. To be a little more clear, the task of the functions are for example, move an object in the world generated by a game with a little intelligence. For example: (a simple example) FUNCTION 1: - Wait until main character is in correct position - Play a sound - Move an enemy from pos X1,Y1 to X2,Y2 - Play an animation - .... - .... So, I don't have a main loop, only function like that (and other kind of functions) that a run as a thread to have all them running simultaneous. Is there other way to do that without having threads? Do I have to have a main loop in order to have the threads running? Perhaps running Python in a separate thread could be a good idea. Thanks, --ugo "Chris Liechti" escribi? en el mensaje news:Xns9237EECAA9CC5cliechtigmxnet at 62.2.16.82... > "Ugo Garc?a" wrote in > news:1024952585.111238 at seux119: > > > Hi all. I have an applicattion who uses Python to control some > > processes. I've made a little script library to work with threads and > > each proccess is a Python thread. The main application make calls to > > Python in order to create these proccesses. The problem is that the > > proccess doesn't run unless I call Python to do something. Now in the > > main loop I have a line like this: > > PyRun_SimpleString("dummy=1"); > > > > This make Python the threads to run. The problem is that this is a > > little slow 'cause if I call Python from tha main application too many > > times the proccesses run well but not the main application, and if a > > make a big pause between calls the proccesses doesn't work at a good > > speed. Is posible to have some threads running in an embedded Python > > without making callings to it continuosly? It would be a better idea > > to have another thread who's only task is to call Python (a line that > > the one written before) in order to have the Python proccesses > > running? > > why not run python in a separate thread (created by your app) and doing the > loop in python, like PyRun_SimpleString("while 1: mainloop()") or so? > you do have a main loop in python, don't you? otherwise you wouldn't need > python threads, right? :-) > > you could possibly also release the GIL, but don't forget to grab it again > when accessing the python interpreter. i'm not sure about this one, so i > would try the above. > > chris > > -- > Chris > From d2002xx at softhome.net Fri Jun 7 09:50:33 2002 From: d2002xx at softhome.net (nobody) Date: 7 Jun 2002 06:50:33 -0700 Subject: Native code compiler for python? Message-ID: Is there any existing native code compiler for python? Or Python to C translator? Or someone is doing this? From dfackrell at DELETETHIS.linuxmail.org Thu Jun 13 09:59:00 2002 From: dfackrell at DELETETHIS.linuxmail.org (Daniel Fackrell) Date: Thu, 13 Jun 2002 07:59:00 -0600 Subject: parse tar file with python References: Message-ID: <3d08a527$1_3@hpb10302.boi.hp.com> Just tossing out some ideas here that may or may not pay off (not in any particular order). 1. Try splitting the files between different directories like another post mentioned. 2. Try using the tar module on one large tar file. 3. Try using the tar module on several medium-sized tar files. 4. (Was going to suggest open()ing a bunch of files at once in case there is some delay there and separating the open() and read() calls might show some speed improvement, but I think I won't.) 5. Consider threads? They can help in some cases where I/O is the speed-limiting factor. 6. Post a sample of the code you have right now so that we can see what you're doing, perhaps including data extracted with the profile module. -- Daniel Fackrell (dfackrell at linuxmail.org) When we attempt the impossible, we can experience true growth. "Shagshag13" wrote in message news:aea0hs$54qq4$1 at ID-146704.news.dfncis.de... > In fact, i don't want to tar/untar files, and especially not in main memory ! > > I wish i could read the tar-ed file line by line (f.readline) and be able to check when i find the beginning of an "inside file" and > get some info about it like name, how and so on... (that's because my original files are plain text file, and i think that tar will > let them unchanged) > > In my tar file there is, for example, a kind of separator like this (but with everything in one long line) with : > > shag.py_0100744_0002033_0001750_00000004414_07500237361_0015314_0_ustar_00_s hagshag_user_0000040_0000417_beginofmyfilehere > > where _ stand for a variable amount of another ascii code that i can't cut/paste... > > Do you kwow what each means (for example the first one is undoubtly the file name, but then...) ? > And what are the fixed position of each of theses ? > Have a clue ? > > Many thanks, > > s13. > > > > > From thomas.mangin at free.fr Mon Jun 3 15:13:50 2002 From: thomas.mangin at free.fr (Thomas Mangin) Date: 3 Jun 2002 12:13:50 -0700 Subject: Created a "file" like command in python (see man 4 magic) and face a showstoper bug Message-ID: <359e75aa.0206031113.6a8bfed1@posting.google.com> Hi, I wrote some code perform "file" like operation and I am facing a nasty bug. the files can be found at : ftp://www.slhan.org/source/circle/ It produce the same output that "file": # ./magic.py core core: ELF 32-bit LSB core file of 'vi' (signal 11), Intel 80386, version 1 (SYSV) # ./magic.py jpg_good.jpg jpg_good.jpg: JPEG image data, JFIF standard 1.01, resolution (DPI), 50 x 50 # ./magic.py jpg_bad.jpg jpg_bad.jpg: JPEG image data, EXIF standard %d.73, 10752 x 2048 Note the %d ! The code causing problem is : if replace: try: mime = mime % replace except: pass In both case mime is containing the string "%d." and replace is in both case of type int and valued 1 and 0. Any idea ? Thomas Mangin From jeff at sasmor.com Mon Jun 17 17:53:37 2002 From: jeff at sasmor.com (Jeff Sasmor) Date: Mon, 17 Jun 2002 21:53:37 GMT Subject: If you use Python -OO is it a permanent condition?? References: Message-ID: 'Fascinating' I'm sure there's a logical reason... somehow. Anyway, I found that if I renamed all the .pyo files to .pyc everything works fine. I guess that's because there's little difference between them. It's too bad that there's no way to switch optimized mode on and off programmatically - would be useful for apps that use compile(). -- #-------------------------------- Jeff Sasmor jeff at sasmor.com "Aahz" wrote in message news:aelamd$fo1$1 at panix1.panix.com... > In article , > Jeff Sasmor wrote: > > > >So I tried: > > > >python -OO P1.pyo > > > >and it works just fine. Does this mean that the interpreter must > >always be started with -OO to execute files compiled with -OO? I can't > >imagine why this would be the case, but it seems to be -- at least as > >far as I can see from my little bit of experimentation. > > Python doesn't search for .pyo files unless it is running in optimized > mode. Try setting the PYTHONOPTIMIZE env var. > -- > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ > > Project Vote Smart: http://www.vote-smart.org/ From s.keim at laposte.net Wed Jun 26 06:32:01 2002 From: s.keim at laposte.net (sebastien) Date: 26 Jun 2002 03:32:01 -0700 Subject: 'parent object'? References: <3d18228c$0$221$4d4ebb8e@news.nl.uu.net> Message-ID: <7da8d8f8.0206260232.44587981@posting.google.com> > Is there, like 'self, also a 'parent' object of some sort? > The problem i'm having is that i have a class, which contains a list of > instances of another class. How can i let this 'childclass' call a function > which is on the 'parent class'? As have said other posters, you should probably avoid this kind of design. But if you absolutely need it, here is a short hack for Python 2.2 that use attribute descriptors: class Parent(object): class Child(object): def __get__(self, obj, cls): self.__parent = obj return self def hello(self): print "Hello, I'm",self,"and my father is",self.__parent child = Child() x = Parent() x.child.hello() From baf at texas.net Thu Jun 27 08:43:01 2002 From: baf at texas.net (Ben Fairbank) Date: Thu, 27 Jun 2002 12:43:01 GMT Subject: [Newbie] How to manipulate variable _names_ ? Message-ID: <3d1b0723.6179705@news.texas.net> I have a program that requires the user to enter a file name, such as "othello," which the program will then open, process, and create a dictionary based on the contents of the file. I would like to name the dictionary "OthelloCount," and then go on and create more dictionaries, each with a name made up of the inputfile name as provided by the user, concatenated with "Count," but I do not know how to make a variable name based on input. Any suggestions? BAF. From thomas.mangin at free.fr Tue Jun 4 04:14:23 2002 From: thomas.mangin at free.fr (Thomas Mangin) Date: 4 Jun 2002 01:14:23 -0700 Subject: "file" like command in python (see man 4 magic) download References: <359e75aa.0206031113.6a8bfed1@posting.google.com> Message-ID: <359e75aa.0206040014.3e3fa8de@posting.google.com> > 1. initialize replace with None > > > if replace: > > use this instead: > if replace is not None: > > and have fun progamming python! > chris It was the source of the problem. Feel free to download the code (GPL) if you need it at ftp://www.slhan.org/source/magic.tar.gz Thomas From look at sig.invalid Wed Jun 26 06:27:16 2002 From: look at sig.invalid (Simo Salminen) Date: Wed, 26 Jun 2002 10:27:16 +0000 (UTC) Subject: Python file upload References: Message-ID: * Bjarne Christiansen [Wed, 26 Jun 2002 08:08:26 +0000] > Hi, > I have some problems uploading binary files though the web browser. It seens > to work fine when uploading ACII file but but binary files seems to be > currupted. The begining of the binary file seems fine, but some data is > missing.... > > Here is my file upload script: > > #!c:\Python\python -d see http://www.python.org/cgi-bin/faqw.py?req=show&file=faq07.012.htp > data1 = cgi.escape(data) > f = open("file1.jpg","wb") > f.write(data1) >>> cgi.escape.__doc__ "Replace special characters '&', '<' and '>' by SGML entities." why would you cgi.escape the data? -- simo salminen iki fi From spammers.do.not.bother at void.bogus Sun Jun 2 07:33:24 2002 From: spammers.do.not.bother at void.bogus (Magnus) Date: Sun, 02 Jun 2002 11:33:24 GMT Subject: How to call functions inside a cgi script from the html interface? References: <2bkcda.c25.ln@10.0.0.1> Message-ID: <8onK8.10334$p56.3020410@newsb.telia.net> Ken wrote: > Where can I find good references with both python and HTML explained in > detail on how they work together? Maybe if you use our friend Google? http://www.google.com/search?hl=en&lr=&q=%2Bpython+%2Bcgi+%2Bhtml+%2Btutorial+%2Bhowto Regards, Magnus From occeanlinux at linuxmail.org Sun Jun 2 17:43:20 2002 From: occeanlinux at linuxmail.org (Gold Fish) Date: Sun, 02 Jun 2002 21:43:20 GMT Subject: List References: <3cfa6ed8_1@news.iprimus.com.au> <3cfa7619_1@news.iprimus.com.au> Message-ID: <3cfa8ef5_1@news.iprimus.com.au> Charl P. Botha wrote: > In article <3cfa7619_1 at news.iprimus.com.au>, Gold Fish wrote: >> Charl P. Botha wrote: >> >>> In article <3cfa6ed8_1 at news.iprimus.com.au>, Gold Fish wrote: >>>> Assume we got 2 list >>>> list 1 = ['ABC','CDG','DAV','FE','FECA','FEAFA','FEA'] >>>> list 2 = [] >>>> how can we copy element from list 1 to list 2 say i just want to copy >>>> the 3 element 'CDG','DAV','FE' to list2 only. >>> >>> list1 = ['ABC','CDG','DAV','FE','FECA','FEAFA','FEA'] >>> list2 = list1[1:4] >>> >>> Is that what you meant? >>> >> No i mean if i got from list1 i wanna take 3 elements in any position to >> list2 but i don't know how many item in that list. > > Could you rephrase that? The example I posted does exactly what your > example showed. Maybe if you gave another example and tried to explain > more clearly, I'd know what you were trying to do. > What i am trying to do is that i got one biglist don't know how big is it say list1 then i like to divided into some small sublists. These sublists will have some elements in the biglist for example 3 elements maximum in each sublist. So if the biglist got 10 elements then it'll be divided into 4 sublists the first 3 will have 3 elements and the last one will have one elements. From jepler at unpythonic.net Tue Jun 4 09:57:52 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 4 Jun 2002 08:57:52 -0500 Subject: Looking for a list subclassing example... In-Reply-To: References: <3cfc994e$0$3851$e4fe514c@dreader4.news.xs4all.nl> Message-ID: <20020604085747.A22766@unpythonic.net> On Tue, Jun 04, 2002 at 01:01:14PM +0200, Shagshag13 wrote: > Is is possible to write a method in an object subclassing from list and which "frees" it ? You could 'del self[:]' (slice deletion) to remove all the entries from self. Jeff From derek at wedgetail.com Fri Jun 21 07:41:22 2002 From: derek at wedgetail.com (Derek Thomson) Date: Fri, 21 Jun 2002 11:41:22 GMT Subject: I'd give up Perl tomorrow if only... References: Message-ID: <3D1310E0.9070803@wedgetail.com> Gerhard H?ring wrote: > >>[...] What we *really* need to do is dynamically create CORBA >>interfaces for Perl modules, but that might be impossible given that >>Perl is like Python in that module and class interfaces aren't >>pre-declared :( > > > Why is that a problem? Why not just override __getattr__ or its > Perl-equivalent and switch to SOAP/XML-RPC instead of CORBA? I'm not sure what you mean. The calls are coming from the client, remember. On the server (Perl side), you have to unmarshall the request, decide which object the request is for, unmarshall the method name and the arguments, then make the right method call on the correct object. I can't see AUTOLOAD (Perl's _getattr_ equivalent) entering into this process anywhere. Besides, how do I deal with distributed object references, or map an object reference on the client to an object on the server in SOAP or XML-RPC? Lots of Perl modules create objects as you use them, as you would expect. Then there's the question of making invocations back to the client to support the push model common in serious distributed computing. You need the infrastructure CORBA provides to do real distributed objects, as far as I can see. SOAP and XML-RPC alone are good only for fairly simple RPC, as they only specify a marshalling scheme. To demonstrate this, I've used XML-RPC as a pluggable marshalling scheme for Fnorb. So, you're using the CORBA infrastructure (object adaptors, object references, connection management and so on), but you're communicating with XML on-the-wire. Best of both worlds? Check it out on the Fnorb CVS repository. It's on the branch tagged xmlrpc. I may merge it into the trunk if enough people are keen. It's pretty nice, you can have some objects talking XMLRPC, and some CORBA-IIOP, and some talking both, without changing any implementation code at all. > You're > restricted to simple data types, then, but that would probably be the > same for CORBA, right? I can't recall how complex SOAP structures can be, but in CORBA-IIOP and XML-RPC you can represent arbitrarily complex structures, just as long as they're not self-referential i.e. only trees not graphs. Regards, Derek. From whisper at oz.net Thu Jun 27 17:07:39 2002 From: whisper at oz.net (David LeBlanc) Date: Thu, 27 Jun 2002 14:07:39 -0700 Subject: Pythoniac: Thoughts on a hardware Python processor In-Reply-To: Message-ID: > -----Original Message----- > From: Gustavo Cordova [mailto:gcordova at hebmex.com] > Sent: Thursday, June 27, 2002 12:54 > To: David LeBlanc > Cc: Python List > Subject: RE: Pythoniac: Thoughts on a hardware Python processor > > > > > > Ahh! Haven't you heard? Forth came in Fifth and the Forth > > chip is dead. In fact I don't think anyone is still offering > > a stack based computer (only HP did AFAIK, the HP 3000). > > > > Dave LeBlanc > > Seattle, WA USA > > > > Which is truly a shame; it's more because of commercial > and market pressures, and nothing to do with true > throughput or technical merit. Actually, it's hard to make zero address machines effeciently in hardware (on chip). At least a (substantial) part of the problem is having to keep pushing and popping parts of the hardware stack into memory. That might be less of a problem these days given VVLSI, but back then 4k of 16 bit stack would have been a big deal - and yet not enough for multi-tasking. Would have been great for embedding though. I agree that theoretically, a stack machine is a thing of grace and beauty. To be honest though, the IBM System 34 tagged architecture is one I would have preferred to have survived. IMO, _that_ could have made Python really really go fast! Personally, i'd settle for a good 3-address CISC machine (which Intel X86 is not), but IIRC, those never went far back when there was still a good deal of experimentation in the MPU world. > Let's see if Python can be ported to Forth, like it was > to Java. If it can, *then* python'll run at hardware speed, > don't you think? I don't know about your Python, but my Python definately runs just as fast as the hardware can make it go ;-). It's going to run a whole lot faster when the AMD "Hammer" 64 bit hummer hits the bricks at a price that mere mortals can afford. Seriously though, there are some aspects of Python that don't lend themselves to efficient implementation in hardware. > Anyhow, as I said, it's a shame that Forth has been lambasted > so much that it's not really possible to find much info > and code on the net. It's actually a quite nice tool. I don't think Forth got lambasted so as to cause it to be hard to find info on - I think it, like many many other computer and natural languages, had it's day and has left the stage. Too bad Lisp hasn't followed it ;-) > :-/ > > -gus Whoever asked if the Intel/AMD FP stack counted: nah - it's not the primary mode of the CPU like it was on the HP 3000 and the Forth chip. BTW, speaking of the Forth chip, I think Forth, Inc. is still offering the IP for that if anyone wants to burn a few hunderd k$ on new silicon. While I think that creating a Python chip is a great and wonderful idea, I doubt it will or should happen: * The CPU vendors are ahead of the power curve and I don't see an Open Source group doing as well, let alone better. I figure a volunteer effort would take on the order of $1,000,000,000 in time/services to get a 1-2 GHZ chip. Intel spent about 4x that for the Itanic...err Itanium ;) and they had the capital, IP and bodies already on hand. (Coming soon: "Itanic 2 - The Resurrection!" (really, Itanium 2 is coming).) * Important IP for modern CPU performance is under patent. Plus, the guys who have the knowledge are probably paid extreme sums and kept in obscure out of the way places, not to mention being contractually obligated up the ying-yang to not disclose, compete or otherwise ply their trade for other then their designated keepers for a long term of years. * Efficient explotation of current and proposed CPU architectures is predicated upon software tools that do a good bit of (proprietary) optimization and organization during code generation before the CPU ever sees the bits. * Burning Python into silicon will tend to fossilize the language. Is Guido done enough with it for that yet? Guido and the gang can whip out a patch for the PVM in a matter of hours. How long would that take for a silicon change and what would it cost? For all these reasons and more, I think a good compiler with a retargetable backend is a better expenditure of time/effort and would yield a result far faster then a silicon development effort. Dave LeBlanc Seattle, WA USA From maxm at mxm.dk Fri Jun 14 06:48:57 2002 From: maxm at mxm.dk (Max M) Date: Fri, 14 Jun 2002 12:48:57 +0200 Subject: Using the locale module on Windows under hte IIS Message-ID: <3D09CA19.5050709@mxm.dk> I have an app that I am putting the final touches on. Including localisation, so that the users can use danish nummeric formats etc. But I am very much in doubt as to how I should use the locale module. I have found out easy enough that I need to set:: from locale import setlocale setlocale(locale.LC_ALL, 'danish') It kind of puzzles me as it seems that it is a global switch that is set for the entire programme. But I wonder exactly where to do this. It's a web app running under the IIS, and so there is no natural starting point for the programme. Should I encapsulate the functionality an a few wrapper functions? Is there some kind of global variable that I can set? Perhaps I should set it in the gloabl.asa ? Anybody's got a clue? regards Max M From PoulsenL at capecon.com Thu Jun 27 13:21:34 2002 From: PoulsenL at capecon.com (PoulsenL at capecon.com) Date: Thu, 27 Jun 2002 13:21:34 -0400 Subject: Most elegant python program to date. Message-ID: <72F73B808A78D511A73600034771D9FF717DCF@dc_exchange2.howrey.com> Just curious. I find it much easier to learn a language by reading lucid examples of its prose. Are there any nominations for the most elegant example of a python program to date. Not sure under what criteria, I leave that up to you. I will say that I use python for matrix manipulation more than anything, but that shouldn't prevent you from nominating your favorite regardless of purpose. Loren From mwh at python.net Thu Jun 13 08:36:22 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 13 Jun 2002 12:36:22 GMT Subject: Extension objects in Python 1.5 and 2.2 References: <20020613071813.GA16764@strakt.com> <15624.19045.700125.215173@12-248-41-177.client.attbi.com> Message-ID: Martin Sj?gren writes: > On Thu, Jun 13, 2002 at 09:20:53AM +0000, Michael Hudson wrote: [Misc/pymemcompat.h] > > Pleasure! Be sure to complain if it doesn't work, won't you? > > So far it's looking good. I still had to ifdef on the Python version > since I'd used PyModule_AddObject, but that was easily fixed. Right. This header is only about the memory interface. I guess it wouldn't be *that* hard to add many of the new API functions to a compat library, but that project would have much wider scope... Actually, the real benefit of pymemcompat.h as I see it are the comments it contains laying down the law about which interfaces to use. Cheers, M. -- > Touche! But this confirms you are composed of logic gates. Crud, I thought those were neurons in there. -- Thomas F. Burdick, Kenny Tilton, comp.lang.lisp From uwe at rocksport.de Mon Jun 3 09:59:52 2002 From: uwe at rocksport.de (Uwe Schmitt) Date: 3 Jun 2002 13:59:52 GMT Subject: different gui-toolkits pros/cons... Message-ID: Hi, I'm looking for an appropriate toolkit for GUI programming, which do you use ? what are pros and cons ??? I'm specially interested in wxPython, pyQt and pyGTK... and I'm intersted in a windows-like look and feel on win platforms... Finally I'm intersted in execution speed. So, I await your answers, greetings, Uwe -- Dr. rer. nat. Uwe Schmitt ICQ# 159647634 Uwe.Schmitt at num.uni-sb.de From gaya at infomail.lacaixa.es Sun Jun 2 17:04:44 2002 From: gaya at infomail.lacaixa.es (Toni Gaya) Date: 2 Jun 2002 14:04:44 -0700 Subject: windows install put short path names to win register Message-ID: <61f6bfa8.0206021304.2abedc3c@posting.google.com> Windows python 2.2.1 installation program puts short file names to some path values in windows register. This makes that programs that read python path or some other information as python path from windows register crash -i'm using NTFS (maybe with FAT32, due that FAT system works with short file names and long file names, works, but as NTFS only works with long file names, some other installation programs just crash)-. Examples: try to install mysqldb (mysql connection) or py2exe on windows with a NTFS disk, and these programs crash. I'm wrong? From emile at fenx.com Tue Jun 18 10:03:52 2002 From: emile at fenx.com (Emile van Sebille) Date: Tue, 18 Jun 2002 14:03:52 GMT Subject: why len(list) instead of list.len() ? References: Message-ID: "Markus Jais" wrote in message news:EhBP8.1$Qn1.1124 at news.ecrc.de... > hello > > I way wondering why one has to write > > list = [2, 3, 5] > print len(list) > > instead of list.len() > > in Ruby I can write > > array = [2, 3, 4] > puts array.length() > > Because a two-line wrapper goes a long way? Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> class myList(list): ... len = list.__len__ ... >>> l = myList([1,2,3,4]) >>> l [1, 2, 3, 4] >>> l.len() 4 >>> l.extend([5,6,7]) >>> l.len() 7 -- Emile van Sebille emile at fenx.com --------- From pyth at devel.trillke.net Mon Jun 17 19:10:32 2002 From: pyth at devel.trillke.net (holger krekel) Date: Tue, 18 Jun 2002 01:10:32 +0200 Subject: inherrited private class varriables In-Reply-To: ; from merkosh@hadiko.de on Tue, Jun 18, 2002 at 12:51:36AM +0200 References: Message-ID: <20020618011032.W15079@prim.han.de> Uwe Mayer wrote: > hi, > > why can't i access a class private varriable from within a predecessor? > f.e. > > class parent: > __length = 5 > def __init__(self): pass > def action(self): > print self.__class__.__length > > class child(parent): > __length = 10 > def __init__(self): pass > > test = child() > test.action() > > will print 5, instead of 10. why? short answer: private names are obtained by textual replacement. child.__length and parent.__length may look similar but the interpreter really sees [*] child._child__length and parent._parent__length and refuses to override. Think 'macro-preprocessor'. long answer from http://www.python.org/doc/1.5/tut/node67.html : Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is now textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard of the syntactic position of the identifier, so it can be used to define class-private instance and class variables, methods, as well as globals, and even to store instance variables private to this class on instances of other classes. regards, holger [*] if you want a proof 'import dis ; dis.dis(parent.action)' From loewis at informatik.hu-berlin.de Fri Jun 14 06:05:27 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 14 Jun 2002 12:05:27 +0200 Subject: Exheritance and Python References: Message-ID: Jonne Itkonen writes: > For new type classes, those that inherit object, this doesn't work, > as __bases__ is read-only. Why? There is a technical problem: If changing the bases would change the layout of instances (due to additional inherited slots, say), then adding new bases is not implementable. > So, is there a way to change the __bases__-attribute of a new type > class? Am I to write a PEP? In this specific case, I'd say a PEP won't help that much - write a patch instead. Regards, Martin From gmcm at hypernet.com Fri Jun 7 09:10:21 2002 From: gmcm at hypernet.com (Gordon McMillan) Date: 07 Jun 2002 13:10:21 GMT Subject: Gordon McMillan's Installer - Data files in the archive References: Message-ID: [posted and mailed] Paul Moore wrote: [snip] > That worked remarkably easily. A trivial example: > > from carchive import CArchive > me = CArchive(sys.executable) > readme_file = me.extract('README')[1] > > One thought occurs - how "supported" is the CArchive class interface? I expect advanced users to do things like this. I also expect them to manipulate TOCs and put extra processing in their spec files. Installer's only a black box if you don't open it :-). -- Gordon http://www.mcmillan-inc.com/ From stephen.boulet at motorola.com Fri Jun 7 19:02:27 2002 From: stephen.boulet at motorola.com (Stephen Boulet) Date: Fri, 07 Jun 2002 18:02:27 -0500 Subject: Confidence intervals and other stats Message-ID: <3D013B83.2E6F0E91@motorola.com> Are there any python modules out there for computing confidence intervals on data? Thanks. -- Stephen From rjones at ekit-inc.com Sun Jun 23 20:00:40 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Mon, 24 Jun 2002 10:00:40 +1000 Subject: PIL, Python and CGI In-Reply-To: <3D165BB7.B901F064@infineon.net> References: <3D1626FD.DA934B09@infineon.net> <1HrR8.44835$n4.10519234@newsc.telia.net> <3D165BB7.B901F064@infineon.net> Message-ID: <200206241000.40596.rjones@ekit-inc.com> On Mon, 24 Jun 2002 09:37, Sascha Ferley wrote: > strange reason it can't find the _imaging extention.. > It is sort of strange that it wouldn't pick it up then.. any more ideas? I'd say there's a chance that the _imaging module has linked to a shared library and the web server doesn't have the appropriate lib dir in its LD_LIBRARY_PATH. That'd cause an ImportError. Unfortunately, PIL is swallowing the exact error - try removing the try/except around the "import _imaging" and see what the real error is. Richard From emile at fenx.com Sat Jun 29 16:03:32 2002 From: emile at fenx.com (Emile van Sebille) Date: Sat, 29 Jun 2002 20:03:32 GMT Subject: ImportError: cannot import name mm_cfg References: Message-ID: "Pedro Bados" wrote in message news:mailman.1025375559.4917.python-list at python.org... > > Hi : > > I am not a python user so I have no idea at all of how I can resolve this > problem with mailman. Currently, I get this error each minute ... > > File "/home/mailman/cron/qrunner", line 90, in ? > from Mailman.Bouncers import BouncerAPI > File "/home/mailman/Mailman/Bouncers/BouncerAPI.py", line 32, in ? > from Mailman import mm_cfg > ImportError: cannot import name mm_cfg > Are you a Mailman user? Or is it there as the result of an RH7x install? You can turn off qrunner if you don't use Mailman. If you use mailman, did it ever work? or are you trying to get it going? Did it just start breaking? Did you change something? Which version of python are you using? Is there more than one installed? The reason you got no responses the first time through is that there are more questions open in your post than any of us can assume to know the answers to, rendering any response non-responsive. (as this is ;-) Provide details. Your error means the python path can't find mm_cfg.(py|pyc). Is there one one your system? Where is it? Is it reachable from python? Are the permissions OK? How about the owner:group settings? Etc, etc, etc... -- Emile van Sebille emile at fenx.com --------- From jimrowe at optilink.com Thu Jun 13 13:57:47 2002 From: jimrowe at optilink.com (James Rowe) Date: 13 Jun 2002 12:57:47 -0500 Subject: __subclasses__ Message-ID: A search for __subclasses__ on the www.python.org documentation search pages turns up empty. I can find not mention of it in my Python books or even in the "What's new in Python 2.2" document. But: class Foo(object): def __init__(self): object.__init__(self) class Bar(Foo): pass dir(Foo) # returns: ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__repr__', '__setattr__', '__str__', '__weakref__'] But there is a __subclasses__ method: Foo.__subclasses__() # returns: [] So I suppose the question is: Why is __subclasses__ not documented or listed? Can we safely use __subclasses__ and not worry about it "going away" in the future? From gleki at gol.ge Fri Jun 28 04:38:18 2002 From: gleki at gol.ge (Giorgi Lekishvili) Date: Fri, 28 Jun 2002 10:38:18 +0200 Subject: squared functions--most Pythonic way? References: Message-ID: <3D1C207A.74F24164@gol.ge> One of the biggest advantages of Python is its nice and elegand mixture of procedural, OO and functional programming... I would prefer lambda stile as the most concise, but it is a matter of personal "phylosophy";) Grtz, Giorgi Sean 'Shaleh' Perry wrote: > > > > functional programming: > > > > # with an internal named function > > def fsquare(f): > > def f2(x): > > return f(x)**2 > > return f2 > > > > this seems to be the most pythonic (lambda is not the preferred approach > usually). > > Of course someone will mention taking this to the next step with a compose() > function which take f(x) and g(x). From usenet at thinkspot.net Sat Jun 1 16:42:43 2002 From: usenet at thinkspot.net (Sheila King) Date: Sat, 01 Jun 2002 13:42:43 -0700 Subject: How to open a HTML file when the python cgi program is executing? References: <9m6ada.31b.ln@10.0.0.1> <83n0uevjvx.fsf@panacea.canonical.org> Message-ID: On 01 Jun 2002 16:12:02 -0400, Kragen Sitaker wrote in comp.lang.python in article <83n0uevjvx.fsf at panacea.canonical.org>: > Sheila King writes: > > print "Location: http://replacement-url\n" > > > > You should have nothing before this, and there's no point in having > > anything after it, since the page is being redirected. > > Some browsers (in particular old versions of Opera) have problems with > redirects every once in a while; that's why redirects traditionally > contain HTML, in case the browser is broken. Printing the Location header is not a "redirect" and should contain no HTML. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From arosado at softhome.net Tue Jun 4 19:59:57 2002 From: arosado at softhome.net (Andres Rosado) Date: Tue, 04 Jun 2002 19:59:57 -0400 Subject: HTML links in a GUI tkinter Message-ID: <5.1.0.14.0.20020604195947.00be66b0@mail.softhome.net> At 03:21 PM 6/3/2002 +0000, you wrote: >Message: 10 > Date: Mon, 3 Jun 2002 15:23:47 +0000 > From: Eric Brunel >Subject: Re: HTML links in a GUI tkinter > >Steve Holden wrote: > > So, all Aurel needs to know now is how to run wxPython widgets inside > > tkinter programs... > >Why? Tkinter has everything to do it: > >---------------------------------- >from Tkinter import * > >root = Tk() >t = Text(root) >t.pack() > >def openHLink(event): > start, end = t.tag_prevrange("hlink", > t.index("@%s,%s" % (event.x, event.y))) > print "Going to %s..." % t.get(start, end) > >t.tag_configure("hlink", foreground='blue', underline=1) >t.tag_bind("hlink", "", openHLink) >t.insert(END, "This is a link\n") >t.insert(END, "http://www.python.org", "hlink") >t.insert(END, "\nAnd text goes on...\n") >root.mainloop() >---------------------------------- > >Control-click on the link and you should see the message "Going to text>", which may be replaced by a webbrowser.open to actually open the >URL. To insert a new link, just do: >t.insert(, , "hlink") By far a more simpler solution. Thanks! >HTH ----------------------------------- Andres Rosado Email: andresr at despammed.com ICQ: 66750646 Homepage: http://andres980.tripod.com/ You should emulate your heros, but don't carry it too far. Especially if they are dead. From fredrik at pythonware.com Thu Jun 6 04:26:10 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 06 Jun 2002 08:26:10 GMT Subject: 64-bit Python? References: <87elfl3yvu.fsf@mathdogs.com> Message-ID: Mike Coleman wrote: > Has anyone looked at making Python 64-bit clean? It is 64-bit clean, and has been so for many years. > I was looking at trying to use the new mmap module to map in a large (>2G) > file, and the comments in the source note that the mmap regions are limited to > int-size (31 bits), primarily because Python objects are also limited to this > size. Python *integer* objects are limited to that size on platforms where a C long is 32 bits. Python runs perfectly fine on tru64, itanium, and other 64-bit platforms. On most of them, Python ints hold 64-bit values. From nessus at mit.edu Mon Jun 3 21:13:13 2002 From: nessus at mit.edu (Douglas Alan) Date: 03 Jun 2002 21:13:13 -0400 Subject: manipulating child processes under Windows Message-ID: Hi. I know lots about Python and lots about Unix, but unfortunately I've been given the task of developing some software for Windows 2000, and I'm having a problem. The problem I'm having is this: I want the Python script to run an executable and then wait for the executable to terminate before continuing. Now, actually, I have no problem doing precisely this under Windows 2000 -- I know how to use wp.CreateProcess() to start up a program under Python and wait for the program to terminate. The problem I am having is that the program itself is apparently just a stub that spawns off the real program and then terminates, while the real program then continues to run. So my Python script ends up continuing right away (because the stub process terminates right way), rather than waiting for the real program to terminate. So, I have two questions: (1) Is this thing where a stub process fires off the real process a typical thing to do under Windows? If so, it seems to make synchronizing processes difficult. (2) What's the best way for me to solve the problem. I.e., what's the best way to get my Python script to wait for the real program to terminate? |>oug From jimrowe at optilink.com Thu Jun 13 18:40:52 2002 From: jimrowe at optilink.com (James Rowe) Date: 13 Jun 2002 17:40:52 -0500 Subject: newbie: from .. import * References: <56e1eff0.0206131437.4ca8ed9e@posting.google.com> Message-ID: On 13 Jun 2002 15:37:38 -0700, Jean-S?bastien Bolduc wrote: >Hi All > >I've been working with Python for a while, but never really felt >confortable with the way namespaces are imported. > >I'm working on a simple application that is to be used in the >interactive mode. The idea is that the behavior of a function is >determined, in part, by some global(?) flags. So I can change my >flags, and explicitely call my function. Really simple. Except that >for some reason, it does not work. > >In "test.py", I have the following: > > flag = 1 > def foo(): > print flag > foo() > flag = 0 > foo() > >In the interactive mode, if I import the code above as: >>>> from test import * >1 >0 > >The output is as expected. However, if I continue: >>>> flag = 1 >>>> foo() >0 > # bar.py flag = 1 def foo(): print flag foo() flag = 2 foo() >>> from bar import * 1 2 >>> import bar >>> foo() 2 >>> flag = 3 >>> foo() 2 >>> bar.flag = 4 >>> foo() 4 From aahz at pythoncraft.com Wed Jun 12 19:12:59 2002 From: aahz at pythoncraft.com (Aahz) Date: 12 Jun 2002 19:12:59 -0400 Subject: Wanted: Potential Python Authors References: <3d07d4a8@news.eol.ca> Message-ID: In article <3d07d4a8 at news.eol.ca>, William Park wrote: > >There is no such thing as "trained as writer", whether it's for computer >books or fiction/nonfiction novels. You either can write or you can't. That's not true. Writing is a skill -- just like programming -- that can be learned and/or taught. Of course, just like programming, innate talent counts for something, but there are few people on this newsgroup who are incapable of writing a book. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I had lots of reasonable theories about children myself, until I had some." --Michael Rios From twister at raplounge.de Tue Jun 11 15:19:07 2002 From: twister at raplounge.de (Ben Thursfield) Date: Tue, 11 Jun 2002 21:19:07 +0200 Subject: Newbie question communicating between 2 progs References: <3D046BF0.DC36542C@raplounge.de> <3D04A938.627EE705@engcorp.com> Message-ID: <3D064D2B.43D73510@raplounge.de> JS schrieb: > Don't fully understand the question, but could you write the list to a > temporary file. It could then be read as needed?? I was thinking about this, but i thought it would be bad to because i would have to set the attributes of a folder to write, which I thought would be probably be a security hole... Thanks for your answer! Ben From bh at intevation.de Fri Jun 21 08:53:27 2002 From: bh at intevation.de (Bernhard Herzog) Date: 21 Jun 2002 14:53:27 +0200 Subject: Advice sought on ps module References: <6e990e29.0206200325.355f0413@posting.google.com> <6e990e29.0206202356.544eb696@posting.google.com> Message-ID: <6qn0tohjy0.fsf@abnoba.intevation.de> eddie at holyrood.ed.ac.uk (Eddie Corns) writes: > P.P.S. Actually it occurs to me there is another solution, namely > creating the diagram with something else (eg a canvas) and generating > (presumably bitmapped) PS from that. Though I'm sure you've already > rejected that idea as being unworthy! I'd also say, that for good results with more complex layouts you'd need a more object oriented approach than going straight to postscript. Personally, I'd do this sort of thing with Sketch, of course, where you could hook your code into in the GUI or simply use Sketch as a highlevel vector graphics library for a command line program. IIRC, reportlab nowadays also has an object oriented graphics/layout library on top of the pdf generator. ISTR it even can generate EPS directly. Bernhard -- Intevation GmbH http://intevation.de/ Sketch http://sketch.sourceforge.net/ MapIt! http://www.mapit.de/ From brian at sweetapp.com Sat Jun 29 04:42:29 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Sat, 29 Jun 2002 01:42:29 -0700 Subject: Python needs better error reporting In-Reply-To: Message-ID: <01c501c21f48$e7ce0460$bd5d4540@Dell2> David LeBlanc wrote: > Cute anthropomorphism is lots of fun, but doesn't _quite_ obscure the fact > that computers don't really "tell" anybody anything, programmers do. IIRC, > Python throws this "Syntax Error: invalid syntax" in a number of places. > In the place that I used as an example, looking at the language reference, > an appropriate error would be more like: > Syntax Error: expected "and", "or", "xor" or ":" There are a lot more tokens than that allowed. What about "+", "*", "\", etc? > This would at least narrow down what should be looked at to resolve the > problem. > Vague error reporting doesn't help new user's self confidance or > acceptance of the language. > > I really DO have a point! Probably. Figure out how to add more meaningful syntax errors and submit a patch. Good luck! Cheers, Brian From cliechti at gmx.net Sun Jun 30 19:47:35 2002 From: cliechti at gmx.net (Chris Liechti) Date: 1 Jul 2002 01:47:35 +0200 Subject: I'd give up Perl tomorrow if only... References: Message-ID: Frank Tobin wrote in news:Pine.LNX.4.44.0206301756130.22298-100000 at palanthas.neverending.org: > Chris Liechti, on 2002-06-30, wrote: > >> well it has. the module unittest provides all thats needed. the >> module just needs a class derrived from unittest.TestSuite and the >> unittest module can find the tests. > > No it doesn't, for two reasons. > > 1) unittest is merely a testing framework, and there is no standard > for using it from an extracted archive. > > 2) unittests are only one way to test; it is generally best suited for > small-unit testing. I personally use it in conjunction with > whole-program blackbox tests. > > Perl also has some fairly standard testing suites, but there is a wide > variety you can choose from. However, the *interface* from an > extracted Perl module is *always* "make test". yes, so all we need is a convention (for the interface) and a small addition to distutils to run the tests, right? point 2) is irrelevant when there is a standarized interface to invoke the tests and return the results. >> its also a convention to have a test() function, but the former is >> more powerful. yes, it should be used more widely. >> >> > 3) a standard installation mechanism (Perl and Python do have) >> > 4) a standard README system (Perl has, Python doesn't) >> >> i don't know the perl way but with python every object has a __doc__ >> attribute, every module, class, function and method etc. and with >> pydoc there is a standard extraction tool right in the standard >> distro. ever tried it? > > I'm very familiar with docstrings. Perl also has its POD. But each > of these is API information. README's are a different sort. > dostrings do not substitute for what a README is for: > > 1) description of the module > 2) describes dependencies > 3) other information that is not API-oriented absolutely nothing speaks againts a readme (altough i would call it README.txt, windows frendly, ya know ;-)... you can add it to an archive made by distutils etc. and most people have one when they distribute a module. i think the only diffrence is that you want to declare it as a _must_. a description is already in the pgk-info file if you build with distutils. i think the dependencies belog in there too as this is a file for the machine and the readme should be a file for the user (freely formated, no need to automaticaly extract vital pakage information from there). >> as metioned above, python has all it needs, now if you talk of an >> organization that runs test on non-standard extension modules, no we >> don't have that right now. the python distro has good tests for the >> standard lib, but as there is no organization that distributes >> extensions, everyone is responsible for testing its modules. (there >> are collections of modules, like The Vaults of Parnassus: >> http://www.vex.net/parnassus/ or ActiveStates Programmer's Package >> Manager (PPM) but thats not as strong or established as CPAN) > > Yes, I'm talking about non-bundled extension modules. That's all > we're talking about here. The standard lib is irrevelant to the > discussion. > > I suggest that you be a Perl programmer for a while, and see what > having CPAN accessible and authoring for it really is like. You > explicitly state you aren't familiar with it. I've been author of a > couple CPAN modules for about 4 years now, and an extensive user for > just as long, and have been a Python module writer for just over a > year now. Python is a great language, but in terms of a reusable code > repository, *nothing* comes close to the jewel that is CPAN. There is > a reason you'll hear this over and over from people coming to Python > from Perl. belive me, i would also like something like CPAN. i have a module out in the wild too. and while i understand that it is nothing for the standard distro i see that a couple of people use it (at least a bunch of people download it each day :-) and a standard way to get it would be cool. i think that an packaging system with dependecy- and downloadmanager, testing and more would be of great value. there are some beginnings of such a system by different people, but nothing lifted off until now. i think, if a group of programers donated enough of their spare time and found a machine to run it on, a prototype could be set up fairly quick (as python has all (99%) it needs to build such a system. i guess required are some conventions for packages and a bit of code). but that needs two things 1) someone who does the work on it 2) the community must use it (test it, make it usable, fill it with modules). maybe, later when we have such a system, everybody will ask how we could have lived without it for such a long time... ;-) > The Vaults and PPM just don't hold a candle to CPAN. For all > practical purposes, they are just big FTP repositories. yes i know and agree, i didn't wanted to express something different. my point was that there are organizations that build collections of modules, even if they don't provide testing, dependecy management etc. (not sure about PPM's capabilities, though). i mean that i must have mentioned them in the context and the way i wrote above. chris -- Chris From tim at remove_if_not_spam.digitig.cix.co.uk Fri Jun 28 08:13:56 2002 From: tim at remove_if_not_spam.digitig.cix.co.uk (Tim Rowe) Date: Fri, 28 Jun 2002 12:13:56 GMT Subject: Problems configuring 4suite Message-ID: <3d1c4f89.1205192@usenet.plus.net> (I thought I'd already posted something on this, but it's not appeared. Sorry if this is a duplicate). I'm having trouble getting 4Suite installed on an MS Windows / Python 2.2 setup. So much so that I've even gone to the extent of removing all traces of Python from my machine, then reinstalling just Python and 4Suite. Having done that, the 4Suite howto says to check it by typing from xml.xslt import Processor from a Python prompt. Unfortunately I just get a "no module named xslt" error. Python seems to be looking at the standard Lib\xml package, and isn't finding 4Suite's Lib\site-packages\Ft\Xml directory (from Xml.Xslt doesn't work either, BTW). Could anybody help me with the correct way to tell Python to look for the 4Suite stuff? Pretty please? From ken at hotmail.com Sat Jun 1 04:16:28 2002 From: ken at hotmail.com (Ken) Date: Sat, 1 Jun 2002 18:16:28 +1000 Subject: How to open a HTML file when the python cgi program is executing? References: Message-ID: "Daniel Yoo" wrote in message news:ad9uv4$g2n$2 at agate.berkeley.edu... > Ken wrote: > : How do I open a HTML file when the cgi program is executing? > > : The only method I can think of, which doesn't work is this: > : > > Not quite sure I understand yet. > > > Do you have a file called 'main.html' that you're trying to display > from your CGI program? I just want to make sure we're work on the > same problem here before babbling. *grin* > > > Talk to you later! Yes, I want to display the content of another html file (main.html in this example) onto the browser. How do I do that? And also, how do I set target to which frame to display? Thanks From chris.gonnerman at newcenturycomputers.net Sun Jun 2 01:23:51 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Sun, 2 Jun 2002 00:23:51 -0500 Subject: writing to a file (atomic operation) References: <20020602050909.GA7192@mercury.senux.com> Message-ID: <002801c209f5$b2da8ca0$0101010a@local> ----- Original Message ----- From: "Brian Lee" > Is this a atomic operation? > > open('/tmp/test.log', 'a').write('test\n') > > from py newbie. No. Why exactly do you need it to be? "Atomic" means that it can't be interrupted by another process before completion; not many operations are truly atomic in modern OS design. Very little of what you do in Python will be truly atomic. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From kragen at pobox.com Sun Jun 2 21:29:43 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 02 Jun 2002 21:29:43 -0400 Subject: variable X procuct - [(x,y) for x in list1 for y in list2] References: <1022619068.34271@newsmaster-04.atnet.at> <1022686332.297659@newsmaster-04.atnet.at> <20020531215914.15202822.larooy@xtar.co.nz> Message-ID: <834rgltaig.fsf@panacea.canonical.org> John La Rooy writes: > Perhaps the translation is correct, but the example you give is a > cartesian product, not a cross product. From my algebra book... Cartesian products are often called cross products. From sholden at holdenweb.com Tue Jun 18 16:50:13 2002 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 18 Jun 2002 16:50:13 -0400 Subject: python cgi + IIS References: <3D0F1813.3010304@gmx.de> Message-ID: "Axel Grune" wrote in message news:3D0F1813.3010304 at gmx.de... > Hi, I'm trying to get my IIS (Win2k Pro) execute my python scripts. > I added the 'App Mapping' info for '.pycgi' files in the properties of > IISAdmin (Computermanagement) as I read in the internet. The string > for the executable file is 'D:\Python22\python.exe -u %s %s' (the path > is valid). > But when i try to call it within my browser, it just displays it like a > normal text file instead of executing it. > > > the script (its called test.pycgi): > #!/usr/bin/python > > print "Content-Type: text/plain\n\n" > print "Hallo Welt" > > > has anyone an idea? > You have almost certainly made a typo, or you didn't apply the changes to the directory you are trying to run the CGI from. I just followed the steps at http://www.e-coli.net/pyiis.html to install .cgipy as a Python-executing extension, and everything worked -- the following program printed out a complete list of environment variables. # # Python CGI script # import os print """Content-Type: text/html Python Web Page """ for k, v in os.environ.items(): print "%s=%s
\n" % (k, v) print """ """ Personally I'd rather run CGI than use ASP under IIS, so I hope you can get it to work. Clearly at the moment IIS isn't recognising the .cgi extension as needing to run the Python interpreter. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From zopestoller at thomas-guettler.de Wed Jun 26 04:03:08 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Wed, 26 Jun 2002 10:03:08 +0200 Subject: Parsing strings (\n and \\) References: Message-ID: <3D19753C.9070104@thomas-guettler.de> Mark McEahern wrote: >>Is there a function for parsing c-like >>strings? I need to parse strings containing >>'\n' and '\\' '\"'. >> > > I suppose it's obvious to anyone from a C background, but I find myself > wondering, "What do you mean by parse?" > > I might be able to help if you provide a little more detail. Look at the two functoins quote and unquote. I wrote them without regular expression because I think it faster. def quote(string): ''' foo\bar --> foo\\bar foo"bar --> foo\"bar ''' new_string=[] for char in string: if char=='\\': new_string.append('\\\\') elif char=='"': new_string.append('\\"') else: new_string.append(char) return ''.join(new_string) def unquote(string): ''' foo\\bar --> foo\bar foo\"bar --> foo"bar ''' new_string=[] i=0 len_str=len(string) while 1: if i==len_str: break char=string[i] if char=='\\': i=i+1 if i==len_str: raise 'Parse Error: Backslash at end of string' char=string[i] if char=='\\': new_string.append('\\') elif char=='"': new_string.append('"') else: raise 'Parse Error: Unsupported character after backslash' else: new_string.append(char) i=i+1 return ''.join(new_string) def test_quote(): strings=['foo', '', '\\', ' ', '"', '\\"', '\\\\'] for s in strings: if unquote(quote(s))!=s: print "Error: s: %s quoted: %s unquoted: %s" % (s, quote(s), unquote(quote(s))) From HH at attbi.com Thu Jun 27 17:48:58 2002 From: HH at attbi.com (HH at attbi.com) Date: Thu, 27 Jun 2002 21:48:58 GMT Subject: Distutils RPM Requires tag Message-ID: Is there any way to get distutils to insert a proper Requires: tag in a bdist_rpm generated RPM for packages which Require more than one package? For example, I'd like a Requires tag that looks like: Requries: foo >= .96, bar >= 1.0.2 but when I try python setup.py bdist_rpm --requires 'foo >= .96, bar >= 1.0.2' the generated Requires tag turns the comma into a space, and RPM subsequently makes a package which Requires only foo. There does not seem to be any way around this. Is this a bug, or is there a solution I have overlooked? Thanks for your help. -- HH From a at a.com Mon Jun 17 08:13:59 2002 From: a at a.com (Adam) Date: Mon, 17 Jun 2002 13:13:59 +0100 Subject: urllib2 getting a webapage authenticating proxy... Message-ID: <3D0DD287.7B221A42@a.com> this code doesnt work for me... i have replaced the proxy details for security... can anyone help... as i havent been able find any helpfull websites/examples for urllib2... is urllib2 what i realy want to use for this... import urllib2 def get_page(url): proxy = urllib2.ProxyHandler({'http':'http://userid:pass at proxy.com:port/'}) opener = urllib2.build_opener(proxy) site = urllib2.urlopen(url).read() print(site) get_page('http://www.python.org/') From aldo at nullcube.com Fri Jun 28 06:04:22 2002 From: aldo at nullcube.com (Aldo Cortesi) Date: Fri, 28 Jun 2002 20:04:22 +1000 Subject: metaclasses vs. inheritance In-Reply-To: References: Message-ID: <20020628100422.GA18469@nullcube.com> Thus spake Ian McMeans (imcmeans at home.com): > Can someone give an example of a problem that is solved > with metaclasses, which would be difficult or impossible > to solve with inheritance? There are some things that can only be done with metaclasses - changing the text representation of a class, for instance. class Extended(type): def __repr__(self): attrs = [] for i in dir(self): attrs.append("%-20s\t\t%s" % (i, type(self.__getattribute__(self, i)))) return "%s:\n\t%s" % (type.__repr__(self), "\n\t".join(attrs)) class Foo(object): __metaclass__ = Extended pass print Foo Baroque, I know, but it illustrates the point. > PS - what's the antonym of meta? Hmmm... the meta- in "metaclass" or "metaphysics" really has no relation to the original Greek, which means "with", or "among" (as in "metatarsus" - the bones in the foot which lie next to the tarsus). So whatever antonym you come up with can't have anything to do with the original etymology of the prefix... Erm... How about mundane? Or actual? Intrinsic? Essential? Or even "per se"....? Cheers, Aldo -- Aldo Cortesi aldo at nullcube.com From shredwheat at attbi.com Sun Jun 2 12:44:20 2002 From: shredwheat at attbi.com (Pete Shinners) Date: Sun, 02 Jun 2002 16:44:20 GMT Subject: SolarWolf 1.1 Released Message-ID: <3CFA4B52.9020901@attbi.com> SolarWolf is a frantic arcade game written in Python, using the Pygame library. Version 1.1 adds easier gameplay and packs many new features to make the game funner. New is stereo sound, support for 8bit display, in-game "comments", and better levels. We've also moved to a website that will be online more than 2 days per month. SolarWolf is the recreation of the classic game, SolarFox (as played on my Atari 2600). You pilot a ship through 48 levels. You must collect the boxes on screen to advance, and each level provides more challenging layouts. To keep things difficult, enemies patrol the edges of the screens. They seem to really enjoy shooting, and in the later levels they become more determined. SolarWolf requires Pygame-1.5 and Python-2.0. Pygame requires the use of SDL, and the SDL support libraries SDL_ttf, SDL_image, and SDL_mixer. It runs on just about every platform available. (with osx support coming as soon as the latest pygame is compiled for osx) SolarWolf Website: http://pygame.org/shredwheat/solarwolf From thenault at nerim.net Mon Jun 17 04:27:22 2002 From: thenault at nerim.net (Sylvain =?iso-8859-1?Q?Th=E9nault?=) Date: Mon, 17 Jun 2002 10:27:22 +0200 Subject: [ANN] PyReverse 0.3 In-Reply-To: References: Message-ID: <20020617082722.GA2359@ntw23.fr> On Friday 14 June ? 14:38, David LeBlanc wrote: > On windows, "setup install" terminates with: > error: file 'logilab\pyreverse\bin\py2tests.bat' does not exist > oops ! a little a packaging problem... It will be fixed as soon as someone at logilab can commit the required fix and put a 0.3.1 on the ftp, since I have no access to do this right now. Until this moment you can put the files joined to this message in the logilab/pyreverse/bin directory and the installation process should work correctly. sorry for this annoyance -- Sylvain Th?nault -------------- next part -------------- #!/usr/bin/env python from logilab.pyreverse import py2tests import sys py2tests.Run(sys.argv[1:]) -------------- next part -------------- A non-text attachment was scrubbed... Name: py2tests.bat Type: application/x-msdos-program Size: 118 bytes Desc: not available URL: -------------- next part -------------- #!/usr/bin/env python from logilab.pyreverse import py2xmi_uml import sys py2xmi_uml.Run(sys.argv[1:]) -------------- next part -------------- A non-text attachment was scrubbed... Name: py2xmi.bat Type: application/x-msdos-program Size: 122 bytes Desc: not available URL: From marklists at mceahern.com Fri Jun 28 11:20:43 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 28 Jun 2002 10:20:43 -0500 Subject: metaclasses vs. inheritance In-Reply-To: Message-ID: > Can someone give an example of a problem that is solved with metaclasses, > which would be difficult or impossible to solve with inheritance? You can intervene in class creation to do aspect-oriented type stuff. E.g., before each method call, do this, after each method call, do that. Etc. I will post a more detailed example as the start of a separate thread shortly. // m - From bokr at oz.net Thu Jun 6 16:37:02 2002 From: bokr at oz.net (Bengt Richter) Date: 6 Jun 2002 20:37:02 GMT Subject: Using AT on XP to run python script - MARK HAMMOND PLEASE READ References: Message-ID: On Wed, 5 Jun 2002 16:48:03 -0700, "David LeBlanc" wrote: >This is most curious, but I believe the commands _are_ getting executed! > >I tried the following (assume time is 16:30) "at 16:32 pythonw >j:\python22\tools\idle\idle.py" (without the qoutes of course). At the >appointed time, there was disk activity, but no idle window popped up (idle >was chosen just to get something to pop up!). However, there _was_ a pythonw >process running in the task manager! I think there might be a way to attach >a console or get access to the GUI, but i'm not sure - maybe Mark Hammond >might have a clue (he being the Python Win guru :) ). > >I tried the following: >#at_test.py >import sys >import time > >tst = open("testfile.txt", 'a+') > >tst.write(time.asctime() + "\n") > >tst.close() > >put into an 'at' job as: at xx:xx python j:\python22\at_test.py > >I expected the output from this to be in j:\python22, but to my surprise, it >was in c:\winnt\system32 where cmd.exe resides! testfile.txt contained the >exact time the 'at' job was set to run at too! > >I suspect your last example that produced no visible output did in fact work >:) > >In any case, it works - now if one could just get visible output! > I's suggest wrapping your python invocation in a .cmd file something like: --< todoat.cmd >-- c: cd \pywk cmd/k D:\python22\python hw.py ------------------ Here hw.py is in c:\pywk --< hw.py >------- print 'Hello World from hw.py\n' ------------------ Then you can do this: ========== [13:19] C:\pywk>at 13:20 /interactive c:\pywk\propt\todoat.cmd Added a new job with job ID = 1 [13:19] C:\pywk>at Status ID Day Time Command Line ------------------------------------------------------------------------------- 1 Next 6 13:20 c:\pywk\propt\todoat.cmd [13:19] C:\pywk> ========== and have a separate console window pop up (and stay), with this in it: (Your paths may vary, of course) ========== C:\WINNT\system32>c: C:\WINNT\system32>cd \pywk C:\pywk>cmd/k D:\python22\python hw.py Hello World from hw.py C:\pywk> ========== Some things to note: The console window popped up, but the path and default directory have nothing to do with where I did the AT command. The title of the new console window is C:\WINNT\system32\MSTask.exe. and the user is the system, with all that may or may not imply ;-) >David LeBlanc >Seattle, WA USA > >> -----Original Message----- >> From: python-list-admin at python.org >> [mailto:python-list-admin at python.org]On Behalf Of Chris Stromberger >> Sent: Tuesday, June 04, 2002 17:35 >> To: python-list at python.org >> Subject: Using AT on XP to run python script >> >> >> I'm having trouble getting AT on XP to run a python script for me. >> Have tried: >> >> at xx:xx "c:\python21\python.exe c:\scripts\script.py" >> at xx:xx "start c:\scripts\script.py" >> at xx:xx "c:\scripts\script.py" >> >> and get "the system cannot find the file specified" for the first two. >> The last version does nothing apparently--no error indication or >> anything. >> >> I imagine it is related to user accounts and such. Anyone have any >> pointers? Your environment and path are not used by the AT command, so use a .cmd file that sets things up as needed and then invokes python or pythonw as needed, depending on whether you want a silent background job or interaction with whoever happens to be around ;-) (I'm not sure what happens if no one is logged in. Presumably /interactive shouldn't work?) Regards, Bengt Richter From mickey at tm.informatik.uni-frankfurt.de Sun Jun 16 06:50:15 2002 From: mickey at tm.informatik.uni-frankfurt.de (Michael 'Mickey' Lauer) Date: 16 Jun 2002 12:50:15 +0200 Subject: SWIG and Callbacks References: <3d0a8b6e@nntp.server.uni-frankfurt.de> <3d0b4fd6@nntp.server.uni-frankfurt.de> Message-ID: <3d0c6d67@nntp.server.uni-frankfurt.de> David Abrahams wrote: > With Boost.Python, what you write looks like a kind of IDL (interface > description language), which just happens to be built out of C++ source > code. Lots of jobs (function argument type checking, conversion, arity > checking) are done automatically, but the library doesn't decide which > elements to wrap. Unlike SWIG and a few others, there's no attempt to parse > your source code. Instead, the compile-time introspection capabilities of > C++ are exploited to automatically build wrappers from function and member > function pointers. I see. So it seems in order to get a nice object oriented Python interface, I can 1.) use SWIG to parse the header file and automatically produce a wrapper 1.1.) and then use this low-level wrapper to write some high-level python classes around it or 2.) use Boost.Python and do the two steps in one by writing a "handcrafted" interface? How would sip come into this picture? Is it more like SWIG for C++ or more like Boost.Python? (Apart from not beeing concerned about the total lack of documentation ;) Yours, :M: From llothar at web.de Wed Jun 12 18:27:19 2002 From: llothar at web.de (Lothar Scholz) Date: Thu, 13 Jun 2002 00:27:19 +0200 Subject: Wanted: Potential Python Authors References: Message-ID: On Wed, 12 Jun 2002 08:03:35 -0500, "Jeff Donahoo" wrote: >I'm looking for somebody to author a short book on Python in my programming >technology series. Who do you think would make a great author that hasn't >already written a book on Python? Candidates include: >- Competent and frequent posters to this newsgroup This can be an indicator. >- Author of articles in the various trade magazines You really mean "trade" magazines ? Normally they are written by marketing peoples who don't have the competence to write more then a 4 page overview. Hands off !!!! >- Expert programmer No, definitely not. Most programmers are not trained on writing tutorials or books - and normally they are really bad. Look more for someone trained as technical writer. From cpbotha at i_triple_e.org Tue Jun 11 06:19:18 2002 From: cpbotha at i_triple_e.org (Charl P. Botha) Date: Tue, 11 Jun 2002 10:19:18 +0000 (UTC) Subject: Sorting list (maybe stupid) References: Message-ID: In article , Eric Brunel wrote: > Charl P. Botha wrote: > >> In article , Jarvinen Petri >> wrote: >>> I have a problem and can't solve it: >>> >>> There is lines of text like: >>> >>> 2. Header2 >>> 1. Header1 >>> 102. Header102 >>> >>> and so on... >>> >>> And I need to sort them according to the number (1,2,3,4...) >> >> Put each line in a tuple, first element the number, second element the >> header. Make a list of these tuples, and then use list.sort() with a comp >> function that compares using the first element in the tuple. > > I think it's useless. Just try: I would NOT use the word "useless" here. You were thinking of "unnecessary", probably. Please don't go into politics, you are bound to cause wars with your choice of words. ;) > l = [(102, 'foo'), (2, 'bar'), (1, 'baz')] > l.sort() > print l > > Apparently, the default sort function already sorts tuples according to > their first element... Making an assumption based on this single example is very dangerous. However, it seems you were lucky in this case. See: http://manatee.mojam.com/~skip/python/fastpython.html (the section on Sorting). -- charl p. botha http://cpbotha.net/ http://visualisation.tudelft.nl/ From rdsteph at earthlink.net Thu Jun 27 20:00:42 2002 From: rdsteph at earthlink.net (Ron Stephens) Date: Fri, 28 Jun 2002 00:00:42 GMT Subject: Be the first on your block to register your computer. References: Message-ID: <3D1B6E69.1090204@earthlink.net> Well, Python just might not be one of the Microsoft approved programs allowed to run. In that case, you would not be able to use Python at all. Secondly, the Microsoft plan is so diabolically evil, and yet at the same time it is conceivable that it could be pushed into reality by a powerful corporate oligarchy in conjunction with a corrupt US government and an apathetic populace, that one might suppose all decent humans would find the whole thing to be a gross affront to human dignity, and thus appreciate being made aware of the whole mess by David Leblanc's timely heads-up on comp.lang.python... From opengeometry at NOSPAM.yahoo.ca Wed Jun 26 19:04:10 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 26 Jun 2002 23:04:10 GMT Subject: Integrals with Python References: <3D188551.6BA00DED@lanl.gov> <3D189307.1417ECD5@info.unicaen.fr> <3D18A010.CAF3FA9E@lanl.gov> Message-ID: Nathan Given wrote: > Matlab has quad, quadl, and quad8... > > > does Numeric have anything like those? > > > > Here is my current (lame) project... > > I am comparing the Monte Carlo method for single integrals against the > answers given by quad, quadl, and quad8 in Matlab. I coded everything > in matlab, and was able to do it just fine... the problem is that it was > SLOW... so, someone suggested that I run python, so I converted all my > code to python (except the quad, quadl, and quad8 parts), and was able > to run my code and get the monte carlo answer much faster.... > > now, i am going to be doing some double integrals, and I was just > wondering if python had some built in functions that will calculate some > double integrals (and single integrals) for me... if there are different > methods, great... I will be able to compare the monte carlo answer to > different methods of calculating the integral... Since the key routine in Monte-Carlo is evaluation of f(), your program would remain the same for 1-D and 2-D. As for different integration methods, there are all sorts of C/Fortran routines for 1-D which you can translate to Python. Long ago, I wrote 2 Simpson's rule in Python. For 2-D, however, your choice is a bit limited. I only know of few approximations based on nicely divisible domains. -- William Park, Open Geometry Consulting, 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin From d2002xx at myrealbox.com Tue Jun 11 23:05:09 2002 From: d2002xx at myrealbox.com (d2002xx) Date: 11 Jun 2002 20:05:09 -0700 Subject: JIT Complier for python? Message-ID: <8d3f4438.0206111905.7934664b@posting.google.com> Is there any JIT Compiler for Python? From duncan-news at grisby.org Wed Jun 12 10:10:23 2002 From: duncan-news at grisby.org (Duncan Grisby) Date: Wed, 12 Jun 2002 14:10:23 GMT Subject: ANN: omniORB 3.0.5 / omniORBpy 1.5 released Message-ID: I am pleased to announce the release of omniORB 3.0.5 and omniORBpy 1.5. The releases are minor updates to the previous versions, containing bug fixes and ports to new platforms, but no significant new features. These releases are the first new versions of omniORB since it became an independent project, following the closure of AT&T Laboratories Cambridge. omniORB and omniORBpy are high performance, robust CORBA ORBs for C++ and Python. They are available free under the terms of the GNU LGPL and GPL. You can find more information at http://omniorb.sourceforge.net/ You can download the new versions by following links from that web page, or directly from http://sourceforge.net/project/showfiles.php?group_id=51138 Many thanks to all the people who have contributed to these releases, either by reporting bugs, providing ports to new platforms, or by building binaries. Enjoy! Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From tchur at optushome.com.au Sat Jun 8 05:17:05 2002 From: tchur at optushome.com.au (Tim Churches) Date: Sat, 08 Jun 2002 19:17:05 +1000 Subject: Creating Dynamic Web Pages (ZOPE) References: Message-ID: <3D01CB91.8B98F2D7@optushome.com.au> Michael Hall wrote: > > I notice no-one has suggested good ol' CGI. For a relatively simple job > such as this, a few basic Python CGI scripts, some templates and MySQLdb > could also be used ... oh, just noticed the MS-SQL database. There is > probably a module around to cope with MS-SQL, no? Object Craft have a Python wrapper for MS SQL Server. See http://www.object-craft.com.au And while you are there, have a look at their Albatross CGI-based stateful Web application framework, which could be just what is required for the rest of the Web site envisaged. In my experience, nearly all Web applications and database-driven Web sites end up needing to retain state information sooner or later. Might as well start with a framework which can go the distance. Albatross is especially nice in this respect because you can choose alternative application models, starting with "SimpleApp" which is just what the name suggests, and later progress to more complex application models through mixins without having to start from scratch or throw away your existing code. Tim C > > Mick > > On 7 Jun 2002, Bill Tate wrote: > > > hwcowan at hotmail.com (Hugh Cowan) wrote in message news:<46ca81a0.0206062016.789d3af6 at posting.google.com>... > > > > [snip] > > > My scenario is typical where I need to put together a company Intranet > > > with a few front end Web-Pages where users can select information, > > > various links, and enter search criteria. The information is then > > > retrieved from the MS-SQL Server and the results are sent back to the > > > user. It's nothing fancy, no shopping carts, or remembering sessions > > > states, etc.. just really a simple front-end interface for > > > non-technical people to easily retrieve information. > > > > > > I don't know if ZOPE would fit my situation or not. I know that it is > > > / can be used to create complex E-commerce sites, but I am wondering > > > if it is overkill for what I need done. Would I be better off trying > > > to find some sort of RAD Web Tool instead (anyone have any good > > > suggestions) ? > > > > I think its safe to say that there are any number of tools that could > > fit the bill here including Zope. There are aspects of zope that can > > make your life much easier (e.g., zsql methods) but it does take some > > time to get used to it and everything it offers. Several recent books > > on the subject I think would be very helpful to you in this regard. > > If you go to zope.org, there is some information on using WYSIWYG > > tools such as Dreamweaver with zope that may also be of interest to > > you as well. > > > > I think zope works bests for you over the long haul where it is > > important to keep things well organized and well structured. The > > ability to collaborate amongst individuals is also a great strength. > > If these issues are important to you, then I would say that Zope would > > be an excellent choice. > > > > Good luck!!! > > > > -- > -------------------------------- > n i n t i . c o m > php-python-perl-mysql-postgresql > -------------------------------- > Michael Hall ninti at ninti.com > -------------------------------- > > -- > http://mail.python.org/mailman/listinfo/python-list From Chris.Barker at noaa.gov Mon Jun 3 13:30:29 2002 From: Chris.Barker at noaa.gov (Chris Barker) Date: Mon, 03 Jun 2002 10:30:29 -0700 Subject: Speeding up the Canvas Widget References: Message-ID: <3CFBA74E.C5EB9213@noaa.gov> Salim Zayat wrote: > I need to draw, and almost constantly redraw, upwards of like > 10,000 or so things to the canvas (lines, text, and rectangles, etc.). > The larger the number of things to be drawn, the slower it is. There are apparently some tricks that can be used to speed some of thee kinds of operations up. I'm not a TKuser, but there wasa a discusson quite a while back (2 yrs?, I cna't find it in the archives, it may predate them) on the wxPython newsgroup about drawing 10,000 rectangles, and someone had found some tricks to make it go much faster with TK. Since then, wxPython has added a couple of "Draw***List()" methods, that draw a whole bunch of points or lines as a single Python call. It speeds up the process of drawing losts of similar items considerably, by putting the loop in C rather than Python. At the moment, only Points and Lines are covered, but there is talk of adding all the draw objects, someone just needs to get around to writing the code..(hint, hint) I have no idea if pyGTK or pyQT support a call to draw lots of objects with a single Python call, but that may be neccesary to get the speed you want. Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From tjreedy at udel.edu Wed Jun 12 16:45:29 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 12 Jun 2002 20:45:29 GMT Subject: methods to parse big foreign ascii-file? References: Message-ID: "holger krekel" wrote in message news:mailman.1023899956.13534.python-list at python.org... > Hello, > > tommorrow i want to convince an old skool C-programmer to > use python. We are going to make a one-day project :-) > > It involves reading 50MB+ files of a strange ascii-format > containing names, floats and flags all around. These items > span multiple lines and should be grouped in lists or objects. > > How would you go about it? Options that come to my mind: IF the fields are comma (delimiter) separated, but you need to ignore commas (delimiters) within "quoted text fields", there is at least one Python module that should help (including dealing with multiline fields). Search google clp archive or ask. IF not, consider the other suggestions. TJR From cliechti at gmx.net Sat Jun 22 20:42:41 2002 From: cliechti at gmx.net (Chris Liechti) Date: 23 Jun 2002 02:42:41 +0200 Subject: TimeoutQueue.py References: Message-ID: Tim Peters wrote in news:mailman.1024698810.22387.python-list at python.org: > [Chris Liechti] >> Anyone ever needed a Queue with timeout? > > Yes. I encourage you to submit a patch to SourceForge, ... patch 572628 :-) that one uses additional 'timeout' args to get() and new to put() too. the old behaviour is still maintained when not using the new argument (unlike the original post which was not backwards compatible). chris -- Chris From tim.one at comcast.net Tue Jun 4 19:50:17 2002 From: tim.one at comcast.net (Tim Peters) Date: Tue, 04 Jun 2002 19:50:17 -0400 Subject: 'for every' and 'for any' In-Reply-To: <20020604072437.GA21777@strakt.com> Message-ID: [Andrae Muys] > Now I just don't understand how this position can possibly make sense? > C dosn't have any 32-bit int types standardised, so what do _you_ use > when you need one? Please don't tell me you don't use int, or I'll > have to hunt you down and put you out of your misery ;). [Martin Sj?gren] > Doesn't C99 specify ? Yes. > With int8_t, int16_t, ..., uint8_t, uint16_t, ... Not necessarily. All of the exact-size stdint gimmicks are optional -- an implementation need not supply any of them. This simply reflects reality. There's a slew of other names, like int_least8_t and int_least32_t, that are required, and those guarantee to resolve to an integer type *at least* big enough. In the Python source, we spell int_least32_t "long", since even C89 required that the platform long hold at least 32 bits' worth of stuff. People who think they need a type exactly N bits wide are people who've never thought about it, or are missing some neurons = N is easy to live with provided you're not trying to optimize for space, or relying on woefully unportable casting tricks). Well, OK, the Python source does assume in several places that "a byte" is an 8-bit thingie. The saving grace there is that any platform on which that's false will never get popular enough to attract a significant user base. 19-bit-microcomputers-are-a-thing-of-the-past-ly y'rs - tim From jonathan at onegoodidea.com Wed Jun 26 05:20:38 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Wed, 26 Jun 2002 10:20:38 +0100 Subject: Suggestions for good programming practices? References: Message-ID: On 26/6/2002 1:53, in article afb3a2$skm$0 at 216.39.172.122, "Bengt Richter" wrote: > Well, I meant using *args to allow detecting actual "no default-overriding > argument passed", in place of x=None. The arg list items (only x here) > don't have to remain unnamed long. E.g., > >>>> def foo(*args): > ... if len(args)==1: > ... print "We know we have one non-default arg: %s" % `args[0]` > ... x = args[0] > ... elif len(args)==0: > ... print "We can supply a default arg, even None" > ... x = None > ... else: raise TypeError,'foo() takes 0 or 1 arguments (%d given)' % > len(args) > ... print 'Effective arg was: %s' % `x` > ... I find this stuff much easier to write with a helper function: >>> def shift(): ... global _0 ... __, _0 = _0[0], _0[1:] ... return __ ... Then I can write the function 'foo' much more naturally as: >>> def foo( *args ): ... global _0; _0 = args ... try: ... x = shift() ... except IndexError: ... print 'We can supply a default arg, even None' ... x = None ... else: ... try: ... shift() ... except IndexError: ... print 'We know we have one non-default arg: %s' % `x` ... else: ... raise TypeError( 'foo() takes 0 or 1 arguments' ) ... print 'Effective arg was: %s' % `x` ... This can be further simplified by removing the '*args' nonsense altogether and defining another helper function: >>> def p( f ): ... def _p( *args ): global _0; _0 = args; f() ... return _p ... >>> def foo(): ... try: ... x = shift() [etc] ... >>> p(foo)( 'hello world' ) How did we get onto this from 'Suggestions for good programming practices'? Jonathan From mwh at python.net Fri Jun 7 10:20:27 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 7 Jun 2002 14:20:27 GMT Subject: Memory leaks when embedding python (debug-version) ? References: <1eed5b9.0206070157.6d281f65@posting.google.com> Message-ID: Sarah_L at gmx.net (Sarah Mayer) writes: > Hi, > maybe someone could help me, > > I just embedded python 2.2.1 into a dll , > > Program looks like: > > MyClass::MyClass() > { > Py_Initialize(); > Py_Finalize(); > } > > > and after the program finishes I get a lot of memory-leaks. > What is missing ??? The interned string dict? There's some call for getting rid of that, but I can't remember it off hand. Cheers, M. -- If you're talking "useful", I'm not your bot. -- Tim Peters, 08 Nov 2001 From bdesth at nospam.free.fr Sun Jun 23 16:12:17 2002 From: bdesth at nospam.free.fr (laotseu) Date: Sun, 23 Jun 2002 16:12:17 -0400 Subject: [newbie] import fails first time, then works :-[ References: <3D1379D1.5020705@nospam.free.fr> <3D132C65.34B38F8C@engcorp.com> <3D138E31.4070409@nospam.free.fr> <3D13D104.A49AF73C@engcorp.com> Message-ID: <3D162BA1.9040103@nospam.free.fr> Peter Hansen wrote: > laotseu wrote: > >>Well... I added '/usr/local/lib/lib-dynload' to my PYTHONPATH and >>'import' does not complain anymore. Everything seems just fine now. But >>that is puzzling me ! [being a python newbie,] I thought the >>'/lib-dynload/' directorie, that is in the '/lib/python/' >>directories, was automagically searched for external modules. Was I wrong ? > > > Searching the executable with "strings" and "grep", I find references > to /usr and /lib/python2.0 (in my case) and both /lib/lib-dynload > and /lib-dynload. When I run python and check sys.path I get > > ['', '/usr/bin', '/usr/lib/python2.0', '/usr/lib/python2.0/plat-linux2', > '/usr/lib/python2.0/lib-tk', '/usr/lib/python2.0/lib-dynload', > '/usr/lib/python2.0/site-packages'] > > All with default values, under RedHat 7.1. Not sure why you've > got troubles... Linux is still Black Magic much of the time to me. :) > > -Peter I guess I'd better make a new clean install of python... Anyway version 2.2.1 is out so !-) Ok, thanks for your help. laotseu -- Ye Old Master Said : "Computers are still black magic much of the time" -- From whisper at oz.net Thu Jun 27 03:12:43 2002 From: whisper at oz.net (David LeBlanc) Date: Thu, 27 Jun 2002 00:12:43 -0700 Subject: How to find out operating system In-Reply-To: <3D1ACBC5.22482.D4313A4@localhost> Message-ID: You might try os.environ: os.environ['WINOS'] -> WIN2000 I don't know if WINOS is defined on '98 or ME, but it should be good for NT, 2K and XP os.environ.has_key('WINOS') will tell you that. However, MS os's are so stupid that there must be some env variable to tell themselves what they are. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of A > Sent: Wednesday, June 26, 2002 23:25 > To: python-list at python.org; tutor at python.org; > activepython at listserv.activestate.com; python-help at python.org > Subject: How to find out operating system > > > Hi, > What is the best way of finding out the kind operating system? > I can use os.name but if the system is Windows I would like also > know if the system is Windows98 or Windows ME or W2K or > Windows XP. > Thanks for help. > Ladislav > > > _______________________________________________ > ActivePython mailing list > ActivePython at listserv.ActiveState.com > To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs > Other options: > http://listserv.ActiveState.com/mailman/listinfo/ActivePython > > > > -- > http://mail.python.org/mailman/listinfo/python-list From gerhard.haering at gmx.de Wed Jun 19 18:59:21 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Thu, 20 Jun 2002 00:59:21 +0200 Subject: GOTO w/ Python? In-Reply-To: References: <3d10ed95@xpl-sdf1-sec1.> Message-ID: <20020619225921.GC12907@lilith.my-fqdn.de> * Fernando P?rez [2002-06-19 16:44 -0600]: > Fredrik Lundh wrote: > > > > > you can find more Python tutorials here: > > > > http://www.python.org/doc/Newbies.html > > > > I've always been curious. Why isn't the standard tutorial linked to here? It > seems like the obvious first link to have, no? Because it's not well suited for _programming_ newbies? It's, however, good material if you already know to program. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From mcherm at destiny.com Fri Jun 14 09:22:52 2002 From: mcherm at destiny.com (Michael Chermside) Date: Fri, 14 Jun 2002 09:22:52 -0400 Subject: Medium to Large Scale Python Deployments Message-ID: <3D09EE2C.2070908@destiny.com> Michael Chermside writes: > In fact, it might be really nice to collect a list of large (successful) > Python projects and post it somewhere so the Python community could use > it for advocacy. Domenic Merenda writes: > Michael, I agree with you. I was formerly the Vice President of Business > Development for BeOpen.com, while we had PythonLabs there, and I can tell > you that we were compiling such a list for that very reason. Using the > WayBack Machine, I was able to grab the list. Here ya go: [... excellent list of companies using python ...] Wow... that's GREAT. I think this should probably be set up as a list that people can easily contribute to to enhance and update. With that in mind, the entries should probably have dates, indicating how recently they were updated. Do you have an estimate of when these were entered? Michael Chermside writes: > Domenic's > ERP system >100 -- Domenic Merrenda writes: > Let's not call it that. :-) And I will check upstairs when we get back > from our vacation to see if it's okay to release the number of lines in the > code. Don't be surprised if it's treated like a National Security issue. > (Shh! If they know how many lines are in the code, they can CRACK US!) This may be a more widespread problem... projects where the project owner (the corporation) does not want to release the information. We could simply ommit them, or we could list under "". I would welcome any other suggestions. Of course, the best solution is convincing them that publicizing thier efforts is really to their benefit, although this may not work in cases like the CIA. -- Michael Chermside From martin at v.loewis.de Fri Jun 7 02:05:37 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 07 Jun 2002 08:05:37 +0200 Subject: minidom and encoding problem References: <17aafe08.0206051514.4af054d2@posting.google.com> <17aafe08.0206061419.6366b12b@posting.google.com> Message-ID: ehab_teima at hotmail.com (Ehab Teima) writes: > > This is a bug in your code. You must not insert (byte) string in a DOM > > tree; always use Unicode objects. > > I do not have control over the sent text. [I assume that the "sent text" is also the one that you pass to createTextNode]. Even if you don't have that control, you still need to know what encoding it uses. If you don't know the encoding, you cannot put it into XML documents. > The issue started when some bullets were copied from a word document > and pasted into a file and the whole file was passed to my > classes. I cound not find a way to convert this text to UTF-8 or > anything else. You don't need to convert it to UTF-8, you need to convert it to Unicode objects. You can use the unicode() builtin to do that. > Is there a way to prevent this from happening? What is "this", and why do you want to prevent it from happening? Regards, Martin From bh at intevation.de Mon Jun 17 05:35:25 2002 From: bh at intevation.de (Bernhard Herzog) Date: 17 Jun 2002 11:35:25 +0200 Subject: Using Python to script a game? References: <3D0D9317.6371F155@del_cygnus-software_del.com> Message-ID: <6qbsaab63m.fsf@abnoba.intevation.de> Bruce Dawson writes: > I did a Game Developers Conference talk on using Python in games. [...] > Ultima Online 2 was also rumoured to be using Python. For this, see http://python9.org/p9-cdrom/13/index.htm Bernhard -- Intevation GmbH http://intevation.de/ Sketch http://sketch.sourceforge.net/ MapIt! http://www.mapit.de/ From vjovanov at stevens-tech.edu Tue Jun 4 12:15:22 2002 From: vjovanov at stevens-tech.edu (Vojin Jovanovic) Date: Tue, 4 Jun 2002 12:15:22 -0400 Subject: self Message-ID: I have been working on a project trying to implement some advanced functionality. Now, one thing that has been a constraint for me is the concept of self. Why is it that within a class one has to use self. (or "any word". ) to refer to instance variables? Would it not be more logical to just use the name of the variable like it is for example in C++? Vin From sholden at holdenweb.com Fri Jun 28 09:51:29 2002 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 28 Jun 2002 09:51:29 -0400 Subject: self destruction :) References: <7x6604ctb1.fsf@ruckus.brouhaha.com> <3d1c2d6a$0$231$4d4ebb8e@news.nl.uu.net> Message-ID: "Guyon Mor?e" wrote ... > > x = [a, b, c] > > > > and you want to remove b from the list? > > > > Just say "del x[1]". > > > yep this is actually what i mean, but the problem is is that this action > should come from the object within the list. this is object 'knows' when > it's done, the list doesn't > > see my problem? > Indeed. If your objects don't "know" which list they are being held on, or what element they are in that list then you have a problem: objects in Python can't tell which variables or other items are bound (refer) to them It's even trickier with a list, because you can't just keep the index as an object attribute: ince you delete one list element, all indexes above it would need to be reduced by one. Perhaps, rather than assuming a particular type of answer is required to your problem, you could just step back a little and describe in application terms what it is you need to do. c.l.py contains enough inventive and gifted programmers you are almost certain to get a workable solution to the real problem. regards ---------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From loewis at informatik.hu-berlin.de Sun Jun 9 07:03:39 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 09 Jun 2002 13:03:39 +0200 Subject: Socket error problem References: Message-ID: "David LeBlanc" writes: > I have this problem on windows where socket.socket(...) keeps returning > 10022, 'Invalid argument'. It's actually dieing in the > poplib.POP3.__init__(...) method. I have verified that host is reasonable > (mymail.myisp.net or something like that ;)), and port is 110. > > If I use the test script in poplib.__main__(...) with the correct host, user > and password, all is well, but if I call it from this other program i'm > trying to get working I get the above error. > > I can't figure out what's wrong - any pointers? You make it sound like something impossible happens, so it is hard to recommend a solution (since clearly you are overlooking some piece of information, which you could not report for the very reason that you are overlooking it). I recommend to put a print statement immediately before the call to socket.socket inside poplib, to see what arguments it actually does pass to that call. Please report any information you gain by doing so. Regards, Martin From d2002xx at myrealbox.com Sun Jun 23 11:13:09 2002 From: d2002xx at myrealbox.com (d2002xx) Date: 23 Jun 2002 08:13:09 -0700 Subject: The best GUI library in python References: <8d3f4438.0206220457.b820418@posting.google.com> <3D1481DE.C0331204@engcorp.com> <8d3f4438.0206221422.6f71287a@posting.google.com> <3D14FFB5.90808865@engcorp.com> Message-ID: <8d3f4438.0206230713.535169aa@posting.google.com> I hope the GUI could work well when I compiling a program in background (in my K6-2 400, running program other than compiler in this kind of situation is allocated only about 10% to 15% CPU resource) Most programs such as opera and emacs works well, except for programs using tk/tkinter. Currently, I know only wxPython and PyQT, they are fast enough, but I want to know are there any GUIs better than the two. From aahz at pythoncraft.com Sat Jun 29 16:59:27 2002 From: aahz at pythoncraft.com (Aahz) Date: 29 Jun 2002 16:59:27 -0400 Subject: can't import generators References: Message-ID: In article , Chris Liechti wrote: >aahz at pythoncraft.com (Aahz) wrote in news:afl5je$4iu$1 at panix1.panix.com: >> In article , >> John Hunter wrote: >>> >>>I am having trouble working with generators. Anyone know what might >>>cause this behavior: >>> >>>Python 2.2.1 (#1, Apr 22 2002, 21:20:54) [GCC 3.0.4] on linux2 >>>Type "help", "copyright", "credits" or "license" for more information. >>>>>> from __future__ import generators >>>Traceback (most recent call last): >>> File "", line 1, in ? >>>ImportError: cannot import name generators >> >> Can't do this in interactive mode. Use a script. > >?!?!? since when? > >$ python >Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 >Type "help", "copyright", "credits" or "license" for more information. >>>> from __future__ import generators >>>> def g(x): >... for p in x: yield p >... >>>> [x for x in g(range(3))] >[0, 1, 2] Huh. That'll teach me to trust the combination of screen output and my memory. Here's some more weird stuff. In a script, this works: x=1 from __future__ import generators this fails with SyntaxError: x=1 print x from __future__ import generators but it works in interactive mode: >>> x=1 >>> print x 1 >>> from __future__ import generators Of course, none of this explains why John gets an ImportError, unless he's got a completely screwed up installation. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From whisper at oz.net Tue Jun 18 17:41:02 2002 From: whisper at oz.net (David LeBlanc) Date: Tue, 18 Jun 2002 14:41:02 -0700 Subject: python version? In-Reply-To: Message-ID: George; Watch out for that tree! - dhl From karczma at info.unicaen.fr Tue Jun 11 09:42:30 2002 From: karczma at info.unicaen.fr (Jerzy Karczmarczuk) Date: Tue, 11 Jun 2002 15:42:30 +0200 Subject: Defining a method final References: <6glN8.35376$86.884025@twister1.libero.it> Message-ID: <3D05FE46.3E9B8430@info.unicaen.fr> Eric Brunel wrote: > Python now have an "official" means to make attributes private by prefixing > them with a double-underscore. And it *does* prevent their use or > overloading: > > class A: > def __private(self): pass > class B(A): > pass > o = B() > o.__private() > > results in: > > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: B instance has no attribute '__private' Some newbies may understand this wrongly. The attribute is still accessible, it has just a different name: _A__private etc. (You don't even need the class B to find out that o=A() o.__private() won't work. But launch dir(A) and look.) Jerzy Karczmarczuk From news at nospam.majid.fm Tue Jun 25 23:28:17 2002 From: news at nospam.majid.fm (Fazal Majid) Date: Tue, 25 Jun 2002 20:28:17 -0700 Subject: Installation problems DCOracle2 & W2000 References: Message-ID: <3D1934D1.3000707@nospam.majid.fm> Talon wrote: > I am having a heck of a time getting DCOracle2 to funcion properly. I > am running on a W2K machine, python2.1.3 and Zope 2.5.1, both of which > run just fine. I installed DCOracle2 and the ZOracleDA under Zope and > it works fine. But standalone python scripts don't see the dco2.py > module. So I tried to install DCOracle2 in the python21/lib folder. I > got that latest version from Zope.org and it said it installed properly. > But it doesn't run. If you try to import it into a script, you get > complaints that it can't find this or that module, all of which are part > of the Zope path. I have gotten DCOracle2 to work correctly on my Windows 2000 setup with 2.1.1 (but I haven't tried it with Zope). You do need to set your Pythonpath environment variable correctly, as well as copy the correct dco2.pyd (DLL) version for your Python and Oracle versions. -- Fazal Majid If you want to respond by email, take the nospam out of my email address. From jblazi at hotmail.com Mon Jun 24 13:40:17 2002 From: jblazi at hotmail.com (JB) Date: Mon, 24 Jun 2002 19:40:17 +0200 Subject: converting an array of chars to a string References: <3d12dda2_6@news.newsgroups.com> <3d17038e_6@news.newsgroups.com> Message-ID: <3d1757c7_1@news.newsgroups.com> Bengt Richter wrote: > No cause for desperation ;-) > > Are you saying that you want modulo 256 arithmetic on > unsigned 8-bit data? No problem. But what does your data > represent? And what does adding a number to such a data > item mean in the real world? Of course you are right. I really needed only some 8-bit shifting. The point is, that there is no need for the overhead that is involved. If anybody uses the array module which, you can argue, is a low level module, he should know what he is doing. -- Janos Blazi -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From whisper at oz.net Sun Jun 9 14:19:56 2002 From: whisper at oz.net (David LeBlanc) Date: Sun, 9 Jun 2002 11:19:56 -0700 Subject: Socket error problem In-Reply-To: Message-ID: > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Martin v. Lowis > Sent: Sunday, June 09, 2002 4:04 > To: python-list at python.org > Subject: Re: Socket error problem > > > "David LeBlanc" writes: > > > I have this problem on windows where socket.socket(...) keeps returning > > 10022, 'Invalid argument'. It's actually dieing in the > > poplib.POP3.__init__(...) method. I have verified that host is > reasonable > > (mymail.myisp.net or something like that ;)), and port is 110. > > > > If I use the test script in poplib.__main__(...) with the > correct host, user > > and password, all is well, but if I call it from this other program i'm > > trying to get working I get the above error. > > > > I can't figure out what's wrong - any pointers? > > You make it sound like something impossible happens, so it is hard to > recommend a solution (since clearly you are overlooking some piece of > information, which you could not report for the very reason that you > are overlooking it). > > I recommend to put a print statement immediately before the call to > socket.socket inside poplib, to see what arguments it actually does > pass to that call. > > Please report any information you gain by doing so. > > Regards, > Martin Martin and Steve; In one part of the program it does this: serv = Pop3Server(adressaux, aux_username, aux_passwd, serverport) and the args are: adressaux: mail.oz.net aux_username: whisper aux_passwd: password serverport: 110 (with aux_passwd changed to protect my innocence). Then, it invokes POP3Server's connect method as: def process (self, serv): """Code actually executed by every thread except the main thread""" config = self.config # Very used log_index = 0 if config.optnotlog: log_index= 0 logAgent = None else: # logAgent collects stadistics and show them at the end (see logger.py) # It has an entry for each server, which get indexed by log_index logAgent = self.logAgent log_index = logAgent.new(serv.alias, thread.get_ident()) # If configured, send logging info to the system log # aprint() (see general.py) takes care of this automatically # if config.optsyslog: # import syslog # syslog.openlog("Animail", 0, syslog.LOG_MAIL) try: messages = 0 aprint(_("Trying to connect (%s)") % serv.alias, general.YELLOW) v = serv.connect() aprint (_('connected!\n'), serv.alias, general.YELLOW) aprint(_("Authenticating (%s)") % serv.alias, general.YELLOW) serv.auth() . . . except smtplib.SMTPException, x: self.error_msg("SMTP Error (%s): " % serv.adress, x, log_index) self.__exit_thread() except socket.error, x: self.error_msg(_("Connection error (%s): ") % serv.name, x, log_index) self.__exit_thread() except poplib.error_proto, x: self.error_msg(_("Protocol Error (%s): ") % serv.adress, x, log_index) self.__exit_thread() ---------------------- The general.* constant references are to colorize the output which is turned off but still results in the "31" in the connection error line in the program output below. NOTE: I didn't write this code, so I have no idea why it's returning the username in the socket.error instead of the host. FWIW, this code is running in a thread, but there is only one thread trying to get mail. POP3Server's connect method: def connect(self): self.lmsg = [] if self.adress == '': raise ConfigError, _("Server address not given!!") if self.ssl: import popslib self.objpop = popslib.POP3S(self.adress, self.port) else: self.objpop = poplib.POP3(self.adress, self.port) welcome = self.objpop.getwelcome() if self.protocol == 'APOP': lwelcome = welcome.split() lwelcome.reverse() self.timestamp = lwelcome[0] return welcome # end if # end def connect ---------------------- "self.ssl" is false, so objpop becomes a poplib.POP3 "self.protocol is POP3, so the APOP stuff isn't executed. At this point, self.adress and self.port are mail.oz.net and 110 In poplib.POP3.__init__(...) they are also mail.oz.net and 110 def __init__(self, host, port = POP3_PORT): self.host = host self.port = port msg = "getaddrinfo returns an empty list" self.sock = None for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: self.sock = socket.socket(af, socktype, proto) self.sock.connect(sa) except socket.error, msg: if self.sock: self.sock.close() self.sock = None continue break if not self.sock: raise socket.error, msg self.file = self.sock.makefile('rb') self._debugging = 0 self.welcome = self._getresp() ---------------------- The output of the program is: K:\tmp\animail>animail -v Opening Config file: c:/user/dave/.animail/animailrc Trying to connect (mail.oz.net) ("Connection error (whisper): (10022, 'Invalid argument')", 31) ####### Operation summary ####### Sun Jun 09 11:01:04 2002 --- Server: mail.oz.net * Total messages: 0 * Total volume on server: 0.00 Bytes * Filtered messages: 0 * Downloaded messages: 0 * Postergated messages: 0 * Incidents: -Connection error (whisper): (10022, 'Invalid argument') Dave LeBlanc Seattle, WA USA From mcalla at insightbb.com Thu Jun 13 08:27:55 2002 From: mcalla at insightbb.com (Mike Callahan) Date: Thu, 13 Jun 2002 12:27:55 GMT Subject: Question about asksaveasfilename Message-ID: I am using asksaveasfilename from tkFileDialog. I want to restrict my users to save filenames with these extensions .unl or .sql. This is my call: from tkFileDialog import asksaveasfilename fn = asksaveasfilename(filetypes=[('Unloaded', '*.unl'), ('Queries','*.sql')]) This gives me the correct dialog box, but how do I force the correct extension on fn? Thanks. Mike C. From dallasm at aiinet.com Thu Jun 13 16:15:39 2002 From: dallasm at aiinet.com (Mahrt, Dallas) Date: Thu, 13 Jun 2002 16:15:39 -0400 Subject: Shrinking Python Message-ID: <638AA0336D7ED411928700D0B7B0D75B682046@aimail.aiinet.com> I am looking into using Python in a small device with limited space for binaries. Due to this, I am both investigating creating a shared library with the interpreter and shrinking the footprint of this library. I have found many threads talking bout shared libraries, so I am not too concerned about that aspect. I am concerned about shrinking the library's binary footprint. I did find several links to a "Deeply Embedded Python" based on 1.5.1 which has since vanished. I have stripped the library to improve size some (to ~1.13 MB) but would like to reduce it further. Has anyone tackled this or even attempted? Are there any links to resources that may help me that I haven't found? --- Dallas S. Mahrt 614-923-1194 Software Engineer Network Management Systems Applied Innovation Inc. Dublin, Ohio From guido at python.org Wed Jun 19 11:07:36 2002 From: guido at python.org (Guido van Rossum) Date: Wed, 19 Jun 2002 11:07:36 -0400 Subject: [Python-Dev] Tcl adept wanted for Stackless problem In-Reply-To: Your message of "Wed, 19 Jun 2002 15:38:46 +0200." <3D108966.9050402@tismer.com> References: <3D108966.9050402@tismer.com> Message-ID: <200206191507.g5JF7ag02088@pcp02138704pcs.reston01.va.comcast.net> > My big question is: > When does Tcl use C stack entries as globals, which > are passed as function arguments to interpreter calls? It's a performance hack, just as stackless :-). Tcl's interpreter data structure has a return value field which can receive a string of arbitrary length. In order to make this efficient, this is initialized with a pointer to a limited-size array on the stack of the caller; when the return value is longer, a malloc()'ed buffer is used. There is a little dance you have to do to free the malloc()'ed buffer. The big win is that most calls return short strings and hence you save a call to malloc() and one to free() per invocation. This is used *all over* the Tcl source, so good luck getting rid of it. --Guido van Rossum (home page: http://www.python.org/~guido/) From h.baumgartl at chello.NOSPAM.nl Thu Jun 20 13:39:42 2002 From: h.baumgartl at chello.NOSPAM.nl (Henry Baumgartl) Date: Thu, 20 Jun 2002 17:39:42 GMT Subject: application development - separating content from function Message-ID: For eight months now, I am preparing for the development of an open source Python application to support individuals in Life Long Learning. It will be a mixture of PIM, extended diary, groupware, project management, and modules to interact with centralised knowledge / skill exchange servers. Most of the user activity is done on individual boxes. However, when and if needed, the application must provide intuitive and standardised interaction with fellow network members (e.g. project workgroups, mentor, and such) and centralised server modules. What needs to be done is: 1. Develop GUIs and modules that are interchangeable on, at least, Linux, Windows, and Mac. 2. Use the modularity of Python to allow personalised application adaptation, thus requiring an effective way of integrating personal variables into almost all scripts. 3. And, last but not least ;-) the application needs to be multi-lingual. The more I have tried to solve these requirements in an elegant and efficient manner, the further I seem to stray from anything remotely resembling a viable solution. In other words, I can't see the forest for the trees anymore. Anyone working on something similar? Or, just plain brilliant in all things Python, and ready and willing to point me in the right direction and make it all worth while again :-) Help! Henry Baumgartl Dynamic Knowledge Network *Please remove .NOSPAM from my e-mail address when abswering me directly.* From shalehperry at attbi.com Fri Jun 7 20:04:56 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 07 Jun 2002 17:04:56 -0700 (PDT) Subject: Detecting OS and Window Manager In-Reply-To: Message-ID: > Alas, I don't think there is an easy answer to this. I think we'll just > have to either: > 1) Settle for a default > 2) Provide different commands such as gfunky and kfunky and just provide > menu entries to point to the appropriate one depending upon which DE you > are running. > yep, that about covers it. From emile at fenx.com Thu Jun 6 09:04:17 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 06 Jun 2002 13:04:17 GMT Subject: check on numerical value? References: <3cff56b4.511834453@news.skynet.be> Message-ID: wrote in message > Is there any way to discover when a value is numerical or not in > Python? I want a check in my code on a given value. If somebody enters > or gives me something like "akjlvq?irq" this is surely not a numerical > value. > int(value) or float(value) depending on what values you'd except. -- Emile van Sebille emile at fenx.com --------- From aahz at pythoncraft.com Mon Jun 3 14:05:15 2002 From: aahz at pythoncraft.com (Aahz) Date: 3 Jun 2002 14:05:15 -0400 Subject: thread module under Windows References: <59d8a5f6.0206030730.1be14ffb@posting.google.com> Message-ID: In article <59d8a5f6.0206030730.1be14ffb at posting.google.com>, Dmitri wrote: > >Reading the conference I see that many people use the python in >multi-threading. How they get the python version for windows with >treading support on ( I am not talking about other optional services >now... )??? Almost everyone downloads the pre-built binary for Windows instead of compiling it themselves; the binary on www.python.org comes with threading enabled. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "In the end, outside of spy agencies, people are far too trusting and willing to help." --Ira Winkler From jonathan at onegoodidea.com Fri Jun 28 05:07:33 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Fri, 28 Jun 2002 10:07:33 +0100 Subject: metaclasses vs. inheritance References: Message-ID: On 28/6/2002 7:23, in article ghTS8.58749$mh.1826422 at news1.telusplanet.net, "Ian McMeans" wrote: > Can someone give an example of a problem that is solved with metaclasses, > which would be difficult or impossible to solve with inheritance? > > I (very barely) understand metaclasses, but to me it just seems like > inheritance, where the classes who get the benefit of the meta-class get the > metaclass' features. Interesting you should ask this as I've spent the last day reading up on metaclasses and playing with them to better understand what can be done with them. I find the best way to understand them is with a little graph: metaclass metaclass ^ ^ | | instance instance | | class B ---inheritance--> class A ^ ^ | | instance instance | | b a This shows that metaclasses are "orthogonal" to normal inheritance. By which I mean when you define a (new-style) class like so: >>> __metaclass__ = type >>> >>> class A: ... pass ... an instance of class 'A' has the type 'A': >>> a = A() >>> >>> a <__main__.A object at 0x3f8cf0> >>> type(a) >>> But 'A' itself is an instance of the metaclass, in this instance 'type': >>> A >>> type(A) >>> Thus the metaclass is used in the construction and definition of classes. A metaclass is a class itself (with the mind-bending result that the type of 'type' is 'type') and new ones can be defined using the same syntax. The easiest way to define a new metaclass is to inherit from 'type' as that defines all of the magic necessary to construct and manage classes. The main reason one would want to define a new metaclass is to override some of this magic in order to bend the way classes work. A useful method that one might want to override in a metaclass is '__init__', which is called to initialise a new class. An example will show what happens: >>> class mytype( type ): ... def __init__( cls, name, bases, dict ): ... print '__init__' ... print ' new class:', cls ... print ' name:', name ... print ' base classes:', bases ... print ' dictionary:', dict ... type.__init__( cls, name, bases, dict ) ... >>> __metaclass__ = mytype >>> >>> class Foo: ... def foo( self ): ... print 'foo' ... __init__ new class: name: Foo base classes: () dictionary: {'__module__': '__main__', 'foo': } >>> You can see from the above example that the 'mytype.__init__' is called immediately after we finish defining the class 'Foo'. It is passed as arguments the information used to initialise a new class, which is: the class name, a tuple of the base classes (none in this example), and the class dictionary which contains the method functions and class instance variables. Most people won't actually have any particular purpose for metaclasses, but for altering the way that the language works they are invaluable. The example I worked on yesterday is a mechanism for declaring methods and classes final (in the Java sense) - prompted by an example someone else wrote a while ago on this group. My metaclass intervenes in the creation of new classes to check that final constraints aren't being broken: >>> from final import * >>> >>> class Foo: ... def foo( self ): ... print 'foo' ... foo = finalmethod( foo ) ... >>> class Bar( Foo ): ... def foo( self ): ... print 'bar' ... Traceback (most recent call last): [..] final.FinalError: finalmethod 'foo' of class 'Foo' may not be overriden >>> and also: >>> class Foo( finalclass ): ... pass ... >>> class Bar( Foo ): ... pass ... Traceback (most recent call last): [...] final.FinalError: finalclass 'Foo' may not be subclassed >>> There's no easy way to do this sort of magic without the use of metaclasses. Hope this helps a little. I'd better go do some real work ;-) Jonathan From emile at fcfw.fenx.com Mon Jun 24 17:20:47 2002 From: emile at fcfw.fenx.com (Emile van Sebille) Date: 24 Jun 2002 16:20:47 -0500 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 24) Message-ID: QOTW: "I read with pleasure all the thread saying that `roundup' has an email interface, is actively being improved, and could replace the SF tracker. Let us hope it will be more usable than its precessors! You know, the real goal of all this is allowing for simple and humble communication between humans, about the knowledge of a problem. I surely used to be a very active reporter for all problems I saw everywhere, at the time maintainers were still reachable. When the effort gets too frustrating, sadly, one might feel less inclined to offer contributions, and rather choose to enjoy more of the sun, music, and life! :-)" -- Fran?ois Pinard on python-dev, Jun 1 2002 Travis N. Vaught announces a Python for Scientific Computing Workshop at CalTech, Pasadena, CA September 5-6, 2002. This workshop provides a unique opportunity to learn and affect what is happening in the realm of scientific computing with Python. Space is limited. http://groups.google.com/groups?selm=mailman.1024366882.23776.python-list at python.org On the question of text to html conversion, Gilles point to StructuredText in Zope as a package that can be used "standalone". He also provides a dozen lines of code as a start: http://groups.google.com/groups?selm=aen4n1$35b$1 at norfair.nerim.net The European Python and Zope Conference 2002 happens June 26-28 in Charleroi, Belgium. It promises to be a great show. ...for general information, see http://europython.zope.nl ...and for schedule and information on the talks being given see http://europython.zope.nl/sessions/talks Fernando Perez on tools for python in science, in response to a question of experiences teaching Biology students with python support. http://groups.google.com/groups?selm=aeqfuh$88n$1 at peabody.colorado.edu Lamy Jean-Baptiste releases TreeWidget 0.2 a pure-Python tree widget for Tkinter... http://groups.google.com/groups?selm=mailman.1024601110.13018.clpa-moderators at python.org ...and EventObj 0.2, a pure Python module that allows to add modification callback (=event) to any Python object (including lists and dicts). http://groups.google.com/groups?selm=mailman.1024601109.12981.clpa-moderators at python.org Gerhard Haring asks if a python based procmail replacement exists, and Radovan Garabik reminds us that he's written one... http://groups.google.com/groups?threadm=mailman.1024444823.19953.python-list at python.org ...Francois Pinard also posts a summary of additional options... http://groups.google.com/groups?selm=mailman.1024451876.25700.python-list at python.org Tom Loredo needs to move into Windows and asks for advise on proceeding: http://groups.google.com/groups?threadm=3D110B55.4D8AD7FA at astro.cornell.edu Steven M. Castellotti gets help connecting to the Microsoft Speech API to synthesize Text-To-Speech output, then posts the working result: http://groups.google.com/groups?threadm=U_6Q8.39803$ks6.8500 at nwrddc02.gnilink.net Here's a discussion on implementing and representing infinity (eg 1e400) in python but if you use it, be sure to test on the target platforms. http://groups.google.com/groups?threadm=3d11ee9b$1 at news.swissonline.ch Anyone ever needed a Queue with timeout? Chris Liechti posts a working implementation. http://groups.google.com/groups?selm=Xns9234F249D7D85cliechtigmxnet at 62.2.16.82 Angela Williams asks for clarification on Python's FAQ 6.26. Why no goto? One gem I found in this thread was a counter proposal for COME FROM... * Example: 10 J=1 11 COME FROM 20 12 WRITE (6,40) J STOP 13 COME FROM 10 20 J=J+2 40 FORMAT (14) * Explanation: In this example, J is set to 1 by statement 10. Statement 13 then causes control to be passed to statement 20, which sets J to 3. Statement 11 then causes control to be passed to statement 12, which writes the current value of J. The STOP statement then terminates the program. ...For more like this, see (Thank Carl Banks for the pointer) http://www.fortran.com/fortran/come_from.html ...For the current discussion on GOTO and python, start here: http://groups.google.com/groups?threadm=uh1s1qdcl5b1b0 at news.supernews.com One lump or two? If you're easily distracted by the rules of punctuation, you may want to follow this thread on python-dev: http://mail.python.org/pipermail/python-dev/2002-June/025074.html ======================================================================== Everything you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Michael Hudson continued Andrew Kuchling's marvelous tradition of summarizing action on the python-dev mailing list once every other week, into July 2001. Any volunteers to re-start this valuable series? http://starship.python.net/crew/mwh/summaries/ http://www.amk.ca/python/dev The Vaults of Parnassus ambitiously collect Python resources http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Links2Go is a new semi-automated link collection; it's impressive what AI can generate http://www.links2go.com/search?search=python Tenth International Python Conference http://www.python10.org Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. [http://www.egroups.com/list/python-url-leads/ is hibernating. Just e-mail us ideas directly.] To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From fredrik at pythonware.com Sat Jun 29 08:06:24 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 29 Jun 2002 12:06:24 GMT Subject: How to get rid the new line References: <3D1AD534.A74EC9F4@ipm.fhg.de> <3D1B1A76.563E5394@engcorp.com> <3D1BA535.1EE16646@engcorp.com> Message-ID: <4phT8.45578$n4.10822996@newsc.telia.net> Peter Hansen wrote: > > Could try this: > > > > def chomp(line): > > if line[-1]=='\n': > > line=line[:-1] > > return line > > Just make sure you pass chomp() only lines that are not equal > to the empty string ''. or add the single character needed to make chomp a bit more robust: def chomp(line): if line[-1:] == '\n': line = line[:-1] return line From pereira at cis.upenn.edu Mon Jun 3 12:43:34 2002 From: pereira at cis.upenn.edu (Fernando Pereira) Date: Mon, 03 Jun 2002 12:43:34 -0400 Subject: Graph distances, how can I speed it up? References: <33803989.0206030235.4134d33e@posting.google.com> Message-ID: On 6/3/02 12:15 PM, in article d571ae53.0206030815.2e52aac at posting.google.com, "Jonathan Ellis" wrote: > The obvious idea then is to not calculate anything until all edges > have been added. Then use dijkstra's algorithm > (http://ciips.ee.uwa.edu.au/~morris/Year2/PLDS210/dijkstra.html) > to compute and store distances as needed. (You can probably get some > savings over the classic algorithm if you know you are going to NEED > distances for ALL vertices -- otherwise you are better off doing lazy > (as-needed) computation.) Dijkstra's algorithm is not a good choice here, because distances from all sources appear to be needed, not from a single source. There is no good, general way of saving parts of the work done for one source node to speed up computing the distances from another source node (but see Johnson's algorithm). So, he may need an all-sources algorithm like Floyd-Warshall, which unfortunately is cubic on the number of nodes. Since the WordNet graph is sparse, and in fact "almost" a tree, Johnson's algorithm might be better. If the graph were a tree, the following much simpler algorithm would do. As always, Cormen, Leiserson and Rivest (+ Stein in the new edition) http://theory.lcs.mit.edu/~clr/ are your friends. -- F From asgarbutt at ucdavis.edu Thu Jun 20 15:30:30 2002 From: asgarbutt at ucdavis.edu (ANdrew) Date: 20 Jun 2002 12:30:30 -0700 Subject: PyQT Complie problems Message-ID: First off, using: Windows 2000 MSVC 6.0 service pack 5 QT eval 3.0.4 Active State Python 2.2 PyQt-3.2.4 (source) I am trying to compile for Qt 3.0.4 eval. Following the win32 instructions, i am able to compile the first makefile (sip_helper.exe). However, when i change dir to the "qt" dir and modify the makefile for the correct version of the .lib file and fix the one type-o in the sipqtDeclqt.h file ( changed #include to #include ), i get a synatx error followed by an unexpected end of file error. This is stated as being in the file "sipqtQPaintDevice.h". The error is "sipqtQPaintDevice.h(44) : error C2146: syntax error : missing ';' before identifier 'sipLazyAttrDef'" I have downloaded the latest snapshot (PyQt-snapshot-20020619.zip)and there is nothing in there about the qt section. I am at a loss and any help would be greatly appreciated. -Andrew From ark at research.att.com Fri Jun 7 15:02:47 2002 From: ark at research.att.com (Andrew Koenig) Date: Fri, 7 Jun 2002 15:02:47 -0400 (EDT) Subject: Python 2.2.1 vs. gcc 3.1? In-Reply-To: <15616.64407.863059.729351@12-248-41-177.client.attbi.com> (message from Skip Montanaro on Fri, 7 Jun 2002 13:29:43 -0500) References: <15616.57963.519636.730290@12-248-41-177.client.attbi.com> <200206071747.g57HlbH01057@europa.research.att.com> <15616.62634.635544.905055@12-248-41-177.client.attbi.com> <200206071804.g57I4fp01212@europa.research.att.com> <15616.63342.559215.644086@12-248-41-177.client.attbi.com> <200206071815.g57IFjg01303@europa.research.att.com> <15616.64407.863059.729351@12-248-41-177.client.attbi.com> Message-ID: <200206071902.g57J2lJ01644@europa.research.att.com> Skip> Dunno. Try "find . -name 'struct*'. It should be in your build/lib* Skip> directory (where "*" matches your configuration name). Not as far as I can see... $ find . -name '*struct*' -print ./Doc/lib/libstruct.tex ./Include/structmember.h ./Include/structseq.h ./Lib/test/test_struct.py ./Lib/test/test_structseq.py ./Modules/structmodule.c ./Objects/structseq.c ./Objects/structseq.o ./Python/structmember.c ./Python/structmember.o ./Tools/modulator/Templates/object_structure From aahz at pythoncraft.com Sun Jun 30 21:04:49 2002 From: aahz at pythoncraft.com (Aahz) Date: 30 Jun 2002 21:04:49 -0400 Subject: I'd give up Perl tomorrow if only... References: Message-ID: In article , Frank Tobin wrote: > >Yes, I'm talking about non-bundled extension modules. That's all we're >talking about here. The standard lib is irrevelant to the discussion. Yes and no. Thing is, historically Python has done better than Perl at pulling publicly recognized libraries into the standard library. This tends to reduce the interest in a CPAN-like construct. Perl has more recently recognized the importance of this, and Perl's standard library has been growing faster than Python's, I think, due to the backlog of stuff in CPAN that is being moved. >I suggest that you be a Perl programmer for a while, and see what having >CPAN accessible and authoring for it really is like. You explicitly state >you aren't familiar with it. I've been author of a couple CPAN modules >for about 4 years now, and an extensive user for just as long, and have >been a Python module writer for just over a year now. Python is a great >language, but in terms of a reusable code repository, *nothing* comes >close to the jewel that is CPAN. There is a reason you'll hear this over >and over from people coming to Python from Perl. But somehow one doesn't hear it very often from people who've been using Python for a long time -- and certainly nobody has truly stepped up to the plate to put all the finishing details into place. Sean Reifschneider came pretty close, then dropped the ball. Where's the itch-scratching that induces people to do the work? You might be able to get some traction if you concentrate on just the testing issue (and possibly the README issue). That's the kind of thing that gets at least public verbal support from Guido. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From paul at boddie.net Tue Jun 25 06:32:11 2002 From: paul at boddie.net (Paul Boddie) Date: 25 Jun 2002 03:32:11 -0700 Subject: Web templating/db tool with best designer/coder separation? References: Message-ID: <23891c90.0206250232.249c8488@posting.google.com> bokr at oz.net (Bengt Richter) wrote in message news:... > > No one mentioned ZPT (Zope Page Templates), > http://www.zope.org//Wikis/DevSite/Projects/ZPT/FAQ This thread wouldn't end if we all started naming template systems, though. ;-) For something similar to the jonpy templating, take a look at http://www.clearsilver.org - a system which I was made aware of recently. If nothing else, that site gives some very good arguments against "Python in HTML" systems. > and from the description, this would seem to have a real advantage over all of > the above, in that it uses attributes of html tags as opposed to special tags > that browsers or design tools won't generally understand and render usefully. It should work well with XML-capable tools. However... > This is touted as enabling the "round trip" from graphic designer to template > logic programmer and back using the same html source. I assume this is > the "round trip" Paul was referring to. To me, it seems a winning point for > ZPT, though I don't know how ZPT works out in practice. Yes, that was what I was referring to. However... > They have a list of design tools that apparently pass through the ZPT markup > they don't understand. According to the FAQ: > > "Q8: What HTML editors work well with ZPT? > We are still compiling a list, but on the commercial (industrial > strength) front, GoLive and Dreamweaver 4 work well with ZPT. Recent > versions of Amaya work well in HTML mode." > > Opinions on ZPT? In my experience, "recent versions of Amaya" either don't work with ZPT, or the secret incantation to make it work hasn't been widely publicised - "HTML mode" doesn't really tell me anything. What happens when I try to load ZPT into Amaya is a large number of warnings about invalid attributes, followed by the loss of those attributes in the saving process. On the other hand, if I use some 'id' attributes in HTML to give "structure" to my template, Amaya will only intervene when two such attributes are identical. Consequently, it's possible to do like Enhydra's XMLC and make a template system operating around those principles. Paul From derek at wedgetail.com Sat Jun 15 09:18:47 2002 From: derek at wedgetail.com (Derek Thomson) Date: Sat, 15 Jun 2002 23:18:47 +1000 Subject: Integer conversion References: <3D0B3257.E8572AE5@sympatico.ca> Message-ID: <3D0B3EB7.2020304@wedgetail.com> Colin J. Williams wrote: > int(string, base) => integer > > For int('127', 8), I had expected this function to deliver 87. It does deliver 87. I enter int('127', 8) at the Python prompt, and I get 87, which is the integer (decimal) value of '127' if interpreted as a base 8 number. > > The example below correctly gives errors at the top and bottom of the > range and > for int('127', 10) delivers 127. Right. > The other cases are not what I expected. The output looks correct to me. For example, '127' as a base 16 integer is 295 (decimal). What output are you seeing, exactly? Regards, Derek. From roy at panix.com Tue Jun 25 07:48:06 2002 From: roy at panix.com (Roy Smith) Date: Tue, 25 Jun 2002 07:48:06 -0400 Subject: Suggestions for good programming practices? References: Message-ID: "David LeBlanc" wrote: > Structs and tuples are different. They're both of the same general category > of aggregate data, but they are different as Brian notes. I've come to really dislike using tuples for data structures, and instead create small data classes. Even if the class is no more complicated than: class myData: def __init__ (self, foo, bar): self.foo = foo self.bar = bar you've added quite a bit of functionality. First, the code becomes a little more self-documenting. "power = ckt.volts * ckt.amps" is a lot easier to read and understand than "power = ckt[0] * ckt[1]". Secondly, it makes it easier to catch programming errors. I was working with somebody the other day who was using tuples to store data. His program was doing something strange. When I made him rewrite one of his data structures as a simple data class instead of a tuple, the reason instantly popped out. He had gotten confused and was using the wrong piece of data. When he had everything as tuples, it just happily took the i'th element of the wrong tuple and gave him garbage. But, when he tried to access an attribute that didn't exist, it immediately raised an exception. From fredrik at pythonware.com Tue Jun 11 17:01:38 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 11 Jun 2002 21:01:38 GMT Subject: tk gui for python References: Message-ID: Martin Krallinger wrote: > I would appreciate any sample code to generate tk gui for python. > i just need to load a file, of past instead a text (protein sequence) > and run on it a c programm and return the content of it's output > > any sample code is welcomed, start here: http://www.python.org/topics/tkinter/doc.html From marklists at mceahern.com Thu Jun 20 12:06:10 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 20 Jun 2002 11:06:10 -0500 Subject: Function to add commas in numbers? In-Reply-To: Message-ID: > Is there a function that will take, for example, 1234567 and return > 1,234,567? Short answer: Look into the locale module. Demo: mynum = 123456 import locale locale.setlocale(locale.LC_ALL, "") locale.format('%.0f', mynum, 3) >>> '123,456' // m - From see at reply.address.invalid Tue Jun 25 02:06:31 2002 From: see at reply.address.invalid (Greg Ewing) Date: Tue, 25 Jun 2002 18:06:31 +1200 Subject: __getattr__ feature References: <3D180042.6000902@earthlink.net> Message-ID: <3D180867.4020703@reply.address.invalid> Hans Nowak wrote: > I didn't know this was possible: > > class Foo: > def __init__(self, obj): > self.obj = obj > def __getattr__(self, name): > return getattr(self.obj, name) > > foo = Foo([1,2,3]) > print foo[2] # prints 3 I think what's happening here is that invoking the [] is causing a lookup for a __getitem__ method, and your __getattr__ is catching this and redirecting it to self.obj, which does have a __getitem__ method. > A quick test learns that this is apparently a > feature new to 2.2; The new feature is that built-in types now have all the relevant special methods accessible by __xxx__ names. Previously they only worked on user-defined classes. > Does anybody > know how/why this works and why it was added? I don't think it was explicitly added -- it's just a side effect of the type/class unification stuff. Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From never at mind.info Sun Jun 2 16:50:32 2002 From: never at mind.info (G. Willoughby) Date: Sun, 2 Jun 2002 21:50:32 +0100 Subject: Reading coords from a scrolled Tkinter Canvas widget? References: Message-ID: >Your code appears not to grok canvasx and canvasy. They translate event.x >style coordinates to canvas model coordinates. Hmmm i know, have you any code to grab the canvasx and canvasy? >BTW you could be using a Python Megawidgets Pmw.ScrolledCanvas here. More >features less pain. I could do but im trying to keep imports to a minimum and keep its portability. --G. Willoughby From phd at phd.pp.ru Mon Jun 3 10:57:31 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 3 Jun 2002 18:57:31 +0400 Subject: mySQL on Solaris .8 In-Reply-To: <79d1869.0206030646.512af52c@posting.google.com>; from dryose@juno.com on Mon, Jun 03, 2002 at 07:46:25AM -0700 References: <79d1869.0206030646.512af52c@posting.google.com> Message-ID: <20020603185731.H29392@phd.pp.ru> On Mon, Jun 03, 2002 at 07:46:25AM -0700, yose wrote: > I am trying to install a mySQL database in solaris 2.8. I have a copy > of the distro for mySQL-python-0.9.1. When I try to run setup.py, I am > told that I am missing distutils.core > > Where do I get this? What package is it part of? Do you use Python 1.5.2? Then download Distutils from http://www.python.org/sigs/distutils-sig/download.html. Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From andreas.ames at Tenovis.com Thu Jun 27 04:43:46 2002 From: andreas.ames at Tenovis.com (Andreas Ames) Date: 27 Jun 2002 10:43:46 +0200 Subject: Interactive session via tcp Message-ID: Hi all, I have a python daemon running with access to an XML messaging system (jabber in this case). I'm wondering, how I can achieve remote control over my daemon. The first thing that I can think of is to start an interactive session via the XML stream. Security is not my concern right now. Following steps seem to be required, afaik (please correct me, if my assumptions are wrong). 1) Deamon receives a command to open an interactive session. 2) The main thread of my daemon starts a read/eval loop and redirects stdout and stder. Is step 2 easily implemented in python? Is it reasonably easy to have more than one concurrent interactive sessions (say one local and one remote or several remote)? If there can be more than one concurrent interactive sessions how is this implemented (different threads, different stdout/stderr etc.)? How do several concurrent interactive sessions possibly interfere (sideeffects etc.), when they use the same interpreter instance (or don't they share the same one)? TIA, Andreas From huaiyu at gauss.almadan.ibm.com Thu Jun 20 23:14:53 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Fri, 21 Jun 2002 03:14:53 +0000 (UTC) Subject: How to represent the infinite ? References: <3d11ee9b$1@news.swissonline.ch> <20020620193230.53d58f8f.christophe.delord@free.fr> <20020620202732.68e67873.christophe.delord@free.fr> <20020620225355.7b8dd9db.christophe.delord@free.fr> Message-ID: Christophe Delord wrote: >On Thu, 20 Jun 2002 20:11:25 +0000 (UTC) >huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) wrote: > >> Christophe Delord wrote: >> [regarding 1e1000 giving inf] >> >With Python 2.2 and Linux it works. The example I gave is a copy-paste from IDLE. It also works with my Python 1.5.2 and 2.3 (I'm under Linux on an Intel processor) >> >> Does 1e200**2 also work for you out of the box? I had to get rid of the >> artificial check for overflow in the source to really use inf in >> computations. I don't remember if 1e1000 works on my box without patch. > > >>>> 1e200**2 >Traceback (most recent call last): > File "", line 1, in ? > 1e200**2 >OverflowError: (34, 'Numerical result out of range') >>>> 1e400 >inf > >When the overflow occurs, the OverflowError exception is thrown. inf can't be the result of a computation (without patch and without catching exception). OK, that's what I thought. I still don't understand why it should default to disabling inf and nan in computation. I've lived without the overflow checking for a year, without noticeable bad effect (with much benefit, of course). Huaiyu From siegfried.gonzi at kfunigraz.ac.at Sat Jun 22 10:43:58 2002 From: siegfried.gonzi at kfunigraz.ac.at (Siegfried Gonzi) Date: Sat, 22 Jun 2002 16:43:58 +0200 Subject: Python hits the spot References: <3D1482AE.8FA299D8@kfunigraz.ac.at> <3D148CD0.4050008@NOSPA_M.online.no> Message-ID: <3D148D2E.3020806@kfunigraz.ac.at> Erlend J. Leiknes wrote: > Siegfried Gonzi wrote: > What do you mean with > "free_software_garbage_2_weeks_installation_nightmare", > Ive never had any problem installing python/idle... Consult the deja news archive and see the many hundred of posts with Tkinter/Tcl/idle problems. And then look for the accompanying Readmes with the Python distribution... >> SWIG helped me to make my external Python C function (with gcc); and >> F2PY helped me to create my external Python Fortran 90 function (with >> the Intel Fortran 95 compiler). > > > Perhaps it wasnt python's fault? > Perhaps it was swig or f2py? No. I have tested the two external functions before and they work. On Windows after the first wavelength the system goes down remarkably but it keeps over water; on Linux Python goes down. S. Gonzi From talon34 at hotmail.com Wed Jun 26 13:30:31 2002 From: talon34 at hotmail.com (Talon) Date: Wed, 26 Jun 2002 17:30:31 GMT Subject: Installation problems DCOracle2 & W2000 References: Message-ID: In article , brueckd at tbye.com wrote: > On Wed, 26 Jun 2002, Talon wrote: > > > I am having a heck of a time getting DCOracle2 to funcion properly. I > > am running on a W2K machine, python2.1.3 and Zope 2.5.1, both of which > > run just fine. I installed DCOracle2 and the ZOracleDA under Zope and > > it works fine. But standalone python scripts don't see the dco2.py > > module. So I tried to install DCOracle2 in the python21/lib folder. I > > got that latest version from Zope.org and it said it installed properly. > > But it doesn't run. If you try to import it into a script, you get > > complaints that it can't find this or that module, all of which are part > > of the Zope path. > > Hi Talon, > > Some of our development machines use the same configuration you list > above. You're probably _very_ close, so I'd stick with DCOracle2 if you > can. Would you mind posting the specific error messages you're getting? > Also, you mentioned that standalone scripts don't work, but just to be > clear, using DCOracle2 in Zope _does_ work without problems? (your > connection object is open, you can browse the database, you can run test > queries, ZSQL methods, etc.) > > If it's working for Zope, then standalone scripts should be able to use > DCO2 if you include the right directory in your PYTHONPATH environment > variable, so please tell us what your PYTHONPATH is too. > > Good luck, > Dave > > > Hi Dave, OK, here you go: Path = C:\Python21\; (I don't have a specific PYTHONPATH variable set. This is in the general PATH variable) The error I get is File "C:\Python21\myfiles\htsa_data_loader_v2.py", line 9, in ? import os,sys,re,string,DCOracle2 File "C:\Python21\DCOracle2\__init__.py", line 91, in ? import DA File "C:\Python21\DCOracle2\DA.py", line 90, in ? from db import DB File "C:\Python21\DCOracle2\db.py", line 89, in ? import DCOracle2, DateTime ImportError: No module named DateTime DateTime is located in C:\Program Files\ZopeDev\lib\python\DateTime are you suggesting that I put the Zope path into the PATH variable as well? DCOracle2 DOES work in Zope, I can do all the things you listed, I have DTML that queries a db and returns the data. By the way, I got things to work well with cx_Oracle this morning, so I do have another option, but I'm very interested in solving this problem. Thanks for your assistance. Mark From garrett at bgb.cc Wed Jun 19 01:23:49 2002 From: garrett at bgb.cc (Don Garrett) Date: Wed, 19 Jun 2002 05:23:49 GMT Subject: What If..... Strong Types References: Message-ID: <3D1014DC.7090600@bgb.cc> brueckd at tbye.com wrote: > On Sun, 16 Jun 2002, Don Garrett wrote: > > I never understood all the hooplah over ints not being classes. I've only > ever seen a handful of cases where it might be useful, and lots of cases > where it'd get abused, but some people really seem to want it. My desire for it is simple desire for orthagonality. The curse of a CS background, I guess. But I'm curious, how could you really abuse it? >> My belief is that almost all the convenience of Python would be >>maintained, but that compilation, optimization, and automated code >>analysis would be simpler. > > > I'm _sort of_ in favor of some optional type annotation for optimization > purposes, and sort of against it, the idea being that after your code is > done you could go back and annotate (or even have a tool suggest > annotation) variables with type information such that you are saying that > a particular variable name will always refer to integers, for example. My > fear, though, is that it would be used too often, i.e. people would > provide type information in places where it wouldn't help at all in terms > of execution speed. One of the beauties of Python is the clean syntax, the > readable code. A good portion of that is the code is not encumbered with > all sorts of variable and type declarations. I like the approach of Pyrex > because it's close to Python but still separate enough to prevent people > from using it too much - if you make it too easy to optimize the code then > people will optimize it too often. Bleh. I have very similar feelings on this. My hope is that high quality compilation could be done without type tagging. I really don't feel comfortable about that, but have some ideas about how to approach it. >> I'm just wondering if the change would be good or bad. Would it really >>break anything important in Python today? > > > You might not consider it important, but it'd break a lot of _my_ code, so > it'd be important to me! :) Python doesn't force you to use all its > dynamic abilities, but I regard that as one of the tools of the Python > toolbox, so yes, I'd be hurt by its removal. What kinds of code would it break? That's what I'm trying to understand. I find that my code doesn't take advantage of these features at all. I use function pointers a lot, but I never change/add/delete methods at run time, and I always define all members in __init__, even if it's just to a default value (or None). Whenever I start to do anything else, it feels hacky and hard to follow. Obviously other people feel differently. >>Would it help with automated code analysis (compilation and optimization >>included) as much as I think it would? > > > Dunno - how much do you think it would? ;-) A better question, is how > often do we really need compilation and optmization at all anyway? If it's > less than 10% (which I believe it is), then the payoff generally wouldn't > be worth language-wide changes. A plain extension module (especially with > the help of Boost, SWIG, PyInline, etc.) isn't too painful, and projects > like Pyrex might have a permanent niche too, but in all cases they are one > step removed from standard Python - which is exactly where they belong. Since what I'm trying (badly) to suggest is discussion of a new language based on Python, but which is compilable..... I'd say it's really needed. As a note, I'm pretty much against adding interfaces to Python. I think it's a matter of adding a feature when it's not needed just because everyone else has them. > -Dave > > > -- Don Garrett http://www.bgb.cc/garrett/ BGB Consulting garrett at bgb.cc From sholden at holdenweb.com Mon Jun 3 08:40:51 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 3 Jun 2002 08:40:51 -0400 Subject: Why no open(f, "w").write()? References: <20020603181332.2975c585.larooy@xtar.co.nz> Message-ID: "John La Rooy" wrote ... > > > > > It is explicitly not a documented part of the interface - the documented > > part is that it is not safe to rely on this behaviour. > > > > When it is explicitly documented that this behaviour is guaranteed now and > > forever, for all implementations of Python after a specified version, I will > > *consider* using this behaviour. Until then it is not worthy of > > consideration. > > > > Tim Delaney > > > > > > It's unlikely to be explicitly documented. from the docs... > > The file() constructor is new in Python 2.2. The previous spelling, open(), > is retained for compatibility, and is an alias for file(). > > So you shouldn't be using open() in new programs anyway > You might want to consider using it for exactly the reason it's been retained: backward compatibility to older versions of Python in use by your potential users. regards -- ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From claird at starbase.neosoft.com Tue Jun 25 17:39:50 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 25 Jun 2002 16:39:50 -0500 Subject: Memory Monitor References: <3D1894B5.720EB7F7@bioreason.com> Message-ID: In article <3D1894B5.720EB7F7 at bioreason.com>, Mitch Chapman wrote: . . . > inf = open("/proc/self/status", "r") > print inf.read() > inf.close() > > >'course, you probably want more concise output, e.g.: > > os.system("cat /proc/self/status | grep VmSize") . . . Rather than os.system("grep VmSize /proc/self/status") ? -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From dyoo at hkn.eecs.berkeley.edu Fri Jun 21 15:46:23 2002 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 21 Jun 2002 12:46:23 -0700 (PDT) Subject: [Tutor] How to find all emails (on the same line) In-Reply-To: <3D12F30D.2071.204353@localhost> Message-ID: On Fri, 21 Jun 2002, A wrote: > I need to find ALL emails in a file. I can use re module but I do not > know how to find all emails if there are more emails on the same > line because re module ( as far as I know )finds only one/first > occurrence on that line. Ah! Try the findall() method from the 're' module: ### >>> def findAllNumbers(line): ... return re.findall(r'\d+', line) ... >>> findAllNumbers("this is a test 42") ['42'] >>> findAllNumbers("this is a test 42 but 43 and 44 are also nice") ['42', '43', '44'] ### Hope this helps! From gerhard at bigfoot.de Mon Jun 17 20:51:06 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Tue, 18 Jun 2002 02:51:06 +0200 Subject: Python Executable Code In-Reply-To: <20020618022953.X15079@prim.han.de> References: <1024357771.569c0ff8rchopra@myrealbox.com> <20020618000621.GA3119@lilith.my-fqdn.de> <20020618022953.X15079@prim.han.de> Message-ID: <20020618005105.GA3468@lilith.my-fqdn.de> * holger krekel [2002-06-18 02:29 +0200]: > Gerhard H?ring wrote: > > Ger'URL-bot'hard > > some day there will be a quick search engine where > people can just type in some keywords and get a good URL. > > oh wait ... Some day there will be method to collect the frequently asked questions from a newsgroup into a searchable interface. http://www.python.org/cgi-bin/faqw.py http://www.python.org/cgi-bin/faqw.py?query=py2exe&querytype=simple&casefold=yes&req=search Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From R.Barrett at ftel.co.uk Wed Jun 26 04:56:33 2002 From: R.Barrett at ftel.co.uk (Richard Barrett) Date: Wed, 26 Jun 2002 09:56:33 +0100 Subject: Python file upload In-Reply-To: Message-ID: <5.1.0.14.2.20020626095102.02a11c78@pop.ftel.co.uk> I think you will find that your calls to cgi.escape the incoming data are the cause of your problem. You do not need to escape incoming multipart/form data. The documentation for cgi.escape says: Use this if you need to display text that might contain such characters in HTML which is clearly not your purpose in handling the incoming data, particularly when it is binary data. At 08:08 26/06/2002 +0000, Bjarne Christiansen wrote: >Hi, >I have some problems uploading binary files though the web browser. It >seens to work fine when uploading ACII file but but binary files seems to >be currupted. The begining of the binary file seems fine, but some data is >missing.... > >Here is my file upload script: > >#!c:\Python\python -d > >import cgi > >print "content-type: text/html\n\n" > >form = cgi.FieldStorage() >if not form: > print """ >
enctype="multipart/form-data"> > > >
> """ >elif form.has_key("filename"): > item = form["filename"] > if item.file: > data = item.file.read() > print cgi.escape(data) > data1 = cgi.escape(data) > f = open("file1.jpg","wb") > f.write(data1) > >Any help will be greatly appriciated! > >Best Regards, >Bjarne Christiansen >bjarne_christiansen at hotmail.com > > >_________________________________________________________________ >MSN Photos is the easiest way to share and print your photos: >http://photos.msn.com/support/worldwide.aspx > > > >-- >http://mail.python.org/mailman/listinfo/python-list From whisper at oz.net Mon Jun 17 19:04:53 2002 From: whisper at oz.net (David LeBlanc) Date: Mon, 17 Jun 2002 16:04:53 -0700 Subject: coding python by web? In-Reply-To: <3eeda89d.0206170317.100549db@posting.google.com> Message-ID: Medusa (http://oedipus.sourceforge.net/medusa/) has an example "scriptserver" that might be what you're looking for. I don't know how it works for sure though. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Thinkit > Sent: Monday, June 17, 2002 4:17 > To: python-list at python.org > Subject: coding python by web? > > > Is there any way to test out simple python code with only a web > browser (no input or files, just printing text)? I'm guessing a > simple cgi setup could do this, but has it been implemented anywhere? > -- > http://mail.python.org/mailman/listinfo/python-list From phd at phd.pp.ru Sat Jun 8 07:22:26 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Sat, 8 Jun 2002 15:22:26 +0400 Subject: Where is Berkeley DB on your system? Can you live without DB 1.85? In-Reply-To: ; from whisper@oz.net on Fri, Jun 07, 2002 at 01:14:59PM -0700 References: <15617.3834.292130.446065@12-248-41-177.client.attbi.com> Message-ID: <20020608152226.E31320@phd.pp.ru> On Fri, Jun 07, 2002 at 01:14:59PM -0700, David LeBlanc wrote: > If Sleepycat will allow it, i'm all in favor of updating to the latest > version! However, they want money for commercial use of versions > 1.85 > AFAIK. They don't. You can freely incorporate BSDDB into an opensource project. http://www.sleepycat.com/faq.html#A22 Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From zopestoller at thomas-guettler.de Fri Jun 28 10:25:17 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Fri, 28 Jun 2002 16:25:17 +0200 Subject: GUI-Control for HTML References: <3D1C4B40.6090803@thomas-guettler.de> Message-ID: <3D1C71CD.6040409@thomas-guettler.de> Gerhard Haering wrote: > In article <3D1C4B40.6090803 at thomas-guettler.de>, Thomas Guettler wrote: > >>Hi! >> >>Is there are GUI-control which can display HTML? >> >>The HTML that will be used will be simple, no javascript or >>form support is needed. >> >>Is there are cross-plattform solution? (Unix + Win32) >> > > Yes, wxPython is available on these platforms, and has a HTML component. There > might be a HTML viewer add-on for Tkinter, too. Has someone tryed gtkHTML? thomas From radix at twistedmatrix.com Thu Jun 6 10:13:37 2002 From: radix at twistedmatrix.com (Christopher Armstrong) Date: 06 Jun 2002 10:13:37 -0400 Subject: array, list, performance... In-Reply-To: <3CFF5F98.2060406@destiny.com> References: <3CFF5F98.2060406@destiny.com> Message-ID: <87sn40xzou.fsf@twistedmatrix.com> > Michael Chermside writes:: > li[n] = x assignment to the middle is O(len(li)) This doesn't seem right. Shouldn't that be O(1), just like access-time? -- Chris Armstrong << radix at twistedmatrix.com >> http://twistedmatrix.com/users/carmstro.twistd/ From mongiaamit at yahoo.com Tue Jun 4 00:05:00 2002 From: mongiaamit at yahoo.com (Amit Mongia) Date: 3 Jun 2002 21:05:00 -0700 Subject: Fatal Python error: GC object already in linked list Message-ID: Hi, I am running a program using pycurl, to upload files on a server. I am using Python 2.2.1. I am using threads and lists in my program. the application just keeps waiting for new files to arrive and uploads them. There are times my program errors out and crashes with this error message. Fatal Python error: GC object already in linked list I am not using the Garbage Collector anywhere in my program. Any idea what can cause this error? Any solutions. I desperately need one. There is nothing given anywhere in any of the books. I am not even sure if its an error with the Garbage Collector. Any comments? Thanks, Amit Mongia From whisper at oz.net Wed Jun 26 18:59:57 2002 From: whisper at oz.net (David LeBlanc) Date: Wed, 26 Jun 2002 15:59:57 -0700 Subject: Pythoniac: Thoughts on a hardware Python processor In-Reply-To: Message-ID: > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Christopher Saunter > Sent: Wednesday, June 26, 2002 3:30 > To: python-list at python.org > Subject: Pythoniac: Thoughts on a hardware Python processor > > > Dear All, > > I have seen the occasional post about creating a specific hardware 'Python > Processor', that could then be built and used in programmable logic or the > like (Valves, relays, core memory - Pythoniac ;-) - in other words, create > a processor that executes Python bytecode directly. There would be > various different reasons for doing this (the 'neat' factor etc...) > I would like to try and implement this, initially in a simulation > environment, then in a real FPGA, with hooks back to a PC allowing the > loading, execution, single step execution and monitoring etc of PBC. > Ideally I would like to reach a state where an interactive interpreter > runs over a serial port... > > So, anyone else interested in this? Comments, suggestions, gaping holes > in my understanding of things as outlined above etc are welcome! > > Regards, > Chris Saunter Have you considered the need for: * Bus control * Interrupts * Memory Management (without even considering pipelining or other performance enhancing techniques) Xilinix makes available a basic FPGA/FPLA design tool for free - an entry level of their full-on product. They are also known to support projects with full copies of their tool and their (not-inexpensive) chips for free. Presumably they do this if they think there might be commercial potential. Here's a starting place: http://www.etek.chalmers.se/~e8cal1/jamcpu.html Introductory survey piece: http://www.eetimes.com/story/OEG20010201S0050 Motherlode of information: http://www.opencores.org/ Includes info on open design tools, most for Linux. 64 bit super-pipelined CPU dev project: http://www.f-cpu.org/ HTH, Dave LeBlanc Seattle, WA USA P.S. Personally, I think a kick-ass true compiler with a retargetable backend would be a better thing to persue. From insyte-clp at emt-p.org Thu Jun 20 18:40:24 2002 From: insyte-clp at emt-p.org (Ben Beuchler) Date: 20 Jun 2002 22:40:24 GMT Subject: M2Crypto / SimpleXMLRPCServer References: Message-ID: In article , Ben Beuchler wrote: > It appears that the SSL part, at least, works great. I'm able to make a > connection using xmlrpclib.ServerProxy("https://blah") but the actual > remote method call hangs indefinitely. > > Is my basic premise flawed? Or just my implementation? FWIW, strace-ing the client and the server indicates that they're both blocking on read()ing from the socket. Of course, since it's all encrypted, I have no idea what they're waiting for... On a related note, anyone know how to get OpenSSL (specifically via M2Crypto) to use a NULL cipher? Being able to dump the traffic with Ethereal or something would be damn spiffy. -Ben -- Ben Beuchler There is no spoon. insyte at emt-p.org -- The Matrix From aahz at pythoncraft.com Thu Jun 6 10:36:56 2002 From: aahz at pythoncraft.com (Aahz) Date: 6 Jun 2002 10:36:56 -0400 Subject: array, list, performance... References: Message-ID: In article , Michael Chermside wrote: > > li.sort() sort is O(len(li)*ln(len(li))) > (I believe it uses quicksort, but if a python > function has to be executed for the compare > that may take some time.) Nope. I forget what Uncle Timmy used as his base, but while the algorithm is O(NlogN) like quicksort, worst-case time is significantly improved over quicksort's worst-case O(N^2), and the algorithm is specifically designed to minimize compares precisely because even if a Python function isn't listed for L.sort(), if L contains Python class instances, it's quite likely to call instance methods. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I had lots of reasonable theories about children myself, until I had some." --Michael Rios From mwh at python.net Thu Jun 20 04:32:04 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 20 Jun 2002 08:32:04 GMT Subject: Windows versions of Python---pros and cons? References: <3D110B55.4D8AD7FA@astro.cornell.edu> <20020619154654.C619@ActiveState.com> Message-ID: Gerhard H?ring writes: > * Trent Mick [2002-06-19 15:46 -0700]: > > My understanding is that for C extensions to work they must be built > > with the same compiler as that used to build the Python with which they > > will run. (I may be wrong. Someone please correct me if I am.) > > You are wrong. As long as you link to the python{major}{minor}.dll you > are binary compatible, no matter which compiler you use. Eh, that's a bit of a stretch isn't it? If your compilers have different ideas about struct layout & so on it would certainly take more effort than just linking the same libraries. > It's just a > matter of providing an additional compiler option to distutils, like in: > > python setup.py build --compiler=mingw32 I do think this works, though. I guess all compiler implementors on Windows try to be compatible with MSVC. Cheers, M. -- Well, you pretty much need Microsoft stuff to get misbehaviours bad enough to actually tear the time-space continuum. Luckily for you, MS Internet Explorer is available for Solaris. -- Calle Dybedahl, alt.sysadmin.recovery From arosado at softhome.net Sat Jun 8 21:03:32 2002 From: arosado at softhome.net (Andres Rosado) Date: Sat, 08 Jun 2002 21:03:32 -0400 Subject: Distributing Packages / os independent installation folder Message-ID: <5.1.0.14.0.20020608210324.00bcff38@mail.softhome.net> At 06:01 AM 6/7/2002 -0400, you wrote: >I'm building a python interface to ImageMagick. I already succeded in >building an installer with distutils, but have some questions regarding >portability: > >- where should my package and shared librarie go to? On windows I put the >dll into python22/DLLs and the rest into a folder >python22/Lib/site-packages/ImageMagick. What to do on other plattforms? I >don't expect a DLLs folder on Linux. ;-) > >- In my __init__.py I have to change one environment variable. Currently I >do it like this: > >import os >os.environ['MAGICK_HOME'] = r'C:\Python22\Lib\site-packages\ImageMagick' >from _ImageMagick import * > >Is there an plattform independent way to get the installation folder of my >package? On windows I can get the python folder from registry, but this will >also break on linux. I'm new at Python, but you could use wrap any platform-dependant code in if statements using the os.name like this: if os.name == 'nt': #Whatever you are going to do in WinNT family pass elif os.name == 'posix': #Whatever you are going to do in Linux pass else: print '''Sorry, we don't support your platform. Maybe continue message here. ''' For the other questions, I don't know. :( ----------------------------------- Andres Rosado Email: andresr at despammed.com ICQ: 66750646 Homepage: http://andres980.tripod.com/ All the world's a stage and most of us are desperately unrehearsed. -- Sean O'Casey From gustav at morpheus.demon.co.uk Wed Jun 12 05:47:21 2002 From: gustav at morpheus.demon.co.uk (Paul Moore) Date: Wed, 12 Jun 2002 11:47:21 +0200 Subject: Python Virtual File System: A spike test References: Message-ID: "Mike C. Fletcher" writes: > Purpose: > > A class for representing file system paths which supports both > method-based operations, and abstraction through object encapsulation to > eventually allow for Virtual File System operations (for instance, > transparently accessing the contents of zip files). [...] > open( ) method for path specifiers [...] > If you're interested in working on such a project (or even using it), > let me know, so I can decide whether to devote any more resources to it. I'm interested, in the sense that I would have a use for a way of doing open() on an arbitrary "path-like" thingy, and getting back a relatively full-featured file-like object, as efficiently as possible. (ie, preferably without grabbing the whole contents of the file into memory and using cStringIO :-)) Most of the rest of the path-manipulation functions are of little interest to me, personally. I would be willing to help in coding the parts I have a use for, but I have limited time. Paul. From mlh at vier.idi.ntnu.no Sun Jun 9 18:57:20 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Sun, 9 Jun 2002 22:57:20 +0000 (UTC) Subject: email: msg.add_payload not synonymous with msg.attach? References: Message-ID: In article , Quinn Dunkan wrote: [snip] >In 1.0 (comes with python 2.2.1), attach is defined as 'attach = add_payload' >so it's synonymous. It also doesn't have any mention of 'add_payload" being >deprecated. I hope it's not really, since I use it all the time. > >CVS is probably not at 1.0 anymore. Probably not. There is a deprecation warning, and they behave differently. Maybe it's a bug in the package -- maybe I'm using it wrong. [snip] >What the error msg probably means is that your message somehow has multiple >payloads, but doesn't have a multipart/* type. Maybe they changed attach >to always make _payload a list or something. Arf... But I don't want a multipart message :| >>(The code is very simple -- basically just instantiating Message and >>adding a payload.) >> >>I'm using the email package from CVS (downloaded everything a day or >>two ago). > >I wouldn't be surprised if the docs are not up to date with the >latest CVS. I'm sure they're not... But this sort of breakage is unfortunate anyway... > You should probably either use 1.0 or check the >Message.py source. I guess so. -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From dreed at capital.edu Sat Jun 29 16:49:17 2002 From: dreed at capital.edu (Dave Reed) Date: Sat, 29 Jun 2002 16:49:17 -0400 Subject: can't import generators In-Reply-To: (aahz@pythoncraft.com) References: Message-ID: <200206292049.g5TKnHx28907@localhost.localdomain> > From: aahz at pythoncraft.com (Aahz) > Newsgroups: comp.lang.python > Organization: The Cat & Dragon > Xref: news.baymountain.net comp.lang.python:170335 > Sender: python-list-admin at python.org > Date: 29 Jun 2002 16:33:50 -0400 > > In article , > John Hunter wrote: > > > >I am having trouble working with generators. Anyone know what might > >cause this behavior: > > > >Python 2.2.1 (#1, Apr 22 2002, 21:20:54) > >[GCC 3.0.4] on linux2 > >Type "help", "copyright", "credits" or "license" for more information. > >>>> from __future__ import generators > >Traceback (most recent call last): > > File "", line 1, in ? > >ImportError: cannot import name generators > > Can't do this in interactive mode. Use a script. Works for me: Python 2.2.1 (#1, May 7 2002, 17:07:14) [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-110)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from __future__ import generators >>> This is a Red Hat 7.3 system with 2.2.1 compiled by me from the .tgz file. Dave From candiazoo at attbi.com Thu Jun 27 13:38:15 2002 From: candiazoo at attbi.com (candiazoo at attbi.com) Date: Thu, 27 Jun 2002 17:38:15 GMT Subject: Most efficient way to write data out to a text file? References: <3d1a6993.248534625@netnews.attbi.com> Message-ID: <3d1b4d29.306797031@netnews.attbi.com> Based on my profile, it looks like several of my functions could be revised. The fix_date_range function converts a string (a year) to an integer, performs a series of tests on it, and ends up returning a string date range (YYYY-YYYY) based on the values... to_string is where I built my output record. I'll try a few things with it... Mike On Thu, 27 Jun 2002 01:28:22 GMT, candiazoo at attbi.com wrote: >I assume some sort of block i/o or preallocating a large block of file space >would be the best way to do it? I am outputting about 700,000 records to a text >file and my program only spits out about 20 records per second. This is using >standard file open and write... > >This is on a W2K machine... perhaps I should use the win32file interface? Any >thoughts/opinions? > >Thank you! > >Mike J. From tdelaney at avaya.com Sun Jun 2 20:31:25 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Mon, 3 Jun 2002 10:31:25 +1000 Subject: Thanks! Message-ID: > From: Banar-Tul [mailto:tonyclick at mindspring.com] > > Ah! That sound you hear is me repeatedly slapping my forehead. Thanks. What type of fish? Tim Delaney From cliechti at gmx.net Sun Jun 30 12:02:26 2002 From: cliechti at gmx.net (Chris Liechti) Date: 30 Jun 2002 18:02:26 +0200 Subject: [Newbie] Is the text delimiter changeable? References: <3d1f26a4.5915886@news.texas.net> Message-ID: baf at texas.net (Ben Fairbank) wrote in news:3d1f26a4.5915886 at news.texas.net: > I have to process large amounts of text and the text includes numerous > apostrophes and quotation marks. It would be very handy if I could > temporarily assign a substitute for Python's use of the caracters " > and ' to delimit text strings. If I could use, for example, the @ > character or the # character, neither of which appears in the text I > have to work with, and if I could disable the " and ' delimiters, then > my task would be greatly simplified. I realize I can backslash escape > these characters in some circumstances, but I do not think that will > work when a user's input is a word such as "can't" or "don't." > Anyway, short of doing something truly drastic, such as recompiling > the system (which I have no intention of doing), is there a workaround > that will permit this? are these text you wan't to process python sources in any way or just normal text? in the later you can load these texts in python strings and there you can have any character without having a special effect. e.g. to replace all "is" in a text with "isn't": out = file("output.txt","w") for line in file("input.txt"): out.write(line.replace("is", "isn't")) #process lines HTH chris -- Chris From bokr at oz.net Thu Jun 6 15:17:31 2002 From: bokr at oz.net (Bengt Richter) Date: 6 Jun 2002 19:17:31 GMT Subject: for , ordering References: Message-ID: On Thu, 6 Jun 2002 17:51:53 GMT, Andrew Koenig wrote: >gabor> for obj1 in objects1: >gabor> objects2.append(obj2(obj1.x)) > > >gabor> 1. isn't there a more elegant way to do this? > >ark> Isn't this the same as saying > >ark> objects2 = objects1[:] > >ark> ? Am I missing something obvious? > Misplaced coffee mug? I know that one ;-) >The answer is yes: I *am* missing something obvious: I didn't >notice the obj2(obj1.x). But why not > > objects2 = map(lambda x: obj2(obj1.x), objects1) Um, objects2 = map(lambda y: obj2(y.x), objects1) ? E.g., (for others ;-) >>> class X: ... def __init__(self,v): self.x=v ... def __str__(self): return '' % self.x ... __repr__ = __str__ ... >>> objects1 = [X(i) for i in xrange(5)] >>> objects1 [, , , , ] >>> def obj2(x): return '' % x ... >>> objects2 = map(lambda y: obj2(y.x), objects1) >>> objects2 ['', '', '', '', ''] > >? >>> map(lambda x: obj2(obj1.x), objects1) Traceback (most recent call last): File "", line 1, in ? File "", line 1, in NameError: global name 'obj1' is not defined I'd second Eric's suggestion though: >>> objects2_eric = [obj2(obj1.x) for obj1 in objects1] >>> objects2_eric ['', '', '', '', ''] Regards, Bengt Richter From xscottgjunk at yahoo.com Fri Jun 28 16:42:42 2002 From: xscottgjunk at yahoo.com (Scott Gilbert) Date: 28 Jun 2002 13:42:42 -0700 Subject: feeding a prompt with python References: <3D1C5341.9070001@huno.net> Message-ID: <79b2b0bb.0206281242.131c385e@posting.google.com> thomas wrote in message news:<3D1C5341.9070001 at huno.net>... > hello, > > is there a way with python to feed a prompt with data? i call sth. with > system($some_cmd) and the cmd gives me a prompt which of course waits > for user input. however i want to automate this, is there a way? > i browsed through the essential reference 2nd edt. but didn't find anything. > > thx, > thomas Look at os.popen(some_cmd). On unixy like places, it will give you a file handle that you can write to. From peter at engcorp.com Sun Jun 2 17:42:38 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 02 Jun 2002 17:42:38 -0400 Subject: string generator References: <3cfa8039_1@news.iprimus.com.au> Message-ID: <3CFA914E.8573BAA2@engcorp.com> Gold Fish wrote: > > I like to create a list of file automatical based on series. For example > user input the number of file say 5. So i want to generate the file > according to this range , this mean the generated files could be > filename1 > filename2 > filename3 > filename4 > filename5 > I using the for loop like that > > for file in range(5): > lis = [file] > string.join('filename',lis[1:]) > how can it didn't work. I am confusing how to do it. The 'for' statement is giving you five passes through the loop, with 'file' set to the integer values 0, 1, ... 4. You put them each time inside a list called 'lis', then take a slice of the list *after* the only element you've put in it. Even if it worked, you would just be throwing away the results of the string.join() since you don't do anything with it. Presumably you are getting an AttributeError as a result. Please *always* post the trackback you get so we know what the exact problem is. Don't make us guess. Anyway, what you want is more like this: for fileIndex in range(5): fileName = 'filename%s' % fileIndex print fileName Now if you want to actually create files with those names, you'll need "file = open(fileName, 'w')" and more. Have you gone through the complete tutorial yet? Something tells me you're missing some of the basics still. -Peter From mark at mceahern.com Wed Jun 12 14:48:40 2002 From: mark at mceahern.com (Mark McEahern) Date: Wed, 12 Jun 2002 13:48:40 -0500 Subject: get a list of classes in this module Message-ID: Suppose I have a list of classes: # validation.py class CreditCardValidation: ... class MasterCard(CreditCardValidation): ... class Visa(CreditCardValidation): ... and I want to make a helper method in the module to translate card type strings into their appropriate class constructor. # someother.py def validate(card_number, card_type=None): import validation import inspect classes = inspect.getmembers(validation, inspect.isclass) class_dict = dict(classes) if not class_dict.has_key(card_type): # use generic validation c = validation.CreditCardValidation() else: c = class_dict[card_type]() c.card_number = card_number c.validate() I know I can use inspect.getmembers() to do this, but what if I want to put the helper method in the same file as the classes (i.e., validation.py)? How do I refer to *this* module? Why do I want the helper in the same module? Well, heck, why not? ;-) Should I use globals()? I mean, that would work--so I guess the question is whether there's a more Pythonic approach? Cheers, // m - From peter at engcorp.com Fri Jun 21 09:30:36 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 21 Jun 2002 09:30:36 -0400 Subject: Dispatching a Win32 COM in the background? References: Message-ID: <3D132A7C.94CE4670@engcorp.com> David LeBlanc wrote: > > Hmmm... if this is working for you, that's great - it just looks strange to > me. > > If Background_TTS is the background speacher thread, shouldn't it have the > queue.get() in it and the foreground have the queue.put()? > > It's also worth noting that self isn't used or needed at the global level, > so self.speech is kind of different ;-) I'm pretty sure from previous postings he was going to call this from within another object, so the "self." used elsewhere might refer to it. As near as I can tell, with that in mind, the .get() and .put() are in exactly the right places. -Peter From aahz at pythoncraft.com Fri Jun 21 14:45:34 2002 From: aahz at pythoncraft.com (Aahz) Date: 21 Jun 2002 14:45:34 -0400 Subject: [newbie] Overwriting class definitions References: Message-ID: In article , Sean 'Shaleh' Perry wrote: > >I find that existing the interpreter is the safest thing to do while doing >interative coding like this. s/existing/exiting/ And I generally work from the command line, running a script over and over rather than going back into the interpreter and retyping stuff. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From jepler at unpythonic.net Sat Jun 1 10:03:16 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Sat, 1 Jun 2002 09:03:16 -0500 Subject: Behavior of += (was Re: [Python-Dev] Customization docs) In-Reply-To: <07d801c20970$cdebe050$6601a8c0@boostconsulting.com> References: <06da01c208f4$d69003c0$6601a8c0@boostconsulting.com> <200206010121.g511LxX19223@pcp742651pcs.reston01.va.comcast.net> <073501c20960$23f367e0$6601a8c0@boostconsulting.com> <200206011334.g51DY1D21669@pcp742651pcs.reston01.va.comcast.net> <07d801c20970$cdebe050$6601a8c0@boostconsulting.com> Message-ID: <20020601090316.A10396@unpythonic.net> On Sat, Jun 01, 2002 at 09:32:39AM -0400, David Abrahams wrote: > My question was about what a new type needs to do in order for things to > work properly in Python. If, as I had incorrectly assumed, Python were > checking a type's mutability before deciding whether it would be putting > the result back into the sequence, I would need to know what criteria > Python uses to decide mutability. IMO the following is an odder behavior: >>> t ([1], [2], [3]) >>> t[1] += [3] Traceback (most recent call last): File "", line 1, in ? TypeError: object doesn't support item assignment >>> t ([1], [2, 3], [3]) Jeff From hfoffani at yahoo.com Thu Jun 20 12:17:04 2002 From: hfoffani at yahoo.com (nntpserver.pppl.gov) Date: Thu, 20 Jun 2002 18:17:04 +0200 Subject: Useful RE patterns (was: Variable Interpolation - status of PEP 215) References: <4PfQ8.44245$n4.10307683@newsc.telia.net> Message-ID: <3D120000.40905@yahoo.com> Fredrik Lundh wrote: > If I were to add a dozen (or so) patterns to the (S)RE module, > what should I pick? What patterns do you find yourself using > over and over again? Most of the time whenever I use regexes I'm trying to solve specific problems. But what comes to mind are lexers-token-like patterns: identifiers, numbers (ints, floats), strings (yes, know :-) They don't have to be _perfect_ to be useful. In fact, laziness takes me to steal them from other places. Regards, -Hernan From dswegen at software.plasmon.com Thu Jun 27 10:23:08 2002 From: dswegen at software.plasmon.com (Dave Swegen) Date: Thu, 27 Jun 2002 15:23:08 +0100 Subject: Difference between HTMLParser and htmllib.HTMLParser In-Reply-To: References: Message-ID: <20020627142308.GD15813@software.plasmon> On Thu, Jun 27, 2002 at 02:14:35PM +0000, Emile van Sebille wrote: > "Dave Swegen" wrote in message > news:mailman.1025178934.31606.python-list at python.org... > > I've just started playing with these, and I'm curious which is the > > better of the two (I noticed the HTMLParser module only came in in > 2.2). > > And is there any reason why the names are so confusingly similiar? I > > tried searching in google for info on this, but the daft naming made > it > > rather hard ;) > > [ helpful explantion stuff removed ] Cheers. That was exactly the sort of info I was looking for. I just wasn't sure which one to use. Cheers Dave From peter at engcorp.com Tue Jun 18 20:44:47 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 18 Jun 2002 20:44:47 -0400 Subject: NEWbie asks "is Python a good tool for automated file/folder generation?" References: <3D0E8773.A1BA95ED@engcorp.com> <3D0F5967.2A9CEE86@noaa.gov> Message-ID: <3D0FD3FF.49FBDFE0@engcorp.com> Chris Barker wrote: > > Peter Hansen wrote: > > Better to learn to use raw-strings, with an "r" in front, > > as in path = r"c:\this is a safe path" or better yet, > > either forward slashes always: path = "c:/this works too". > > Or even better, use os.path.join(), you never know when you will > encounter a Mac. (of course, if it's OSX, the above will work as well) I started writing that, then went to the interactive prompt and concluded (after brief experimentation) that there was no way to join the "c:" and the "this works too" portions of the path without explicitly specifying a "/" to force it to be an absolute path. Doubtless I did something wrong, but I decided to avoid the issue by skipping any mention of os.path.join(). Of course, since drive letters are not portable anyway this is all a moot point. For any hardcoded path like that, you can't have a very good cross-platform solution I suppose. -Peter From bkc at Murkworks.com Mon Jun 3 11:04:13 2002 From: bkc at Murkworks.com (Brad Clements) Date: Mon, 3 Jun 2002 11:04:13 -0400 Subject: Interfacing to 1-Wire LAN, especially Dallas temperature sensors? References: <3CF82E8E.23C6FA10@engcorp.com> Message-ID: <3cfb83e2$1_4@goliath.newsgroups.com> There is a technique where you can use a UART at some whacky baud rate and bits/byte setting to communicate. There's an APPNOTE somewhere, I don't have it handy. -- Novell DeveloperNet Sysop #5 _ "Peter Hansen" wrote in message news:3CF82E8E.23C6FA10 at engcorp.com... > Christian Aastorp wrote: > > > > I'm considering doing some temperature control and logging, both > > enviromental and inside computers. Did a google search, and found > > references to the range of temperature sensors from Dallas > > Semiconductors. > > > > I also found schematics for interfacing with the serial port, and > > timing diagrams for implementing 1-Wire Lan using direct control of > > the port. > > > > As I'm using Python for my programming, these days, I would like some > > pointers to modules or techniques to use Python to read the > > temperature sensors. > > Although I have not tried it with Python, and I would never say > something is impossible without more study, I am _fairly_ sure you > cannot do this reliably with Python. > > The Dallas 1-Wire chips have protocol timing requirements somewhere > down in the low _tens_ of microseconds. This requires some kind of > real-time code and not only is Python itself unlikely to have > high enough performance on almost any current machine, but the > OS you're running it on is even less likely to support the > necessary latency. > > We've been struggling just to get a 16MHz 68HC12 working with > these things, without having to disable interrupts for hundreds > of microseconds at a time. It hasn't been easy. > > It might be very instructive to try, however, and I'd be happy > to hear somebody say they'd proven me wrong (and curious what > was done to reach a solution). > > -Peter -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From aahz at pythoncraft.com Wed Jun 19 15:19:52 2002 From: aahz at pythoncraft.com (Aahz) Date: 19 Jun 2002 15:19:52 -0400 Subject: Pop a list from beginning ? and memory saving... References: Message-ID: In article , James T. Dennis wrote: > > It might be better to have a hack to the implementation of the > list primitives --- so they defer the shift of remaining elements > until GC. The head of the list could point at the first none > deleted item. Then pop(0) could be implemented in O(1) time and > the garbage collector would eventually come along to do it's > job. While this might be a worthwhile optimization, it has absolutely nothing to do with GC. Each time an element were popped off the front, its object would be decreffed and possibly deleted. GC runs completely independently of individual objects. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From stefan1werner at hotmail.com Tue Jun 11 16:34:52 2002 From: stefan1werner at hotmail.com (Stefan Werner) Date: Tue, 11 Jun 2002 22:34:52 +0200 Subject: Embedding Python 2.2 in non-reentrant application Message-ID: Hi group, I am working on embedding Python 2.2 in a large scale application. Now the problem is, that Python 2.2 supports multithreading, where the functions we want to expose to Python are not threadsafe. Is there something like a flag to make my whole module single-threaded for Python access or do I have to wrap every single function call in Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADS macros? Thanks, Stefan From benji_york at cknainc.com Thu Jun 27 09:18:28 2002 From: benji_york at cknainc.com (Benji York) Date: 27 Jun 2002 06:18:28 -0700 Subject: printing (again!!) References: Message-ID: "Geoff Tarrant" wrote in message news:... > I want to use Python as the language in a Computing course that I teach. > However, I can't find a way that is relatively straightforward to send data > to a printer in a Windows environment. If you have a recent win32all installed, then the function below will send plain text (requires both carrage returns and line feeds) to the printer. You can also throw in some PCL if you like, but for more complex stuff I would use some of the suggestions seen elsewhere in this thread (PDF or wxPython (especially it's HTML printing functions)). import win32print def rawPrint(data, jobName, printerName=None): if printerName == None: printerName = win32print.GetDefaultPrinter() printerHandle = win32print.OpenPrinter(printerName) printJob = win32print.StartDocPrinter(printerHandle, 1, (jobName, None, None)) win32print.WritePrinter(printerHandle, data) win32print.EndDocPrinter(printerHandle) win32print.ClosePrinter(printerHandle) happy-printing-ly y'rs, Benji York benji_york at cknainc.com From Sascha.Ferley at infineon.net Sun Jun 23 15:52:29 2002 From: Sascha.Ferley at infineon.net (Sascha Ferley) Date: Sun, 23 Jun 2002 13:52:29 -0600 Subject: PIL, Python and CGI Message-ID: <3D1626FD.DA934B09@infineon.net> Hi, I have a problem when writing a program of mine and moving it into a CGI based form. Basically if i run the python program in shell mode, it works fine. But when i run it via cgi mode it screws up horobly. The problem is, I am using the function from the PIL library as follows. import sys import cgi import Image from urllib import urlretrieve form = cgi.FieldStorage() inputPath = form["inpP"].value compPath = form["secP"].value try: im1 = urlretrieve(inputPath)[0] im2 = urlretrieve(compPath)[0] print im1 print im2 except: print "Error occured in grabbing files!" sys.exit(1) try: Image1 = Image.open(im1) # Tried Image.open(im1).histogram() still gives error Image2 = Image.open(im2) except: print "Error opening files" sys.exit(1) print image1.histogram() print image2.histogram() Looking at the error-log i see just following: Traceback (most recent call last): File "/export/server/web/cgi-bin/compare.py", line 29, in ? print image1.histogram() File "/usr/local/lib/python2.2/site-packages/PIL/Image.py", line 577, in histo gram self.load() File "/usr/local/lib/python2.2/site-packages/PIL/ImageFile.py", line 126, in l oad self.load_prepare() File "/usr/local/lib/python2.2/site-packages/PIL/ImageFile.py", line 180, in l oad_prepare self.im = Image.core.new(self.mode, self.size) File "/usr/local/lib/python2.2/site-packages/PIL/Image.py", line 39, in __geta ttr__ raise ImportError, "The _imaging C module is not installed" ImportError: The _imaging C module is not installed Anyone have any ideas? Sascha From fperez528 at yahoo.com Thu Jun 20 17:51:35 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Thu, 20 Jun 2002 15:51:35 -0600 Subject: logical statements (in Python and Numeric) References: <3D11F1B2.21587F31@lanl.gov> <3D122C5D.C6985686@noaa.gov> <3D124BEF.9EC71977@noaa.gov> Message-ID: Chris Barker wrote: > oops, that's what I get for posting untested code. You need parentheses, > the above was trying to bitwise-and -2.0 and x > > (x >= -2.) & (x < 0.) > works. > Ah, thanks. That actually makes the code almost like the OP's (moudulo the necessary parens). An it looks nicer than the logical_and() variation. Somethin new learned, thanks a lot. f. From aahz at pythoncraft.com Sat Jun 22 15:14:16 2002 From: aahz at pythoncraft.com (Aahz) Date: 22 Jun 2002 15:14:16 -0400 Subject: Python hits the spot References: <3D1482AE.8FA299D8@kfunigraz.ac.at> <3d149f19$0$53133$edfadb0f@dspool01.news.tele.dk> <3D14AD7F.3D5D243F@engcorp.com> Message-ID: In article <3D14AD7F.3D5D243F at engcorp.com>, Peter Hansen wrote: >Aahz wrote: >> In article <3d149f19$0$53133$edfadb0f at dspool01.news.tele.dk>, >> Frihtiof Andreas Jensen wrote: >>> >>>My bet is that once you cool off and sits down with some debugging tools >>>like GDB, Boundschecker or Electric Fence you will indeed find the >>>programming error and fix it. >>> >>>My bet is also that you will not tell anyone either. >> >> Ya know, you could have saved yourself a lot of typing by simply saying >> PBCAK. ;-) > >To save us from those who can't Google: Problem Between Chair And Keyboard. >(It was new to me, too.) Ya coulda ast me, too. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From mark at mceahern.com Tue Jun 25 09:26:53 2002 From: mark at mceahern.com (Mark McEahern) Date: Tue, 25 Jun 2002 08:26:53 -0500 Subject: import precedence Message-ID: Suppose I have a package like this: spam/ __init__.py setup.py foo.py For cygwin, setup.py creates: foo.dll For linux2, setup.py creates: foo.so But for win32, setup.py is basically a no-op because I can do what I need to do in foo.py using pythoncom. Here's the question: Can I just assume that: from spam import foo will only import the foo.py module if the foo.dll and foo.so are not found--that is, if the import statement is executed on win32 (where those extensions won't exist)? I looked at the documentation for import and it's not clear to me that it addresses this issue. Perhaps because noone in their right mind would consider this approach? ;-) Thanks, // mark - From nadavh at envision.co.il Tue Jun 18 11:03:46 2002 From: nadavh at envision.co.il (Nadav Horesh) Date: Tue, 18 Jun 2002 17:03:46 +0200 Subject: Distutils for python 2.2.1 under win2000: util.py patch Message-ID: <3D0F4BD2.5060100@envision.co.il> Hi! I had problems installing Gnuplot1.5 package under python2.2.1. I got an error which was a result of calling distutils.util.convert_path with an empty string argument. To correct the problem I added if len(pathname ) == 0: return pathname as the first executable statement in that function. After that the Gnuplot installation completed succesfully. The question: Is it a legal path to keep (did I corrected a bug or just generated a new one)? Nadav. From huaiyu at gauss.almadan.ibm.com Fri Jun 21 13:25:25 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Fri, 21 Jun 2002 17:25:25 +0000 (UTC) Subject: How to represent the infinite ? References: Message-ID: >[Christophe Delord] >> ... >> >>> 1e200**2 >> Traceback (most recent call last): >> File "", line 1, in ? >> 1e200**2 >> OverflowError: (34, 'Numerical result out of range') >> >>> 1e400 >> inf >> >> When the overflow occurs, the OverflowError exception is thrown. >> inf can't be the result of a computation (without patch and >> without catching exception). The patch is in fact very simple: just remove the extra code whose sole purpose is to throw an exception. No patch to catch the exception is needed. Tim Peters wrote: > >It can, but it's a x-platform crapshoot as to exactly how. For example, >under current Windows CVS, this still "works": > >>>> 1e300 * 1e300 >1.#INF >>>> > >Here's a clumsier way : > >>>> 1.6e308 + 1.6e308 >1.#INF >>>> > >Both of those assume the user hasn't installed and enabled the fpectl >module, whose purpose in life is to cause even this to complain. > >maybe-number-crunchers-will-agree-on-something-after-i'm-dead- > but-i'm-not-holding-my-breath-ly y'rs - tim Now I'm confused. I thought from previous discussions that you intended to disable inf and nan until full ieee floating point compliance is implemented in Python. And I infered that that's in order to make Windows work. Since it could be made to work on Linux, I simply commented out the checking in pyport.h. Voila, instant ieee compliance! Your example appears to show that Windows can also live with nan and inf. So my question is, are there any significant platforms out there that still really need such checkings which make nan and inf almost useless? If, in reality, only some very niche platforms need such checkings, maybe it is better to let those platforms without ieee compliance suffer (in terms of having to add a small patch), rather than depriving most of the mainstream platforms of a very useful feature? I'm looking forward to the day when I don't need to patch Python when a new version comes out. Huaiyu From john at johnnypops.demon.co.uk Mon Jun 17 19:30:57 2002 From: john at johnnypops.demon.co.uk (John Popplewell) Date: 17 Jun 2002 16:30:57 -0700 Subject: tray icon using tkinter References: Message-ID: Anoop P B wrote in message news:... > hi, > > is there a way that i can provide a tray icon ie. next to the clock (on > win32) for my program (using tkinter) ? i know that there is a way of > doing this in wxpython but i need to know whether its possible in tkinter. > > thanks, > anoop Have you had a look at "Tray It!" ? http://www.teamcti.com/trayit/index.html cheers, John. From loewis at informatik.hu-berlin.de Thu Jun 6 04:37:42 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 06 Jun 2002 10:37:42 +0200 Subject: libpython as a shared library? References: <20020604143402.GB22993@hal.mediasupervision.de> Message-ID: Gregor Hoffleit writes: > If I compile the sources with -fPIC, but put them in a static library, > there's nearly no speed difference to non-PIC code in a static library. > My best guess is that the speed penalty is caused by the indirection > step that's necessary when calling routines from a shared lib; but then, > that's no real explanation for a loss of 30% speed! Can you elaborate a bit what you measured to get that speed difference? If it involves startup time, the time for locating libpython surely involves part of startup time. Also, it might be necessary to perform many relocations to libpython at run time that might not be necessary for the application. Regards, Martin From emile at fcfw.fenx.com Mon Jun 17 16:30:17 2002 From: emile at fcfw.fenx.com (Emile van Sebille) Date: 17 Jun 2002 15:30:17 -0500 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 17) Message-ID: <52F61289899FD9D9.327A292D46CD5CB7.E0BCFB87CA7B8ABD@lp.airnews.net> QOTW: "People will inevitably associate me with my father, but I would not have anyone believe that I am trading on the name Edison. I would rather have you know me merely as the result of one of my father's earlier experiments." - Charles Edison (son of the inventor), during his campaign for governor of New Jersey in 1940 http://theliterarylink.com/quotes.html "Sprinting is intense and exhilarating. Everybody bounces questions and ideas off of each other while sitting in front of real, evolving code. You learn about coding practices such as unit tests and factoring interface descriptions, as well as real Zope 3 component architecture code. But far more interesting is the human interaction." -- Paul Everitt, quoted from http://europython.zope.nl/interviews/entries/paul_everitt Happy Father's Day - Guido's First! Watch for photos at: http://www.python.org/~guido/orlijn/#latest Collin Monahan asks about the nature of lists: http://groups.google.com/groups?threadm=mailman.1023833476.10249.python-list at python.org Fabio Corneti wants a way to create final methods, and Jeff Epler shows one way to do it: http://groups.google.com/groups?threadm=mailman.1023812475.3715.python-list at python.org Edward K Ream announces leo, a programmer's editor and a flexible browser for projects, programs, classes or data. Leo clarifies design, coding, debugging, testing and maintenance. http://groups.google.com/groups?selm=mailman.1023895323.9169.clpa-moderators at python.org Jerzy Karczmarczuk provides a different answer to the question of creating executables from python source by pointing us to an interview of Guido: http://groups.google.com/groups?selm=3CFDF148.AA2035FF at info.unicaen.fr Prabhu Ramachandran announces the availability of the MayaVi Data Visualizer version 1.2. MayaVi is a free, easy to use, scientific data visualizer, written in Python and using VTK, the Visualization Toolkit. One significant change is a license change from GPL/LGPL to BSD. http://groups.google.com/groups?selm=mailman.1023914707.18194.python-list at python.org "You knew the job was dangerous when you took it, Fred." James Rowe asks about documentation on __subclasses__... http://groups.google.com/groups?selm=a9bcagho74.22t.jimrowe at optilink.com ...a question still open in the in-progress Thinking in Python book... http://www.mindview.net/Books/TIPython/BackTalk/A_251 ...but I did find some documentation (thanks google), including another new-class built in method, mro (method resolution order) at: http://cvs.astro-wise.org:4711/__builtin__.html#type Neil Schemenauer releases Version 0.1 of the Sancho unit testing framework, the unit test module in use at the MEMS Exchange: http://groups.google.com/groups?selm=mailman.1024086967.9147.clpa-moderators at python.org Anoop is looking for a way to create a systray icon on win32 using tkinter. Interesting question -- any answers? http://groups.google.com/groups?selm=mailman.1023950718.20009.python-list at python.org Greg Ewing is working to speed things up with pyrex release 0.3. Pyrex is a new language for writing Python extension modules. http://groups.google.com/groups?selm=mailman.1023502562.5896.clpa-moderators at python.org Jean-Sebastien Bolduc wants to understand about import * and namespaces... http://groups.google.com/groups?selm=56e1eff0.0206131437.4ca8ed9e at posting.google.com ...prompting Tim Delaney to point to section 1.1 at http://py-howto.sourceforge.net/doanddont/doanddont.html Aahz reminds us that a failed import doesn't get better with repeated imports... http://groups.google.com/groups?selm=aeat13$pli$1 at panix1.panix.com ... and questions a class/type unification bu^h^hfea^h^h^h... well, a 'gotcha: http://groups.google.com/groups?threadm=aeau48$111$1 at panix1.panix.com Neal Josephson announces that Version 2.1 of the Hap python debugger and IDE has been made available for download as source and binary zip files at: http://sourceforge.net/projects/hapdebugger PythonCard, a GUI construction kit for building cross-platform desktop applications on Windows, Mac OS X, and Linux, moves to version 0.6.7. New additions include chat, webserver, pictureViewer, slideshow, and webgrabber. See Kevin Atlis' announcement at: http://groups.google.com/groups?selm=gyoO8.45$YM3.33091 at news.uswest.net Wow. Check out Dave's (age 12) request for help. Note particularly the responses given... and more particularly the responses _not_ given. It's good to here... http://groups.google.com/groups?threadm=Xns922D5FE7B72D8duncanrcpcouk%40127.0.0.1 ...and Duncan Booth provides a link to the LiveWires Python course, intended to teach the Python programming language to people who have never programmed before: http://www.livewires.org.uk/python/index.html ======================================================================== Everything you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Michael Hudson continued Andrew Kuchling's marvelous tradition of summarizing action on the python-dev mailing list once every other week, into July 2001. Any volunteers to re-start this valuable series? http://starship.python.net/crew/mwh/summaries/ http://www.amk.ca/python/dev The Vaults of Parnassus ambitiously collect Python resources http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Links2Go is a new semi-automated link collection; it's impressive what AI can generate http://www.links2go.com/search?search=python Tenth International Python Conference http://www.python10.org Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. [http://www.egroups.com/list/python-url-leads/ is hibernating. Just e-mail us ideas directly.] To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From dougz at cs.washington.edu Wed Jun 19 22:57:01 2002 From: dougz at cs.washington.edu (Douglas Zongker) Date: Thu, 20 Jun 2002 02:57:01 GMT Subject: using os.chmod in windows References: <3D110C99.5090607@portzer0.virtualave.net> Message-ID: Locke wrote: : I need to change a file to be 'hidden' in windows. [...] So how : do I do this? If you have the win32 extensions that come with ActivePython [aspn.activestate.com], then you can do: import win32api, win32con def hide_file( fn ): x = win32api.GetFileAttributes( fn ) x |= win32con.FILE_ATTRIBUTE_HIDDEN win32api.SetFileAttributes( fn, x ) def unhide_file( fn ): x = win32api.GetFileAttributes( fn ) x &= ~win32con.FILE_ATTRIBUTE_HIDDEN win32api.SetFileAttributes( fn, x ) dz From kragen at pobox.com Mon Jun 24 18:00:55 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 24 Jun 2002 18:00:55 -0400 Subject: Generic Python References: <3D16E465.F0D2509E@ifib.uni-karlsruhe.de> Message-ID: <83ptygl4ko.fsf@panacea.canonical.org> Uwe Mayer writes: > The problem is that I've got a base class and there should be many > subclasses of it. Each subclass just overwriting an output method and > serving as a template: > ... > Is there another way to solve this problem? Several people have offered ways to do this with metaclasses or run-time code generation with exec, but I agree with Michael Chermside that you should use a factory function or just override the output method on individual instances instead. From drifty at bigfoot.com Mon Jun 3 17:54:10 2002 From: drifty at bigfoot.com (Brett C.) Date: 3 Jun 2002 14:54:10 -0700 Subject: ANN: Pure Python strptime() Message-ID: Out of frustration of not always having strptime() available and not liking something in the standard library saying something is only available on "Most modern Unix systems" when it does not have to be this way, I wrote strptime() in pure Python (requires Python 2.2 or higher; if there is enough demand I could back-port to older versions since most of the 2.2 capabilities used were for convenience of performance issues). The module can be found at the Python Cookbook at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/56036 . I wrote strptime() before (over a year ago), but I got around to rewriting it finally and removing any dependence on the programmer knowing any locale-specific info ahead of time. Now you do not need to enter any locale-specific information; you can use the function just like the version that is in the time module. There is some extra functionality, though, so look at the recipe to see what extras are available (performance and locale abilities). I personally would like to see this included in the standard library since it is a nice function to have. How should I go about this? Since the time module is a C extension, I realize that this can't just be pasted into it. Does this mean that I am going to have to write a PEP to request that this be added as a module in the standard library? Do I just need to convince Guido to include it? Do I need to push to change the time module into a Python module with the current module renamed _time and then just have a stub module to globally import the _time module? I have posted this as a patch at SF (patch #474274), but I am wondering if I have to do anything that I just previously mentioned on top of this. Any guidance on this would be helpful. Thanks. -Brett C. From tlirobot at tlirobotics.cc Wed Jun 12 19:14:37 2002 From: tlirobot at tlirobotics.cc (Dylan Appleman) Date: Wed, 12 Jun 2002 23:14:37 GMT Subject: Best Hosting Package - 22810 References: Message-ID: HOSTING @ BSolution UNIX Servers "Best Solution" wrote in message news:sGIN8.301359$t8_.51255 at news01.bloor.is.net.cable.rogers.com... HomePage Programming Web-Design Networking Careers About Us Hosting Sign Up Form Sign Up Now! HOSTING PRICES Service Package Base Business Professional Monthly $8 $15 $30 Annual $75 ($6.25/mo) $130 ($10.83/mo) $250 ($20.83/mo) Setup Fee no no $20 Disk Space 30 MB 100 MB 500 MB Traffic unlimited unlimited unlimited Support ASP 3.0 / ASP .NET no no yes PERL (CGI) yes yes yes PHP 4.x Support yes yes yes MS Access DataBases no no yes MySQL 2000 yes yes yes E-mail boxes 10 50 200 SSI Support yes yes yes FTP yes yes yes Statistics and .log access yes yes yes SSL Support no yes yes Password directories no yes yes E-MAIL PRICES E-Mail Setup Fee free Monthly payment no OTHER SERVICES Domain name registration (.com, .net, .org, cc, .info, .biz) $20 Domain name: YOURNAME.bsolution.net free On-Line Web Store Support $15/mo SPAMMER!!!!! -------------- next part -------------- An HTML attachment was scrubbed... URL: From huaiyu at gauss.almadan.ibm.com Tue Jun 4 21:06:42 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Wed, 5 Jun 2002 01:06:42 +0000 (UTC) Subject: Behavior of += (was Re: [Python-Dev] Customization docs) References: <3CFCF3E7.AE891EBE@noaa.gov> Message-ID: [Huaiyu Zhu] > This is not unlike the situation of the > division operator with distinct behaviors on floats and ints. [Chris Barker] I suppose that is a pretty good parallel, but not quite the same, as the behavior of += is much more similar for the different types ... [Huaiyu Zhu] In fact, the behavior of += is even more different in different situations. Integer division sometimes equals real division, but modification in an object is never the same as modification in namespace. In-place modification affects all names referencing the same object, as the following example shows [Steve Holden] >>> a = b = (1, 2, 3) >>> a += ('boo!',) >>> a, b ((1, 2, 3, 'boo!'), (1, 2, 3)) >>> a = b = [1, 2, 3] >>> a += ['boo!'] >>> a, b ([1, 2, 3, 'boo!'], [1, 2, 3, 'boo!']) [Donn Cave] Well, it is consistent. Maybe not in a way that you can see and still remain sane. "Mutable" or not, it must always work like "a = iadd(a, b)", where iadd attempts to perform some computation like __iadd__() or eventually "+". [Huaiyu Zhu] That "must" is only an artifact of trying to incorporate rebinding increment for the sake of immutables. It is similar to that / "must" return an integer for integer oprerands. [Huaiyu Zhu] It is interesting to spell out the analogy with integer division: - Real division is not well defined for integers (if result must be integer). - Integer division is a useful approximation that works for intergers. - Integer division is also meaningful for reals, but it is different from real division. - Python uses the same symbol / for both operations depending on operarands, causing quite some inconsistency and confusion. - The solution is to use / for real division only, while introducing another operator // for integer division. - In-place increment is not well defined for immutables. - Rebinding increment is a useful approximation that works for immutables. - Rebinding increment is also meaningful for mutables, but it is different from in-place increment. - Python uses the same symbol += for both operations depending on operands, causing quite some inconsistency and confusion. - The solution might be to use += for inplace increament only, while introducing another operator (?) for rebinding increment. Chris Barker gave details of several kinds of inconsistencies. [Donn Cave] Not really - the current semantics are actually better than the fixed version, inasmuch as they are at least consistent. As I interpret the proposal, the fixed += would sometimes work without rebinding (if the object supports it) and sometimes would be an assignment (falling back to +.) To me, to allow an object to dictate its relationship to its computational environment like that is anathema. [Huaiyu Zhu] That is one proposal. My proposal is to disallow += for immutables. Another symbol would be used for rebinding operations. (Or maybe swap the role of these symbols.) Thus for mutables both operations would be available. No, 'a=a+b' is not enough for rebinding, as the following shows: [Bengt Richter] >>> foo()[0]+=1 side effect >>> foo()[0] = foo()[0]+1 side effect side effect Huaiyu From johnroth at ameritech.net Mon Jun 3 18:32:34 2002 From: johnroth at ameritech.net (John Roth) Date: Mon, 3 Jun 2002 18:32:34 -0400 Subject: Behavior of += (was Re: [Python-Dev] Customization docs) References: <06da01c208f4$d69003c0$6601a8c0@boostconsulting.com> <200206010121.g511LxX19223@pcp742651pcs.reston01.va.comcast.net> <073501c20960$23f367e0$6601a8c0@boostconsulting.com> <200206011334.g51DY1D21669@pcp742651pcs.reston01.va.comcast.net> <07d801c20970$cdebe050$6601a8c0@boostconsulting.com> Message-ID: "Steve Holden" wrote in message news:oWIK8.179611$%u2.31494 at atlpnn01.usenetserver.com... > "Emile van Sebille" wrote ... > > wrote: > > > IMO the following is an odder behavior: > > > >>> t > > > ([1], [2], [3]) > > > >>> t[1] += [3] > > > Traceback (most recent call last): > > > File "", line 1, in ? > > > TypeError: object doesn't support item assignment > > > >>> t > > > ([1], [2, 3], [3]) What I believe is going on here is that the list t[1] is being updated since it's mutable, and then the attempt to insert the new version of the list into the tuple is being rejected - hence the error. The fact that it shows the change is most likely due to the list not having moved in memory. I hope that the reference count was handled properly! AFIC, this is clearly wrong - operators should be atomic - no side effects. Either they work, or they don't. > > > > Here's another that's differently wrong: > > >>> a = ('aaa',) > > >>> a[0]+='bbb' > > Traceback (most recent call last): > > File "", line 1, in ? > > TypeError: object doesn't support item assignment > > >>> a > > ('aaa',) > > >>> This is the exact same case, except that instead of a list, the tuple contains a string - another immutable type. Therefore, it fails on attempting to update the string, rather than attempting to update the tuple. Maybe. It might actually update the string, producing 'aaabbb' at a different location in memory, and then (properly) fail to update the tuple. John Roth From gbien at intekom.co.za Tue Jun 11 14:14:53 2002 From: gbien at intekom.co.za (Geoff Bien) Date: Tue, 11 Jun 2002 20:14:53 +0200 Subject: unknown opcode Exception then AV References: Message-ID: Found the problem. There is a known bug in version 2.1 ?? when "continue" is used within a try...except block From db3l at fitlinxx.com Mon Jun 10 15:35:20 2002 From: db3l at fitlinxx.com (David Bolen) Date: 10 Jun 2002 15:35:20 -0400 Subject: Python 2 Monolithic Executable References: Message-ID: Anoop P B writes: > I need to write a program which will take user input and mail it to a > predesignated email address. The constraint is that it needs to be a > single, small executable (without requiring installation and no > dependencies) (Windows). Is there a way to create such an executable > from a python program? Gordan McMillan's installer package [1] supports creating a single executable. It's actually an archive in the form of an executable, and when it runs, it unpacks temporary copies of external DLLs or files that it needs, and the files are removed when the application exits. The end user need not know about this - so to them it can look just like a single executable to run. You're probably going to have a tough time with "small" though depending on your definition. A minimum application is likely to be around 450-500KB, since it has to include at least the Python DLL and whatever libraries you use. [1] http://www.mcmillan-inc.com/install1.html -- -- David -- /-----------------------------------------------------------------------\ \ David Bolen \ E-mail: db3l at fitlinxx.com / | FitLinxx, Inc. \ Phone: (203) 708-5192 | / 860 Canal Street, Stamford, CT 06902 \ Fax: (203) 316-5150 \ \-----------------------------------------------------------------------/ From calves at coelce.com.br Wed Jun 19 07:30:14 2002 From: calves at coelce.com.br (Alves, Carlos Alberto - Coelce) Date: Wed, 19 Jun 2002 08:30:14 -0300 Subject: =?ISO-8859-1?Q?ENC=3A_how_i_use_=27=E3=27_in_python=3F=3F=3F?= Message-ID: <29A97D00F387D411AC7900902770E148058B2E65@lcoeexc01.coelce.net> Python accept that, just represent it as hex. Look below: >>> s='?' >>> s '\xe2' >>> print s ? Another work around, is to use the chr() function, just like that: chr(226)=>? > -----Mensagem original----- > De: jubafre at zipmail.com.br [mailto:jubafre at zipmail.com.br] > Enviada em: quarta-feira, 19 de junho de 2002 01:39 > Para: python-list at python.org > Assunto: how i use '?' in python??? > > > i?m brazilian, and in my laguage(Portguese) there are many > other caracters > how ?, ?, ? and a string in python doesn?t support this > how i can use??? have a import module for this??? > > BRASILEIROS DA LISTA COMO VCS CONSEGUEM USAR ACENTO NO PYTHON?? > > for exmple: > s='?' > doesn?t work?why?? > > > Juliano Freitas > www.gebrasil.hpg.com.br > > > > ------------------------------------------ > Use o melhor sistema de busca da Internet > Radar UOL - http://www.radaruol.com.br > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From threeseas at earthlink.net Tue Jun 25 20:40:47 2002 From: threeseas at earthlink.net (Timothy Rue) Date: Wed, 26 Jun 2002 00:40:47 GMT Subject: Reminder of a python Project. Message-ID: <2218.941T781T12224051threeseas@earthlink.net> First off, it's ok that I got such a high level of resistance to my initial posting here about this project. Thanks to some research that /. had an article on, regarding the size of GPL project teams. But anyway.... Remember the autocoding project I mentioned? 60 billion in cost to consumer/small business (shoddy software failure) http://www.computerworld.com/managementtopics/management/itspending/story/0,10801,72245,00.html (slashdot has an article today that links to this - and the comments...) SCIENTIFIC AMERICAN - Sept. 1994 Article - "Software's Chronic Crisis" Mass-produced PC products makes up less than 10% of the $92.8 billion U.S. software market. COMDEX SPRING and WINDOWS WORLD 95 Power Panel - "What's Wrong with Software Development" ** In The U.S. Only ** $81 Billion = 31% of software development gets cancelled before complete $59 Billion = 53% of software development has cost over-runs of 189% 16% success - project success and failure ratio 61% customer requested features and functions make it in Maintenance and repair is where most of the U.S. dollars are going, instead of new, better, easier to use software. That's 140 Billion before the cost of successful project is added in. And a total cost increase over a 1 year period of: 47.2 + billion (I suppose this can be cross checked with stock market or such.) The Autocoding solution direction: http://groups.google.com/groups?q=Autocoding&hl=en&lr=&ie=UTF-8&safe=off&selm=5512.785T1955T13695089threeseas%40earthlink.net&rnum=1 My 1997 estimate of software failures all around (total of industry and consumer level development and use): Low estimate of 300 Billion. http://groups.google.com/groups?selm=2084.7123T966T2172%40mindspring.com&output=gplain at 60 billion figured at 20% of total market ... = 300 billion. Of course 10% means 600 billion. --- *3 S.E.A.S - Virtual Interaction Configuration (VIC) - VISION OF VISIONS!* *~ ~ ~ Advancing How we Perceive and Use the Tool of Computers!* Timothy Rue What's *DONE* in all we do? *AI PK OI IP OP SF IQ ID KE* Email @ mailto:timrue at mindspring.com >INPUT->(Processing)->OUTPUT>v Web @ http://www.mindspring.com/~timrue/ ^<--------<----9----<--------< From nhodgson at bigpond.net.au Wed Jun 19 09:17:19 2002 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Wed, 19 Jun 2002 13:17:19 GMT Subject: imp.loadmodule creates compiled file Message-ID: I've been using imp.loadmodule with Python 2.2 (on both Windows and Linux) to load changed versions of source code into a long running process where they will run alongside objects already created from earlier versions of the source code. An unexpected result of the call is to create a compiled module on disk with a name based on the filename argument with "c" appended. >>> f = file("x.py") >>> import imp >>> imp.load_module("y", f, "z", (".py", "r", 1)) At this point, a "zc" file is created. I would prefer no compiled file be created. The documentation indicates that file and filename arguments can be None and '' when the module is not being loaded from a file but this makes litle sense as there is no other argument to provide the module contents from other than a file. Trying '' as the filename argument leads to a compiled file called "c". The compiled files can be unlinked but it would be better to have a solution that avoided writing to disk at all as there may be problems such as name clashes with other running instances or with being in a protected directory. Any other techniques for creating mdoules from source code? Neil From sonnenbu at informatik.uni-bonn.de Sat Jun 8 13:16:02 2002 From: sonnenbu at informatik.uni-bonn.de (Frank Sonnenburg) Date: Sat, 8 Jun 2002 19:16:02 +0200 Subject: Q: scope of module functions Message-ID: Hello all, a little tricky problem (at least from my point of view); given module CALLER: # i need "fct" and some other from module "UTILS" from UTILS import * fct() # END of module CALLER Now, inside fct(), how do i determine the module - in this case CALLER - from where fct() was called? Even concerning cases like (continuation of example): # Now we are in __main__ import CALLER fct_in_main = CALLER.fct fct_in_main() Appreciation for any help Frank Sonnenburg, BioSolveIT GmbH, Sankt Augustin, Germany From eric.brunel at pragmadev.com Wed Jun 19 11:25:31 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Wed, 19 Jun 2002 15:25:31 +0000 Subject: tkinter menu (newbie question) References: Message-ID: Stephane Ninin wrote: > Thanks for the help. No problem. > If I want to use several of these windows, > can still use for base class Tk, instead of Frame ? Nope: the instance of Tk is your main window. There should only be one, and closing it will end your application. If you want to create other windows, you should create instances of Toplevel. If you do not have a main window, there are means to work around this limitation, but they're not really natural. If you need to know how to do it, feel free to ask... HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From jason at tishler.net Fri Jun 21 22:11:34 2002 From: jason at tishler.net (Jason Tishler) Date: Fri, 21 Jun 2002 22:11:34 -0400 Subject: Python+Cygwin+XML SAX build failure of PyXML 0.7.1 In-Reply-To: <59d8a5f6.0206210804.25353aa3@posting.google.com> References: <59d8a5f6.0206210804.25353aa3@posting.google.com> Message-ID: <20020622021134.GA1792@tishler.net> Dmitri, On Fri, Jun 21, 2002 at 09:04:10AM -0700, Dmitri wrote: > [snip] > Searching the net: > 1. I did not find the precompiled version of the PyXML for cygwin. > Does someone know where can I get it, it it does exist? Sorry I don't, but see below... > 2. The problem like "initializer element is not constant" is shown but > [snip] See the following for the solution to the above: http://cygwin.com/ml/cygwin/2002-06/msg00273.html Would you like to contribute a pre-built Cygwin PyXML to the Cygwin distribution? Jason From alf at logilab.fr Tue Jun 11 08:20:00 2002 From: alf at logilab.fr (Alexandre Fayolle) Date: Tue, 11 Jun 2002 12:20:00 +0000 (UTC) Subject: [ANN] constraint-0.2 References: Message-ID: Terry Reedy a ?crit : > To paraphrase Magnus Lie Hetland, the general constraint-propagation > system constraint-0.2 takes 100 times as long to do the 8-queens > problem as the specific backtracking queens.py found in the standard > Python distribution: 15 versus .1 sec on comparable machines. Yup. But we do mean to make it faster. > The is about the same comparison, for some computations, as between > generic/dynamic Python and type-specific C. In both cases, there are > two more questions of practical interest: which platform/method is > faster for the *programmer*? and, is the slow method fast enough? This is a good point. Using the constraint package for 8 queens is very easy, since all you have to do is describe the problem in terms of variable and constraints, and call Solver().solve(Repository(variables,domains,constraints)) Is it fast enough? Well, it really depends. The good point in the situation at hand is that I have not yet started thinking about optimizing the code. There are other things to deal with first (adding other kind of domains, such as finite sets, and the basic constraints that go with these domains), so my personal answer is that it is for now fast enough as far as I'm concerned. Which does not mean it's ready for production use. Hey, this is version 0.2! > So, what is the relative programming speed of the general constraint > propagation system versus specific backtracking? I suspect that some > people could whip up something like queens.py as fast or faster that > they could the (unpublished?) constraint input for the same problem. O(N) algorithm available for N queens has been published and proven to be of minimal complexity, and will always be faster than a constraint propagation approach which needs to consider N*(N-1) constraints, and therefore will always have a complexity > O(N^2) > However, I also suspect the reverse would be true for the more > realistic and useful scheduling example that Fayolle used to > illustrate and motivate constraint-0.2. > http://www.logilab.org/python-logic/documentation.html N-Queens is a well known problem, and it can be used as a benchmark for solvers. Same for SEND+MORE=MONEY, which is also in the examples directory of the constraint module. Since these problems are both well known and simple in their expression, they can give an idea of the relative performance of solvers. The scheduling example on the web page is completely made up, and its purpose is to give a more "real-life" flavour to the tutorial. There are many other constraint satisfaction problems that can be solved with the module, or the the constraint module will be able to solve in the near future (how to select tunes from a CD to best fill up a tape, how to arrange your furniture in the flat you're going to move in, finding a new password that you'll be able to easily memorize while passing through the devious filters set up by your sysadmin, choosing which fruits and vegetables to buy in the market in order not to eat the same same thing every week...) > Real world problems may have no solution as given. On the other hand, > constraints may not be absolute. In the scheduling example, two > workshops *can* be scheduled simultaneously, if necessary, even though > many people want to take both. So a stepwise procedure may be needed. > (Given multiple solutions, one might also want to add 'wishes' as > pseudoconstraints to help select just one.) So, is it equally easy, > with the two approaches, to add or drop constraints and rerun? This > would be fairly simple with c-0.2 input but probably harder for > backtracking code unless planned for from the beginning. Is it > equally easy to give constraints priorities and have the system > automatically either add them in order from the highest or drop them > from lowest? Constraint-0.2 evaluates constraints in the order > listed, but I do not know if it properly backtracks from failure to > report the most satisfying solutions. The short answer is no, because solving overconstrained problems is a tricky thing. The longer answer is that you could quite easily build on top of the constraint package an engine which would try to relax constraints when no solution can be found. When finite set domains are implemented in the solver, building this engine will be possible with the constraint package itself. But this approach will not be as efficient as a dedicated overconstrained package solver. Now, a little annecdote: when writing the scheduling example, the first set of constraints I had come up with gave 1152 possible solution, which I found was too many. So I did exactly what you suggested, I added more constraints (this was really easy because adding a consrtaint is a one-liner), twiddled with the choice of the non-simultaneous conferences, until I found a combination which gave "only" 64 possible solutions. It took me about 20 runs to get this, which was fairly quick because the conference.py script runs in about 2 seconds on my machine. Alexandre Fayolle -- LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org Narval, the first software agent available as free software (GPL). From marklists at mceahern.com Fri Jun 28 08:33:31 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 28 Jun 2002 07:33:31 -0500 Subject: Is Python growing? In-Reply-To: Message-ID: [Matthew Dixon Cowles] [...] > Python is wonderfully easy to get started with. But someone who's new > to programming doesn't need to learn everything about Python in order > for it to be useful and fun. (That sounds obvious but it's less true > in many other languages.) So if Guido adds a feature here and there, > that doesn't necessarily make the learning curve much worse. I've been > using Python for some years now and there are corners of the standard > library that I haven't explored because I haven't needed to. Indeed, > there are aspects of the core language that I haven't found out much > about because I haven't needed them. [...] This is true for me as well. For instance, I typically don't use map, filter, zip, et al. Paul Rubin replied to your post with an example that used max and map to return the longest string in a list. What's so beautiful about Python is that all I had to do was fire up the interactive interpreter and do this to remind myself of what map does: >>> print map.__doc__ So not only is the language incredibly expressive, clear, and pragmatic, but it provides tools for exploration that make it easy to focus on what works. Those tools allow you to expand your working subset of the language slowly over time as needed. // m - From ark at research.att.com Fri Jun 14 12:50:01 2002 From: ark at research.att.com (Andrew Koenig) Date: Fri, 14 Jun 2002 16:50:01 GMT Subject: I feel stoopid ... this code is to verbose References: <3D0A1791.3060307@mxm.dk> Message-ID: Max> I just cannot seem to find the nice 3-liner I expected from the Max> beginning. Has anybody got a better solution ? I thought somebody Max> might find it a fun exercise. Well I have... Well, it's a little more than three lines, but how about this? def stringSlicer(string, chunkSize = 3): suffix = '' while len(string) > chunkSize: suffix = '.' + string[-chunkSize:] + suffix string = string[:-chunkSize] return string + suffix -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From kragen at pobox.com Thu Jun 6 12:58:59 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 06 Jun 2002 12:58:59 -0400 Subject: Compiling Python References: <3CFDF148.AA2035FF@info.unicaen.fr> <3CFE49CA.46A5FEE1@tds.net> Message-ID: <838z5sgx7w.fsf@panacea.canonical.org> "Edward K. Ream" writes: > BTW, a compiled version of a Python program would be valuable > commercially, as it would allow companies to protect their source code, > as well as (possibly) improve performance. I'm worried about this myself; perhaps the compiler could include the source code in the resulting executable to prevent this. From phd at phd.pp.ru Thu Jun 27 12:50:42 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Thu, 27 Jun 2002 20:50:42 +0400 Subject: Python crashed on me Message-ID: <20020627205042.A18986@phd.pp.ru> Hello! Recently Python (one program that I am dbugging) started to crash. FreeBSD kills it with "Bus error", Linux with "Segmentation fault". I think the program crashed in the cPickle.dump(file, 1), because after the crash the file is corrupted and cannot be load back (upon loading cPickle complain EOFile). The error is reproduceable. How can I debug the situation? May be my data grew too big? The pickle file is about 800K. Details. The program is my URL robot (http://phd.pp.ru/Software/Python/#bookmarks_db). The robot runs urllib.urlretrive() on my bookmarks file and report the results. Between runs data may be saved in different formats, including pickle. While trying to understand what is going on and make full run faster I replaced the call to urlretrive with fake function that returns nothing. The robot crashed with the same segfault. Python is Python 2.2.1 (#2, Apr 10 2002, 15:15:56) [GCC 2.95.2 20000220 (Debian GNU/Linux)] on linux2 Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From kragen at pobox.com Sat Jun 1 02:49:16 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 01 Jun 2002 02:49:16 -0400 Subject: Iterating through two lists References: <3cee0ae6_1@news3.newsgroups.com> <3cee2338_2@news3.newsgroups.com> <1022297508.675568@yasure> Message-ID: <831ybrwl1v.fsf@panacea.canonical.org> "Donn Cave" writes: > Paul Prescod was right (as paraphrased on the followup page linked > in the page above) - he really did choose an example that favored > Lisp. Sort of. > The function that carries data is cool enough. Lisp does it easier > than Python, and in fact does "functional programming" better than > Python by a long shot. That's debatable. > But then, Python does OOP better than Lisp! Your certainty suggests deep ignorance. How familiar are you with CLOS? > He seems vaguely mystified that Python programmers would favor the > much more tedious class solution, but of course if you wanted to add > some requirement like support two functions over that data instead > of just one, then the mystery evaporates. Like (defun addergetter (x) (list (lambda (i) (incf x i)) (lambda () x))) ? > When you take on a comparison between two decent languages, though, > you have a lot of impossible questions about which big picture concepts > are really going to pay off. Does OOP live up to its promise on > re-use of code, can ordinary people really "get" functional programming > and become really productive in it, does one approach or another really > reduce complexity in a meaningful way. Jury's still out. I think it's pretty clear that object orientation and functional programming both reduce complexity in a meaningful way. From kragen at pobox.com Mon Jun 10 18:28:08 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 10 Jun 2002 18:28:08 -0400 Subject: htmllib and parsing data sourrounded by HTML tags References: Message-ID: <83elfeojk7.fsf@panacea.canonical.org> Milos Prudek writes: > I studied htmllib hard and I was able to subclass it and do some > processing of HTML tags. I managed to extend it to process , for > instance. > > But what about the text that is surrounded by HTML tags? I think you want to define a handle_data method. From guido.goldstein at a-nugget.de Fri Jun 28 01:17:18 2002 From: guido.goldstein at a-nugget.de (Guido Goldstein) Date: 28 Jun 2002 07:17:18 +0200 Subject: How to get rid the new line References: <3D1AD534.A74EC9F4@ipm.fhg.de> <3D1B1A76.563E5394@engcorp.com> <7xlm90cmxx.fsf@ruckus.brouhaha.com> Message-ID: Hi! On 27 Jun 2002 16:38:02 -0700 Paul Rubin wrote: [...] > If you don't mind removing all trailing whitespace, there's also > > line = line.strip() > > or more portably > > import string > line = string.strip(line) If you really would like to remove *trailing* whitespace you better should use rstrip(). The strip() method strips from both sides! Just my 2 cents. HAND Guido From eric.brunel at pragmadev.com Thu Jun 6 14:57:31 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Thu, 6 Jun 2002 18:57:31 +0000 Subject: problem with isinstance and relative/absolute import References: <87adq8jsq1.fsf@tux.ntw23.fr> Message-ID: Sylvain Thenault wrote: > does someone can explain to me the following test case, or should it be > considered as a bug ? > > [syt at tux syt]$ ls tests/ > __init__.py module2.py module.py > [syt at tux syt]$ cat tests/__init__.py > [syt at tux syt]$ cat tests/module.py > class A: pass > > a = A() > > [syt at tux syt]$ cat tests/module2.py > from module import A > > b = A() > > [syt at tux syt]$ export PYTHONPATH=$PWD > [syt at tux syt]$ cd tests > [syt at tux tests]$ python > Python 2.1.3 (#1, Apr 20 2002, 10:14:34) > [GCC 2.95.4 20011002 (Debian prerelease)] on linux2 > Type "copyright", "credits" or "license" for more information. >>>> from module2 import b >>>> from tests.module import A, a >>>> isinstance(a, A) > 1 >>>> isinstance(b, A) > 0 I already noted this problem. The cause seems to be that in module2.py, you import A with: from module import A which is in turn imported in your main script via: from module2 import b But in your main script, you do: from tests.module import A This seems to confuse the interpreter which creates two classes named A: one in the module "module", and one in the module "tests.module", that are not identified as being the same. However, when you do: >>>> from tests.module import A, a >>>> from tests.module2 import b the line "from module import A" in module2.py is now executed from the import "from tests.module2 import b". So the interpreter knows that "module" is in the same directory than module2.py, and is therefore correctly identified as being the same than tests.module... The solution is simple: try to avoid importing the same module in two different ways. First, it's quite ugly; second, it may confuse the interpreter... HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From nospam at bigfoot.com Tue Jun 18 09:04:23 2002 From: nospam at bigfoot.com (Gillou) Date: Tue, 18 Jun 2002 15:04:23 +0200 Subject: Listing all available (not just loaded) modules References: Message-ID: pydoc that's in the standard distro browses all that's in the python path. Perhaps reading this module will give you the enlightenment. --Gilles glenfant AT bigfoot DOT com "Michael Steuer" a ?crit dans le message news: aem9om$888fb$1 at ID-140151.news.dfncis.de... > I've been searching the newsgroup for information on this but so far have been > unsuccessful: > > Is there a way to dynamically list all available modules (not just those that > are already loaded) in python? By available I mean those modules, which are > installed on the machine executing python (in the lib path(s)). > > Cheers, > > Mik.e > > From python at rcn.com Sat Jun 29 20:57:36 2002 From: python at rcn.com (Raymond Hettinger) Date: Sat, 29 Jun 2002 20:57:36 -0400 Subject: Is this a __slot__ bug? References: Message-ID: "Steve Menard" wrote in message > However, I also love(need) private variables (those __X). It seems they > dont work with slots. > So if this is by design, I will not agree but I will do the workaround. > If not, well then seems I founda bug :) > > Steve Yes, you found a bug. It takes a keen eye to spot one :-) However, someone faster on the draw already reported it and I've already fixed it (for Py2.2.2 and Py2.3). Raymond Hettinger From phr-n2002b at NOSPAMnightsong.com Sun Jun 23 17:16:56 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 23 Jun 2002 14:16:56 -0700 Subject: Python hits the spot References: <3D1634ED.B9ACF9EC@engcorp.com> Message-ID: <7xfzzdhf07.fsf@ruckus.brouhaha.com> "Matt Gerrans" writes: > > > for i in range(50*1000*1000): > > > pass > > You call that a bug? Did you consider trying xrange()? Maybe not a bug, but a pretty serious misfeature IMO. From sholden at holdenweb.com Wed Jun 5 08:35:34 2002 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 5 Jun 2002 08:35:34 -0400 Subject: semi-concatenated strings References: <3CF6F202.7274E43E@engcorp.com> Message-ID: "Peter Hansen" wrote in message news:3CF6F202.7274E43E at engcorp.com... > "Delaney, Timothy" wrote: > > > > > From: Peter Hansen [mailto:peter at engcorp.com] > > > > > > And which has both embedded "\n" newlines and many more leading > > > spaces before each line... > > > > That's why I would bind it to a name first - that allows me to preprocess > > the query before passing it in. > > > I would much rather write it so it is readable, then process it for the > > database, than the other way around. > > > > sql = """ > > select cities.city, state, country > > from cities, venues, events, addresses > > where cities.city like %s > > and events.active = 1 > > and venues.address = addresses.id > > and addresses.city = cities.id > > and events.venue = venues.id > > """ > > # The next three lines are bogus > > sql = string.split(sql) > > sql = string.join(sql, ' ') > > sql = string.strip(sql) > > > > rows = self.executesql(sql, (city,)) > > What a lot of extra work to make something "readable"! > I don't think that this is more readable than the simple, straightforward > approach Skip presented. It uses many more lines and a bunch of > superfluous operations (without even a comment explaining why > you are splitting and joining things this way instead of just using > simple string concatenation). > Not only that, but for any reasonable database the whole schemozzle is completely unnecessary. SQL is a free-format language, and newlines and spaces embedded in statements make absolutely no difference. > If I saw code like this in my team I'd ask that a comment be > added to explain it, and if the comment said "# doing this so the > code is more readable" I'd ask that it be refactored so it didn't > need the comment at all, after I got back up off the floor. > I expect the refactoring would take the form of the original > example which needs no extra operations or commenting. > Or simply remove the three bogus lines and leave the SQL as it's generated. > > Skip also asked why I would bind the statement to a name. For a query of > > this size, I find it easier to read - the sql query is separate and (to my > > eye) cleaner than having the literal as a function parameter. Plus it uses > > much less horizontal white space. I hadn't realised there was a shortage :-) [Seriously, I like the embedded newline style, as I underline below...] > > Nothing wrong with separating things out like that if you think it > looks more readable, but this is one case where I agree with Skip's > approach even though it looks a lot like "hardcoded strings" which > is generally a Code Smell. Simpler is much better here. > > (I might agree with you more if I thought that maintaining the > string-concatenated version would actually be harder. Given the > likely nature of the maintenance -- adding fields to the line with > "from cities, ..." for example, or adding a new line to the > "where" intersection -- I don't believe it would be *any* harder.) As I said earlierrr, in another post: '''would personally much prefer to see this written as ("""select cities.city, state, country from cities, venues, events, addresses where cities.city like %s and events.active = 1 and venues.address = addresses.id and addresses.city = cities.id and events.venue = venues.id""", (city,)) ''' but it's largely a matter opf taate. What clealy *should* be avoided is unnecessary programmed transformation of SQL statements. regards Steve -- ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From mjais at web.de Mon Jun 3 10:56:20 2002 From: mjais at web.de (Markus Jais) Date: Mon, 03 Jun 2002 16:56:20 +0200 Subject: different gui-toolkits pros/cons... References: Message-ID: <_rLK8.12$fd2.979@news.ecrc.de> with pyQT there might be problems with the license if you want to make your programm freely available (but I am not a lawyer, so I might be wrong) pyGTK might be faster, because wxWindows is AFAIK an additional layer on top of Gtk. but only in Unix/Linux platforms, AFAIK I do not know if Gtk is really stable for Windows now. you should try to use Gtk2 pyGtk seems to be pretty fast, but I have made no tests markus Uwe Schmitt wrote: > Hi, > > I'm looking for an appropriate toolkit for GUI programming, > which do you use ? what are pros and cons ??? > I'm specially interested in wxPython, pyQt and pyGTK... > and I'm intersted in a windows-like look and feel on win platforms... > Finally I'm intersted in execution speed. > > So, I await your answers, greetings, Uwe > From skin_pup-python-list at happypoo.com Mon Jun 24 12:52:33 2002 From: skin_pup-python-list at happypoo.com (Skinny Puppy) Date: Mon, 24 Jun 2002 12:52:33 -0400 Subject: My .py CGI script works in IE but not Netscape In-Reply-To: <79b54d28.0205311837.731002aa@posting.google.com> References: <79b54d28.0205311837.731002aa@posting.google.com> Message-ID: <20020624165233.GF19586@shitbomb.com> Chris [chouster at uclink4.berkeley.edu] wrote: > My script doesnt work in Netscape for some reason. I'm developing on a > UNIX envionrment with Python 2.2.1. I open up Netscape in windows and > only the background picture of my webpage loads... nothing else. > However in IE it works perfectly. Any general ideas as to what may be > going on? Thanks. I have run in to this before. Make sure that your script has something like this before it outputs other text. print "Content-type: text/html" print "" THe start of the issue is with the web server, most are set to default to output "Content-type: text/plain" unless you tell it other wise (This is correct BTW). Now when netscape receives this it renders your scripts output as a plain text file, no HTML rendering. IE on the other hand starts to render the output as plain text, but it notices the tags and switches to rendering HTML. Jeremy From dreed at capital.edu Tue Jun 11 20:26:44 2002 From: dreed at capital.edu (Dave Reed) Date: Tue, 11 Jun 2002 20:26:44 -0400 Subject: lists and sequences In-Reply-To: (message from Tim Peters on Tue, 11 Jun 2002 19:32:25 -0400) References: Message-ID: <200206120026.g5C0QiD24559@localhost.localdomain> > From: Tim Peters > Cc: cmonahan at yahoo.com > > [Collin Monahan] > > What is a python list? Is it a linked list or a random access structure > > in contiguous memory? > > A contiguous vector of pointers to objects. > > > What type of situations should be avoided when using it? > > Depends on the app and your judgment of appropriate tradeoffs. > > > E.g. when does n^2 time happen using it? > > alist.insert(0, newthing) physically moves len(alist) elements. Ditto Just to be clear, these are order n, not order n^2. Dave From jadestar at idiom.com Tue Jun 18 02:13:55 2002 From: jadestar at idiom.com (James T. Dennis) Date: 18 Jun 2002 06:13:55 GMT Subject: string generator References: Message-ID: Gustavo Cordova wrote: >> I like to create a list of file automatical based on series. >> For example >> user input the number of file say 5. So i want to generate the file >> according to this range , this mean the generated files could be >> filename1 >> filename2 >> filename3 >> filename4 >> filename5 >> I using the for loop like that >> >> for file in range(5): >> lis = [file] >> string.join('filename',lis[1:]) >> how can it didn't work. I am confusing how to do it. >> > Yeah, but where do you wanna put your results? > You could also: > FNs = ["filename%d" % i for i in range(5)] > or also you could: > FNs = map(lambda i:"filename%d" % i, range(5)) > or many other variations thereof. > Good luck! > -gustavo Here's a variation: >>> string.split(' filename'.join([str(x) for x in range(5)]))[1:] ['filename1', 'filename2', 'filename3', 'filename4'] >>> string.split(' filename'.join([str(x) for x in range(-1,5)]))[1:] ['filename0', 'filename1', 'filename2', 'filename3', 'filename4'] although the map(lambda ...)) with the % operatator is even more clever. From bokr at oz.net Mon Jun 24 21:51:35 2002 From: bokr at oz.net (Bengt Richter) Date: 25 Jun 2002 01:51:35 GMT Subject: SOLVED (Re: Python hits the spot) References: <3D1482AE.8FA299D8@kfunigraz.ac.at> <3D14CF95.4030501@kfunigraz.ac.at> <3D158F3E.1010907@kfunigraz.ac.at> <3D16DD5C.1050708@kfunigraz.ac.at> <3D171291.2060905@kfunigraz.ac.at> Message-ID: On Mon, 24 Jun 2002 14:37:37 +0200, Siegfried Gonzi wrote: >RPM1 wrote: > >> Hey! That's why I was asking if your laptop was a Hewlitt >> Packard. I had a Hewlitt Packard Pavillion laptop that would >> die when the fan kicked on. >> >> Any chess program will keep your CPU at 100%. >> >> GnuChess is probably on your system now. If not, it is a free >> program. Ask around on rec.games.chess.computer if you need >> help. > >It was really the laptop processor. I tried the calculation on a >stationary machine (Pentium II 450 MHz and SuSE 8.0), and it works. > >Die Typen k?nnen jetzt was erleben. > Well, lucky guess on the heat. That _probably_ accounts for laptop going to 87% and then shutting down, but how about the other huge slowdowns in your big loop of 8? Did you get that diagnosed too? Just curious ;-) Regards, Bengt Richter From kragen at pobox.com Sat Jun 1 02:11:55 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 01 Jun 2002 02:11:55 -0400 Subject: matching one time through a loop References: Message-ID: <837kljwms4.fsf@panacea.canonical.org> vvainio at tp.spt.fi (Ville Vainio) writes: > BTW, how does perl do re.findall()? Or re.sub using function return > values to dynamically determine the replacement? I can't remember I > ever used such features with perl. re.findall(): my $string = 'a moon upon a lunar tune aroon'; my @list = ($string =~ /\w+n/g); print map { "$_\n" } @list; I'm afraid I always have to look up what // returns every time I use it. re.sub using function return values is approximately the /e modifier, but without the need to wrap a 'lambda:' around the replacement: my %dict = qw(a the moon rock upon above lunar solar tune song aroon boon); my $string = 'a moon upon a lunar tune aroon'; $string =~ s/\w+/$dict{$&}/ge; print $string, "\n"; Compare Python: import re mydict = {'a': 'the', 'moon': 'rock', 'upon': 'above', 'lunar': 'solar', 'tune': 'song', 'aroon': 'boon'} astring = 'a moon upon a lunar tune aroon' astring = re.sub(r'\w+', lambda mo: mydict[mo.group(0)], astring) print astring Not only is the Python harder to read (to me), but it took me four tries to get it to work, because I made the following three mistakes: - I got the order of re.sub arguments wrong (and got a *very* unhelpful traceback from line 177 in sre.py) - I called the lambda argument 'aword' in one place and 'word' in the other - I thought the lambda argument was the matched string, not the match object (if it had been the matched string, I could have written mydict.get instead of the lambda expression) The Perl version worked the first time; you will note that none of the three Python mistakes have a reasonable analogue in the Perl version. > My experience is that Python regexps are better when you go beyond > non-trivial, with clear group & matchobject semantics I wholeheartedly agree. But the vast majority of my regexps are trivial. From peter at engcorp.com Mon Jun 24 21:58:33 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 24 Jun 2002 21:58:33 -0400 Subject: adding attributes to builtin functions References: Message-ID: <3D17CE49.E3D16ABE@engcorp.com> Douglas Zongker wrote: > > import mymodule > print mymodule.myfunction > mymodule.myfunction.special = 6 > > gives me: > > > Traceback (most recent call last): > File "", line 1, in ? > TypeError: 'builtin_function_or_method' object has only read-only > attributes (assign to .special) > > Is there a way to define a builtin function whose attributes aren't > read-only? Maybe something like this? import mymodule def myfunction(*argp, **argn): return mymodule.myfunction(*argp, **argn) mymodule.myfunction = myfunction mymodule.myfunction.special = 6 Tada! (Actually, I have *no* idea if this works. :-) -Peter From fperez528 at yahoo.com Tue Jun 25 15:20:04 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Tue, 25 Jun 2002 13:20:04 -0600 Subject: Integrals with Python References: <3D188551.6BA00DED@lanl.gov> <3D189307.1417ECD5@info.unicaen.fr> <3D18A010.CAF3FA9E@lanl.gov> Message-ID: Nathan Given wrote: > Matlab has quad, quadl, and quad8... > > > does Numeric have anything like those? Go look at SciPy (http://scipy.org), it comes with a reasonable set of integration routines. But as Jerzy warned you, you first need to understand correctly the structure of your integrands. Black box integration is similar to russian roulette (just look at some of the disasters the famous Mathematica spits out). But at the level you seem to be working, scipy would definitely be a good start. Then you can refine the routines therein if needed. Another option is to use C integrators wrapped with weave (part of Scipy). That's what I do because it's faster and I have tighter control over exactly what is going on under the hood. With weave, the wrapping job is very simple. Cheers, f From pyth at devel.trillke.net Fri Jun 7 08:17:49 2002 From: pyth at devel.trillke.net (holger krekel) Date: Fri, 7 Jun 2002 14:17:49 +0200 Subject: Efficient python programming... In-Reply-To: <3D00A456.4315EDA3@engcorp.com>; from peter@engcorp.com on Fri, Jun 07, 2002 at 08:17:26AM -0400 References: <3D00A456.4315EDA3@engcorp.com> Message-ID: <20020607141749.C16359@prim.han.de> Peter Hansen wrote: > Eddie Corns wrote: > > > > A friend is fond of quoting this to me: > > > > Rules of Optimization: > > Rule 1: Don't do it. > > Rule 2 (for experts only): Don't do it yet. > > -- M.A. Jackson > > > > I wasn't going to bother contributing since others have said the same thing > > but the more people say the more you'll believe it :) > > > > Especially for a beginner the important thing is to get clear and obvious > > code. Later, IF IT ISN'T FAST ENOUGH, then you think about ways to speed it > > up. > > You forgot the even more important first thing for a beginner: > get it correct! The only good way to do this is to write unit > tests that prove it. If you don't have tests, you don't have > working code (or how can you prove it?). yeah. writing tests is *the way* to go if you want other people use your code. Although successfull unittests theoretically don't prove anything they tend to do in reality. if-it's-not-proven-then-test-it-ly yours, holger From shalehperry at attbi.com Fri Jun 7 20:07:26 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 07 Jun 2002 17:07:26 -0700 (PDT) Subject: Efficient python programming... In-Reply-To: <3D013FB1.3D7477EA@engcorp.com> Message-ID: > > I disagree, if the tests are written first (and run, proving that > they will fail when the code is wrong or missing). > > The tests are executable requirement specifications. Running > them "proves" (yes, not 100%... nothing could) that the code > meets the specs. The specs could be wrong of course, but that > doesn't mean the code is broken... > this also assumes the test covers every possible failure. this also assumes one can write tests for that section of code. From richardt at edshk.demon.co.uk Tue Jun 18 08:16:56 2002 From: richardt at edshk.demon.co.uk (Richard Townsend) Date: Tue, 18 Jun 2002 13:16:56 +0100 Subject: Embedding Python - time module problem Message-ID: I have been having problems embedding Python in a small C program which calls a Python script which, in turn, imports the time module. This fails with the error: "ImportError: dynamic module does not define init function (inittime)" I have simplified this down to a minimal C program which just tries to import the time module. This gives the same error. #include #include int main(int argc, char **argv) { PyObject *module; Py_Initialize(); module = PyImport_ImportModule("time"); if (module == NULL) { PyErr_Print(); } } If I substitute "os" or "sys" for "time" then no error occurs. However "math" does give a similar error. If I run the interpreter on its own, I can import time and math with no problems. I am using Python 2.2.1 on HP-UX 11i Is there something special I need to do to be able to import time and math modules when using embedded Python? From maxm at mxm.dk Mon Jun 24 11:39:14 2002 From: maxm at mxm.dk (Max M) Date: Mon, 24 Jun 2002 17:39:14 +0200 Subject: Python hits the spot References: Message-ID: <3D173D22.9090304@mxm.dk> Tim Peters wrote: >>Don't some implementations of malloc offer a way to ask the operating >>system to commit to the memory being available when you allocate it? >>If so, I can imagine testing for that facility at config time and >>using it if available. > > SourceForge remains open 24 hours a day for patches. My bet is that nobody > cares enough to bother -- the barrier for complaining on Usenet is one an > ant can hurdle with ease . Oh... somebodys grumpy that he isn't at EuroPython ;-) regards Max M From shagshag13 at yahoo.fr Sun Jun 2 08:15:21 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Sun, 2 Jun 2002 14:15:21 +0200 Subject: Pop a list from beginning ? and memory saving... References: <3CFA0676.68F80DE6@engcorp.com> Message-ID: "Peter Hansen" a ?crit dans le message de news: 3CFA0676.68F80DE6 at engcorp.com... > Shagshag13 wrote: > > > > I had a huge list containing consuming data, as i only need a one pass in a > > for statement, i'm wondering if by doing this with a pop i could save memory ? > > Maybe, maybe not. The implementation _probably_ makes a copy of > the entire list at some point as you shrink it. That would mean that > at least at some interval, you would temporarily consume almost twice > the memory of the original list as the original list is copied, then > freed. You might end up with less memory used, but with double the > memory needed. Of course, the same would have held true as you built > the list in the first place... > > Why are you trying to save memory? Are you really working with such > a large amount of data in one chunk that you will run out? Maybe > there is some other approach you haven't thought of. This effort > almost smells like premature optimization (the root of all evil). > > -Peter in fact i had huge memory troubles !!! i'm a python newbie, but i use it because i needed a language which allow fast development (and can't remind me of things like C or Java...) and yes i'm working with large amount of data : i'm trying to index something like 1 go of plain text by using conventionnal text retrieval structures (i mean without compression tricks, because i *don't* have time to implement theses, but with stoplist and so on) and wishing to do it in one pass without relying on hdd temp files (i'm starting to think that i were dreaming...) the most i think i could simply do is this : i use integer each time as possible, i free everything i don't need anymore with = None, and what could i do more ? Advices are ***greatly*** welcome !!! s13. ps : do you know if any python databases could handle without trouble more than 1 or 2 go of data ??? From sabine at textraeume.de Mon Jun 3 06:48:52 2002 From: sabine at textraeume.de (Sabine Richter) Date: Mon, 03 Jun 2002 12:48:52 +0200 Subject: word wrap on different OS Message-ID: <3CFB4994.DD35AEA2@textraeume.de> Hello, I am not sure if I think clear on this subject: A simple text file has been created for example on MS Dos or MacOS. So the sign for a word wrap will be "\r\n" on MS Dos or "\r" on MacOS. Then I save the file on a windows file system. The sign for the word wrap will be converted to "\n". If I now read the file content into a string and search for a word wrap in the string I have to search for "\n". For example with string.split or with an regular expression. Is that all right? And next question: If I write a script, which uses MyODBC and the odbc-module from win32 extensions to connect to a MySQL-database, it can only be used on windows. Isn't it? So, in consequence I don't have to handle different signs for word wraps in my script? Or would it make any sense to do so? The purpose of the script is to update a database structure based on a given dump file. Thanks in advance for your answers Sabine From shalehperry at attbi.com Sat Jun 29 11:58:00 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Sat, 29 Jun 2002 08:58:00 -0700 (PDT) Subject: exception handing In-Reply-To: Message-ID: On 29-Jun-2002 Rhymes wrote: > I'm reading "Learning Python" and in the section "gotchas" > of the exception handling chapter the book itself states > that the exception matching is made by identity not equality. > It also write an example such as this: > >>>> ex1 = "spam" >>>> ex2 = "spam" >>>> >>>> ex1 == ex2, ex1 is ex2 > (1, 0) > > <--- here i get (1, 1) ----> > looks like the interpreter is now optimizing shared strings. >>>> try: > ... raise ex1 > ... except ex1: > ... print 'got it' > ... > got it >>>> try: > ... raise ex1 > ... except ex2: > ... print 'Got it' > ... > Traceback (innermost last): > File "", line 2, in ? > spam > > but in my Python 2.2 i don't get back any error from the interpreter > about the second example... why? What has changed (since 1.5 release) > about objects identity? > modern python uses exception classes and not strings. >>> class BadThingsException: pass ... >>> try: ... raise BadThingsException ... except BadThingsException: ... print 'got it' ... got it From olc at ninti.com Sat Jun 8 05:53:31 2002 From: olc at ninti.com (Michael Hall) Date: Sat, 8 Jun 2002 19:23:31 +0930 (CST) Subject: Creating Dynamic Web Pages (ZOPE) In-Reply-To: Message-ID: I notice no-one has suggested good ol' CGI. For a relatively simple job such as this, a few basic Python CGI scripts, some templates and MySQLdb could also be used ... oh, just noticed the MS-SQL database. There is probably a module around to cope with MS-SQL, no? Mick On 7 Jun 2002, Bill Tate wrote: > hwcowan at hotmail.com (Hugh Cowan) wrote in message news:<46ca81a0.0206062016.789d3af6 at posting.google.com>... > > [snip] > > My scenario is typical where I need to put together a company Intranet > > with a few front end Web-Pages where users can select information, > > various links, and enter search criteria. The information is then > > retrieved from the MS-SQL Server and the results are sent back to the > > user. It's nothing fancy, no shopping carts, or remembering sessions > > states, etc.. just really a simple front-end interface for > > non-technical people to easily retrieve information. > > > > I don't know if ZOPE would fit my situation or not. I know that it is > > / can be used to create complex E-commerce sites, but I am wondering > > if it is overkill for what I need done. Would I be better off trying > > to find some sort of RAD Web Tool instead (anyone have any good > > suggestions) ? > > I think its safe to say that there are any number of tools that could > fit the bill here including Zope. There are aspects of zope that can > make your life much easier (e.g., zsql methods) but it does take some > time to get used to it and everything it offers. Several recent books > on the subject I think would be very helpful to you in this regard. > If you go to zope.org, there is some information on using WYSIWYG > tools such as Dreamweaver with zope that may also be of interest to > you as well. > > I think zope works bests for you over the long haul where it is > important to keep things well organized and well structured. The > ability to collaborate amongst individuals is also a great strength. > If these issues are important to you, then I would say that Zope would > be an excellent choice. > > Good luck!!! > -- -------------------------------- n i n t i . c o m php-python-perl-mysql-postgresql -------------------------------- Michael Hall ninti at ninti.com -------------------------------- From skip at pobox.com Sun Jun 16 15:17:39 2002 From: skip at pobox.com (Skip Montanaro) Date: Sun, 16 Jun 2002 14:17:39 -0500 Subject: [Extending] Py_BuildValue( "((OiiO))",...) creates empty string? In-Reply-To: <3D0CDEEB.2070208@rogers.com> References: <3D0CDEEB.2070208@rogers.com> Message-ID: <15628.58451.320049.77386@12-248-41-177.client.attbi.com> Does Py_BuildValue("(OiiO)", tagobj, childStart, childPosition, childResults); create a valid tuple? Do you have a simple test case you can post that demonstrates the problem? -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From maxm at mxm.dk Wed Jun 12 06:17:42 2002 From: maxm at mxm.dk (Max M) Date: Wed, 12 Jun 2002 12:17:42 +0200 Subject: Reload an imported file References: Message-ID: <3D071FC6.5000309@mxm.dk> Felix Seeger wrote: > I have a config file. This is a normal python file. > Can I reimport this file during runtime ? > So changing the configuration will not need a restart of my program. import myModule reload(myModule) regards Max M From BPettersen at NAREX.com Wed Jun 12 14:54:02 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Wed, 12 Jun 2002 12:54:02 -0600 Subject: Adding and running functions at runtime Message-ID: <60FB8BB7F0EFC7409B75EEEC13E2019221519E@admin56.narex.com> > From: John Dunn [mailto:jhndnn at yahoo.com] > > Hello- > > I am currently embedding Python in my C++ application and > would like to add function 'scriplets' defined by strings and > then call them from C. Let me explain what I am trying to do - > > 1. load a string that defines a function ( or functions ) > 2. get the function object for a defined function > 3. call function with arguments > 4. get return value and modified argument values > > so the code might look something like > > const char * funcs = > "def foo( arg1, arg2 )\n" > " arg2 = arg2\n" > "def foo2( arg1, arg2 )\n" > " return arg1+arg2\n" > > Mythical_PyLoad( funcs ); > PyObject* foo = Mythical_PyGet_Function( "foo" ); > PyObject* foo2 = Mythical_PyGet_Function( "foo2" ); > PyOjbect* args = some code here to create arguments > // this should return the sume of the args > PyObject* result = PyEval_CallObject( foo2, args ); > // this should modify the second arg > PyObject* result = PyEval_CallObject( foo, args ); > > I have been able to load code using Py_CompileString, but > that appears to run inline code, and I couldn't get it to > return a value or modify something in the dictionary. I'm working on something similar. The interface looks like e.g.: py::Namespace ns; NDate d(1970, 5, 2); ns.set("tmp", d); py::stmts( "def two(): \n" " return 2 \n", ns); int result = py::expr("two() + tmp.getYear()", ns); i.e. it uses a namespace to keep track of your function definitions and you get values by assigning the result of py::expr() to the appropriate type. I can send you the code if you'd like... oh, and it also deals with SIP wrapped libraries :-) -- bjorn From emile at fenx.com Wed Jun 19 09:18:22 2002 From: emile at fenx.com (Emile van Sebille) Date: Wed, 19 Jun 2002 13:18:22 GMT Subject: Tkinter and the Menu Widget References: <2259b0e2.0206190415.1f232447@posting.google.com> Message-ID: Michele Simionato > import Tkinter > def dosomething(s): > print s > root=Tkinter.Tk() > mn=Tkinter.Menu(root) #attach the menu mn to root > menuD={'File':['File1','File2'],'Help':['Help1','Help2']} > smn={} #dictionary keys->submenu-objects defined below > for key in menuD.keys(): > smn[key]=Tkinter.Menu(mn) #define a submenu of mn > mn.add_cascade(label=key,menu=smn[key]) #attach smn[key] to mn > for submenu in menuD[key]: > smn[key].add_command(label=submenu,command=lambda : > dosomething(key+'='+submenu)) You've got a scope issue. Try: smn[key].add_command(label=submenu,command=lambda key=key, submenu=submenu: dosomething(key+'='+submenu)) -- Emile van Sebille emile at fenx.com --------- From astavale at yahoo.co.uk Thu Jun 27 13:48:26 2002 From: astavale at yahoo.co.uk (Alistair Thomas) Date: Thu, 27 Jun 2002 18:48:26 +0100 Subject: sys.argv[0] - Returns path and filename. References: Message-ID: In article , "Guy" wrote: > How do I get the current path of the script I am running, on the mac osx > and the linux box ? Does sys.path[0] make any difference? -- Alistair From jdhunter at nitace.bsd.uchicago.edu Sat Jun 29 16:56:17 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Sat, 29 Jun 2002 15:56:17 -0500 Subject: can't import generators References: Message-ID: >>>>> "Aahz" == Aahz writes: Aahz> Can't do this in interactive mode. Use a script Tried that first -- still a no go > cat ./test.py #!/usr/local/bin/python2.2 from __future__ import generators > ./test.py Traceback (most recent call last): File "./test.py", line 2, in ? from __future__ import generators ImportError: cannot import name generators > /usr/local/bin/python2.2 -V Python 2.2.1 > /usr/local/bin/python2.2 /usr/local/lib/python2.2/test/test_generators.py Traceback (most recent call last): File "/usr/local/lib/python2.2/test/test_generators.py", line 1, in ? from __future__ import generators ImportError: cannot import name generators Any other thoughts? The only thing slightly non-standard about by install is that I compiled python2.2 for large file support with OPT= -ggdb -O2 -Wall -Wstrict-prototypes -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 but I can't see that making a difference. John Hunter From phd at phd.pp.ru Thu Jun 13 12:36:36 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Thu, 13 Jun 2002 20:36:36 +0400 Subject: filter2 In-Reply-To: <20020613160557.GC25416@unpythonic.net>; from jepler@unpythonic.net on Thu, Jun 13, 2002 at 11:06:02AM -0500 References: <20020613160557.GC25416@unpythonic.net> Message-ID: <20020613203636.H19424@phd.pp.ru> On Thu, Jun 13, 2002 at 11:06:02AM -0500, Jeff Epler wrote: > funcs = [l2.append, l1.append] > map(lambda x: funcs[bool(test(x))](x), list) Wow! That's nice! Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From pimpao at bestway.com.br Sun Jun 16 19:41:35 2002 From: pimpao at bestway.com.br (Thiago) Date: 16 Jun 2002 16:41:35 -0700 Subject: How refresh a page trhough httplib Message-ID: <6e458916.0206161541.100be8eb@posting.google.com> hi, I need a problem, i was using python to build a application to verify a status of web page, and i used proxy, to connect a internet, and i would like to refresh the page on proxy, because it's cached on proxy! Thiago From gumuz at looze.net Wed Jun 12 09:40:19 2002 From: gumuz at looze.net (Guyon Morée) Date: Wed, 12 Jun 2002 15:40:19 +0200 Subject: Bits and bytes? Message-ID: <3d074e6d$0$224$4d4ebb8e@news.nl.uu.net> ok, this might be a strange question.... but i was wondering: how can i read or write 'bits'? if i have a string, how can i convert to it's basic 0's and 1's? and offcourse, the other way around.... let's say i want to store some bit-sequence(0011101110) to a file. how do i do this? thanx, Guyon From spam at melkor.dnp.fmph.uniba.sk Wed Jun 19 02:38:59 2002 From: spam at melkor.dnp.fmph.uniba.sk (Radovan Garabik) Date: Wed, 19 Jun 2002 08:38:59 +0200 Subject: procmail replacement in Python References: Message-ID: <3u8pea.617.ln@127.0.0.1> Gerhard H?ring wrote: : Does such a thing exist? I've recently looked into the procmail sources http://melkor.dnp.fmph.uniba.sk/~garabik/pycmail.html -- ----------------------------------------------------------- | Radovan Garabik http://melkor.dnp.fmph.uniba.sk/~garabik | | __..--^^^--..__ garabik @ fmph . uniba . sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From kragen at pobox.com Mon Jun 10 17:35:50 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 10 Jun 2002 17:35:50 -0400 Subject: Correct code/unit testing (was Re: Efficient python programming...) References: <3D00A456.4315EDA3@engcorp.com> <834rgd5isv.fsf@panacea.canonical.org> <3D02FB3B.CF75E925@engcorp.com> Message-ID: <83u1oaq0jt.fsf@panacea.canonical.org> Peter Hansen writes: > Kragen Sitaker wrote: > > Peter Hansen writes: > > I also agree that unit tests are very useful for reducing bugginess. > > > > But I do not think that they are either necessary or sufficient for > > writing correct code. > > Without tests, how much confidence can you have in the correctness > of your code? It's been said "you don't know it works if you > don't test it". Tests are one way to increase your confidence in the correctness of your code, but they are not the only way. > > I think (and extensive experimentation has > > shown) that careful reasoning and code reviewing is necessary and > > sufficient to write correct code. > > Whoa! "extensive experimentation has shown"?? Yes. (Well, I guess "correct code" is probably overstating the case. "Code with many fewer bugs per line than most code in use" is probably more accurate.) Are you familiar with Cleanroom programming? > I would suggest that what extensive experience (I change the word > deliberately) has shown many of us is that careful reasoning and > code reviewing, no matter how extensive, will *always* leave bugs in > the code. Have you never spent a large amount of time carefully > designing and coding a wonder little program, and checked it over > very carefully, even with a peer, and later found a bug in it? Of course! People are fallible, it's much easier to do a bad code review than a good one. > Maybe you're just a better programmer than I, and many others, but I > would say this inevitable outcome is the source of the term "egoless > programming" -- if you have a big ego, you'll be devastated by the > repeated proof that you will never, ever get it right the first > time, or even after lots of reviewing. Yes, one of the beautiful things about programming is how it impresses upon each of us how fallible we are. For what it's worth, the term "egoless programming" was invented by Gerald Weinberg for his book _The Psychology of Computer Programming_ to describe a programming style in which group reviews focus on finding bugs in code. It comes from Weinberg's observation that code reviews work very poorly if the author is defensive about bugs, and much better if the author is trying to find bugs too. Of course, it's true of testing too; testing works best if you're trying to find bugs. > > It is certainly possible to err too far in the direction of believing > > your code correct simply because it passes its test suite, and this is > > a common beginner's error. I think it is also possible to err too far > > in the direction of writing and running tests instead of desk-checking > > code. > > I can only suggest that until you have tried test-first development, > in which the code is written in very, very small steps only to make > small failing tests pass, and discovered the possibilities of > emergent design, and other aspects of this approach, then we will not > find much common ground in this discussion. Test-first development, exactly as you describe it above, has been my preferred development style since mid-2000, at least when working on programs of more than 100 lines, especially with other people. I've written a lot of code that way. I think now we have each committed the same arrogant gaffe in this discussion: "It is only possible to disagree with me if you do not know what I am talking about." I was wrong, and so are you. > I simply disagree with your last sentence above, and I believe > beginners _never_ write unit tests anywhere that I've seen, so I > disagree with the first one too. :) Beginners almost always test their code, but rarely by writing a formal test suite --- usually by hand. I think inspection can find bugs that are very difficult to find by testing, and vice versa. That is the reason for my second statement; a balance of careful reasoning and testing can produce better code than the same amount of time spent on either alone. From gh_pythonlist at gmx.de Mon Jun 17 12:06:22 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Mon, 17 Jun 2002 18:06:22 +0200 Subject: coding python by web? In-Reply-To: <3eeda89d.0206170317.100549db@posting.google.com> References: <3eeda89d.0206170317.100549db@posting.google.com> Message-ID: <20020617160622.GA878@lilith.my-fqdn.de> * Thinkit [2002-06-17 04:17 -0700]: > Is there any way to test out simple python code with only a web > browser (no input or files, just printing text)? I'm guessing a > simple cgi setup could do this, but has it been implemented anywhere? Hi, "Thinkit", dunno if it's implemented, yet, but it's not difficult to do. Below I've put a quick, working draft, replace exec with print to see the code. The trick is to redirect sys.stdout and use exec. Things not implemented in the draft: - using a restricted environment - handling exceptions gracefully, displaying a traceback import zlib,base64 exec(zlib.decompress(base64.decodestring(""" eNpdUstq3TAQ3esrplMu2HBjh0IpBNubQKCrLLItFNnWdURkSUjjJCbk3zvy49atVvM4OjNnZr5+ KacYSuM6acpW29LP9Oys0KN3gaAb9BniHHf/iYK2w89HIUiGQRHUgCWDbtLXVnYvvXOh8DMK8Uyj SWnEKplN1bp+bgRsr7q4MMLKUuMpW6084gFC6p3DSoKVo6oxdkF7QgjuLdb47Rahc4atH98R3oL0 Nb7qQJM02JyyFZzHqtxZGvjLrK2fCGj2iXZqR03YVOUSPdQvU49H/z8JPqhrJTcRf071UrQqF80s XohFaJ1GWTxoZfonckEOKsvF+pNzCVKw/FdpJpXtQs88vFwIF/TwO1LPFRjKyyhWR7TT5aICx/at FLuRuK84BqxIIcZ5MK6VJnLs45PdZe+bJ9S76mDrSVu4gs+wA8W/tIfOtmaKqNRLdstde+6EAO+d JWXpJo36DtIqlsn8srhDljs5wQeuF4B321Gw+uNkOb6V4FX2WX5Nc2I1WIH4A+u46F4= """))) Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 29.2 ?C Wind: 3.3 m/s From maxm at mxm.dk Tue Jun 25 05:04:31 2002 From: maxm at mxm.dk (Max M) Date: Tue, 25 Jun 2002 11:04:31 +0200 Subject: ? and %s placeholders, help? References: <3D178542.604@mxm.dk> Message-ID: <3D18321F.6010006@mxm.dk> Duncan Smith wrote: >>>>query = 'INSERT INTO %s (%s) VALUES (%s)' % (tblname, string.join(vars, >>> > ', '), string.join(['%s']*len(vars), ', ')) > >>>>query >>> > 'INSERT INTO tbl (var1, var2, var3) VALUES (%s, %s, %s)' > >>>>curs.execute(query % ("'a'", "'b'", "'c'")) >>> > 1L > #Hurray, but does this avoid parsing the statement on each INSERT? No! >>>>query = 'INSERT INTO %s (%s) VALUES (%s)' % (tblname, string.join(vars, >>> > ', '), string.join(['?']*len(vars), ', ')) > >>>>query >>> > 'INSERT INTO tbl (var1, var2, var3) VALUES (?, ?, ?)' > >>>>curs.execute(query, ("'a'", "'b'", "'c'")) >>> > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python22\Lib\site-packages\MySQLdb\cursors.py", line 70, in > execute > raise ProgrammingError, m.args[0] > ProgrammingError: not all arguments converted Here is where you misunderstand it. If you use the ? notation the dbi will automatically quote and escape as needed. No need to double quote a string like "'string'". Treat it as a plain string "string". This is one of the greatest features of th dbi. You won't even have to escape 'weird' characters "this's also a good string" So this will do instead:: curs.execute(query, ("a", "b", "c")) regards Max M From peter at engcorp.com Mon Jun 17 22:19:43 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 17 Jun 2002 22:19:43 -0400 Subject: Import caches names (was Re: Problems with importing; must do it twice?) References: Message-ID: <3D0E98BF.B2A9A6C2@engcorp.com> Aahz wrote: > > Python caches import names even when the import fails > (protects against circular references) I thought about this for a while and suppose I can see how it protects against circular reference problems (I'm guessing it creates a new module object and stores it in sys.modules immediately upon encountering the import statement, and only subsequently does it try to import and execute the contents), but what I don't understand is why it doesn't clean up after itself in the case of a failed import. Should it not be considered a bug that a failed import leaves a broken module around? Is it possible to redefine this so that it cleanly removes the newly created reference if an import fails? Or would it then be a problem that circularly imported modules might now have references back to a module which appears never to have been imported (because it failed, and was deleted)? And have I now answered all my questions? :-) -Peter From fredrik at pythonware.com Wed Jun 26 04:10:23 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 Jun 2002 08:10:23 GMT Subject: Reminder of a python Project. References: <2218.941T781T12224051threeseas@earthlink.net> Message-ID: Chris wrote: > Gah. I thought I had this guy in my message rules under "Delete from > Server." > > I will remedy this immediately... too late. Guido has already added "True" to the language... From shagshag13 at yahoo.fr Mon Jun 3 10:23:42 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Mon, 3 Jun 2002 16:23:42 +0200 Subject: Efficient posting-list References: <3iKK8.99777$%y.10468246@bin4.nnrp.aus1.giganews.com> Message-ID: > For English text, one would almost certainly reduce the number of text > keys by deleting some suffixes, so that 'statistic', 'statistics', > 'statistical', 'statistically', and maybe 'statistician' would be one > key. But I have no idea of word structure of non-Indo-European > languages and what one should do to reduce key number. I already do stemming via a pos tagger... > By 'length of a posting list' do you mean number of text keys? Ie, > size of key dict? The length of list attached to each key is at most > number of documents. you're right... key dict will be about 500,000 - 600,000, i currently have 140,000 documents but i'll reach 400,000 soon... > You do not specify 'node object'. By now i use a node with : 2 int and 1 float. Node objects are handled in a python list. > This is crucial since these take up > most of memory. (This a good reason not to index the 2000 or so most > common keys.) I already index only useful parts and can't *shrink* it more... > For pure Python, tuple is most space efficient. If > each node really is (integer id, integer count), one could devise a > system using a pair of array (module) objects or 2-dimensional > numerical python arrays; which store actual integers rather than > pointers to int PyObjects. When filled, they would have to be copied > to larger arrays in much the same manner as done automatically by > Python lists. So here you think that i should use only one list (i can't use a tuple, i need to update values) containing : [id_x, count_x, float_x, id_x+1, count_x+1, float_x+1, ...] and so on ? thanks, s13. From cliechti at gmx.net Fri Jun 28 18:57:35 2002 From: cliechti at gmx.net (Chris Liechti) Date: 29 Jun 2002 00:57:35 +0200 Subject: Redirect stdout with createfilehandler References: <3D1CE1FB.9060007@caramail.com> Message-ID: Fabien HENON wrote in news:3D1CE1FB.9060007 at caramail.com: > With the script below I keep getting the error ' maximum recursion depth > exceeded'. ... > 8<-------------snip--------------->8 > import sys,os > import Tkinter > from Tkinter import * > > root = Tk() > > T=Text(root) > T.pack() > > cmd = 'mega +i1.pov +w320 +h240 +dgt +v -f' > c_in,c_out=os.popen4(cmd) > > def stdout_handler(): > T.insert('1.0',c_out) > root.tk.deletefilehandler(c_out) > root.tk.createfilehandler(c_out, Tkinter.READABLE, stdout_handler) > root.after(1000,stdout_handler()) don't know muchabout tkinter... but here your CALLING stdout_handler, you're sure you want this? from the 'root.after' i would expect that you should pass a callable as second parameter -> leave away the paranthereses. root.after(1000,stdout_handler) > root.tk.createfilehandler(c_out, Tkinter.READABLE, stdout_handler) here you pass a callable (a function object here), like i would expect it in the other cases too. > root.after(1000,stdout_handler()) same here ^^ > root.mainloop() > 8<--------------snap--------------->8 chris -- Chris From dradul at yahoo.com Fri Jun 21 21:40:57 2002 From: dradul at yahoo.com (P. Alejandro Lopez-Valencia) Date: Fri, 21 Jun 2002 20:40:57 -0500 Subject: Windows versions of Python---pros and cons? References: <3D110B55.4D8AD7FA@astro.cornell.edu> <3D1214B6.E9BB77D2@noaa.gov> <3D125B79.6090903@skippinet.com.au> Message-ID: "Mark Hammond" escribi? en el mensaje news:3D125B79.6090903 at skippinet.com.au... > Chris Barker wrote: > > > On that note: does anyone know if there is a way to turn a Python script > > into something that acts like an application on Windows...without > > resorting to Py2exe and the like. What I want is something just like: > > Add the .py extension to your PATHEXT environment variable, and you can > execute "foo.py" at the command prompt. Like much of Windows, this is > based on the extension rather than file attributes. Ehem! :) This only works in WINNT class OSs that use cmd.exe as their default command line processor. Lowly DOS32 OSs such as the Win98 mentioned by the OP, that only have command.com, just can't. From benjl at cse.unsw.edu.au Thu Jun 13 07:35:27 2002 From: benjl at cse.unsw.edu.au (Benno) Date: 13 Jun 2002 04:35:27 -0700 Subject: How to call a function using apply with keyword args? References: Message-ID: <332c7c11.0206130335.6b97b7aa@posting.google.com> "Achim Domma" wrote in message news:... > Hi, > > I have a function like this: > > def MyFkt(A,B,C): pass > > and some parameters from a config file: > > params = {'A':5,'B':8,'C':9} > > how can I call MyFkt with this parameters? I tried apply(MyFkt,[],params) > but get this error: > > TypeError: MyFkt() takes exactly 3 non-keyword arguments (0 given) The code looks ok to me. This: def pants(A, B, C): print A, B, C dikt = {"A":1,"B":2, "C":3} # We can use 2.1 syntax to avoid calling apply pants(**dikt) # Or we can use apply if we want to. apply(pants, [], dikt) This works for me, so i'm not sure what you have missed. Benno From kseehof at neuralintegrator.com Tue Jun 11 19:58:34 2002 From: kseehof at neuralintegrator.com (Ken Seehof) Date: Tue, 11 Jun 2002 16:58:34 -0700 Subject: Sorting list (maybe stupid) In-Reply-To: Message-ID: > Is sort() stable -- that is, is the relative order of elements > which compare > equal preserved? A quick shufti through the ActivePython docs wasn't > illuminating. > > -- > James Kew > james.kew at btinternet.com Documentation? Real programmers don't read (or write) documentation. :-) >>> a = [1,1.0,3.0,3,2.0,2,0,0.0] >>> a [1, 1.0, 3.0, 3, 2.0, 2, 0, 0.0] >>> a.sort() >>> a [0, 0.0, 1, 1.0, 2.0, 2, 3.0, 3] So yes, sort() is stable. I suppose it's theoretically possible for a different python implementation to use a different sort algorithm, but practically speaking, that is very unlikely. - Ken Seehof From quinn at upchuck.ugcs.caltech.edu Thu Jun 27 01:53:29 2002 From: quinn at upchuck.ugcs.caltech.edu (Quinn Dunkan) Date: 27 Jun 2002 05:53:29 GMT Subject: Suggestions for good programming practices? References: Message-ID: On Mon, 24 Jun 2002 16:31:14 -0500, Mark McEahern wrote: >How do you choose between these: > > if x is None: > > if x: > >The latter is what you'd use if you wanted to work with instances that >defined __nonzero__ and or __len__. In other words, you don't really care >what the type of x is, nor whether it's identity is zero, just whether it >considers itself nonzero. > >Is one more or less polymorphic than the other? I don't really know. But >it sure does sound good. They both serve their own purposes and you have to know what you want. For example, I recently tracked down an annoying bug where I said 'if x' when I meant 'if x is not None'. Everything worked until x's __len__ returned 0 and it was hard for me to see 'if x' as being buggy code. I wasted a lot of time trying to figure out why 'x' was occaisionally None. From observer at NOSPAM.space.pl Thu Jun 13 05:05:31 2002 From: observer at NOSPAM.space.pl (Johann) Date: Thu, 13 Jun 2002 11:05:31 +0200 Subject: How to check version of Python under CGI References: <873cvrin1q.fsf@tux.ntw23.fr> Message-ID: On Thu, 13 Jun 2002 10:57:21 +0200, Johann wrote: >Do you know how to check what modules are installed? E.g. I >would like to check if PYANA or other xml modules are installed. for x in dir(__builtins__): print x Is it all i can get? -- Johann From dyoo at hkn.eecs.berkeley.edu Sat Jun 1 04:00:36 2002 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Sat, 1 Jun 2002 08:00:36 +0000 (UTC) Subject: How to open a HTML file when the python cgi program is executing? References: Message-ID: Ken wrote: : How do I open a HTML file when the cgi program is executing? : The only method I can think of, which doesn't work is this: : Not quite sure I understand yet. Do you have a file called 'main.html' that you're trying to display from your CGI program? I just want to make sure we're work on the same problem here before babbling. *grin* Talk to you later! From irmen at NOSPAMREMOVETHISxs4all.nl Tue Jun 11 17:41:11 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Tue, 11 Jun 2002 23:41:11 +0200 Subject: M2Crypto: select() behaves weird on SSL sockets References: <3D04ED17.5070606@NOSPAMREMOVETHISxs4all.nl> Message-ID: <3D066E77.4070901@NOSPAMREMOVETHISxs4all.nl> Donn Cave wrote: > I'm no expert on this, but my theory is that you must call > SSL_pending(self->ssl) to see if any data remains in its buffer. > Then only when no data remains, you would call select. I looked around a bit and oh boy, M2Crypto supplies a "pending" method on SSL sockets, that apparently returns the remaining data. I now have a workaround; if my socket is an SSL socket, and there are still bytes pending (socket.pending()>0), I don't call select. In all other cases it is 'safe' to call select. My code (Pyro with SSL and timeouts) now works, I'm happy :-) Thanks for the help! Irmen de Jong From tdelaney at avaya.com Tue Jun 11 00:32:33 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Tue, 11 Jun 2002 14:32:33 +1000 Subject: Correct code/unit testing (was Re: Efficient python programmi ng...) Message-ID: > From: Peter Hansen [mailto:peter at engcorp.com] > > Kragen Sitaker wrote: > > > > Peter Hansen writes: > > > Have you never spent a large amount of time carefully > > > designing and coding a wonder little program, and checked it over > > > very carefully, even with a peer, and later found a bug in it? > > > > Of course! People are fallible, it's much easier to do a bad code > > review than a good one. > > I have to confess I have never seen a successful code review, nor > an environment in which they were used regularly and which had a > high level of code quality. Clearly as a result I'm fairly biased > against them -- I should keep a more open mind on the issue perhaps. I presume you mean a full, formal review by a group for a large piece of code? I'm certain that with your experience with XP, you have seen and taken part in *many* successful reviews (where success means the code is improved as a result). Tim Delaney From BPettersen at NAREX.com Wed Jun 26 15:59:56 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Wed, 26 Jun 2002 13:59:56 -0600 Subject: tomorrow in yyyymmdd format Message-ID: <60FB8BB7F0EFC7409B75EEEC13E201922151B3@admin56.narex.com> > From: Conrad [mailto:zneptune at zexcite.zcom] > > Years ago, Nostradamus predicted that on Tue, 18 Jun 2002 > 20:52:25 -0500, > Gerhard H?ring would write, saying: > > > * Sean 'Shaleh' Perry [2002-06-18 > 18:38 -0700]: > >> >> > >> >> Sure there is :-) time.mktime() can take a "malformed" > time tuple > >> >> and do something sensible with it. You can therefore get a time > >> >> tuple from gmtime, add one to the day position and call > >> >> time.mktime() on the result: > >> >> > >> >> >>> x = (2002, 2, 29, 0, 31, 42, 2, 170, 0) > >> >> >>> time.gmtime(time.mktime(x)) > >> >> (2002, 3, 1, 7, 31, 42, 4, 60, 0) > >> >> >>> > >> >> >>> > >> > Pure luck that this works. Don't complain if it stops workin in > >> > Python 2.7 and your code breaks ;-) > >> > > >> > > >> actually that is a function of the mktime() function in > the C library > >> which the python module wraps. Based on my reading of a > man page or > >> two this behaviour seems guaranteed by POSIX. Now, the > assumption made > >> is the mktime() function on YOUR system follows POSIX. > > > > Fine. I've just read the Python documentation which doesn't > make this > > guarantee. I'll leave it to others to check if this works on win32, > > MacOS, as I'm using mxDateTime for this kind of tasks, anyway. > > > > Gerhard > > > Hmm - here's what I've done - a bit klutzy but it seems to work: > > from time import * > one_day = 60*60*24 # number of seconds in day > # make a julian for tomorrow - > # note: depending on what you want be careful around midnight! > tomorrow = mktime(localtime()) + one_day > print 'tomorrow is',localtime(tomorrow) > print 'today is',localtime() The problem with this approach is that it doesn't account for DST. This may or may not be a problem for you... 00h15+24-1'ly y'rs -- bjorn From mjais at web.de Thu Jun 13 10:55:20 2002 From: mjais at web.de (Markus Jais) Date: Thu, 13 Jun 2002 16:55:20 +0200 Subject: Poll: Readable languages References: Message-ID: Chris Gonnerman wrote: > On Thu, 13 Jun 2002 09:36:06 -0400 (EDT), Attila Horvath wrote: > >> In my years of experience I have come across VERY readable assembler and >> very unreadable COBOL, PASCAL, FORTRAN, ADA, C/C++, JAVA, etc. So I >> suggest that a langauge does not inherently make resultant code readable. > > True, and false. It is possible to write bad code in any language; but in > my opinion, any programmer who has mastered Python (takes what, a couple > of weeks? :-) *tends* to write more readable code than an equivalently > accomplished programmer in any other language. > > Those of us who have been here a while have learned from experience of the > ease of writing Python code, and reading it again later. I have to admit, > most of the Python I write is little stuff to do jobs I would have done > with Bourne shell in the past... but I tend to save them for reuse as I > would not have done with a command-line pipeline. I can confirm this. when I write Python or Ruby code the programms tend to be much more readable that with Perl or C/C++. and definitely much shorter than C/C++ which makes it also more readable markus From pyth at devel.trillke.net Mon Jun 17 06:34:41 2002 From: pyth at devel.trillke.net (holger krekel) Date: Mon, 17 Jun 2002 12:34:41 +0200 Subject: a possibly foolish question about slices In-Reply-To: ; from mwh@python.net on Mon, Jun 17, 2002 at 09:36:09AM +0000 References: <4c877253.0206162149.bff3ae3@posting.google.com> Message-ID: <20020617123441.O15079@prim.han.de> Michael Hudson wrote: > garth at deadlybloodyserious.com (Garth T Kidd) writes: > > > > x[p:][:n] > > > > Does the parser take the appropriate short-cut, here, > > No. Wouldn't be the parser anyway, would it? > > > or do we end up with a temporary list? > > It's very easy to answer questions about whether Python performs this > sort of optimization: it doesn't. :-) [michael probably knows the following, nevertheless] python's compiler can't possibly optimize unless it somehow had additional information about the *name* where an object is bound to. As things stand the names 'x','p','n' in the above expression could point to almost any object with as many sideeffects as imaginable. More specifically in 'x[p:]' the slice-operator of the object denoted by 'x' could have sideeffects which the compiler can't try to guess. on the flip side you get the powerful dynamisms of python which spares time in many other respects :-) seriously though, the above expression is not very nice if 'x' is a big list. It then executes *much much* slower compared to something like: def numslice(x, start, maxnum): end=start+maxnum if start<0 and end>=0: return x[start:] return x[start:end] Plus this also makes it possible to let numslice(x, -5, 10) return the last 5 elements. cheers, holger From rowen at cesmail.net Fri Jun 28 12:35:05 2002 From: rowen at cesmail.net (Russell E. Owen) Date: Fri, 28 Jun 2002 09:35:05 -0700 Subject: Help with an algorithm wanted References: <7934d084.0206271628.665b03b3@posting.google.com> Message-ID: >So effectively you have a conversion graph, where each vertex >represents a known representation, and each edge represents a >conversion (presumably with a conversion function as an annotation to >the edge). > >What you are asking for appears to be an algorthm to find the shortest >path between to representations in the graph. Fortunately for you, >Dijkstra provided a solution to this problem a number of years ago, >and implementing it is a standard algorthms assignment (I do hope >you're not asking for help with a homework assignment?). > >You'll find an implementation in the Python Cookbook @ >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/119466 > >The recipie was submitted by David Eppstein. It dosn't look >optimised, but that's ok because it is legible (much more important) >and the algorithm is efficient. Thank you very much for the pointer. My problem is exactly one of converting data to different representations. In my case I am dealing with targets for a telescope that may be in FK5, ICRS, Galactic, Apparent Geocentric, Apparent Topocentric... coordinates. It's not a homework assignment, but is for a telescope control GUI I'm working on. The code will be available to others, probably being served at my web site . (I serve all my utility routines there, but the internals of the user interface I consider not of general interest, so I only send that by request. I suspect this code will end up in the former category, but I can't be sure until I finish modularizing and writing it.) Finding the shortest path isn't an issue, because the path between any two representations will always be unique. Still, anything that can find a shortest path can find a unique path. I'll definitely have a look at the recipe. The main thing I'm worried about is once I have a solution, how best to implement on object that implements it. I'm afraid that might not make much sense, but I hope it's clear from another posting I made with a solution to the problem. That solution is definitely not optimised but I hope it is legible. Regards, -- Russell From ji at tarzan.it.jyu.fi Fri Jun 14 04:50:39 2002 From: ji at tarzan.it.jyu.fi (Jonne Itkonen) Date: Fri, 14 Jun 2002 08:50:39 +0000 (UTC) Subject: Exheritance and Python Message-ID: ECOOP 2002 had an interesting workshop on inheritance -- whish I could have attended. It had a particularly interesting paper about exheritance -- well, I'm a bit tempted to read Mr Sakkinen's papers :) http://www.cs.jyu.fi/~sakkinen/inhws/papers/Sakkinen.ps Exheritance is like inheritance, but other way around. As inheritance specialises, exheritance generalises. If you, my humble reader, can't think of any use for exheritance, please feel free to skip the rest of the message. My first idea after reading the paper was 'well, it should be possible to exherit in Python', and after a bit of testing, I found out that Python actually can do exheritance better than I thought...for old type classes... :( (Old type class is class which does not inherit 'object'.) So, for an old type class C one can say: C.__bases__=C.__bases__+(A,) and after that, even subclasses of C find methods of A. (If you read Sakkinen's paper, hold on. I'm now just considering using exheritance as 'interface exheritance' or even bare 'type inheritance', that is, I'm not yet trying to exherit any methods or attributes.) For new type classes, those that inherit object, this doesn't work, as __bases__ is read-only. Why? (Answering my own questions, PEP252 tells that "The introspection API is a read-only API", but continues "A future PEP may define some semantics for some such assignments". It seems I'll be to writing a PEP. PEP253 also has an innocent open issue "assignment to __dict__, __bases__".) I found an article posted here some time ago, which suggested using type() to re-define class, like: C=type(C.__name__, C.__bases__+(A,), C.__dict__) but for two reasons, this does not work: 1. C.__dict__ is a proxy to dict, not a dict object. 2. If there are classes using old class C, they hold references to that class, but new classes inherited from C refer to new C. This is clear, type() doesn't change the old class, it creates a new one 'overrides' the name of the old class. So, is there a way to change the __bases__-attribute of a new type class? Am I to write a PEP? Is anyone interested contributing? Or am I just to use the old type of classes? Jonne From ajw126NO at SPAMyork.ac.uk Sat Jun 29 16:18:08 2002 From: ajw126NO at SPAMyork.ac.uk (Andrew Wilkinson) Date: Sat, 29 Jun 2002 21:18:08 +0100 Subject: SSE With Swig Message-ID: Hi, I'm trying to develop a Vector class that uses Intel's SSE extension. It works very well when called using c or c++, but when I wrap the class with Swig I get a privileged instruction exception error (this is under Windows 2000 using MSVC++ 6sp5 with the processor pack installed). I've included the code below, any suggestions would be greatly appreciated Andrew Wilkinson swig.i %module Vector %{ #include "Vector.h" %} class Vector { public: Vector(); virtual ~Vector(); Vector* operator+(const Vector *other); float x; float y; float z; float w; }; __ vector.h class Vector { public: Vector(); virtual ~Vector(); Vector* operator+(const Vector *other); __declspec(align(16)) union { __m128 v; struct { float x; float y; float z; float w; }; }; }; --- vector.cpp #include "Vector.h" #include Vector::Vector() { x = 0.0f; y = 0.0f; z = 0.0f; w = 0.0f; } Vector::~Vector() { } Vector* Vector::operator +(const Vector *other) { Vector* r = new Vector; r->v = _mm_add_ps(v, (other->v)); // The exception occurs here. return r; } -- --- Ditch The Decimal System! Lets Use Hex - http://www.intuitor.com/hex/switch.html From ngiven at lanl.gov Wed Jun 26 17:56:56 2002 From: ngiven at lanl.gov (Nathan Given) Date: Wed, 26 Jun 2002 15:56:56 -0600 Subject: Integrals with Python References: <3D188551.6BA00DED@lanl.gov> <3D196758.3040604@kfunigraz.ac.at> Message-ID: <3D1A38A8.9BD2CA47@lanl.gov> > If you have got measurements only and want to numerically integrate that > you can get a small Simpson function from me (a few lines of python > code). Drop me a note. I use it heavily in combination with measurements > (and the precision is okay; you know measurement values...). that would be great... you can email it to me... thanks -- nathan From shalehperry at attbi.com Sat Jun 8 01:20:21 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 07 Jun 2002 22:20:21 -0700 (PDT) Subject: Efficient python programming... In-Reply-To: <3D018306.D01A8C9B@engcorp.com> Message-ID: > > Automated testing of GUIs is a very underdeveloped area of software > development, but it's a frontier that almost nobody is bothering to > explore. If more people check it out I think we'll make better > progress developing it. > the problem is that extra level adds more code, more bloat and is one more thing for new hackers to learn when they approach the project. Yes I know tight coupling is usually bad. But sometimes it is the best way to solve the problem at hand. and now I have walked this sufficiently off topic to bore most of the readers of this list. From hesterloli at hotmail.com Tue Jun 18 16:48:14 2002 From: hesterloli at hotmail.com (George Hester) Date: Tue, 18 Jun 2002 20:48:14 GMT Subject: python version? References: <3tingu8psfmefoab93pl8gips8hg7sgpvp@4ax.com><9YBP8.44418$GY.13865843@twister.nyroc.rr.com> Message-ID: Bah humbug. -- George Hester _________________________________ "Cliff Wells" wrote in message news:mailman.1024423525.24359.python-list at python.org... > On Tue, 18 Jun 2002 08:12:53 GMT > George Hester wrote: > > I think you guys don't how to do it. > > I think you wouldn't know an answer if it bit you: > > [You] > What is a simple script that will tell me the version of python I am currently > running? IIS 5.0 Windows 2000. > > [Jeremy Yallop] > Look up sys.version and sys.version_info. > > [You] > Traceback (innermost last): File " > > > > Perhaps you'd like someone to come out and type it for you as well. > > Please remember that the people on this list aren't being paid to help you > write your program. They expect you to do at least /a little/ of the research > yourself. It's understandable if you don't know where to look, but when > someone points you to the relevant portion of the docs, you should at least > read it before asking again. It's clear from your postings that you haven't > even read the tutorial. > If you can't do that then you should pay someone to write your program for you. > > -- > Cliff Wells, Software Engineer > Logiplex Corporation (www.logiplex.net) > (503) 978-6726 x308 (800) 735-0555 x308 > > From donn at u.washington.edu Mon Jun 24 19:04:45 2002 From: donn at u.washington.edu (Donn Cave) Date: 24 Jun 2002 23:04:45 GMT Subject: AF_UNIX + SOCK_DGRAM References: Message-ID: Quoth "James T. Dennis" : [... re sockaddr_un->path fix ] | So, should this be reported to the Python dev list? If so, how? | Can we get it fixed by 2.3? How would my code work if it was fixed? | What would/should be returned for this case? If Chris Liechti submits it to Sourceforge as he proposed to do, that should eventually lead to a fix in the distributed version, assuming everyone concerned agrees with the solution. I don't know where they are with 2.3 (heck, I've never even seen 2.2 yet), but would think this kind of bug fix ought to be acceptable up through alpha testing. I can't guess at what your code does in any interesting detail. Functions that return an address should return something that will work as an address. In the UNIX domain, that means a string representing the file (path). Donn Cave, donn at u.washington.edu From kragen at pobox.com Sat Jun 1 15:52:50 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 01 Jun 2002 15:52:50 -0400 Subject: Which is fastest dict or list.index() ? References: Message-ID: <83vg92vkrx.fsf@panacea.canonical.org> "Shagshag13" writes: > My question is which is the best way (best = quickest and memory safe) to > handle this ? > Should i subclasse from dict or list ? I don't think so. > Should i consider using only one list with toons (and use their index as id) > ? Yes, I think that's what you should do. If you have a lot of toons, that may be too slow, but unless you can quantitatively estimate the amount of time list.index will take (and it's too much), try the simpler method first, and then optimize by adding the dict if necessary. > Should i use 2 dicts ? I don't think so. From gerhard.haering at gmx.de Fri Jun 21 19:15:14 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Sat, 22 Jun 2002 01:15:14 +0200 Subject: TimeoutQueue.py In-Reply-To: References: Message-ID: <20020621231514.GA873@lilith.my-fqdn.de> * Tim Peters [2002-06-21 18:32 -0400]: > [Chris Liechti] > > Anyone ever needed a Queue with timeout? > > Yes. I encourage you to submit a patch to SourceForge, [...] I like it. It would certainly be a useful addition. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From quinn at upchuck.ugcs.caltech.edu Thu Jun 27 01:11:06 2002 From: quinn at upchuck.ugcs.caltech.edu (Quinn Dunkan) Date: 27 Jun 2002 05:11:06 GMT Subject: Questiion on list References: Message-ID: On Thu, 27 Jun 2002 14:36:03 +0000, SiverFish wrote: >I got the list of words now i want to calculate how many word in that >list which is the same word (insensitive case),can anyone show me how to do >it for example ls = ['abc','cd','abc','adf',abc','dwc','cd'] >it will show abc = 3 ,cd = 2, adf = 1, dwc=1 import string d = {} for e in map(string.lower, ls): d[e] = d.get(e, 0) + 1 freqs = [ (count, w) for w, count in d.items() ] freqs.sort() freqs.reverse() print ', '.join([ '%s = %d' %(count, w) for count, w in freqs ]) From safarzadeh at hotsheet.com Thu Jun 13 00:21:09 2002 From: safarzadeh at hotsheet.com (H. Safarzadeh) Date: 12 Jun 2002 21:21:09 -0700 Subject: Python GUI Message-ID: <9ddd154e.0206122021.1b06f89a@posting.google.com> Hi all, I know that this subject is discussed in many other places, but I don't think it is harmful to talk about it more! I want to what library I should use to make GUI for my Python apps? I have examined many of them, but I couldn't find what I need. Here is the result of some of my examinations: -Tkinter: A nice simple lib, but really simple! It dosn't have enough widgets, and I do not like its look in addition! -wxPython: Really perfect. It has many widgets, and do many works(not only in GUI). But it is toooo big!(both on disk and in memory). I need a smaller one. -pyGTK and pyQt: I do not know enough about them. But I know that I do not like GTK look on Windows and Qt for Windows has some problems with its lisence(and it is tooo big, too!) -Jython/Swing: ....it's Jython, after all! -Win32 extensions: It is not portable!!! Any comments? Other possibilities? Thanks. From maxm at mxm.dk Mon Jun 24 16:46:58 2002 From: maxm at mxm.dk (Max M) Date: Mon, 24 Jun 2002 22:46:58 +0200 Subject: ? and %s placeholders, help? References: Message-ID: <3D178542.604@mxm.dk> John Hunter wrote: > As far as I know, the '?' syntax is used in the perl DBI but nowhere > in the python MySQLdb. So forget about that one. It is also part of the Python DBI spec. > To start with a simple example from the docs: > > c.execute("""SELECT spam, eggs, sausage FROM breakfast > WHERE price < %s""", (max_price,)) c.execute("""SELECT spam, eggs, sausage FROM breakfast WHERE price < ?""", (max_price,)) Should work just as well. > # use python string format to build the mysqldb query string > # query == 'INSERT INTO mytable (var1,var2,var3) VALUES %s,%s,%s' > query = "INSERT INTO %s (%s) VALUES %s" % \ > (tbl, string.join(vars, ','), valsfmt) Or with the '?' as a placeholder query = "INSERT INTO %s (%s) VALUES %s" % \ (tbl, string.join(vars, ','), ','.join(len(vars)*['?'])) Generally you would use the %s to insert tablenames, variablenames etc. And you will use ? to insert the variables. you can do: execute('select firstName, lastName from employess where age > 42') or execute('select firstName, lastName from employess where age > ?', (42,)) or qs = 'select %s from employees where age > ?' % ('firstName, lastName', 'employees') execute(qs, (42,)) regards Max M From aahz at pythoncraft.com Mon Jun 17 16:34:46 2002 From: aahz at pythoncraft.com (Aahz) Date: 17 Jun 2002 16:34:46 -0400 Subject: '__builtin__' vs. __builtins__ References: Message-ID: In article , Beni Cherniavksy wrote: > >Why is the '__builtin__' module available under the __builtins__ name? >By what's the logic one is supposed to remember it? (If I do remember >that it's different I would still confuse which is what...) My paraphrase of what Tim Peters said the last time this came up: Main reason is to avoid getting flooded with output when calling ``vars()`` in interactive mode. (From my upcoming OSCON tutorial.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From sarmstrong13 at mac.com Thu Jun 13 13:36:17 2002 From: sarmstrong13 at mac.com (SA) Date: Thu, 13 Jun 2002 12:36:17 -0500 Subject: Translating Tcl/Tk code into Python/Tkinter help please... Message-ID: Hi Everyone- I am trying to translate a tcl program that use tk into python. I seem to be going along fine until I get to the process that wants to "catch" the results onto one text screen. Here is what I am looking at: proc python {} { catch {exec /sw/bin/python -c [.t1 get 0.0 end]} output .t2 delete 0.0 end .t2 insert end $output } Basically, this process catches the output from running the code in the text widget .t1 through python -c and places it into the variable ouput. The text widget .t2 is then cleared and the contents of the variable $output are displayed in the text widget .t2. I can translate all of the widgets into python/tkinter code, but I'm not sure about how to translate this process. Is there a function similar to "catch" in Python? Thanks. SA From BPettersen at NAREX.com Wed Jun 12 14:35:35 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Wed, 12 Jun 2002 12:35:35 -0600 Subject: Can Distutils include .pyd files directly? Message-ID: <60FB8BB7F0EFC7409B75EEEC13E2019221519D@admin56.narex.com> > From: Thomas Heller [mailto:theller at python.net] > > "Bjorn Pettersen" wrote in message > news:mailman.1023837255.23228.python-list at python.org... > > I've built my extension modules using the MS Devstudio IDE > and now I > > would like to use Distutils to create a Windows installer > for me that > > puts both the debug and release versions of the extension in the > > python22\DLLs directory. Is this possible? If not, is there > a way to > > have Distutils build my extension in both debug and release > mode and > > install both? > > > > -- bjorn > > Sure. The 'build' command builds a 'pseudo installation tree' > in the directory build\lib.win32-2.2, all of this will later > be installed by the 'install' command. So you can > python setup.py build > to build the release version, > python setup.py build -g > to build the debug version, and Is there any way I can skip having Distutils building the extension? If there isn't, is there a way to provide a separate 'library_dirs' option for debug libraries? (We have our release libraries in \active\release and the debug libraries in \active\debug, and they have the same names...) > python setup.py install > will install all of this into Python22\lib\site-packages. > python setup.py bdist_wininst > will create a windows installer containing the debug _and_ > the release version (everything that's in the build directory). > > Thomas -- bjorn From gerhard.haering at gmx.de Thu Jun 20 08:15:06 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Thu, 20 Jun 2002 14:15:06 +0200 Subject: module string.py In-Reply-To: <3d11bd6a.11177520@news.polito.it> References: <3d11bd6a.11177520@news.polito.it> Message-ID: <20020620121505.GA1043@lilith.my-fqdn.de> Hi "Nop", * NOPollution [2002-06-20 11:38 +0000]: > I have two trouble: > > 1) looking at the module "string.py" I have seen that are described > some functions like "lower", "rjust", etc. Ther problem is that it > seems not to describe exactly how this functions are made, but there > is only a comment about their properties. So in which file are these > functions described? The behaviour of these functions is described in the documentation, for example in http://www.python.org/doc/current/lib/module-string.html: lower(s) Return a copy of s, but with upper case letters converted to lower case. In this particular case, the docstring of the function has just as much info: >>> string.lower.__doc__ 'lower(s) -> string\n\n Return a copy of the string s converted to lowercase.\n\n ' If you're looking at additional info for _how_ exactactly these functions are implemented, then the source code is the only info there is. Btw. in current Python versions the string module just delegetages to the string methods, which are the preferred option. So you could just as well use. > 2) I tried to cancel the file "string.py". After that, the Python > Interpreter doesn't work anymore (it can't even start working). Why? You're not supposed to delete modules from the standard library. If you don't want your Python to fail in obscure ways, you'd better get that file back into place. Btw. my Python 2.1.3 and 2.2.1 starts up fine even without the string module. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From deckerben at freenet.de Sun Jun 23 17:37:27 2002 From: deckerben at freenet.de (deckerben) Date: Sun, 23 Jun 2002 23:37:27 +0200 Subject: Fork References: <3d15c022$0$26988$9b622d9e@news.freenet.de> <3D15C638.EE5797F9@phekda.freeserve.co.uk> Message-ID: <3d16405b$0$166$9b622d9e@news.freenet.de> > Look in the libc docs: > > info libc alpha fork Thanks for the reference, it shed more light on the matter than the FAQ did. I'm 100% sure now that its the fork that makes distutil builds using GCC "run out of memory" :-) I started working on on of the python library scripts that defines the make sequence so that it no longer calls python funcion 'os.fork()'. It is _possible_ that the next release of Python will support distutil builds _to_a_limited_degree_. For those who are interested, here is a new feature list of *currently* running modules that exist in the latest port that were not present in the previous test. Next release date is still undetermined. socketmodule (using watterloo library - DOS packet driver is needed.) expat module - James Clark's XML parser inside a Python wrapper libxml wrap- the Python wrapper for the GNOME 'LibXML' library, latest CVS release Mathematical/Scientific visualization using NUMERIC (complete) and the DISLIN display driver Runar Tenfjord's Python adaptation of Mark Spink's NURBS toolbox has been incorperated as an example of the dislin/numpy facilities. Others: termios, selectmodule, syslogmodule, parsermodule The fate of cursesmodule depends on the hopefuly successful implementation of the DXE2 dynamic linking library, as many symbols it defines/requires interfere with DISLIN. Ben From fschaef at ces.clemson.edu Wed Jun 19 17:18:44 2002 From: fschaef at ces.clemson.edu (Frank Schaefer) Date: 19 Jun 2002 14:18:44 -0700 Subject: file .seek() under MS-Windows Message-ID: <4169349c.0206191318.7f0d99d9@posting.google.com> Hi, The following code: fh = open("myfile.pot", "r") ... fh.seek(-1,1) ... produces an error: [IOError 22] Invalid Argument under MS Windows (XP). It works fine under Unix, though (for years). I appriciate any help. Thanks, Frank. From campbells4 at ozemail.com.au Fri Jun 28 07:56:09 2002 From: campbells4 at ozemail.com.au (Alistair Campbell) Date: Fri, 28 Jun 2002 21:56:09 +1000 Subject: [NEWBIE]- Syntax error Message-ID: Hi, I imagine the answer to this post is very simple ... but I'm not proud. Using Python2.2 on Windows OS Anyway, when I try to run a script fom the command line in IDLE or Python >>>python name_of_script.py the interpreter complains that there is a syntax error and highlights the "name_of _script" part. I imagine that I have not initialised some PATH variable or other. I guess that i need to put something in the autoexec.bat. Can anyone suggest what? Alistair Campbell Brisbane, Qld, Australia From have.a.look at the-body.com Tue Jun 18 18:25:16 2002 From: have.a.look at the-body.com (Giulio Cespuglio) Date: Tue, 18 Jun 2002 22:25:16 +0000 (UTC) Subject: tomorrow in yyyymmdd format Message-ID: Hello everybody, We all know that if I want to get the present GMT date in yyyymmdd format I should say print time.strftime("%Y%m%d", time.gmtime() ) Now, what about tomorrow? Note that a simple string manipulation is not the solution I'm looking for, as tomorrow might be next month, next year, the 29th of February and such. Do you confirm that there's nothing better than the following silly-looking expression? time.strftime("%Y%m%d", time.gmtime(time.time() + 60*60*24)) Thanks, Giulio _______________________________________________ To reply, please replace ".pizza." with "." giulio.pizza.agostini(at)libero.pizza.it From TuxTrax at fortress.tuxnet.net Wed Jun 5 06:31:19 2002 From: TuxTrax at fortress.tuxnet.net (TuxTrax) Date: Wed, 05 Jun 2002 10:31:19 -0000 Subject: Compiling Python Message-ID: Hello all I am new to this forum, and to Python, please excuse the newbie question. I have started reading the o'reilly book, "learning python" and find python to be an amazing language so far. My first impression of it is a language that is easier than basic to learn and use, and more powerful than many other high level languages such as pascal. My question is this; I realize that Python compiles to bytecode automatically as part of the interpreters tokenization run, but is there a way to permanently compile python code outputting to an executable binary? Cheers, Mathew -- TuxTrax (n.) An invincible, all terrain, Linux driven armored assault vehicle that can take as much fire as it gives ;-) ASSASINATION ANTHRAX PRESIDENT NUCLEAR TALIBAN AMMONIUM NITRATE Yes, I am a Penguin cult high priest. Fin readings upon request. ROT13 this email address to mail me: uvtuqrfregzna at lnubb.pbz From mwh at python.net Wed Jun 12 09:59:45 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 12 Jun 2002 13:59:45 GMT Subject: Zope Newbie query References: Message-ID: "Tony B" writes: > Apologies if this is an innaproprate newsgroup - it's the closest I could > find. http://lists.zope.org/mailman/listinfo/zope is probably the best place to ask this question. > I have been playing with zope and would like to use it properly now the > problem I'm encountering is: How do I remotely install zope on a raq4 on > which I am not the main raq4 administrator (i.e I have a subdirectory on > which my site is hosted).? Do I have to have root priveliges to install and > run zope? Probably not. Don't know any more than that though :) Cheers, M. -- Whaaat? That is the most retarded thing I have seen since, oh, yesterday -- Kaz Kylheku, comp.lang.lisp From js_nntp at nospam_blackrocksoftware.com Sat Jun 8 17:52:02 2002 From: js_nntp at nospam_blackrocksoftware.com (J Swartz) Date: Sat, 08 Jun 2002 21:52:02 GMT Subject: Comparison: HTTP with Java, Perl or Python References: <3D009911.9000904@gmx.de> <3D0127D2.2060604@gmx.de> <3D022634.9050304@gmx.de> Message-ID: This one: public class URLTest { public static void main(String[] arguments) { String myurl = "http://www.uni-dortmund.de"; try { java.io.BufferedReader reader = new java.io.BufferedReader ( new java.io.InputStreamReader((new java.net.URL(myurl)).openStream()) ); for (String curLine = reader.readLine(); curLine != null; curLine = reader.readLine()) System.out.println( curLine ); reader.close(); } catch (java.io.IOException ex) { System.out.println(ex); } } } is 11 lines (text is wrapped here to make 13), took about 4 minutes to write and test. It was quite straightforward. BTW the Java 1.4 API is online here: http://java.sun.com/j2se/1.4/docs/api/index.html - JS On 6/8/02 8:43 AM, in article 3D022634.9050304 at gmx.de, "Ingo Linkweiler" wrote: > Thanks a lot for your versions. > Which of ALL solutions is the shortest, and which the best ? > Do you know good ways to measure the size? (LOC, irredundant or packed > bytes....) > But even without this: > > The Python version is quite short, even after adding exception handling. > TCL seems to be same. > The Perl version seems to be the shortest, but can you read it without > knowing Perl? > > Can you estimate the time you needed for writing it? > Did you have any difficulties? > My Python version needed 2 Minutes, with Java I needed 20, because I did > not unterstand the f******* manual. > > > > > PS: > This was my own Java solution: > > package meintest; > import java.lang.Exception; > import java.net.*; > import java.io.*; > public class getURL { > public static void main(String[] args) { > try { > URL url = new URL("http://www.uni-dortmund.de"); > InputStream in = url.openStream(); > for (;;) > { > int data = in.read(); > if (data == -1) > break; > else > System.out.print ( (char) data); > } > } > catch (Exception e) { } > } > } > From donn at drizzle.com Thu Jun 13 01:13:28 2002 From: donn at drizzle.com (Donn Cave) Date: Thu, 13 Jun 2002 05:13:28 -0000 Subject: socket module htonl/ntohl bug References: Message-ID: <1023945194.166778@yasure> Quoth davidma at eskimo.com (David Margrave): | The following statement should work, but does not, on python 1.5.2 and | python 2.2: | | >>> socket.htonl(pow(2L,32)-1) | Traceback (innermost last): | File "", line 1, in ? | OverflowError: long int too long to convert | | 2^32-1 is a valid 32-bit value, equal to 32 1s in binary, and htonl | should be able to handle it. This is not related to the argument | being a long int and htonl not accepting that type, because | socket.htonl(4294967295) raises the same exception, and 4294967295 can | be represented as a regular int in python2 (but not 1.5). I think you may understand this, but 2^31-1 is not a valid 32-bit signed integer, and that's what Python's int is (on platforms where C int is 32 bits.) Since there is no unsigned int, you would have to represent the value as a negative number (v - pow(2L,32).) Arguably the htonl function might convert to unsigned int, to match the C variable, but it's going to return a signed int anyway, so there's an element of consistency here. On a DEC Alpha, incidentally, even though Python supports an int of that size, I get >>> x = socket.htonl(y) Traceback (most recent call last): File "", line 1, in ? OverflowError: signed integer is greater than maximum while I get "long int too long to convert" with pow(2L, 64) - 1. So in this particular context it looks like there's more going on here than just an accidental collision with integer overflow. Donn Cave, donn at drizzle.com From NineOfSix at gmx.de Fri Jun 21 12:19:58 2002 From: NineOfSix at gmx.de (Axel Grune) Date: Fri, 21 Jun 2002 18:19:58 +0200 Subject: enlightenment (Re: python cgi + IIS) References: <3D0F1813.3010304@gmx.de> <3D102AF2.5010204@gmx.de> Message-ID: <3D13522E.6010703@gmx.de> > for, and so forth) give an account of all the steps you have performed This steps: http://www.e-coli.net/pyiis.html This doc tells you to change the 'App Mapping' in the properties of [IISAdmin] to enable the execution of python files for the entire server but for any reason it doesn't work. In the end our admin suggested to change the properties of 'Default Web Site' (the node above [IISAdmin]) and then it works. Thanks, Axel -- please check /dev/zero for further information From mwh at python.net Mon Jun 17 05:36:09 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 17 Jun 2002 09:36:09 GMT Subject: a possibly foolish question about slices References: <4c877253.0206162149.bff3ae3@posting.google.com> Message-ID: garth at deadlybloodyserious.com (Garth T Kidd) writes: > > x[p:][:n] > > Does the parser take the appropriate short-cut, here, No. Wouldn't be the parser anyway, would it? > or do we end up with a temporary list? It's very easy to answer questions about whether Python performs this sort of optimization: it doesn't. Cheers, M. -- I also feel it essential to note, [...], that Description Logics, non-Monotonic Logics, Default Logics and Circumscription Logics can all collectively go suck a cow. Thank you. -- http://advogato.org/person/Johnath/diary.html?start=4 From mwh at python.net Fri Jun 7 11:19:01 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 7 Jun 2002 15:19:01 GMT Subject: Native code compiler for python? References: Message-ID: d2002xx at softhome.net (nobody) writes: > Is there any existing native code compiler for python? Or Python to C > translator? Or someone is doing this? http://www.google.com/search?q=psyco Cheers, M. -- Make this IDLE version 0.8. (We have to skip 0.7 because that was a CNRI release in a corner of the basement of a government building on a planet circling Aldebaran.) -- Guido Van Rossum, in a checkin comment From salmonia at cf.ac.uk Wed Jun 19 09:53:35 2002 From: salmonia at cf.ac.uk (Al) Date: Wed, 19 Jun 2002 14:53:35 +0100 Subject: Newbie deluxe References: Message-ID: <3D108CDF.3010706@cf.ac.uk> Yes Python can be used for graphical applications. I am writing one just now: http://salstat.sunsite.dk - it's for statistical analysis (a bit like a smaller, simpler version of SPSS). It has a spreadsheet like grid for data entry, the output is in html (in its own window, not a separate browser), and there is hypertext help, so I suppose fully fledged graphical applications can be developed. I used wxPython for the GUI things (it's a separate download, but costs nothing) - this means my application now runs on Windows, Linux, Unix and MacIntosh OSX - without a single change of line code, something that I didn't find possible when I used Kylix and Delphi. The problem with wxPython is that you will probably need to learn how to program it - there are GUI designers if you want (Boa Constructor and PythonCard being 2 that spring to mind), but if you want the power, you will be best off learning how to write the code by hand. It really isn't that difficult once you get going - if I can do it, I am sure you can! ;) To summarise - since using Python, I really haven't looked back once! Alan. btw - I found its functional language constructs to be superb and very time saving. Zach wrote: > I've just started taking a look at Python (experienced in Delphi) and so far > it looks very clean and comprehensible. My question is, what are the > fundamental differences and similarities between it and Perl? I hear so > much about these two languages, especially in Linux circles and just > wondered what sets them apart. Can full fledged graphical applications be > built with Python or does it lean more towards scripting? I'm aware that it > has OOP capabilities so I assume it reaches beyond just scripting but like I > said, I've no experience with it. I would like to broaden my coding skills > with the addition of another language so any general opinions with regards > to its usefulness are appreciated. > > TIA. > > Zach > > From mcherm at destiny.com Fri Jun 14 09:08:38 2002 From: mcherm at destiny.com (Michael Chermside) Date: Fri, 14 Jun 2002 09:08:38 -0400 Subject: Medium to Large Scale Python Deployments Message-ID: <3D09EAD6.10701@destiny.com> > I'm working on a large web project whose name I hafta jump thru > permission hoops to reveal No problem... if it's OK with you, I'll list it with your name but no project name. Will that satisfy the hoopmasters? -- Michael Chermside From phd at phd.pp.ru Fri Jun 21 17:24:52 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Sat, 22 Jun 2002 01:24:52 +0400 Subject: do...while In-Reply-To: <3D13841D.F3C9EB5B@noaa.gov>; from Chris.Barker@noaa.gov on Fri, Jun 21, 2002 at 12:53:02PM -0700 References: <3D13841D.F3C9EB5B@noaa.gov> Message-ID: <20020622012452.A24417@phd.pp.ru> On Fri, Jun 21, 2002 at 12:53:02PM -0700, Chris Barker wrote: > while line = file.readline(): In Python it is spelled for line in file.xreadlines(): ... Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From logiplexsoftware at earthlink.net Fri Jun 21 01:09:04 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: 20 Jun 2002 22:09:04 -0700 Subject: Inhibiting duplicate apps in Windows? In-Reply-To: <3D1283EC.A28A45CB@engcorp.com> References: <3D11F9E8.DFFFC8E4@tds.net> <3D1283EC.A28A45CB@engcorp.com> Message-ID: <1024636145.10524.2.camel@localhost.localdomain> On Thu, 2002-06-20 at 18:39, Peter Hansen wrote: > Chris Liechti wrote: > > > > "Edward K. Ream" wrote in news:3D11F9E8.DFFFC8E4 at tds.net: > > > What I would like is for the second copy of Leo to detect that another > > > copy of leo.py is already running, send a message to the first copy and > > > then exit. I wonder if anyone knows how this might be done? > > > dumb solution: create a "lock file" and remove it on programm exit. the > > other problem is that you have to delete it manually when the app crashes > > (i deleted may lock files with older Netscapes ;-) > > I wonder whether there's not a simple way to avoid manual deletion. > If one application creates the lock file, it can hold it open as > long as it is running. A second invocation can detect the first > by its failure to open the same file for writing. If the file > already exists, it can try to delete it with os.remove(). That > should fail if the first application still has it open, but if > the first application actually crashed, the OS should allow the > file to be removed, at which point the new invocation can safely > recreate it, knowing it now has the lock. A fairly fool-proof/portable method is to open a socket. If the app is run a second time it will fail on the attempt. Even if the app crashes, the socket will be closed by the OS (although it may take a couple of seconds on occasion). Regards, Cliff From gh_pythonlist at gmx.de Tue Jun 11 16:54:23 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Tue, 11 Jun 2002 22:54:23 +0200 Subject: RfD: Automagically making a class instance 'synchronized' (draft impl.) Message-ID: <20020611205423.GA28113@lilith.my-fqdn.de> For one of my projects, I'll need something not quite unlike the following code. It's not tested, yet, but it looks ok and complete to me. I thought that it could be useful to other developers who need to use multithreading, so I'm posting it here. Maybe something like this would even be a useful addition to the Standard Library? Gerhard from threading import RLock class Connection: def begin(self): print "begin" def commit(self): print "commit" class LockingWrapper: def __init__(self, proxy, obj): self.proxy = proxy self.obj = obj def __call__(self, *args, **kwargs): self.proxy.__dict__["rlock"].acquire(1) try: self.obj(*args, **kwargs) except: self.proxy.__dict__["rlock"].release() raise return self.proxy.__dict__["rlock"].release() class LockingProxy: """LockingProxy proxies an instance of a class, so that in that instance, only one method can be active at any given point in time. In Java-speak, it automatically makes all methods of this class 'synchronized'.""" def __init__(self, obj, methodnames): """obj -> a callable methodnames -> a list of method names""" self.__dict__["obj"] = obj self.__dict__["rlock"] = RLock() self.__dict__["methodnames"] = methodnames def __getattr__(self, attr): val = getattr(self.__dict__["obj"], attr) if attr not in self.__dict__["methodnames"]: return val else: return LockingWrapper(self, val) conn = Connection() lp = LockingProxy(conn, ["begin", "commit"]) lp.begin() -- This sig powered by Python! Au?entemperatur in M?nchen: 16.6 ?C Wind: 0.6 m/s From quinn at vomit.ugcs.caltech.edu Sun Jun 23 22:00:17 2002 From: quinn at vomit.ugcs.caltech.edu (Quinn Dunkan) Date: 24 Jun 2002 02:00:17 GMT Subject: re.rsearch? References: Message-ID: On Sun, 23 Jun 2002 22:10:01 GMT, Fredrik Lundh wrote: >Quinn Dunkan wrote: >> Occaisionally I find myself wanting an re.search that will find the rightmost >> match. > >just prepend ".*" to the pattern... Oh, I should have thought of that :) Of course, that changes the match, but I can get my span with ()s and m.span(1) >> Unfortunately, AFAIK, re.search also lacks a 'start_searching_at' >> type option. > >if you use a compiled pattern, you can pass in start >and end offsets: > > p = re.compile(pattern) > p.search(string, start, end) Phoey... don't know how I missed that one in the docs. Guess I looked at the modules search() and assumed the method was the same... thanks! From jepler at unpythonic.net Fri Jun 7 11:17:52 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 7 Jun 2002 10:17:52 -0500 Subject: positional modifiers in python? In-Reply-To: <20020607143021.GA3038@foof.i3.cz> References: <20020607143021.GA3038@foof.i3.cz> Message-ID: <20020607151751.GB12501@unpythonic.net> On Fri, Jun 07, 2002 at 04:30:21PM +0200, fuf wrote: > hello everyone, > > does python support positional parameters in the print method? ie. > something like: > print "there %2$s something %1$s" % ("there", "is") print "there %(verb)s something %(where)s" % {'verb': 'is', 'where': 'there'} Jeff From huaiyu at gauss.almadan.ibm.com Tue Jun 18 15:02:39 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Tue, 18 Jun 2002 19:02:39 +0000 (UTC) Subject: What If..... Strong Types References: <3D0C0F0D.4030900@bgb.cc> Message-ID: Don Garrett wrote: > I'm not suggesting any real changes to any, only proposing a thought >experiment. > > What if Python had been built from the start with strong types? And I mean >strong types, not strong typing. The distinction I am trying to draw is that >variables would not be typed, but that all types would have rigid interfaces. > > Primarily, what if classes always had rigidly defined interfaces. I mean >that public members had to be declared to exist, and that methods couldn't be >modified on an instance. Private members could exist but would be really private. > > All types would be classes (including ints and such). Amoung other things, >I would add the concepts of Interfaces, instanceof operators. > > Local variables would not require declaration, and would work just like >today. Introspection would work, but be read-only. > > My belief is that almost all the convenience of Python would be maintained, >but that compilation, optimization, and automated code analysis would be simpler. > > I'm just wondering if the change would be good or bad. Would it really >break anything important in Python today? Would it prevent any common errors? >Would it help with automated code analysis (compilation and optimization >included) as much as I think it would? What you are talking about is not strong types. Python already has strong types. You are talking about interfaces, which is quite different from classes. Classes define a hierarchy of implementation, so that attributes of base classes can be used in derived classes. Interfaces define a hierarchy of requirements, so that a sub-"type" can be used in places that require a base-"type". They cannot be combined easily because the two hierarchies do not share the same inheritance structure. Example 1: You might want to define a class of file-like objects that shares no implementation with builtin files. You want just the interface. Example 2: Mathematically a square is a kind of rectangle. So anywhere a rectangle is required, a square should do. But for graphical classes it's often better to code Rectangle as a subclass of Square, because it uses most of the methods of Square, in addition to its own. This is implementation. Example 3: It is often necessary to require that an object is one of several types, AFTER the types have been defined. For example, you might code up a Time class, whose __init__ accepts numbers (as seconds), strings (in the common time format), and tuples (as hours, minutes and seconds). If you want to label all these as TimeData, it cannot be a base class for strings, numbers and tuples, as these have already been defined. The relations of interfaces are often built from specific to general, in the opposite direction of class inheritances. We can conclude from these considerations that mixing the implementation hierarchy with the requirement hierarchy is not a good general solution, although it is sometime useful. Java's interfaces and C++'s abstract classes re-uses the same inheritance structure of implementation for interfaces. Such interfaces are not as useful as it could have been, while creating some additional problems. To do it right, interfaces must have an inheritance hierarchy that is separate from that of implementation. It is possible to re-use the existing class hierarchy for this purpose if done carefully in special cases, such as Python's exception classes. But a general type-hierarchy (serving as interfaces) has to be separate from class-heirarchy. Will it be beneficial to Python? At least, it will allow many formal correctness guarantees. It will help compiling. It will reduce much of current type checking against implementational classes. It will reduce the computational burden of much of run time type checking. How difficult would it be? Well, it has to be optional. It has to have an inheritance syntax that is not confused with classes. There need to be syntax to specify requirements (such as with function arguments). There need to be syntax to specify invariance assertions. The checking should best be done at C-level, possibly in the compile stage, for the sake of efficiency. Last but not least, there need to be a good name beside the word 'type', which is becoming similar to 'class' in Python now. I think that once it is decided what it should look like, there are many capable people who can actually implement it. Huaiyu From phd at phd.pp.ru Fri Jun 28 04:52:51 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Fri, 28 Jun 2002 12:52:51 +0400 Subject: Python crashed on me In-Reply-To: ; from bokr@oz.net on Thu, Jun 27, 2002 at 08:45:16PM +0000 References: Message-ID: <20020628125251.A27385@phd.pp.ru> Hi! On Thu, Jun 27, 2002 at 08:45:16PM +0000, Bengt Richter wrote: > > Recently Python (one program that I am dbugging) started to crash. > >FreeBSD kills it with "Bus error", Linux with "Segmentation fault". > > > > I think the program crashed in the cPickle.dump(file, 1) I replaced cPikle.dump with pikle.dump and got infinite rcursion. The traceback is below. What's that? Are there any limits that an object to be pikled must follow? Could it be a tree with loops? (I am pretty sure it could - I used the program for years, and data structures was not changed much). Could it be "new" Python class? (Recently I changed one of my classes to be derived from builtin list instead of UserList). Well (or not so well), the traceback: Traceback (most recent call last): File "/home/phd/lib/bookmarks_db/check_urls.py", line 158, in ? run() File "/home/phd/lib/bookmarks_db/check_urls.py", line 145, in run storage.store(root_folder) File "bkmk_stpickle.py", line 23, in store File "/usr/local/lib/python2.2/pickle.py", line 973, in dump Pickler(file, bin).dump(object) File "/usr/local/lib/python2.2/pickle.py", line 115, in dump self.save(object) File "/usr/local/lib/python2.2/pickle.py", line 219, in save self.save_reduce(callable, arg_tup, state) File "/usr/local/lib/python2.2/pickle.py", line 245, in save_reduce save(arg_tup) File "/usr/local/lib/python2.2/pickle.py", line 225, in save f(self, object) File "/usr/local/lib/python2.2/pickle.py", line 374, in save_tuple save(element) File "/usr/local/lib/python2.2/pickle.py", line 225, in save f(self, object) [about 1000 lines skipped - they are all the same] File "/usr/local/lib/python2.2/pickle.py", line 498, in save_inst save(stuff) File "/usr/local/lib/python2.2/pickle.py", line 225, in save f(self, object) File "/usr/local/lib/python2.2/pickle.py", line 447, in save_dict save(value) File "/usr/local/lib/python2.2/pickle.py", line 219, in save self.save_reduce(callable, arg_tup, state) File "/usr/local/lib/python2.2/pickle.py", line 245, in save_reduce save(arg_tup) File "/usr/local/lib/python2.2/pickle.py", line 225, in save f(self, object) File "/usr/local/lib/python2.2/pickle.py", line 374, in save_tuple save(element) File "/usr/local/lib/python2.2/pickle.py", line 225, in save f(self, object) File "/usr/local/lib/python2.2/pickle.py", line 414, in save_list save(element) File "/usr/local/lib/python2.2/pickle.py", line 143, in save pid = self.persistent_id(object) RuntimeError: maximum recursion depth exceeded Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From christian.aastorp.killspam at siemens.no Thu Jun 6 08:24:15 2002 From: christian.aastorp.killspam at siemens.no (Christian Aastorp) Date: Thu, 06 Jun 2002 14:24:15 +0200 Subject: Interfacing to 1-Wire LAN, especially Dallas temperature sensors? References: <1bf96e7f.0206060356.417a7394@posting.google.com> Message-ID: On 6 Jun 2002 04:56:02 -0700, python at tykebsd.net (Dave Moor) wrote: >Hi > >I have just started producing a PyOneWire module it currently can >search the one wire network for families of devices and read the >temperatures from DS1820 devices. What platform are you wanting to >run it on, I could send you a prerelease versiob to try. That is great! I'm running on Windows 2000, and XP. Remove the obvious from my mail adress. From pde at cs.mu.oz.au Sat Jun 29 10:15:08 2002 From: pde at cs.mu.oz.au (Peter Eckersley) Date: Sun, 30 Jun 2002 00:15:08 +1000 Subject: Partial Parsing of Python Message-ID: <20020629141507.GA6507@luminance.reworld.org> Hi, I'm currently working on a python-based alternative to a standard *nix shell. I imagine lots of other people have built such animals, but this one is supposed to be graphical and include nifty features like smart auto-completion and running commentary on one's commands (which should be handy for newbies). Anyway, having implemented some of the completion features the simple way-- using tokenize.tokenize(), string analysis, and the odd call to parser.expr() to guess what the user might want to type next, I've reached the conclusion that doing too much more will lead to Madness and Spaghetti Code. So the alternative is of course to use a proper python parser, which can include hooks suggesting how bits of the grammar can be completed. Basically, what this parser needs to do is attempt to accept its input, noting along the way when it meets the user's cursor. If it fails, it needs to preserve an incomplete parse tree, record which production rule it was trying to use, and which symbol in that rule caused the problem. It's not immediately obvious how to achieve this with a minimum of fuss. A few different strategies might be: * hack the cPython parser to provide this extra stuff (not having emersed myself in the parser, I imagine this could be a lot of work, but would love to hear information to the contrary, or receive few pointers as to how it might be done) * use bison to implement a new parser from scratch (ugly, perilous, and I'd have to learn yacc/bison along the way :( ) * write a minimalist, brute-force recursive descent parser in python, which would be a more-or-less direct translation of the grammar, but would almost certainly be damnably slow Suggestions about which strategy to pursue would be gratefully appreciated! (CCs off-list, IINTMT) -- Peter Eckersley Department of Computer Science & mailto:pde at cs.mu.oz.au IP Research Institute of Australia http://www.cs.mu.oz.au/~pde The University of Melbourne From gnpowell at powerup.com.au Sat Jun 1 23:27:54 2002 From: gnpowell at powerup.com.au (Daniel Powell) Date: Sun, 2 Jun 2002 13:27:54 +1000 Subject: system variables Message-ID: hi guys, I'm new to python and I'm teaching myself from a website. I'm stumped on one thing this is the exact wording "You will need to cause the directory containing the file named python.exe to be listed in your system environment variable named path." the website is http://softwaredev.earthweb.com/sdopen/article/0,,12077_626311,00.html it says when you do this if you type something like "python junk.py" it will run the "junk.py" scipt if anyone can help me do this i would grealty appreciate it. My OS is Win 98SE thanks in advance Daniel Powell thecubical at hotmail.com From Grant_member at newsguy.com Mon Jun 3 13:52:31 2002 From: Grant_member at newsguy.com (Grant Griffin) Date: 3 Jun 2002 10:52:31 -0700 Subject: getting windows processes list Message-ID: Hi Gang, Does anybody know offhand how to use Python to get the list of processes that are currently running on Windows? (I'm essentially trying to get the information that appears in Window's Task Manager's "Processes" tab.) not-gifted-at-finding-needles-in-haystacks-ly y'rs, =g2 _________________________________________________________________________ Grant R. Griffin g2 at dspguru.com Publisher of dspGuru http://www.dspguru.com Iowegian International Corporation http://www.iowegian.com From dom at edgereport.put_a_c_o_m_here Fri Jun 7 16:45:36 2002 From: dom at edgereport.put_a_c_o_m_here (Domenic R. Merenda) Date: Fri, 07 Jun 2002 20:45:36 GMT Subject: Medium to Large Scale Python Deployments References: Message-ID: "Michael Chermside" wrote in message news:mailman.1023460091.14067.python-list at python.org... > Folks, I think this is a pretty useful thing to collect. > In fact, it might be really nice to collect a list of large (successful) > Python projects and post it somewhere so the Python community could use > it for advocacy. Michael, I agree with you. I was formerly the Vice President of Business Development for BeOpen.com, while we had PythonLabs there, and I can tell you that we were compiling such a list for that very reason. Using the WayBack Machine, I was able to grab the list. Here ya go: Digital Creations http://web.archive.org/web/20001119052700/http://www.digicool.com/ Digital Creations built its flagship product, Zope, in Python. Zope is an advanced, highly adaptable web application server and content management system in production use across the globe. Zope enables web developers and content managers to rapidly deploy interactive, dynamic, scalable, community-oriented web sites. Zope is available at http://web.archive.org/web/20001119052700/http://www.zope.org/. eGroups (acquired by Yahoo!) http://web.archive.org/web/20001119052700/http://www.egroups.com/ eGroups empowers people to share interests and ideas by delivering the world's best web-based email group service, a technology built in Python. Email groups facilitate group communication through the ease and convenience of a user's email account. Python has allowed eGroups to rapidly evolve its service offering as well as enable it to scale to unprecedented levels. eGroups decision to use Python helped them achieve rapid growth, leading to their acquisition by another market leader, Yahoo!. Google.com http://web.archive.org/web/20001119052700/http://www.google.com/ Google's mission is to organize the world's online information and to make it universally accessible and useful. Google rocketed to the top of the web portal industry by making extensive use of Python throughout its web crawler and search engine technologies (later optimized for further performance in C). Google's web crawler now spans the entire public Internet, with over 1 billion indexed URL's. The total number of searches served by Google exceeds 13 million per day. Helix Code http://web.archive.org/web/20001119052700/http://www.helixcode.com/ Helix Code is a startup building a free Internet desktop based on the GNOME desktop platform, for Linux and Unix. The company is headed by the leading devevelopers of the GNOME project. Helix Code ships a variety of Python programming interfaces for the GNOME libraries and its associated graphical widget set GTK+. Hewlett Packard e-speak http://web.archive.org/web/20001119052700/http://www.e-speak.net/ HP used Python to build a truly open Market Making Broker with XML/HTTP interfaces at all major interface points. This broker was far ahead of its time, working across a large space of market makers. Initially, Python was used only to produce the first prototype, with plans for a production version to be done in Java. After the Java-intensive product proved less stable with even fewer features than the Python prototype, Java work was discontinued and the Python prototype was reworked in order to meet critical deadlines. IBM http://web.archive.org/web/20001119052700/http://www.ibm.com/ IBM uses Python on OS/390 UNIX System Services to facilitate automated testing of Internet tools. IBM is using Python to create the business practice logic for the factory tool control applications that manage a semiconductor plant. Code that had been previously written in an internal, proprietary scripting language has been given new life via its port to Python. Infoseek (acquired by Go Network) http://web.archive.org/web/20001119052700/http://www.infoseek.com/ Ultraseek Server, Infoseek's commercial search engine product, is implemented as an elaborate multi-threaded Python program, with the primitive indexing and search operations performed by a built-in module. Most of the program is written in Python, and both a built-in spider and HTTP server can be customized with additional Python code. The program contains over 11,000 lines of Python code while the user interface contains over 17,000 lines of Python-scripted HTML templates. ITI http://web.archive.org/web/20001119052700/http://www.iti-oh.com/pdi ITI's Product Data Interoperability (PDI) business provides software tools and services enabling companies to effectively exchange, reuse, and share CAD/CAM/CAE/PDM and related engineering data among diverse software applications used throughout a manufacturing enterprise and it's supply chain. ITI has had amazing success with Python. Lawrence Livermore National Laboratories Los Alamos National Laboratory http://web.archive.org/web/20001119052700/http://www.llnl.gov/ http://web.archive.org/web/20001119052700/http://www.lanl.gov/ A group at the Lawrence Livermore National Laboratories based its new numerical engineering environment, CDAT, on Python, replacing a home-grown scripting language of ten-year standing. CDAT used Python's exceptionally versatile design to integrate C, C++, and FORTRAN subroutines, affording climate research scientists an effortless analysis of global climate model data sets. MCI Worldcom http://web.archive.org/web/20001119052700/http://www.mciworldcom.com/ The Data Subnet Manager, MCI Worldcom's internal frame relay configuration and provisioning suite, uses JPython for regression testing, interactive debugging, and rapid prototyping of its Java Client. They also use Python in their automated build processes and CGI scripts. Microsoft eShop http://web.archive.org/web/20001119052700/http://www.eshop.com/ eShop, Inc. was originally formed in December 1993 to produce desktop electronic commerce software. By November 1995, Pandora's Box had been opened -- the Internet was something that had to be addressed directly, rather than simply accounted for, and eShop had to move quickly or lose its competitive advantages. By the time eShop was acquired by Microsoft, less than a half-dozen engineers had built an entire Web-based shopping system with Python in about four months. The resulting server was stable, maintainable, robust, and scalable showing no compromise in quality for such a brief development period. NASA http://web.archive.org/web/20001119052700/http://www.nasa.gov/ Johnson Space Center uses Python as the standard scripting language in its Integrated Planning System. Efforts are underway to develop a modular collection of tools for assisting shuttle pre-mission planning and replacing older tools written in PERL and shell dialects. Python will also be installed in the new Mission Control Center to perform auxiliary processing integrated with a user interface shell. Ongoing developments include an automated grammar based system, whereby C++ libraries may be interfaced directly to Python via compiler techniques. This technology can be extended to other languages in the future. Penguin Computing http://web.archive.org/web/20001119052700/http://www.penguincomputing.com/ Penguin Computing is a leading manufacturer of Linux servers for web, database, and other enterprise uses. Much of the software developed at Penguin for internal use and for shipping with their servers is developed in Python -- after other languages proved too limiting and difficult to maintain. PyBiz http://web.archive.org/web/20001119052700/http://www.pybiz.com/ Python enabled a small team of senior architects at PyBiz to produce and deliver both XDisect and eContentMgr on short schedule. It was estimated that it would have required 3 times the build time and 1.5 times the number of developers to deliver comparable functionality in Java. Building in Python allowed delivery of a working product early in the life cycle, providing more time to evolve the product towards customers' needs as well as optimize performance of critical areas. Real Networks http://web.archive.org/web/20001119052700/http://www.real.com/ RealNetworks has developed a Python binding for their RealMedia client. It is used extensively in load testing and feature testing of both their server and client on all of their supported platforms. Additionally, RealNetworks' build system and bug tracking system have very significant Python components. Red Hat http://web.archive.org/web/20001119052700/http://www.redhat.com/ In the highly competitive Linux market, easy-to-use and flexible installation technologies have become a key business differentiator. Red Hat, a leader in Linux and Open Source technologies, identified Python as a unique and powerful tool for building their installer, Anaconda. Sapient http://web.archive.org/web/20001119052700/http://www.shn.net/ Sapient Information Systems built the Sapient Health Network for WebMD with Python. The service provides chronically and terminally ill people with information related to their illness. All of the backend web programming uses Python, as do a large number of internal tools. Sonics http://web.archive.org/web/20001119052700/http://www.sonicsinc.com/ Sonics engineers use Python exclusively to construct graphical and configuration tools (the FastForward Development Environment) which provide the layout of micro-network-based system-on-chips. Their experiences over the years with many languages and systems led them to conclude that, with the available time and resources, they could never have developed the technology without Python. Yahoo! Mail and Four11 http://web.archive.org/web/20001119052700/http://www.yahoo.com/ Yahoo! acquired a company called Four11, a technology providing both an Internet White Pages and a web-based e-mail reading system (renamed from Rocketmail to Yahoo! Mail). Both of these services were written in Python to obtain strong performance and flexibility. The Internet White Pages holds a large number of email address records and the complete US residential telephone directory -- so searching performance is key. Having acquired both 411 and eGroups, Yahoo! now relies on a wide range of Python-driven technologies to provide the highly interactive experience its users expect. 80-20 Software http://web.archive.org/web/20001119052700/http://www.80-20.com/ 80-20 Software used Python to rapidly develop a scalable and extensible document management system that sits on top of the popular Microsoft Exchange messaging technology. By using Python, they were able to develop and release to market a feature rich client/server solution in under a year with only 4 developers. Python provided an excellent prototyping tool for the server technology, which originally was supposed to be converted to C++ for production use. 80-20 found during its testing that only a few components needed to be in C++ for greater speed and that more than 90% of the prototype code could be used unchanged without any significant performance impact. > Alternatively, if such a list already exists, let me know where, and > I'll volunteer to help update and promote it. > > Domenic's > ERP system >100 -- Let's not call it that. :-) And I will check upstairs when we get back from our vacation to see if it's okay to release the number of lines in the code. Don't be surprised if it's treated like a National Security issue. (Shh! If they know how many lines are in the code, they can CRACK US!) -- Domenic R. Merenda Editor, The Edge Report http://www.edgereport.com From graham_guttocks at yahoo.co.nz Tue Jun 4 14:54:13 2002 From: graham_guttocks at yahoo.co.nz (Graham Guttocks) Date: Tue, 4 Jun 2002 11:54:13 -0700 (PDT) Subject: os.path.expanduser ignores os.seteuid In-Reply-To: Message-ID: <20020604185413.26385.qmail@web10303.mail.yahoo.com> Sean 'Shaleh' Perry wrote: > > It uses short circuit eval for the '~' case and simply > reads the environment $HOME. If you could pass '~user/' > it would give you the answer you want. Well, I also need to support lots of existing ~/foo cases. Looks like I can just set $HOME after the os.seteuid() call with the following: os.environ['HOME'] = pwd.getpwuid(os.geteuid())[5] Then subsequent os.path.expanduser calls should work as I want. Regards, Graham __________________________________________________ Do You Yahoo!? Yahoo! - Official partner of 2002 FIFA World Cup http://fifaworldcup.yahoo.com From hesterloli at hotmail.com Sat Jun 15 18:23:38 2002 From: hesterloli at hotmail.com (George Hester) Date: Sat, 15 Jun 2002 22:23:38 GMT Subject: python version? Message-ID: What is a simple script that will tell me the version of python I am currently running? IIS 5.0 Windows 2000. -- George Hester _________________________________ From jeremy at jdyallop.freeserve.co.uk Wed Jun 19 06:34:34 2002 From: jeremy at jdyallop.freeserve.co.uk (Jeremy Yallop) Date: 19 Jun 2002 10:34:34 GMT Subject: zlib/gzip + anydbm or ... References: Message-ID: * James T. Dennis | Is there an obvious and simple way to use the existing standard | libraries to support transparently compressed dbm files? | | (Any combination of zlib/gzip etc with any of the dbm files would | be considered). I've done something similar to this before using dbhash/gdbm and zlib. The code was something like: import dbhash, zlib, tempfile if file_exists(filename): dbfile = open(filename) tmpfilename = tempfile.mktemp() temporary_file = open(tmpfilename, 'w') temporary_file.write(zlib.decompress(dbfile.read())) temporary_file.flush() dbfile.close() db = dbhash.open(tmpfilename, mode) with code to recompress the file when the database is closed. It worked fairly well, but I was only using it for fairly small files (20 megabytes or less). If you'd like the full code (around 180 lines) contact me by email. Jeremy. From fcorneti at libero.it Tue Jun 11 07:35:30 2002 From: fcorneti at libero.it (Fabio Corneti) Date: Tue, 11 Jun 2002 11:35:30 GMT Subject: Defining a method final Message-ID: <6glN8.35376$86.884025@twister1.libero.it> Is there any way to define a method final in Python? I've searched through the docs and through the web, but it seems there's no way to to such a thing using standard language statements. Some suggestions? -- Fabio Corneti Network Administrator fcorneti AT libero DOT it From aleax at aleax.it Mon Jun 24 13:10:01 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 24 Jun 2002 19:10:01 +0200 Subject: [Python-Help] File Copying In-Reply-To: <1024934961.9bd8aff8rchopra@myrealbox.com> References: <1024934961.9bd8aff8rchopra@myrealbox.com> Message-ID: On Monday 24 June 2002 06:09 pm, Rajat Chopra wrote: > How do you copy a file from one directory to another. I have looked all > over and haven't found any documentation on it. Essentially, I want to copy > a file from $SRC_DIRECTORY to $TARGET_DIRECTORY. Python does not support variable names starting with $, so I can only guess at what you mean. Maybe you want environment variables: you'll find those in dictionary os.environ (obviously you need to import os). You don't tell us what is the filename you want to copy; assuming you have it in a string, you can join that string to each directory name with os.path.join. Finally, shutil.copyfile does the copy for you (you need to import shutil). Also look at shutil.copy, shutil.copy2, etc etc, depending on exactly what you want to do. Please don't post to both python-help AND python-list. Choose one or the other. python-list has a lot more traffic; python-help is for those cases in which you'd rather NOT let everybody in python-list know about your problems. Thanks for your cooperation on this issue. Alex From whisper at oz.net Tue Jun 11 09:52:27 2002 From: whisper at oz.net (David LeBlanc) Date: Tue, 11 Jun 2002 06:52:27 -0700 Subject: Defining a method final In-Reply-To: <6glN8.35376$86.884025@twister1.libero.it> Message-ID: "final" is a Java concept not supported in Python. You could possibly simulate it with an 'init' method called after an instance of a subclass is created to adjust the dictionary so that the base classes' method is always called in preference to any same-named method in the derived class(es). Potentially this could even be done in the derived classes' __init__ method that calls the base class __init__ and thus not need an additional explict initialization step. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Fabio Corneti > Sent: Tuesday, June 11, 2002 4:36 > To: python-list at python.org > Subject: Defining a method final > > > Is there any way to define a method final in Python? > I've searched through the docs and through the web, but > it seems there's no way to to such a thing using standard > language statements. Some suggestions? > > -- > Fabio Corneti > Network Administrator > fcorneti AT libero DOT it > -- > http://mail.python.org/mailman/listinfo/python-list From marklists at mceahern.com Thu Jun 13 12:00:24 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 13 Jun 2002 11:00:24 -0500 Subject: modifying string objects In-Reply-To: Message-ID: Short answer: Stick the string in something that is mutable: s = "foobar" def change_it(x): x[0] = x[0] + "foo" x = [s] change_it(x) s = x[0] print s // m - From sholden at holdenweb.com Tue Jun 25 13:26:35 2002 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 25 Jun 2002 13:26:35 -0400 Subject: HTML Error from Python CGI Script References: <79b54d28.0206241618.6c78dbde@posting.google.com> Message-ID: "Jon Ribbens" wrote ... > In article <79b54d28.0206241618.6c78dbde at posting.google.com>, Chris wrote: > > I copy this exact text to my own computer (versus operating over > > network) and open it and it looks fine. Exactly what I need. However, > > when I put a link to it on another webpage on the network, an internal > > server error occurs and complains about the following: > > > > syntax error at line 2: `newline or ;' unexpected > > Obviously your server is trying to use your static page as some kind > of script. You haven't given enough information to work out why this > might be though. Look at your server's configuration, and see whether the extension you are using for the temporary files is treated as executable on the server (in Apache you'll be looking at httpd.conf or .htaccess files). Since you don't say whether the error appears on the client or the server, I suppose it's also possible you are delivering content that the client-side (i.e. the machine you run your browser on) is trying to execute your content. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From xah at xahlee.org Sun Jun 16 07:58:23 2002 From: xah at xahlee.org (Xah Lee) Date: 16 Jun 2002 04:58:23 -0700 Subject: python install through fink, mac os x References: <7fe97cc4.0206142251.164d9ec5@posting.google.com> Message-ID: <7fe97cc4.0206160358.6dbd1696@posting.google.com> problem solved by doing a fink selfupdate first. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html > > [xah at localhost ~][Fri Jun 14,23:48:52] > > fink install python > > sudo /sw/bin/fink install python > > Password: > > Reading package info... > > Information about 435 packages read in 5 seconds. > > The following 9 additional packages will be installed: > > db3 db3-shlibs expat gdbm gdbm-shlibs gmp gmp-shlibs manconf tcltk > > Do you want to continue? [Y/n] y > > curl -f -L -s -S -O http://www.sleepycat.com/update/3.3.11/db-3.3.11.tar.gz > > curl: (22) The requested file was not found > > ### curl failed, exit code 22 > > Downloading the file "db-3.3.11.tar.gz" failed. > > > > (1) Give up > > (2) Retry > > > > How do you want to proceed? [2] From loredo at astro.cornell.edu Wed Jun 19 18:53:09 2002 From: loredo at astro.cornell.edu (Tom Loredo) Date: Wed, 19 Jun 2002 18:53:09 -0400 Subject: Windows versions of Python---pros and cons? Message-ID: <3D110B55.4D8AD7FA@astro.cornell.edu> Hi folks- I've been using Python heavily on a Solaris box and a Mac for a few years now. For reasons I'll spare you from, I now am venturing into Windows territory (a Dell Inspiron 7500 laptop, if that matters). I see at least two Windows versions of Python---that at Python.org, and the ActiveState version. The obvious "pro" for the ActiveState version is simplicity of the install (batteries included, etc.). But what about after that? Are their substantial differences between the versions that I will bump into down the line? In particular, I write many C extensions; can one use distutils and the Borland or gcc free compilers to build C extensions in both versions? Thanks for your patience and advice for this PythonWin newbie! -Tom Loredo From jknapka at earthlink.net Tue Jun 25 01:09:53 2002 From: jknapka at earthlink.net (Joseph A Knapka) Date: Tue, 25 Jun 2002 05:09:53 GMT Subject: Python and Eclipse Message-ID: <3D17FAF4.35CC9F1B@earthlink.net> Hi folks, I am interested in having Python support in Eclipse - interested enough to contribute code, or to tackle the task myself, if need be. Of course, I'd like the Python support to be at least as good as the Java support, which is a pretty tall order, 'cause the Java support in Eclipse is awfully damn good --- it nearly allows me to *enjoy* writing Java code :-) Anyway, I know some other folks have expressed interest in this as well, and I'd like to hook up with them. If you're working on Python+Eclipse and you've got code in any state of completion, I'm willing to alpha- or beta-test, fix stuff, add new stuff, etc. Cheers, -- Joe "It was me, drove off the offramp / of the sweetheart highway..." -- Joe Strummer & The Mescaleros, "Bummed-Out City" From phd at phd.pp.ru Thu Jun 27 04:47:21 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Thu, 27 Jun 2002 12:47:21 +0400 Subject: How to get rid the new line In-Reply-To: ; from occeanlinux@linuxmail.org on Thu, Jun 27, 2002 at 06:34:27PM +0000 References: Message-ID: <20020627124721.C12145@phd.pp.ru> On Thu, Jun 27, 2002 at 06:34:27PM +0000, SiverFish wrote: > Anyone tell me how to skip the empty line when you read through the file > and copy the information in to the list(no empty line ) It depends on how you have opened the file - in text or binary mode. In text mode it is simple: infile = open(filename, 'r') for line in file: # require python 2.2 if line != '\n': # end-of-line in the beginning of the line - the line is empty process(line) Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From whisper at oz.net Sun Jun 9 16:45:19 2002 From: whisper at oz.net (David LeBlanc) Date: Sun, 9 Jun 2002 13:45:19 -0700 Subject: Socket error problem In-Reply-To: Message-ID: > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Martin v. Loewis > Sent: Sunday, June 09, 2002 13:17 > To: python-list at python.org > Subject: Re: Socket error problem > > > "David LeBlanc" writes: > > > The general.* constant references are to colorize the output > which is turned > > off but still results in the "31" in the connection error line in the > > program output below. NOTE: I didn't write this code, so I have > no idea why > > it's returning the username in the socket.error instead of the > host. FWIW, > > this code is running in a thread, but there is only one thread > trying to get > > mail. > > That deserves some investigation since this, again, sounds impossible > (how can it possibly know what the user name as, when this piece of is > not being passed the user name). The only possible explanation is that > self.error_msg prints unrelated information; I recommend to remove all > except clauses and let the exception pass through. > > > self.sock = socket.socket(af, socktype, proto) > > Please put a print statement before this socket call, to print all > three arguments. > > > self.sock.connect(sa) > > except socket.error, msg: > > And put one here, printing socket.error. > > Regards, > Martin > -- > http://mail.python.org/mailman/listinfo/python-list It knows the username because it got it out of a config file and supplied it to the initializtion of POP3Server, which is what "serv" is. I've put print statements around all this before I first tryed the ml, but here they are again: def __init__(self, host, port = POP3_PORT): self.host = host self.port = port msg = "getaddrinfo returns an empty list" self.sock = None print 'poplib._init__: self.host = %s ' % self.host, 'self.port = %s' % self.port for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: self.sock = socket.socket(af, socktype, proto) self.sock.connect(sa) except socket.error, msg: print 'poplib.__init__ socket.error msg = %s' % msg if self.sock: self.sock.close() self.sock = None continue break if not self.sock: raise socket.error, msg self.file = self.sock.makefile('rb') self._debugging = 0 self.welcome = self._getresp() And the output is: K:\tmp\animail>animail -v Opening Config file: c:/user/dave/.animail/animailrc Trying to connect (mail.oz.net) poplib._init__: self.host = mail.oz.net self.port = 110 poplib.__init__ socket.error msg = (10022, 'Invalid argument') ("Connection error (whisper): (10022, 'Invalid argument')", 31) David LeBlanc Seattle, WA USA From peter at engcorp.com Tue Jun 4 23:34:44 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 04 Jun 2002 23:34:44 -0400 Subject: Pop a list from beginning ? and memory saving... References: <3CFA0676.68F80DE6@engcorp.com> <3CFD5B60.90831F21@engcorp.com> Message-ID: <3CFD86D4.C4F81404@engcorp.com> Terry Reedy wrote: > > "Peter Hansen" wrote in message > news:3CFD5B60.90831F21 at engcorp.com... > > > self._v[:] = [] > > I can't parse that. What does it do? > > Try the wonerful interactive interpreter: > > >>> l = range(10) > >>> l > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > >>> l[3:7] = [] > >>> l > [0, 1, 2, 7, 8, 9] > >>> l[:] = [] > >>> l > [] Okay, so it's modifying the list in place to be empty, equivalent to the del self._v[:] thing someone else posted? I must have missed the _why_ part... ah! enlightenment: you are removing the contents of the list, which might have other references to it, rather than rebinding the name self._v to a new empty list but leaving those other references alone. Still have to think about times when that would be desirable, but thanks for the nudge. :) -Peter From fredrik at pythonware.com Sat Jun 29 13:16:45 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 29 Jun 2002 17:16:45 GMT Subject: Newbie that don't understand References: Message-ID: <1YlT8.45606$n4.10833103@newsc.telia.net> Martin St?hl wrote: > if a == b: > print "The absolute values of", a,"and",b,"are equal" > else: > print "The absolute values of a and b are different" > > with the output being: > The absolute values of 23 and 23 are equal" > > how can 23 and -23 be equal? "value of" != "absolute value of" in ordinary math notation, the absolute value of a number x is written |x|, and is simply what you get if you remove the sign. in python, it's usually written: abs(x) also see: http://mathworld.wolfram.com/AbsoluteValue.html From tim.one at comcast.net Sat Jun 29 21:22:07 2002 From: tim.one at comcast.net (Tim Peters) Date: Sat, 29 Jun 2002 21:22:07 -0400 Subject: can't import generators In-Reply-To: Message-ID: [John Hunter] > I am having trouble working with generators. Anyone know what might > cause this behavior: > > > /usr/local/bin/python2.2 > Python 2.2.1 (#1, Apr 22 2002, 21:20:54) > [GCC 3.0.4] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> from __future__ import generators > Traceback (most recent call last): > File "", line 1, in ? > ImportError: cannot import name generators > >>> Start Python with the -v switch to see how imports are getting resolved. __future__.py is an actual module that actually gets imported. If you're picking up a wrong version of the Python libraries, that would explain it (maybe due to a bad PYTHONPATH setting, or some local module named __future__.{py,pyc,pyo}). Note that you *are* successfully importing *some* module named __future__, else the error msg would have been different. Here's what's in the correct __future__.py for 2.2.1: >>> import __future__ >>> dir(__future__) ['CO_FUTURE_DIVISION', 'CO_GENERATOR_ALLOWED', 'CO_NESTED', '_Feature', '__all__', '__builtins__', '__doc__', '__file__', '__name__', 'all_feature_names', 'division', 'generators', 'nested_scopes'] >>> __future__.generators _Feature((2, 2, 0, 'alpha', 1), (2, 3, 0, 'final', 0), 4096) >>> From a.schmolck at gmx.net Mon Jun 10 09:47:06 2002 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 10 Jun 2002 14:47:06 +0100 Subject: __imul__ broken for 'objects' in 2.2.1 References: <3n79guskvoaeqtr4srg11kaqse7jcqutt4@4ax.com> Message-ID: Christos Georgiou writes: > On 07 Jun 2002 18:17:45 +0100, rumours say that Alexander Schmolck > might have written: > > >class Breaky(object): > > def __imul__(self, other): > > print "imuling" > > return self > >sq = Breaky() > >sq *=1. > > > >gives: > > > >Traceback (most recent call last):[...] line 10, in ? > > sq *=1. > >TypeError: can't multiply sequence to non-int > > Just in case: it is indeed your intention to multiply the object with a > float, right? > Indeed it is and this nice little bug basically means that the matrix class I've been working on for quite some time is now somewhat screwed (I need a new-style class *and* inplace operations). > PS It seems that a Breaky instance is not (incorrectly) considered a > sequence in 2.3a0 (20020603). Nice to hear, but only a limited consolation since it quite some time will pass before 2.3 comes out and is sufficiently widely adopted. I really wonder where this bizzarre behavior comes from -- it is really none of the interpreter's business to take guesses whether my class is a sequence or not -- finding out if there is a problem with the supplied arguments should be left to the discretion of the method itself. alex From mcfletch at rogers.com Tue Jun 4 11:40:12 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 04 Jun 2002 11:40:12 -0400 Subject: Creating explorer link on Win32 References: <3CFCB72E.4010405@haftmann-online.de> <20020604115516.GB704@lilith.my-fqdn.de> Message-ID: <3CFCDF5C.8070903@rogers.com> There's a demo of creating a shell link in site-packages\win32comext\shell\test\link.py (obviously only if you've installed win32all). Just so you don't have to do a lot of searching for it. Enjoy, Mike Gerhard H?ring wrote: > * Florian Fredegar Haftmann [2002-06-04 13:48 +0100]: > >>Hi! >> >>I'm searching for a possibility to create an explorer link (*.lnk) to a >>file on Win32. Has anyne heard of a python module able to do that in a >>simple way? > > > Mark Hammond's win32 extensions. On my homepage, under VitaminP, there > is a pure-C solution, which you can live with software explictely marked > as 'experimental'. IOW, I'd go with the win32 extensions. > > Gerhard _______________________________________ Mike C. Fletcher http://members.rogers.com/mcfletch/ From emile at fenx.com Tue Jun 11 10:30:38 2002 From: emile at fenx.com (Emile van Sebille) Date: Tue, 11 Jun 2002 14:30:38 GMT Subject: if number is 1-2, 4 or 6-8 or 12-28, 30, 32... References: Message-ID: John Machin > === bot bait ================================ > bignum, long, fast, speed, optimize snot out of > Hook many bots this way? ;-)) My favorites would include: impossible, floatingpoint, pre-compile, and depending on what I was fishing for, I might also try: Free, QT, PSU, Tkinter, If-it-was-easy-they'd-call-it-catching ly y'rs -- Emile van Sebille emile at fenx.com --------- From dfackrell at DELETETHIS.linuxmail.org Fri Jun 21 12:41:10 2002 From: dfackrell at DELETETHIS.linuxmail.org (Daniel Fackrell) Date: Fri, 21 Jun 2002 10:41:10 -0600 Subject: [newbie] Overwriting class definitions References: <3D13563D.AB80D324@athensgroup.com> Message-ID: <3d135729$1_2@hpb10302.boi.hp.com> Mike, You'll need to reload(circle), as import will simply reuse a version that has already been loaded. -- Daniel Fackrell (dfackrell at linuxmail.org) When we attempt the impossible, we can experience true growth. "Mike Christie" wrote in message news:3D13563D.AB80D324 at athensgroup.com... > I'm a complete newcomer to Python; I'm teaching myself Python and this is just > about the only Python code I've ever typed in, so my apologies for posting a > dumb beginner question. Here's my problem. > > I tried a slight variation on the Circle class example from "The Quick Python > Book" by Harms and McDonald. I figured I'd put the class definitions in > script files so I could edit and reload them quickly, rather than retyping. I > entered this in a file called circle.py: > > class Circle: > def __init__(self): > print "Hello, version 1" > > Then I did this: > > import circle > circle.Circle() > > and got > > Hello, version 1 > > as expected. Then I edited the file to say "version 2" and saved it, and then > typed in the import statement and circle.Circle() statement again. It says > version 1 again. > > So what's happening? I assumed that when I imported the file again, it would > read in the class definition again and overwrite the old definition. But that > doesn't appear to be happening. When I exit Pythonwin and reenter, it runs > just fine. > > Do I need to destroy the existing class def first? > > Mike From BPettersen at NAREX.com Wed Jun 26 17:13:32 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Wed, 26 Jun 2002 15:13:32 -0600 Subject: Help with an algorithm wanted Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192158F04@admin56.narex.com> > From: Russell E. Owen [mailto:rowen at cesmail.net] > > I'd like some help solving a problem in Python. > > The basic idea is I have an item of data that can be > represented in any > of four ways: A,B,C and D. I also have conversion functions between > certain pairs of representations, such that there's always a path > between any two data representations. In this case suppose I > know A<->C, > B<->C and C<->D, or graphically: > > A <--+ > +--> C <---> D > B <--+ > > I'd like to create objects that have one of these items > (A,B,C,D) as a > given, then be able to query any such object for any data > representation. > > For instance, an object with A as the given would return D by solving > A->C->D. > > What I'm trying to figure out is a simple and reasonably > elegant way to > code such objects. > > I am pretty sure recursion is the heart of the solution. An > object with > A as the given could have a method getD that returned D<-C > and a method > getC that returned C<-A. > > The real issue is creating such objects without hand coding each one > (since in the real world I have more representations and the > number of > casese proliferates badly). > > I suspect I should use recursion to create the object, too, but it > sounds like it'll need a lot of introspection. For instance > to create an > object with A as the given, one might: > - start by defining method getA to return A > - look through the set of conversion functions that output A; > the only > one is A<-C, so method getC returns C<-A. > - repeat with all methods that return C and don't have > methods already > defined; this gives method getB returns B<-C and method getD returns > D<-C. > > Alternatively, I can imagine making each object basically identical > except for some kind of meta-data that tells each method > which data item > to query; the appropriate function can then be looked up as > needed (e.g. > via a dictionary that takes as a key the output and input > representation). This would slow down the methods but avoid the > introspection. > > Any suggestions? Here's some lightly tested code to get you started. It does a depth first search of the graph. Detecting cycles in the graph, and populating the mapping is left as an exercise to the reader -- bjorn def fromAtoB(): pass def fromAtoC(): pass def fromCtoD(): pass mapping = { 'A' : [('B', fromAtoB), ('C', fromAtoC)], 'C' : [('D', fromCtoD)] } def findShortestPath(mapping, source, dest): bestPath = [[]] # ref list def _findSP(source, dest, res): try: next = mapping[source] except KeyError: return # dead end for item in next: if item[0] == dest: res += [item[1]] if bestPath[0] == [] or len(res) < len(bestPath[0]): bestPath[0] = res else: _findSP(item[0], dest, res + [item[1]]) _findSP(source, dest, []) return bestPath[0] print findShortestPath(mapping, 'A', 'D') From erno-news at erno.iki.fi Tue Jun 11 10:36:52 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 11 Jun 2002 17:36:52 +0300 Subject: How could i get execution times ? References: Message-ID: In article , Ken Seehof writes: | In other words, time.clock() is far more precise for elapsed | time (the above example demonstrates precision on the order | of microseconds -- more than adequate for profiling python | code). But time.time() apparently has a granularity on the | order of a tenth of a second (on windows), which is fine for | profiling slower applications like Microsoft Outlook :-) the above is correct on windows. the situation is approximately the reverse on unix. on unix, time.time() is very accurate in measuring elapsed wall clock time, whereas time.clock() has poor resulution and poor accuracy but tries to measure consumed cpu time instead of wall clock time. -- erno From irmen at NOSPAMREMOVETHISxs4all.nl Wed Jun 12 14:20:17 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Wed, 12 Jun 2002 20:20:17 +0200 Subject: M2Crypto: select() behaves weird on SSL sockets References: <3D04ED17.5070606@NOSPAMREMOVETHISxs4all.nl> <3D066E77.4070901@NOSPAMREMOVETHISxs4all.nl> Message-ID: <3D0790E1.9080904@NOSPAMREMOVETHISxs4all.nl> Ng Pheng Siong wrote: > Just wondering: Does your code look contrived structured the way you have? > IOW, will any (simple) change(s) to M2Crypto's interfaces make it more > natural to express what you wish in this case? Well, I would appreciate a wrapper around select.select, one that acts on SSL sockets the way I expected (from the man page of select). That means: a select() wrapper that 1) works on regular files and sockets 2) works on SSL sockets 3) in the case of SSL sockets, honors the pending bytes that might still be available after a recv() (or send): don't block but return the socket in the 'read' or 'write' list if bytes are pending... This would greatly simplify my socket reading/writing functions... Irmen From ftobin at neverending.org Mon Jun 10 23:05:44 2002 From: ftobin at neverending.org (Frank Tobin) Date: Mon, 10 Jun 2002 23:05:44 -0400 Subject: Iterators vs. Generators In-Reply-To: References: Message-ID: On 10 Jun 2002, Aahz wrote: > So when would one actually write an iterator instead of a generator? > I've been trying to think of an example and failing. Probably any time you want to have the thing 'do more' by being a full object. I personally haven't written any generators yet, but I do use iterators a lot, just because I use OOP a lot. -- Frank Tobin http://www.neverending.org/~ftobin/ From db3l at fitlinxx.com Wed Jun 5 20:19:05 2002 From: db3l at fitlinxx.com (David Bolen) Date: Wed, 5 Jun 2002 20:19:05 -0400 Subject: self Message-ID: <926F937512224245A616323693D3F16B1C01EF@ctmsg01.corp.fitlinxx.com> > everything is a google-search away if you know the right codewords :-) > I don't in this case, though ... Sorry, I must admit to being temporarily overcome with a fit of laziness. I had actually fumbled around a bit before finding the posts I mentioned, so I should really have tried to include a reference. Lest the codewords remain secret, I managed to wind my way there with a search on "eval dictionary instance" in comp.lang.python (which referenced a post of Tim's on the fourth page of results). The messages I had found occurred deep into a "Dictionary from list?" thread from last October which crossed over into the subject of subclassing dictionaries: http://groups.google.com/groups?th=2338421ec8397bec&seekm=mailman.1004338951 .27778.python-list%40python.org is a pointer to the relevant portion including a response by both Tim and Guido. -- David /-----------------------------------------------------------------------\ \ David Bolen \ E-mail: db3l at fitlinxx.com / | FitLinxx, Inc. \ Phone: (203) 708-5192 | / 860 Canal Street, Stamford, CT 06902 \ Fax: (203) 316-5150 \ \-----------------------------------------------------------------------/ From kseehof at neuralintegrator.com Sat Jun 1 16:04:50 2002 From: kseehof at neuralintegrator.com (Ken Seehof) Date: Sat, 01 Jun 2002 13:04:50 -0700 Subject: prototyping good OOdesign in Python? In-Reply-To: Message-ID: > Maybe this was already discussed, but I'd liked to raise this topic again. > > Python has superb OOProgramming support. Lets not dispute this for a > moment. Now let's consider that we need to make well-designed OOP solution > first prototyped in Python. > > What troubles are there? Python is too dynamic and all that. And all > those nifty features need to be translated properly into, say, C++. > > Recently I encountered the following piece of code > (from Arts++ project): > > //================================================================ > =========== > // Copyright Notice > // > // By accessing this software, arts++, you are duly informed > // of and agree to be bound by the conditions described below in this > // notice: > // > // This software product, arts++, is developed by Daniel W. McRobb, and > // copyrighted(C) 1998 by the University of California, San Diego > // (UCSD), with all rights reserved. UCSD administers the CAIDA grant, > // NCR-9711092, under which part of this code was developed. > // > // There is no charge for arts++ software. You can redistribute it > // and/or modify it under the terms of the GNU Lesser General Public > // License, Version 2.1, February 1999, which is incorporated by > // reference herein. > // > // arts++ is distributed WITHOUT ANY WARRANTY, IMPLIED OR EXPRESS, OF > // MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE or that the use > // of it will not infringe on any third party's intellectual > // property rights. > // > // You should have received a copy of the GNU Lesser General Public > // License along with arts++. Copies can also be obtained from: > // > // http://www.gnu.org/copyleft/lesser.html > // > // or by writing to: > // > // Free Software Foundation, Inc. > // 59 Temple Place, Suite 330 > // Boston, MA 02111-1307 > // USA > // > // Or contact: > // > // info at caida.org > //================================================================ > =========== > > // constructor > > ............skip > > Arts::Arts() > { > this->_data._ipPath = (ArtsIpPathData *)0; > this->_data._asMatrix = (ArtsAsMatrixData *)0; > this->_data._netMatrix = (ArtsNetMatrixData *)0; > this->_data._portTable = (ArtsPortTableData *)0; > this->_data._portMatrix = (ArtsPortMatrixData *)0; > this->_data._protocolTable = (ArtsProtocolTableData *)0; > this->_data._selectedPortTable = (ArtsSelectedPortTableData *)0; > this->_data._interfaceMatrix = (ArtsInterfaceMatrixData *)0; > this->_data._nextHopTable = (ArtsNextHopTableData *)0; > this->_data._bgp4RouteTable = (ArtsBgp4RouteTableData *)0; > this->_data._rttTimeSeriesTable = (ArtsRttTimeSeriesTableData *)0; > this->_data._tosTable = (ArtsTosTableData *)0; > > #ifndef NDEBUG > ++_numObjects; > #endif > } > > Arts::Arts(const Arts & arts) > { > this->_header = arts.Header(); > this->_attributes = arts.Attributes(); > > switch (this->_header.Identifier()) { > case artsC_OBJECT_IP_PATH: > this->_data._ipPath = new ArtsIpPathData; > assert(this->_data._ipPath != (ArtsIpPathData *)0); > *(this->_data._ipPath) = *(arts.IpPathData()); > break; > > case artsC_OBJECT_AS_MATRIX: > this->_data._asMatrix = new ArtsAsMatrixData; > assert(this->_data._asMatrix != (ArtsAsMatrixData *)0); > *(this->_data._asMatrix) = *(arts.AsMatrixData()); > break; > > case artsC_OBJECT_NET: > this->_data._netMatrix = new ArtsNetMatrixData; > assert(this->_data._netMatrix != (ArtsNetMatrixData *)0); > *(this->_data._netMatrix) = *(arts.NetMatrixData()); > break; > > case artsC_OBJECT_PORT: > this->_data._portTable = new ArtsPortTableData; > assert(this->_data._portTable != (ArtsPortTableData *)0); > *(this->_data._portTable) = *(arts.PortTableData()); > break; > > case artsC_OBJECT_SELECTED_PORT: > this->_data._selectedPortTable = new ArtsSelectedPortTableData; > assert(this->_data._selectedPortTable != > (ArtsSelectedPortTableData *)0); > *(this->_data._selectedPortTable) = *(arts.SelectedPortTableData()); > break; > > case artsC_OBJECT_PORT_MATRIX: > this->_data._portMatrix = new ArtsPortMatrixData; > assert(this->_data._portMatrix != (ArtsPortMatrixData *)0); > *(this->_data._portMatrix) = *(arts.PortMatrixData()); > break; > > case artsC_OBJECT_PROTO: > this->_data._protocolTable = new ArtsProtocolTableData; > assert(this->_data._protocolTable != (ArtsProtocolTableData *)0); > *(this->_data._protocolTable) = *(arts.ProtocolTableData()); > break; > > case artsC_OBJECT_TOS: > this->_data._tosTable = new ArtsTosTableData; > assert(this->_data._tosTable != (ArtsTosTableData *)0); > *(this->_data._tosTable) = *(arts.TosTableData()); > break; > > case artsC_OBJECT_INTERFACE_MATRIX: > this->_data._interfaceMatrix = new ArtsInterfaceMatrixData; > assert(this->_data._interfaceMatrix != > (ArtsInterfaceMatrixData *)0); > *(this->_data._interfaceMatrix) = *(arts.InterfaceMatrixData()); > break; > > case artsC_OBJECT_NEXT_HOP: > this->_data._nextHopTable = new ArtsNextHopTableData; > assert(this->_data._nextHopTable != (ArtsNextHopTableData *)0); > *(this->_data._nextHopTable) = *(arts.NextHopTableData()); > break; > > case artsC_OBJECT_BGP4: > this->_data._bgp4RouteTable = new ArtsBgp4RouteTableData; > assert(this->_data._bgp4RouteTable != (ArtsBgp4RouteTableData *)0); > *(this->_data._bgp4RouteTable) = *(arts.Bgp4RouteTableData()); > break; > > case artsC_OBJECT_RTT_TIME_SERIES: > this->_data._rttTimeSeriesTable = new ArtsRttTimeSeriesTableData; > assert(this->_data._rttTimeSeriesTable != > (ArtsRttTimeSeriesTableData *)0); > *(this->_data._rttTimeSeriesTable) = > *(arts.RttTimeSeriesTableData()); > break; > > default: > break; > } > > #ifndef NDEBUG > ++_numObjects; > #endif > } > > ..........skip the rest of file - there are 2-3 more similar > .......... switch-constructs. > > ------------------------------------------------------------ > > This code looks like... automatically generated. Rather than manually > written. I do not know why it was written in C++ at all. Of course, I > imagine 2-3 variants of how to refactor it if I were writing the code > in Python. I am pretty sure there were no select statement (switches) > in Python code, because that is what polymorphism is about. > > But then again, translating back to C++ could be difficult. The > mentioned example is all about reading a specially formatted binary > file to produce certain slices of information. And for each > class it uses separate .cc/.hh file! While all the difference > between different classes - structure of corresponding data entries. > > My approach in this case could be one resource file, with format > specification (like DTD). Plus one univarsal class to handle big > binary file according to "DTD"). Plus maybe separate resource file > with data query specifications. And it could be at most 80 Kb Python > project, not that monster Arts++ is in both source and binary forms... > > Well, if you still follow this thread, the question is - how well > Python could serve as an ARCHITECTURAL prototype if it has too rich > OOP facilities? That is, is Python of help when trying to > prototype certain design? Developing in C++ looks so unnecessary hard > after things were done in Python... > Or, it may be put this way: what discipline a Python programmer must > obey to allow it's prototype to be conveniently rewriten in C++? > The above thoughts aren't probably well-formed. But I hope > my concern is understood. > > > Sincerely yours, Roman Suzi I agree with what you are saying. Here's my approach :-) 0. Write a project schedule for management; something like this: 1. Prototype in python 2. Convert to C++ 1. Prototype in python 2. Give a nice demo, and convince management to skip step 2 3. Re-implement a few cpu intensive classes in C++ Since most of the code never /actually/ gets rewritten in C++, the need for special C++ "discipline" in the python code goes away. Weeks are slashed from the schedule, and the program is more maintainable. Another nice advantage is that the python programmer gets to ask for a raise, and has excellent job security! There may be a few oddball examples of projects that actually need to end up written in C++ after prototyping in python, but for the most part, the most common reason to target C++ is to alleviate fear of the unknown. (Hmm, is this also why people, (including myself), still buy from Microsoft? :-) - Ken Seehof From zopestoller at thomas-guettler.de Fri Jun 28 07:40:48 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Fri, 28 Jun 2002 13:40:48 +0200 Subject: GUI-Control for HTML Message-ID: <3D1C4B40.6090803@thomas-guettler.de> Hi! Is there are GUI-control which can display HTML? The HTML that will be used will be simple, no javascript or form support is needed. Is there are cross-plattform solution? (Unix + Win32) The tags will be: -li -ol -br -h? -table, td, tr, th, -a -img thomas From fabien.henon at caramail.com Fri Jun 28 18:23:55 2002 From: fabien.henon at caramail.com (Fabien HENON) Date: Sat, 29 Jun 2002 00:23:55 +0200 Subject: Redirect stdout with createfilehandler Message-ID: <3D1CE1FB.9060007@caramail.com> I am trying to redirect stdout from a raytracer back to a Tkinter Text with createfilehandler. With the script below I keep getting the error ' maximum recursion depth exceeded'. I have been stuck with this redirection problem for 2 months. This is driving really nuts now. If I turn off the verbose in the command line '-v', the image is raytraced till the end with the recursion error. If I turn the verbose on, the raytrace stops after roughly a second. What the raytracer does when the verbose is turned on, is to spit out the line being rendered while raytracing. I get the image, not the stdout to the Tkinter text. Could one Guru tell me what I am doing wrong here. Or at least have one working example One thing : You can download the executable and the POV script (the raytracer) at http://pyvon.sourceforge.net/executable_file.tgz Fabien HENON 8<-------------snip--------------->8 import sys,os import Tkinter from Tkinter import * root = Tk() T=Text(root) T.pack() cmd = 'mega +i1.pov +w320 +h240 +dgt +v -f' c_in,c_out=os.popen4(cmd) def stdout_handler(): T.insert('1.0',c_out) root.tk.deletefilehandler(c_out) root.tk.createfilehandler(c_out, Tkinter.READABLE, stdout_handler) root.after(1000,stdout_handler()) root.tk.createfilehandler(c_out, Tkinter.READABLE, stdout_handler) root.after(1000,stdout_handler()) root.mainloop() 8<--------------snap--------------->8 From rdacker at pacbell.net Fri Jun 21 13:00:44 2002 From: rdacker at pacbell.net (rdack) Date: 21 Jun 2002 10:00:44 -0700 Subject: urllib POST question References: <644f6688.0206200930.48110837@posting.google.com> Message-ID: <644f6688.0206210900.68dd930c@posting.google.com> Ben Beuchler wrote in message news:... > In article <644f6688.0206200930.48110837 at posting.google.com>, rdack wrote: > > i am doing a POST to a server using urllib and it works. > > is there some way i can see exactly what is being posted? > > a way to get the post object out of urllib - the exact lines it is sending? > > I'm a big fan of Ethereal... > "Sniffing the glue that holds the internet together!" > > http://www.ethereal.com/ i am looking into it. seems overkill for wanting to see a few bytes that python is generating. No way within python to see what urllib intends to send out for the POST? From tim.one at comcast.net Mon Jun 3 17:27:05 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 03 Jun 2002 17:27:05 -0400 Subject: python tool: finding duplicate code In-Reply-To: Message-ID: [Michal Wallace] > Thanks for the link! I found a javascript version of a > suffix tree algorithm online. I ported it to python and it > seems to work... Unfortunately the original code is very > hard to understand. I did a straight port and then tried to > clean it up and make it a little more object oriented, but > when I started looking into the algorithm, I just couldn't > track what was going on. Don't feel bad! Suffix trees are very surprising. In fact, they caught everyone by surprise when they were invented, allowing linear-time solution of several problems that were conjectured to be impossible to solve in linear time. Ukkonen's algorithm (on which the JavaScript version seems to be based) is considered much clearer than its predecessors, but it's also subtle to the point of madness . A much more obvious approach is to materialize all the suffixes explicitly into a list, and then just sort the list. Stop right there and you're close to a "suffix array". Building a tree from the sorted list is simple then. But this doesn't work in linear time, so misses part of the point. In any case, suffix tree algorithms probably need to be coded in C to be of practical use (lots of low-level fiddling involved). > ... > There's also a suffix tree module written in C, but with a > python binding here: > > http://www-hkn.eecs.berkeley.edu/~dyoo/python/suffix_trees/ Wow! Danny sure gets around -- if I can weasle a few free hours I'll definitely play with this. Thanks for the link! From shalehperry at attbi.com Thu Jun 6 12:01:33 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Thu, 06 Jun 2002 09:01:33 -0700 (PDT) Subject: Program to an interface, not an implementation In-Reply-To: <20020606121159.A975@bork.demon.nl> Message-ID: On 06-Jun-2002 Egbert Bouwman wrote: > Hello, > Can someone shed some light on the GoF adagium: > 'program to an interface, not an implementation' > and especially what it means for programming in Python ? > GoF is not easy. Sure we can even use python as the example (-: Any object can act like a list or a dict if they implement the right methods. This is an interface. l = [1,2,3] # use a python list uses the implementation. To further this, if your class included code which made decisions based on how you knew say dict was implemented rather than just using ['string'] or .has_key() that would be violating the interface. From Chris.Barker at noaa.gov Fri Jun 21 16:01:55 2002 From: Chris.Barker at noaa.gov (Chris Barker) Date: Fri, 21 Jun 2002 13:01:55 -0700 Subject: How to represent the infinite ? References: Message-ID: <3D138632.8B40F968@noaa.gov> Huaiyu Zhu wrote: > If, in reality, only some very niche platforms need such checkings, maybe it > is better to let those platforms without ieee compliance suffer (in terms of > having to add a small patch), rather than depriving most of the mainstream > platforms of a very useful feature? hear hear!! (or is that here here!) -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From davegaramond at icqmail.com Fri Jun 21 06:34:51 2002 From: davegaramond at icqmail.com (David Garamond) Date: Fri, 21 Jun 2002 17:34:51 +0700 Subject: I'd give up Perl tomorrow if only... References: <3D12F6FC.3000608@wedgetail.com> Message-ID: <3D13014B.8070203@icqmail.com> Derek Thomson wrote: >> .. there was something equivalent in scope and breadth to CPAN. > I (almost) agree, and sympathise :) whom is it that you sympathize on? perl? python? the original poster? i pick python to sympathize on. :-) -- dave From peter at engcorp.com Sat Jun 22 13:01:51 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 22 Jun 2002 13:01:51 -0400 Subject: Python hits the spot References: <3D1482AE.8FA299D8@kfunigraz.ac.at> <3d149f19$0$53133$edfadb0f@dspool01.news.tele.dk> Message-ID: <3D14AD7F.3D5D243F@engcorp.com> Aahz wrote: > > In article <3d149f19$0$53133$edfadb0f at dspool01.news.tele.dk>, > Frihtiof Andreas Jensen wrote: > > > >My bet is that once you cool off and sits down with some debugging tools > >like GDB, Boundschecker or Electric Fence you will indeed find the > >programming error and fix it. > > > >My bet is also that you will not tell anyone either. > > Ya know, you could have saved yourself a lot of typing by simply saying > PBCAK. ;-) To save us from those who can't Google: Problem Between Chair And Keyboard. (It was new to me, too.) -Peter From donn at u.washington.edu Fri Jun 7 12:16:52 2002 From: donn at u.washington.edu (Donn Cave) Date: 7 Jun 2002 16:16:52 GMT Subject: Using popen interactively References: Message-ID: Quoth Joe Mason : ... | So I'm trying to use popen2.Popen3("executable-name") to get handles to | stdin and stdout. Works fine, except that I'm not sure how to detect | when the app has stopped printing and is waiting for input. readline() | gets the first lines ok, but then the ">" line has no newline on the | end, so it blocks. Apparently read() is supposed to return an empty | string when it hits EOF, but it blocks too - so apparently on an | interactive file stream like this EOF isn't set when its waiting for | input. Right. I expect you'd do better to throw away the file objects popen2 makes for you, and use the pipe file descriptors directly. Instead of infile = app.fromchild ... line = infile.readline() say infile = app.fromchild.fileno() ... data = posix.read(infile, 8192) # split into lines if you care The stdio buffering in a file object is only trouble for you. Part of this trouble is on the other end, if your external process buffers output - in that case you'll have to figure out how to use ptys. Donn Cave, donn at u.washington.edu From mhammond at skippinet.com.au Mon Jun 17 18:50:23 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Mon, 17 Jun 2002 22:50:23 GMT Subject: Help: win32gui & threads References: <33803989.0206170318.9d3a225@posting.google.com> Message-ID: <3D0E6849.3050909@skippinet.com.au> Miki Tebeka wrote: > Hello All, > > I've written a little logger daemon with UI in Windows taskbar. > (See code below) > It seems to work fine but when I choose 'Quit' the windown closes but > the pythonw is still alive and I need to kill it from the TaskManager. > > Any idea how to make it close? You will need to do a little more work to give us more information. * Is the DestroyWindow() call being made? * Does the main thread ever appear to end - ie, if you put a print statement after the PumpMessages(), will it appear. Mark. From emile at fenx.com Tue Jun 18 21:48:58 2002 From: emile at fenx.com (Emile van Sebille) Date: Wed, 19 Jun 2002 01:48:58 GMT Subject: I have .py, I want .exe, how?? References: Message-ID: wrote in message news:mailman.1024448546.1172.python-list at python.org... i have a file.py how i make e executable file .exe for run in windows??? http://www.python.org/doc/FAQ.html#4.28 -- Emile van Sebille emile at fenx.com --------- From quinn at groat.ugcs.caltech.edu Sat Jun 15 01:49:33 2002 From: quinn at groat.ugcs.caltech.edu (Quinn Dunkan) Date: 15 Jun 2002 05:49:33 GMT Subject: filter2 References: Message-ID: On Thu, 13 Jun 2002 18:50:23 +0400, Oleg Broytmann wrote: >On Thu, Jun 13, 2002 at 04:39:51PM +0200, Thomas Heller wrote: >> >> "Oleg Broytmann" wrote in message news:mailman.1023975618.6474.python-list at python.org... >> > I want to have new python builtin - filter2. It is exactly like filter, >> > but it returns also a list of items that didn't pass the test. >> >> IIRC, in Smalltalk they were named 'select' (like filter), and 'reject' (like your filter2). >> IMO these are much better names then filter and filter2. > > It is too late to rename builtin filter, so I modelled fiter2 after it. In haskell they call it "partition" which I think is better since the emphasis is that it returns both selected and rejeted. I wrote mine in python with a plain for loop. I'm not sure C would really get you that much efficiency, but it would be easy enough to find out. Not sure it's worth being in the core (maybe there should be a module for list utils or something), but I like partition better than filter2. From peter at engcorp.com Mon Jun 17 20:28:22 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 17 Jun 2002 20:28:22 -0400 Subject: Embedded systems References: Message-ID: <3D0E7EA6.1E96C53F@engcorp.com> Stuart wrote: > > Is Python practical for embedded systems? I am working on a project at the > moment that uses a GSM/GPRS modem and a GPS receiver. I have prototyped the > whole thing in Visual Basic, and now I need to port it over to a suitable > processor (possibly on a 68000 device using Linux). > > I don't really want to get into C for this project, and was wondering if > Python was suitable? Are memory requirements an issue? We are building embedded Linux systems using Python as the primary language (with bits of C for some custom drivers). Our processors are x86 but a standard port to 68K should work fine I suppose. Memory is about what you might expect, which is to say that it requires more than C by several times, but any system capable of running Linux and a few apps can handle Python on top of it without much trouble, IMHO. For what it's worth, we had a 386-based proprietary system running with a compacted Python running in 1MB RAM and 1MB flash, but it was way too tight for our needs. We now use 486/100 processors with 32MB RAM and 64MB CompactFlash cards, and have _plenty_ of room to spare. We could probably get by with as little as 4-8MB RAM and 16-32MB flash for what we currently do. -Peter From dw133 at cs.york.ac.uk.go.away Fri Jun 7 19:45:08 2002 From: dw133 at cs.york.ac.uk.go.away (Darren Winsper) Date: Sat, 08 Jun 2002 00:45:08 +0100 Subject: Detecting OS and Window Manager References: <3d00bfb5$1_2@hpb10302.boi.hp.com> <3d00d248$1_1@hpb10302.boi.hp.com> Message-ID: In <3d00d248$1_1 at hpb10302.boi.hp.com>, Daniel Fackrell wrote: >> Well, I could attempt to see if something like "kdesktop" is running, >> since if it is, the chances of running KDE are very high. It's kludgy, >> but I can't really think of anything else, since KDEINIT would be running >> if a single kde application is running IIRC. > > If you're thinking of scanning the currently running processes for the > existence of a particular process, then you won't get the results you want > there, either. The reason for this is that there can be multiple logins for > a single user or multiple users, and KDE-related processes will exist if any > one of those logins is running KDE, but not necessarily the current one. Good point. > Maybe import your kde module(s), and then try to do something KDE specific > without KDE running and see what kind of error this causes so you will know > what to trap for? I don't believe there really is anything there you can do. I certainly don't know of anything in KDE that requires you to be running the KDE DE to actually perform the command. If there is anything, I'm fairly certain it'll be a kludge and won't really be portable. > Hopefully some other newbie (for a much less significant > value of new, AKA expert) is still following this thread to give you a > better answer. Alas, I don't think there is an easy answer to this. I think we'll just have to either: 1) Settle for a default 2) Provide different commands such as gfunky and kfunky and just provide menu entries to point to the appropriate one depending upon which DE you are running. -- ICQ: 8899775 Jabber ID: darren at rooter.dyndns.org Stop the EUCD before it's too late: http://uk.eurorights.org/issues/eucd/ http://www.tomchance.uklinux.net/articles/darkages.shtm From emile at fenx.com Tue Jun 18 22:30:00 2002 From: emile at fenx.com (Emile van Sebille) Date: Wed, 19 Jun 2002 02:30:00 GMT Subject: I have .py, I want .exe, how?? References: <3D0F6623000012D8@www.zipmail.com.br> Message-ID: Gerhard H?ring > > It's a FAQ and answered here: > > http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.028.htp > > Gerhard, who considers making an editor macro for this question When you get enough macros you can apply for bot status. Of course, you'll have to find out where to apply from the PS From skip at pobox.com Tue Jun 25 10:12:42 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 25 Jun 2002 09:12:42 -0500 Subject: Thread Memory Leak In-Reply-To: <3D18745D.554A7C44@engcorp.com> References: <3D18745D.554A7C44@engcorp.com> Message-ID: <15640.31322.834546.849385@12-248-8-148.client.attbi.com> >> You never remove any thread objects from your listThread list. It >> fills up with completed threads. Peter> Actually, the list is rebound to a new empty list each pass Peter> through the while loop... Duh... That's what I get for answering questions so early in the morning... I do see some strange behavior, now that I actually run the code. Running it as python threadgrowth.py | egrep -v RSS | uniq yields output like 3288 1984 3292 1992 3296 1996 13536 2016 3296 1996 15584 2020 3296 1996 21728 2044 19680 2028 15584 2020 3296 1996 19680 2028 3296 1996 17632 2032 3296 1996 I don't know why it bounces around like that, but the minimum VSZ does go up: 3296 1996 19680 2032 7392 2008 3296 1996 20704 2032 4320 2000 16608 2028 20704 2040 20704 2036 4320 2000 20704 2036 4320 2000 16608 2024 4320 2000 14560 2020 4320 2000 20704 2032 4320 2000 16608 2024 18656 2032 4320 2000 18656 2028 4320 2000 This was after just a couple minutes of running. Skip From logiplexsoftware at earthlink.net Thu Jun 20 13:47:15 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Thu, 20 Jun 2002 10:47:15 -0700 Subject: How to represent the infinite ? In-Reply-To: <3d11ee9b$1@news.swissonline.ch> References: <3d11ee9b$1@news.swissonline.ch> Message-ID: <20020620104715.5d4f11ae.logiplexsoftware@earthlink.net> On Thu, 20 Jun 2002 17:02:33 +0200 erreur wrote: > Will somebody have an idea, to represent the infinite one? > > I have variables to initialize with is +inf (or - inf). To be sure that > later, all will be smaller (or larger) than my variables. > I tried to redefine the operators on an object. It goes for Inf>10 but I do > not arrive for 10>Inf (because that takes > of Int). > > -------------------- > > def __gt__(self, val): > > return 1 > > -------------------- Well, here's a start: class inf(int): def __init__(self): int.__init__(self) self.sign = 1 def __str__(self): return "" def __repr__(self): return "" def __cmp__(self, n): if isinstance(n, inf): return cmp(self.sign, n.sign) return self.sign def __neg__(self): retval = inf() retval.sign = self.sign * -1 return retval if __name__ == '__main__': import sys m = -inf() n = inf() assert(m < n) assert(n > m) assert(m == m) assert(n == n) assert(m != n) assert(m < 0) assert(n > 0) assert(m < -sys.maxint) assert(n > sys.maxint) assert(m < -m) assert(n == -m) -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From irmen at NOSPAMREMOVETHISxs4all.nl Fri Jun 28 13:33:44 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Fri, 28 Jun 2002 19:33:44 +0200 Subject: M2Crypto: select() behaves weird on SSL sockets References: <3D04ED17.5070606@NOSPAMREMOVETHISxs4all.nl> <3D066E77.4070901@NOSPAMREMOVETHISxs4all.nl> <3D0790E1.9080904@NOSPAMREMOVETHISxs4all.nl> <831ybavprx.fsf@panacea.canonical.org> <3D0919AF.7050903@NOSPAMREMOVETHISxs4all.nl> <83it45lxfb.fsf@panacea.canonical.org> <3D1B92A2.7030605@NOSPAMREMOVETHISxs4all.nl> Message-ID: <3D1C9DF8.3010607@NOSPAMREMOVETHISxs4all.nl> Steve Holden wrote: > asyncore/asynchat really repay the effort of study, so I would advise you to > take a fresh look when you get time. I will. Am I correct to conclude that the benefits of using asyncore as a basis for Pyro are: 1. uses a well-tested stable I/O module (though the current implementation in Pyro isn't bad at all) 2. able to process multiple requests without using threads, because the I/O is multiplexed 3. able to handle very many concurrent connections (no thread overhead per connection -- but is a thread really that heavy?) > To assist you, I plan to add documentation for asynchat for 2.3. That's nice because I was looking for that one just yet :) But glancing at the code of asynchat makes me think that this one isn't suited for Pyro because Pyro is no line-based command-response protocol. > when-sourceforge-stops-playing-silly-buggers-ly y'rs - steve What's wrong with SF? Cya Irmen de Jong From pyth at devel.trillke.net Sun Jun 16 06:23:29 2002 From: pyth at devel.trillke.net (holger krekel) Date: Sun, 16 Jun 2002 12:23:29 +0200 Subject: What If..... Strong Types In-Reply-To: <3D0C0F0D.4030900@bgb.cc>; from garrett@bgb.cc on Sun, Jun 16, 2002 at 04:08:26AM +0000 References: <3D0C0F0D.4030900@bgb.cc> Message-ID: <20020616122329.H15079@prim.han.de> Hi Don, You wrote: > What if Python had been built from the start with strong types? And I mean > strong types, not strong typing. The distinction I am trying to draw is that > variables would not be typed, but that all types would have rigid interfaces. your wording doesn't really make sense to me. There is no such thing as "variables" in python. EVERYWHERE in modules, classes, instances, globals(), locals() ... there are only name=object "name-object-bindings" Objects *have* strong types (or strong typing if you like). The difference to e.g. Java is that python does DYNAMIC typing instead of java's STATIC typing. This is the main hinderance for doing certain optimizations on compilation time. See the types-SIG for further and very interesting discussion: http://www.python.org/sigs/types-sig/ > Primarily, what if classes always had rigidly defined interfaces. I mean > that public members had to be declared to exist, and that methods couldn't be > modified on an instance. Private members could exist but would be really private. OK. There is lots of discussion about 'interface' concepts. Today interfaces only exist implicitely in python. There have been lots of efforts to introduce interface concepts like the one for Zope2/Zope3's components: http://www.zope.org/Members/jim/PythonInterfaces/Interface (maybe outdated) I think there is a reason, though, why there is no great rush to introduce any current interface concept to python. None of the current proposals have really convinced a large enough portion of python developers to become part of the core language. I am sure that when python gets explicit interfaces it's going to be a great thing (tm). But IMO one of the main questions is how do you mix the declarative nature of interfaces with pythons powerful dynamic object and namespace model? My personal fantasies focus on connecting IDL-specified interfaces (OMG's *I*nterface *D*efinition *L*anguage which is used in many domains) with python namespaces. Something basically like: mymodule.py # a python module mymodule.idl # interface definitions python's compiler would use *both* files to make sure that they match. For a to-be-discussed definition of 'match' :-) regards, holger From gerson.kurz at t-online.de Fri Jun 7 12:40:27 2002 From: gerson.kurz at t-online.de (Gerson Kurz) Date: Fri, 07 Jun 2002 16:40:27 GMT Subject: Newby: How do I strip HTML tags? References: Message-ID: <3d00e1b1.47853937@news.t-online.de> This is a quite straight forward function: def StripTags(text): finished = 0 while not finished: finished = 1 # check if there is an open tag left start = text.find("<") if start >= 0: # if there is, check if the tag gets closed stop = text[start:].find(">") if stop >= 0: # if it does, strip it, and continue loop text = text[:start] + text[start+stop+1:] finished = 0 return text Or, if you feel lucky, you could use this more complicated solution def StripTags(text): flag = [1] def stripfunc(c): if not flag[0]: if c == '>': flag[0] = 1 return 0 elif c == '<': flag[0] = 0 return flag[0] return filter(stripfunc,text) From baas at ira.uka.de Mon Jun 24 16:52:46 2002 From: baas at ira.uka.de (Matthias Baas) Date: Mon, 24 Jun 2002 22:52:46 +0200 Subject: PYREX References: <3d1749d3.19107439@news1.news.adelphia.net> Message-ID: On Mon, 24 Jun 2002 16:34:57 GMT, edlsoft at mindspring.com (Burt Leavenworth) wrote: >Has anyone installed Pyrex on Windows? If so, can you share the >details? - Download Pyrex and Plex. - Unpack Pyrex (you can use filzip (www.filzip.de), winzip (www.winzip.com) or the cygwin tools (www.cygwin.com)) - Unpack Plex - Copy the "Plex" directory into the Pyrex directory (the other files aren't necessary for executing pyrex) Now you can already call pyrexc, but probably you also want to add the Pyrex directory to your path and rename "pyrexc" into "pyrexc.py". If you want to use Plex yourself, it'd be better to install it as a regular module, but if you just want to get pyrex running you can get away with the above procedure. - Matthias - From peter at engcorp.com Thu Jun 20 21:05:45 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 20 Jun 2002 21:05:45 -0400 Subject: Flame fests (was Re: python version?) References: <3D107948.B3FEE4BB@engcorp.com> <3D112BA6.4CA5F584@engcorp.com> Message-ID: <3D127BE9.9BD93FC3@engcorp.com> Aahz wrote: > > In article <3D112BA6.4CA5F584 at engcorp.com>, > Peter Hansen wrote: > >Aahz wrote: > >> > >> Everybody have fun playing "kick the newbie"? Maybe it's time to quit? > > > >I think we'd all object strongly to the characterization that we were > >"kicking a newbie". > > Well, then, if you're not kicking a newbie, you're swallowing trolled > bait. Which makes you feel better? Swallowing trolled bait, no contest. I'm not yet convinced it was such though, although similar further postings would prove your point. -Peter From aahz at pythoncraft.com Thu Jun 20 20:20:16 2002 From: aahz at pythoncraft.com (Aahz) Date: 20 Jun 2002 20:20:16 -0400 Subject: Raw String Output References: Message-ID: In article , Chris Liechti wrote: >"mike" wrote in news:aetnkf$tot$1 at news.umbc.edu: >> >> If I have a string variable with the value '\n' how do I output it to >> a file with the value of '\012' instead ? > >i assume that its clear to you that '\n' == '\012' so i guess you want the >string r'\012' in the file and not the newline character?!? > >then you must do it by hand, i think. this one replaces all characters < 32 >with their octal value: >>>> print ''.join([ c>=' ' and c or '\\%03o' % ord(c) for c in 'hello\n']) >hello\012 Actually, I'd guess the problem is more that Mike is using a text file on a platform where \n is *not* \012 (e.g. Windows). In that case, he'll have to stick chr(012) into the files directly, preferably opening files in binary mode first. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From deltapigz at telocity.com Sat Jun 29 21:29:51 2002 From: deltapigz at telocity.com (Adonis) Date: Sat, 29 Jun 2002 21:29:51 -0400 Subject: possibly a dumb question Message-ID: <3d1e5eff$1_7@nopics.sjc> can a class return a value? i have treid to google this, but have found myself short of an answer, i know i could place it in a member and retrieve it or through a function, but im trying to simplify my life.. just a little.. any help would greatly be appreciated. Adonis From pollosgbr at netscape.net Sat Jun 29 17:51:04 2002 From: pollosgbr at netscape.net (Just a dude) Date: Sat, 29 Jun 2002 21:51:04 GMT Subject: Newbie that don't understand References: Message-ID: <3d1e262f.3755054@news.clara.net> On Sat, 29 Jun 2002 17:00:16 GMT, "Martin St?hl" wrote: >I have never been programming before and now I am reading the I have just [this week] decided to try Python myself. I haven't done any programming since I had a 48K Specky [except for a little dabble in Rexx some years back] I too have started with the "Non-Programmers Tutorial For Python" but understand [I think] absolute values. But if I didn't I don't think I'd understand your reply's. I'm sorry I know the value of these groups and really appreciate the help you all give freely and I'm very grateful, but for 'Newbies' like myself I would ask for simple answers if that's possible. Please don't take this the wrong way but as a beginner what seems easy and obvious to you is sometimes way over our heads. >with the output being: >The absolute values of 23 and 23 are equal" > >how can 23 and -23 be equal? > To some this can be a hard concept to grasp. My son is an electronics design engineer, and I still can't get my head around negative voltages, how the hell do you get a -12 V supply... to him it's basic but to me.............. Cheers and thanx for you help Steve. From rs at onsitetech.com Fri Jun 28 16:07:46 2002 From: rs at onsitetech.com (Robb Shecter) Date: 28 Jun 2002 20:07:46 GMT Subject: Introspection: determining parent classes? Message-ID: <3D1CC1CA.70004@onsitetech.com> Hi, Is there any way to determine the parent classes given an instance? I'm writing unit test code, and I want to assert that a particular result is a subclass of some other class. In Java, you can do something like: anInstance.getClass().isSubclassOf( aClass ) I looked through the type(), __class__, etc. info, but these seem to just return string-like objects that don't allow further introspection. Is there an equivalent in Python? Thanks, Robb From dm_top at hotmail.com Mon Jun 3 11:30:01 2002 From: dm_top at hotmail.com (Dmitri) Date: 3 Jun 2002 08:30:01 -0700 Subject: thread module under Windows Message-ID: <59d8a5f6.0206030730.1be14ffb@posting.google.com> Hi All, I have been searching the conference for the simple question like " where the thread module is " and got the answer that it's inside the python if the threading support is on. Ok. Reading the conference I see that many people use the python in multi-threading. How they get the python version for windows with treading support on ( I am not talking about other optional services now... )??? Now the question - I understand, that I could and must rebuild the python under the unix/linux/cygwin environment to have the treading support be on. What about the windows? Could I download the python with optional services installed, i.e. should I build the python for the windows myself if I want to have some optional services be on? If yes, I think that the only way to do it is to build the python under cygwin. Would it be compatible enough to run the python from windows command prompt after that? With the best regards, Dmitri Top From dave5774 at hotmail.com Mon Jun 17 17:44:36 2002 From: dave5774 at hotmail.com (Dave) Date: Mon, 17 Jun 2002 17:44:36 -0400 Subject: Please help with Python Script/MS-Access (DAO) Message-ID: Hey all, I'm having trouble writing a Python script relating to Microsoft Access. If anyone could help me I would greatly appreciate it. Here's the problem : I built an MS-Access table with 5 columns(fields) : OrderID, OrderDate, PlantID, ProductID, OrderQty, with OrderID as the primary key. All fields are numeric, except for OrderDate(which is a date field). Now I want to populate this table with data from a web page (http://opim.wharton.upenn.edu/~opim101/spring02/Plant1.html). please check the site. My object is to read the the data and insert it record by record into my Access table. Here's what I have so far : import urllib, string Plant1 = urllib.urlopen('http://opim.wharton.upenn.edu/~opim101/spring02/Plant1.html' ) lines1 = Plant1.readlines() import win32com.client engine = win32com.client.Dispatch("DAO.DBEngine.35") db=engine.OpenDatabase(r'd:\Plants.mdb') I have several problems : Firstly, when I read the lines, I notice that not all of them are relevant. I need to ignore , , etc. at the beginning of the file, as well as the column headers, so that the action really begins from line 4 of the file and ends with Also, I need to eliminate

from every line in the file in order to get to the five comma-delimited fields that follow, and then split the rest of the string to get to each field. Here's what I think part of the code should look like : for line in lines1.readlines(): line=line.rstrip() inOrderID,inOrderDate,inRegionID,inProductID,inOrderQty = line.split(",") Something like that, I'm not sure... Lastly, now that I've read all the fields, I need to insert them each as a single record into my table of my access database using Python DAO using the Insert statement. Also, the OrderDate field that I read in, looks like a text type to Access, so I need to pad it with the # sign on either side before inserting it into the Access database, so that Access interprets it as a Date/Time type. Finally, I need to get the same information from 2 other plants and tag them onto the same table...from the web page http://opim.wharton.upenn.edu/~opim101/spring02/PlantPortal.html where plant1's data shows up first, plant2's data shows up below it, and plant3's data shows up last...so all plants' data in the same table. If anyone could help me by writing the script I would greatly appreciate it... Thank you so much. Sincerely, Dave From cliechti at gmx.net Sun Jun 2 14:19:05 2002 From: cliechti at gmx.net (Chris Liechti) Date: 2 Jun 2002 20:19:05 +0200 Subject: Python Turing machine References: Message-ID: Tobias Brandvik wrote in news:d9akfu0c7ro0sebio1vd9c6ik2i0fg59le at 4ax.com: > Has anyone seen a model of a Universal Turing Machine coded in Python? > I've seen examples in Scheme, Java and Perl, but I'd really like to > look at one made in Python... Any pointers? hint: post some URLs of those implementations to the list. that way we don't need to look up what it is and people here have fun trying to solve things pythonic... chris -- Chris From hwcowan at hotmail.com Fri Jun 14 16:01:00 2002 From: hwcowan at hotmail.com (Hugh Cowan) Date: 14 Jun 2002 13:01:00 -0700 Subject: Creating Dynamic Web Pages (ZOPE) References: <46ca81a0.0206062016.789d3af6@posting.google.com> Message-ID: <46ca81a0.0206141201.23db4a8c@posting.google.com> Steve, Thanks for the suggestion and sample web-site, I will definetly check-it out. Does DreamWaver support ASP then, or rather provide support? I mean, I know that you could just add the ASP code mixed in with the HTML manually, but does it offer any RAD type tools to help make using ASP easier? Also, I thought that Dreamweaver was more of just a HTML Editor, while something like Zope provided extra functionality, tools, wizards, etc.. to allow you to create Dynamic Web-Sites quicker and easier? I am just trying to figure out where to concentrate my search for software and tools. I originally looked through the various *Freeware* web-sites for HTML editors -- but there are so many of them out there (hard to pick one from the other -- almost makes you want to go back to a plain old text editor). While some offer advantages over others, they all seem to basically assist you in generating the HTML code for web-pages (either by coding or using a WYSIWYG type interface)? Thanks, Hugh > > At the risk of sounding like a heretic... > > I recently started to use DreamWeaver UltraDev (one of my clients mandated > its use) and I've been relatively impressed. For a really small > database-driven web created in DreamWeaver take a look at > > http://www.holdenweb.com/TinySite/ > > This web has precisely four pages, and I built it to explain to beginners > how database contents can affect a site's navigation as well as its readable > content. > > DreamWeaver MX is now out, and targets several more backends. It would be > nice if it had one that drove some suitable Python framework -- possibly > WebWare. > > If you are already familiar with ASP, this will get you up to speed on your > tasks much more quickly than learning Zope. Won't be as much fun, though. > > regards > Steve From osantana at netbank.com.br Fri Jun 7 21:31:55 2002 From: osantana at netbank.com.br (Osvaldo Santana Neto) Date: Fri, 7 Jun 2002 22:31:55 -0300 Subject: How to install Python without root priviledges ? In-Reply-To: References: Message-ID: <20020608013155.GD28708@netbank.com.br> On Tue, May 28, 2002 at 12:36:23PM +0200, Shagshag13 wrote: > > I'm a real newbie in unix's world and i would like to install python on a > machine where *i can't have* any root priviledges, how should i do that ? > > (it's on a HP Unix, but don't even know how to check the exact os name or > version...) > > i do this : > > mkdir /home/shagshag/local > download Python-2.2.1.tgz > gunzip > tar -xvf Python-2.2.1.tgz > cd Python-2.2.1 > ./configure --prefix=/home/shagshag/local > make make install > > And i get nothing !!!! > > Is it the good way to install ??? > > Thanks in advance, > > S13. > > please, don't forget i'm not a skilled unix guy... > > > -- > http://mail.python.org/mailman/listinfo/python-list -- Osvaldo Santana Neto - aCiDBaSe ICQ#: 11287184 - www.osantana.f2s.com From gerson.kurz at t-online.de Sat Jun 1 10:15:19 2002 From: gerson.kurz at t-online.de (Gerson Kurz) Date: Sat, 01 Jun 2002 14:15:19 GMT Subject: Python and HTML frames References: Message-ID: <3cf8d6d3.14806203@news.t-online.de> I'm assuming you're writing a CGI, so: #! /usr/bin/python import cgi, sys, os print "Content-type: text/html\n" def GenerateMainFrame(): print """ <body><p>blablabla</p> </body>""" def GenerateFrame1(): print "

TODO: add code for frame #1

" def GenerateFrame2(): print "

TODO: add code for frame #2

" page, form = None, cgi.FieldStorage() if form.has_key('cmd'): page = form['cmd'].value if page == "frame1": GenerateFrame1() elif page == "frame2": GenerateFrame2() else: GenerateMainFrame() From gumuz at looze.net Tue Jun 25 04:30:38 2002 From: gumuz at looze.net (Guyon Morée) Date: Tue, 25 Jun 2002 10:30:38 +0200 Subject: 'parent object'? References: <3d18228c$0$221$4d4ebb8e@news.nl.uu.net> <3D182662.CBC925DB@alcyone.com> Message-ID: <3d182943$0$227$4d4ebb8e@news.nl.uu.net> thanx a lot for your quick response! "Erik Max Francis" wrote in message news:3D182662.CBC925DB at alcyone.com... > "Guyon Mor?e" wrote: > > > Is there, like 'self, also a 'parent' object of some sort? > > > > The problem i'm having is that i have a class, which contains a list > > of > > instances of another class. How can i let this 'childclass' call a > > function > > which is on the 'parent class'? > > An instance has access to its class (.__class__ attribute), and a class > has access to its parent classes (.__bases__ attribute). > > -- > Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ > __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE > / \ See the son in your bad day / Smell the flowers in the valley > \__/ Chante Moore > Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ > A personal guide to Aliens vs. Predator 2. From kragen at pobox.com Thu Jun 20 11:20:39 2002 From: kragen at pobox.com (Kragen Sitaker) Date: Thu, 20 Jun 2002 11:20:39 -0400 Subject: Fw: Inter Process Communication with Numeric arrays Message-ID: <20020620152039.GA16770@canonical.org> The problem with http://pobox.com/~kragen/sw/arrayfrombuffer/ has been fixed. Thanks for letting me know. From js_nntp at nospam_blackrocksoftware.com Sat Jun 8 07:23:20 2002 From: js_nntp at nospam_blackrocksoftware.com (J Swartz) Date: Sat, 08 Jun 2002 11:23:20 GMT Subject: Comparison: HTTP with Java, Perl or Python References: <3D009911.9000904@gmx.de> <3D0127D2.2060604@gmx.de> Message-ID: On 6/7/02 2:38 PM, in article 3D0127D2.2060604 at gmx.de, "Ingo Linkweiler" wrote: > thanks a lot for your help. > > Do you know SHORTER solutions in Java? Here's one: public class URLTest { public static void main(String[] arguments) { String myurl = "http://www.uni-dortmund.de"; try { java.io.BufferedReader reader = new java.io.BufferedReader ( new java.io.InputStreamReader((new java.net.URL(myurl)).openStream()) ); for (String curLine = reader.readLine(); curLine != null; curLine = reader.readLine()) System.out.println( curLine ); reader.close(); } catch (java.io.IOException ex) { System.out.println(ex); } } } Instead of reading the url completely before printing, this version prints line by line. Still, it's pretty close. The java.io package could definitely use a simple method to download the complete contents of a stream at once. Below is a similar version: public class URLTest { public static void main(String[] arguments) { String myurl = ( "http://www.uni-dortmund.de" ); try { java.io.BufferedInputStream input = new java.io.BufferedInputStream( (new java.net.URL(myurl)).openStream() ); java.io.ByteArrayOutputStream output = new java.io.ByteArrayOutputStream(); for (int val = input.read(); val != -1; val = input.read()) output.write( val ); input.close(); System.out.println( output ); } catch (java.io.IOException ex) { System.out.println(ex); } } } This one is 2 lines longer but it is closer in function to your sample program. - JS From tjreedy at udel.edu Tue Jun 4 22:23:40 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 05 Jun 2002 02:23:40 GMT Subject: Behavior of += (was Re: [Python-Dev] Customization docs) References: Message-ID: "Huaiyu Zhu" wrote in message news:slrnafqppg.4ea.huaiyu at gauss.almadan.ibm.com... > Objects are referenced by their ids (or equivalent). Their memory location > may or may not change when it is modified, but if it is the same object, > every name that was refering to it will remain referencing to it after the > modification, regardless of its memory location. Conceptually, PyObjects do not even *have* a memory location. In the current CPython implementation for computers, they have a *fixed* location, which happens to be used for the unique integer id. A (fixed-location) list object contains a pointer to an auxiliary array which may be moved when resized. Same for dicts. Terry J. Reedy From fperez528 at yahoo.com Thu Jun 20 20:36:50 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Thu, 20 Jun 2002 18:36:50 -0600 Subject: Passing inner functions as arguments References: Message-ID: Pablo Ripolles wrote: > Hello all! > > I am new to python, so sorry if i am asking the obvious. Here it > comes. Is there anything wrong with this code? > > # Module to define math tools. > def momentum(f, k, a, b): > # Momentum of kth order of the given function f in [a, b]. > from Quadrature import quadrature > def integrand(x): > # Momentum's integrand in terms of the passed function f and k. > return (f(x)) ** k > return quadrature(integrand, a, b) > > I am not sure if it is correct. It runs OK in Python 2.2.1 but not at > all in Jython 2.1 (java1.4.0). I am not sure about the scoping rules. > I there's something strange, please let me know! Nested scopes are not on by default in 2.1 You need AT THE TOP of your file to put 'from __future__ import nested_scopes'. Cheers, f. ps. De paso, en ingl?s se usa 'moment/moments' para describir los momentos de una funci?n/distribuci?n. 'momentum/momenta' es la palabra cuyo significado es el momento mec?nico (masa*velocidad en su descripci?n m?s simple, o derivada de la Lagrangiana en general). El problema es que en espa?ol usamos 'momento' para ambas cosas :) From phoengeist38259 at arcor.de Mon Jun 3 13:25:34 2002 From: phoengeist38259 at arcor.de (phoengeist38259 at arcor.de) Date: Mon, 3 Jun 2002 19:25:34 +0200 Subject: Entschuldigen Sie bitte die Störung! Message-ID: Entschuldigen Sie bitte die St?rung! Mir ist etwas zu Ohren gekommen. Eine relativ aussergew?hnliche Ger?chtek?che, aus der man mir ein schwerverdauliches S?ppchen vorgesetzt hat, ist der Grund meiner Mail. Unappetitlich ist gar kein Ausdruck! Ist es m?glich auf funktechnischem Wege(in welchen Frequenzbereichen?) jemanden zu beeinflussen oder zu manipulieren? Oder sogar zu schikanieren und terrorisieren? Unter dem Motto:"Einen am Sender?Nich ganz alleine? Kleine Mannim Ohr?Falsche Wellenl?nge?Bohnen in den Ohren? Auf den Zahn gef?hlt(Amalgam)?Mal unverbindlich reinh?ren? Der Pullacher Wanzentanz? Ist das Spinnerei?Das geht doch gar nicht,oder? Und wenn wie sieht das ethisch moralisch aus? Zur technischen Seite der Sache gibt es zwar Berichte und Webseiten: Totalitaer,de - Die Waffe gegen die Kritik http://www.raum-und-zeit.com/Aktuell/Brummton.htm http://www.fosar-bludorf.com/Tempelhof/ http://jya.com/haarp.htm http://www.zeitenschrift.at/magazin/zs_24_15/1_mikrowaffen.htm http://www.bse-plus.de/d/doc/lbrief/lbmincontr.htm http://home.nexgo.de/kraven/bigb/big3.html http://w3.nrl.navy.mil/projects/haarp/index.html http://cryptome.org/ http://www.raven1.net/ravindex.htm http://www.calweb.com/~welsh/ http://www.cahe.org/ http://www.parascope.com/ds/mkultra0.htm http://www.trufax.org/menu/mind.html http://www.trufax.org/menu/elect.html http://mindcontrolforum.com/ http://www.trufax.org/menu/elect.html usw. usw. usw. ,aber,das kann doch nicht sein,das soetwas gemacht wird,oder? Eine Menschenrechtsverletzung sonder gleichen!?! Ist es m?glich,durch Pr?paration,der Ohren und im Zusammenspiel mit eventuell vorhandenem Zahnersatz? Mit relativ einfacher Funktechnik?? In diesem Land?Hier und heute??? Unter welchen Motiven? Wo ist eigentlich die Abteilung 5 des BND und des Verfassungsschutzes? Kann es sein,da? es Leute gibt,die dem BND/Verfassungsschutz,auf funktechnischem Wege permanent einen Situationsbericht abliefern,ohne es selbst zu merken,im Kindesalter machbar gemacht?? Werden durch solche inoffiziellen Mitarbeiter,beim BND und Verfassungsschutz,nach Stasimanier, Informationen von und ?ber,rein theoretisch, jeden Bundesb?rger,gesammelt? Gibt es dann noch ein Recht auf Privatsphere? Wer kontrolliert eigentlich den BND,MAD und Verfassungsschutz auf Unterwanderung??? In der Mail geht es mir eigentlich um die Frage,ob es kriminellen Elementen, aus dem Motiv der Bereicherung,oder Gruppierungen aus ideologischen Motiven, m?glich ist ,sich Wissen und Technik anzueignen,die zu anderen Zeiten, aus anderen Motiven(Westfernsehen?),entwickelt wurde. Und stellt der technische Wissensstand, der der Allgemeinheit bekannt ist wirklich das Ende der Fahnenstange dar? Ist es denn nicht kriminellen Elementen genauso m?glich, ich sage das jetzt mal verharmlost und verniedlichend, einzelne Personen oder Gruppen mit relativ einfachen Mitteln, aus welchen Motiven auch immer, auszuspionieren? Und stellt diese "Ausspioniererei" nicht einen erheblichen Eingriff in die Privatsph?re dar? Ist es m?glich einzelne Personen oder Gruppen, eine Akzeptans einer gewissen ?ffentlichkeit(suggeriert?), die z.B. mit Hilfe von Internetseiten,wie zum Beispiel dem "Pranger"geschaffen werden k?nnte, mal vorausgestzt,zu terroriesieren und oder zu schikanieren, und das in aller (suggerierten)?ffentlichkeit?Haben die Leute die da am Pranger, oder auf irgendeiner anderen Seite verunglimpft,oder gar Verleumdet werden, eigentlich eine Chance zur Gegen?ffentlichkeit?Ist das nicht Rufmord? Vor einigen Jahren bin ich per Zufall auf die Seite "Der Pranger" gesto?en, damals lief das noch nicht unter dem Deckmantel der Partnervermittlung. K?nnen sich einzelne Personen,oder Interessengemeinschaften, aus reinem Selbstzweck,solcher Seiten bedienen, um unter dem Deckmantel einer fragw?rdigen Zivilkourage, durch anzetteln irgendwelcher Hetzkampagnen,eigene, ganz pers?hnliche Interessen durchsetzen? K?nnen solche Seiten zur Koordination von kriminellen machenschaften dienen? Die Frage,ist es M?glichkeit oder Unm?glichkeit,technisch und gesellschaftlich, einzelne Personen,oder auch Gruppierungen,aus einer kriminellen/ideologischen Energei heraus,zu manipulieren oder zu beeinflussen,terrorisieren oder zu schickanieren,und zwar gezielt. Zielgruppenmanipulation durch Massenmedien sind allt?gliche Manipulation, der mansich,mehr oder weniger,entziehen kann. Wird das Recht auf Privatsph?re,schleichend,tiefenpsychologisch, durch Sendungen,wie,zum Beispiel "Big brother",untergraben? Sollte bei einem der Angemailten ein gewisser Wissensstand zum Thema vorhanden sein, w?re ich ?ber Hinweise zum Thema froh. Auf der Suche nach Antworten auf meine Fragen maile ich verschiedene Adressen aus dem Internet an, und hoffe aufkonstruktive Antworten und Kritiken. ?ber einen Besuch auf der Seite w?rde ich mich freuen. Sollten Sie von mir mehrfach angeschrieben worden sein,so bitte ich Sie,mir dies zu entschuldigen, das war nicht beabsichtigt. Der Grund f?r meine Anonymit?t ist die Tatsache, da? bei derlei Fragenstellerei, verst?ndlicherweise,schnell der Ruf nach der Psychatrie laut wird. Was auch Methode hat(ist). Sollten Sie die Mail als Bel?stigung empfinden, m?chte ich mich hiermit daf?r entschuldigen! Big brother is watching you? Excuse please the disturbance! Me something came to ears. A relatively unusual rumor kitchen, from which one put forward to me a heavydigestible soup, is the reason of my Mail. Unappetizing is no printout! Is it possible on radio Wege(in for which frequency ranges?) to influence or manipulate someone? Terrorize or to even chicane and? Under the Motto:"Einen at the Sender?Nich quite alone? Small Mannim Ohr?Fal Wellenlaenge?Bohnen in the ears? On the tooth clean-hear gefuehlt(Amalgam)?Mal witthout obligation? The Pullacher bug wanzentanz? Isn't the Spinnerei?Das goes nevertheless at all, or? And if as looks ethicalally morally? For the technical page of the thing there is to report and web page: Totalitaer,de - Die Waffe gegen die Kritik http://www.raum-und-zeit.com/Aktuell/Brummton.htm http://www.fosar-bludorf.com/Tempelhof/ http://jya.com/haarp.htm http://www.zeitenschrift.at/magazin/zs_24_15/1_mikrowaffen.htm http://www.bse-plus.de/d/doc/lbrief/lbmincontr.htm http://home.nexgo.de/kraven/bigb/big3.html http://w3.nrl.navy.mil/projects/haarp/index.html http://cryptome.org/ http://www.raven1.net/ravindex.htm http://www.calweb.com/~welsh/ http://www.cahe.org/ http://www.parascope.com/ds/mkultra0.htm http://www.trufax.org/menu/mind.html http://www.trufax.org/menu/elect.html http://mindcontrolforum.com/ http://www.trufax.org/menu/elect.html usw. usw. usw. but, that cannot be nevertheless, which is made soetwas, or? A violation of human rights resemble special!?! Is it possible, by preparation, the ears and in interaction with possibly available artificial dentures? With relatively simple radio engineering?? In this Land?Hier and today??? Under which motives? Where is the department actually 5 of the BND and the protection of the constitution? Can it be that there are people, which deliver the Federal Intelligence Service/protection of the constitution, on radio way permanently a situation report, without noticing it, in the infancy feasiblly made? By such unofficial coworkers, with the BND and protection of the constitution, after Stasimanier, is information collected of and over,purely theoretically, each Federal citizen? Is there then still another right to Privatsphere? Who actually checks the BND, WAD and protection of the constitution for infiltration??? Into the Mail actually concerns it to me the question whether it criminal items, from which motive of enriching, or groupings from ideological motives is possible, to acquire itself knowledge and technique which were developed at other times, from other Motiven(Westfernsehen?).And does the technical knowledge status place, to that the public admits is really the end of the flag bar? Is it not to criminal items just as possible, I legend that now times played down and does nice-end, individual persons or groups with relatively simple means, to spy from whatever motives always? And doesn't this " Ausspioniererei " represent a substantial intervention into the privatsphaere? It is possible individual persons or groups, one acceptance to of a certain Oeffentlichkeit(suggeriert?), e.g. by Internet pages, how for example the " Pranger"geschaffen could become, times vorausgestzt, to terroriesieren and or chicane, and in everything (the people suggerierten)Oeffentlichkeit?Haben there at the Pranger, or on any other page to be reviled, or slandered, actually a chance to the Gegenoeffentlichkeit?Ist that not character assassination? Some years ago I am by coincidence the page " the Pranger " encountered, at that time ran not yet under the cover of the partner switching.Itself can individual persons, or communities of interests, from pure self purpose, such pages to serve, over under the cover of a doubtful Zivilkourage, through plot any rushing campaigns, own, quite persoehnliche interests to intersperse? Can such pages serve for the co-ordination of criminal machinations? The question, is it possibility or impossibility, technically and socially, individual persons, or also groupings of manipulating or of influencing from an criminal/ideological Energei, terrorizes or to schickanieren, directed.Target group manipulation by mass media are everyday manipulation, from which, more or less, can extract itself. Does the right to privatsphaere, creeping, by transmissions become deep psychological, how, for example " Big undermine brother"? If the Angemailten should be available a certain knowledge status to the topic with one, I would be glad over notes to the topic On the search for responses to my questions maile I different addresses from the Internet on, and hope up-constructional responses and criticisms.Over an attendance on the page wuerde I are pleased.If you should have been written down by me several times, then please I you to excuse me this that was not intended. The reason for my anonymity is the fact that with such Fragenstellerei, understandably, fast after the call the Psychatrie loud becomes. Which also method hat(ist). If you should feel the Mail as annoyance, I would like to apologize hereby for it! Big is watching you? Veuillez excuser le d?rangement! Moi quelque chose concernant des oreilles est venu. Une cuisine de bruit relativement inhabituelle, dont on m'a plac? un Sueppchen schwerverdauliches devant, est la raison de mes Mail.Aucune expression n'est peu app?tissante! Il est possible sur un Wege(in funktechnischem pour quelles r?ponses fr?quentielles?) quelqu'un influencer ou manipuler? Ou m?me schikanieren et terroriser? Sous le Motto:"Einen au Sender?Nich tout ? fait seulement? Petits Mannim Ohr?Falsche Wellenlaenge?Bohnen dans les oreilles? Sur la dent gefuehlt(Amalgam)?Mal non contraignant reinhoeren? Le Pullacher Wanzentanz? Le Spinnerei?Das n'est-il quand m?me pas du tout va, ou? Et si comme cela para?t ?thiquement moralement? Au c?t? technique de la chose, il y a certes des rapports et des Webseiten: Totalitaer,de - Die Waffe gegen die Kritik http://www.raum-und-zeit.com/Aktuell/Brummton.htm http://www.fosar-bludorf.com/Tempelhof/ http://jya.com/haarp.htm http://www.zeitenschrift.at/magazin/zs_24_15/1_mikrowaffen.htm http://www.bse-plus.de/d/doc/lbrief/lbmincontr.htm http://home.nexgo.de/kraven/bigb/big3.html http://w3.nrl.navy.mil/projects/haarp/index.html http://cryptome.org/ http://www.raven1.net/ravindex.htm http://www.calweb.com/~welsh/ http://www.cahe.org/ http://www.parascope.com/ds/mkultra0.htm http://www.trufax.org/menu/mind.html http://www.trufax.org/menu/elect.html http://mindcontrolforum.com/ http://www.trufax.org/menu/elect.html usw. usw. usw. toutefois qui ne peut quand m?me pas ?tre qui on fait soetwas, ou? Une violation des droits de l'homme s?parer ressembler!?! Il est possible, par la pr?paration, des oreilles et dans l'effet avec la proth?se dentaire ?ventuellement existante? Avec la technique de radio relativement simple?? Dans ce Land?Hier et aujourd'hui Sous quels motifs? O? le d?partement est-il en r?alit? 5 du BND et de la protection d'constitution? peut il ?tre qu'il y a les personnes qui livrent en permanence le BND/Verfassungsschutz, de mani?re funktechnischem un rapport de situation, sans le remarquer le -m?me , dans l'enfance rendu possible?? Par de tels collaborateurs officieux, avec le BND et la protection d'constitution, apr?s mani?re, des informations sont-elles rassembl?es et plus de, purement th?oriquement, chaque citoyen allemand? Il y a alors encore un droit ? des Privatsphere? Qui contr?le en r?alit? le BND, mad et protection d'constitution sur une infiltration??? Il s'agit en r?alit? dans le Mail me la question de savoir si lui ?l?ments criminels, dont le motif de l'enrichissement, ou de groupements des motifs id?ologiques, possible de s'acqu?rir le savoir et la technique qui ? d'autres temps, est autre MotivenEt place-t-il le savoir technique dont le public vraiment la fin la barre de drapeau a connaissance ? Il n'est pas donc exactement la m?me chose possible pour des ?l?ments criminels, moi cela maintenant fois verharmlost et minimisant une l?gende, personnes ou groupes particuliers avec des moyens relativement simples, de quels motifs aussi toujours, auszuspionieren?(Westfernsehen?), a ?t? d?velopp?. Et ce "Ausspioniererei" ne repr?sente-t-il pas une intervention consid?rable dans la vie priv?e? Il est possible personnes ou groupes particuliers, pour certain Oeffentlichkeit(suggeriert?), celui p. ex. ? l'aide des c?t?s Internet, comme par exemple "le Pranger"geschaffen pourrait, fois vorausgestzt schikanieren terroriesieren et ou , et qui toute (suggerierten)Oeffentlichkeit?Haben les personnes ceux l?, ou d'un autre c?t? verunglimpft, ou on ne pas calomnie, en r?alit? une chance au Gegenoeffentlichkeit?Ist qui meurtre d'appel? Il y a quelques ann?es, je ne suis pas encore par hasard sur le c?t? "celui" pouss?, fonctionnais alors cela sous la couche de pont de l'entremise partenaire. Des personnes particuli?res, ou des communaut?s d'int?r?ts le peuventelles, d'un autobut pur, de tels c?t?s servent, sous la couche de pont d'un Zivilkourage douteux, tracent plus de des campagnes de pr?cipitation, propres int?r?ts tout ? fait persoehnliche entrem?lent? De tels c?t?s peuvent-ils servir ? la coordination des manoeuvres criminelles? Question, est lui possibilit? ou impossibilit? de manipuler ou d'influencer techniquement et socialement, particuli?re personnes, ou aussi groupements, criminelle/ponctuel id?ologique Energei dehors, , terroriser ou schickanieren, et ce.Une manipulation de groupe cible par des masse-m?dias ?tre la manipulation quotidienne qui peut extraire mansich, plus ou moins. Le droit ? la vie priv?e est-il min?, ramment, tiefenpsychologisch, par des envois, comme, par exemple "des Big brother"? Avec un les Angemailten si un certain savoir devait exister sur le th?me, je serais heureux sur des indications sur le th?me.Sur la recherche des r?ponses ? mes questions je diff?rentes adresses maile d'Internet dessus, et esp?re r?ponses et critiques aufkonstruktive. Sur une visite du c?t? http://hometown.aol.de/reinerhohn38259/homepage/index.html> je me r?jouirais. Si vous deviez avoir ?t? ?crit ? diff?rentes reprises par moi, je vous demande de m'excuser cela qui n'?tait pas envisag?. La raison de mon anonymat est le fait qu'avec telle des Fragenstellerei, l'appel devient ce qui est bien compr?hensible, rapidement bruyant apr?s le Psychatrie. Ce que la m?thode a ?galement (ist). Si vous deviez ressentir les Mail comme un ennui, je voudrais m'excuser par ceci pour cela! Big brother is watching you? From hammond at U.Arizona.EDU Fri Jun 21 11:17:26 2002 From: hammond at U.Arizona.EDU (Michael T Hammond) Date: Fri, 21 Jun 2002 08:17:26 -0700 Subject: python, xml, windows, sunos Message-ID: Hi. I've got a program that parses an xml file. It runs just fine under the most recent python (from www.python.org) on windows, but I can't get it to run on my sun machine. I have version 2.2.1 installed there. I'm not sure it's necessary, but I have Pyxml installed there as well (as on the windows machine). The error I get is: xml.sax._exceptions.SAXReaderNotAvailable: No parsers found. Does anybody have any idea what to do here? Mike H. From irmen at NOSPAMREMOVETHISxs4all.nl Mon Jun 10 15:29:51 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Mon, 10 Jun 2002 21:29:51 +0200 Subject: M2Crypto: select() behaves weird on SSL socket References: <3D04ECED.2030202@NOSPAMREMOVETHISxs4all.nl> <3D04FBF5.8090407@NOSPAMREMOVETHISxs4all.nl> Message-ID: <3D04FE2F.6070302@NOSPAMREMOVETHISxs4all.nl> To add some more info... > A.M. Kuchling wrote: > >> Perhaps there really is no more data on the socket because OpenSSL has >> read it all, but the decrypted data is now sitting in a buffer The manual page of select(2) says: "select waits for a number of file descriptors to change status. Three independent sets of descriptors are watched. Those listed in readfds will be watched to see if characters become available for reading (more precisely, to see if a read will not block - in particular, a file descriptor is also ready on end-of-file), those in writefds will be watched to see if a write will not block, and those in exceptfds will be watched for exceptions." The way I interpret this is that -buffering or not- select must return a FD if there is more data available. In my case, the SSL socket indeed has more data available, and a recv() on the socket will not block. I therefore think that either M2Crypto or OpenSSL is doing the wrong thing because select() doesn't behave as it should? The recv() may read from a buffer, I don't care, but it doesn't block on my next call and thus I expect select() to return the socket as being ready for reading... am I wrong here? irmen From smst at bigfoot.com Mon Jun 3 15:18:49 2002 From: smst at bigfoot.com (Steve Tregidgo) Date: 3 Jun 2002 12:18:49 -0700 Subject: Help for Tkinter and python's programming References: Message-ID: "Russell E. Owen" wrote in message news:... [snip to code fragment of GC class] > def __call__(self, *lastArgs, **kwArgs): > if kwArgs: > netKWArgs = self.__firstKWArgs.copy() > netKWArgs.update(self.__kwArgs) > else: > netKWArgs = self.__firstKWArgs > return self.__callback (*(self.__firstArgs + lastArgs), > **netKWArgs) I think this code contains a mistake. 'self.__kwArgs' should probably be simply 'kwArgs' (4th line above). Convenient class, anyhow! Cheers, Steve From marco.stagnoNOSPAM at libero.it Mon Jun 10 16:31:58 2002 From: marco.stagnoNOSPAM at libero.it (Marco Stagno) Date: Mon, 10 Jun 2002 20:31:58 GMT Subject: How convert all list/tuple... Message-ID: <523aguoljk3qceh4kkki7emn6283d6sqpt@4ax.com> Hi There is a fast way to convert all item in a tuple/list into a string type, without do a loop? I wish to translate something like: [1,2,"string"] into: ['1','2','string'] in the fastest way thank you in advance MAS! From kragen at pobox.com Mon Jun 10 18:08:27 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 10 Jun 2002 18:08:27 -0400 Subject: What is a classmethod for? References: Message-ID: <83y9dmokh0.fsf@panacea.canonical.org> Frank Tobin writes: > On Sun, 2 Jun 2002, Dennis Peterson wrote: > > That's nice, but I can't think of a use for it, given that we have > > inheritance and isinstance(). Can anyone enlighten me? > > Personally, I like using classmethods as secondary constructors, generally > gones that are able to construct 'from' something. > > e.g.: > > class HostPortAddress(tuple): > def from_str(self, s): > return self(s.split(':', 1)) > from_str = classmethod(from_str) That's so you don't have to write this? class HostPortAddress(tuple): pass def HostPortAddress_from_str(s): return HostPortAddress(s.split(':', 1)) Are there times when it's more compelling? From mcfletch at rogers.com Thu Jun 6 22:45:51 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Thu, 06 Jun 2002 22:45:51 -0400 Subject: Medium to Large Scale Python Deployments References: <3D000B36.5C7BCEBF@engcorp.com> Message-ID: <3D001E5F.3000808@rogers.com> Hey, that's a fun little tool (pycount)... I seem to create projects in libraries of around 20KLOC. Do projects accumulate the LOCs of their used libraries though? Is it only libraries you have created that count? If so, I've got 2 projects of ~50KLOC (the top-level projects, and one of the ~20KLOC libraries were closed-sourced, the rest were my open-source work). If used libraries don't count, most of my "projects" are ~ 5 thousand lines of glue code. Ah well, back to work, thanks for the diversion, Mike Peter Hansen wrote: > "Domenic R. Merenda" wrote: > >>"Sam Penrose" wrote: >> >>>I'm also curious about large amounts of Python, period. Who knows of >>>~50K Python lines-of-code (LOC) systems? 100K LOC? More? ... > Running pycount (http://starship.python.net/crew/gherman/playground/pycount/ ) > as "pycount.py -R *.py" in the top level of your source tree would tell > you something more accurate if you wished. > > -Peter _______________________________________ Mike C. Fletcher http://members.rogers.com/mcfletch/ From sandeep182 at hotmail.com Fri Jun 14 19:03:21 2002 From: sandeep182 at hotmail.com (Sandeep Gupta) Date: Fri, 14 Jun 2002 23:03:21 GMT Subject: Python and SQL Server 2000 Message-ID: I'm running python 2.2 on Redhat 7.2 and I need to access SQL Server 2000. The command are simple SQL queries and updates. We don't even use joins. There seem to be several common methods for doing so: 1. Use the python application at http://www.object-craft.com.au/projects/mssql/ with Sybase ASE 11.9.2 2. Use the python application at http://www.object-craft.com.au/projects/mssql/ with FreeTDS. 3. Use mxODBC with iODBC 4. Use mxODBC with unixODBC It is not clear to me if I will still need to use Sybase ASE or FreeTDS with iODBC/unixODBC. Which option do people recommend? Are there any other options? Thanks Sandeep From aahz at pythoncraft.com Thu Jun 13 16:08:40 2002 From: aahz at pythoncraft.com (Aahz) Date: 13 Jun 2002 16:08:40 -0400 Subject: Type subclassing: bug or feature Message-ID: Consider the following code: class MyStr(str): def contains(self, value): return self.find(value) >= 0 s = MyStr("hello, world!") s = s.capitalize() if s.contains('Hello'): print "Found it!" It fails with an AttributeError when it calls s.contains(), because s.capitalize() returned a str instead of a MyStr. Anyone want to take a whack at defending this as the correct behavior? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I had lots of reasonable theories about children myself, until I had some." --Michael Rios From johnroth at ameritech.net Sat Jun 29 18:34:38 2002 From: johnroth at ameritech.net (John Roth) Date: Sat, 29 Jun 2002 18:34:38 -0400 Subject: private References: <3D1DE132.4A890D9D@engcorp.com> Message-ID: "James Kew" wrote in message news:afl3e4$f8abc$1 at ID-71831.news.dfncis.de... > > I don't -- in my admittedly very limited experience -- find Python classes > as immediately self-documenting. It's not obvious from the class definition > what is intended to be called or modfied by the client and what is internal > to the implementation. The fact is, there is no such thing as a 'self-documenting' language. COBOL demonstrated that to me a long time ago. If you want your code to say something to someone, it's up to the two (or however many) of you to set up coding conventions that communicate the intent - and stick to them. There are a number of such conventions within the Python community, including the underscore for internal methods. As a number of posters have mentioned, the issue has been discussed many times. The general feeling is that access protection attributes (and similar things) are not what Python is about. Python does not support declarations at all. Some people feel this is a weakness. Some people feel it is a strength. In general, the kinds of problems which declarations are intended to solve are less visible in Python than in compiled languages. Hope this helps give you some background. John Roth From stever at gate.net Fri Jun 21 23:44:46 2002 From: stever at gate.net (Steve Reeves) Date: 22 Jun 2002 03:44:46 GMT Subject: telnetlib option negotiation callback should be a method Message-ID: I have an application using telnet that requires option subnegotiation (specifically, it needs to set a terminal type in the manner of RFC 1091). The standard telnetlib doesn't currently support this. I would like to extend it to do so, but the current design of the option negotiation callback makes this difficult. Currently, the callback is a function taking a socket as an argument. This is adequate for sending data to the server, but not for receiving. It bypasses the Telnet object's internal queue, which may already contain the data you're waiting for. It also requires you to reimplement the special processing the protocol requires (undoubling IAC characters), and the default negotiation behavior. The callback really needs to be a method of the Telnet object, with access to the internal queue. It can implement the default DONT/WONT negotiation. Subclasses can override it to handle the specific options they want and forward the rest to the base class. The set_option_negotiation_callback() method would no longer be needed. (This question of function vs. method was briefly raised when the telnetlib patch was first submitted, , but it was left as a function.) Opinions? -- Steve Reeves stever at gate.net From logiplexsoftware at earthlink.net Fri Jun 21 14:17:33 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Fri, 21 Jun 2002 11:17:33 -0700 Subject: ssl on windows In-Reply-To: References: Message-ID: <20020621111733.2cbf3463.logiplexsoftware@earthlink.net> On Fri, 21 Jun 2002 13:09:33 -0500 Scott Hathaway wrote: > I would like to use ssl on Windows with Python 2.2. Is this available yet? > If so, how can I go about getting it installed? When I try to get an https > address with urllib, it tells me that https is an unknown protocol. Google turned up the following for python+ssl+windows: http://mail.python.org/pipermail/python-announce-list/2002-March/001312.html -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From uwe at rocksport.de Sat Jun 1 19:31:28 2002 From: uwe at rocksport.de (Uwe Schmitt) Date: 1 Jun 2002 23:31:28 GMT Subject: wxPython performance References: Message-ID: Andrei Kulakov wrote: | Hello, | "hello world" type program from wxPython tutorial takes 6 | seconds to start on my cel 366 128mb system (running Debian). Is | this typical? Why is it so slow? I'm looking for a graphic | toolkit that'd be fairly quick. I don't want to use Tk because of | the looks. I had the same problem which appeared when I used py2exe. The generated exe just neads one second instead of four... Greetings, Uwe. -- Dr. rer. nat. Uwe Schmitt ICQ# 159647634 Uwe.Schmitt at num.uni-sb.de From gcordova at hebmex.com Thu Jun 6 18:39:21 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Thu, 6 Jun 2002 17:39:21 -0500 Subject: SNIP IT: Object gatekeeper for multithread apps. Message-ID: Hi y'all. I've been toying around with multithreading apps, and one of the (small) deficiencies I've seen is that, besides Queue, there's no other object gatekeeper to regulate access to shared objects. Now; Queue is quite cool, very nice. But, because of it's design (I mean, it *is* a queue), only the objects at the top can be accessed (or the bottom... you know). Also, they have no name. I didn't like that. So, I began writing my own gatekeeper. I've been through many iterations, each one getting killed because of my inherent developer paranoia ("And, what if one thread does this... *damn*, another deadlock posibility"). Until this version. It seems as clean as it's ever gonna get, so I'm sending it out to the wild, in hopes that it may prove useful to somebody else. Please, enjoy. Also, I'm taking bug reports, *possible* bugs, design deficiencies (or improvements!), and also, please please please, a better name :-) "Holder" just doesn't ring right. So, please, enjoy. -gustavo pd: Ah! This is 2.2+ specific, because it uses properties. Sorry for all you pre-2.2 programmers. This is my properties self-test-exam. I Passed!! ;-) -------------- next part -------------- A non-text attachment was scrubbed... Name: Holder.py Type: application/octet-stream Size: 6394 bytes Desc: not available URL: From jarvin24 at tutor.cc.tut.fi Fri Jun 28 04:05:30 2002 From: jarvin24 at tutor.cc.tut.fi (=?iso-8859-1?Q?J=E4rvinen?= Petri) Date: Fri, 28 Jun 2002 08:05:30 +0000 (UTC) Subject: Packages +reload() Message-ID: Hey, I feel like complite lost. I have created nice package structure, but I encountered lot's of troubles when using it with IIS and ASP. Structure is: eNAct\ documents\ listDocuments\ showPage() enactXML() -> main package eNAct and sub-packages eg. documents and it's sub-packages eg. listDocuments The problem is that I can't reload the modules. I have tried various ways of importing listDocuments but IT doesn't get reloaded. eg. from eNAct.documents import listDocuments reload(listDocuments) listDocuments.showPage() or import eNAct reload (enact) eNAct.documents.listDocuments.showPage() Questions: 1. How should the structure be? 2. Is it possible that I only reload the eNAct and all sub-modules get reloaded. 3. What does reload(eNAct.documents) reload? - Petri J?rvinen From dkuhlman at rexx.com Sat Jun 29 14:45:32 2002 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sat, 29 Jun 2002 11:45:32 -0700 Subject: Most efficient way to write data out to a text file? References: <3d1a6993.248534625@netnews.attbi.com> <3d1dc547.468619140@netnews.attbi.com> Message-ID: candiazoo at attbi.com wrote: [snip] Thank you for posting this. Very helpful. Could we have a bit of evaluation and explanation please. I'm suspicious about whether some of these changes actually made a difference. I'd like a little understanding before I start changing my Python coding style. I'd also like some enlightenment about *why* they would make an improvement. > my aforementined optimizations... > > 1) "import sys" became "import exit from sys" > 2) "import os" became "import makedires from os" Does importing a function from a module (as opposed to importing the whole module) save a look-up each time the function is called? > 3) "import time" bacame "import asctime from time" (this one is > used frequently) > 4) I localized constants I was using in boolean > tests (there were declared at the beginning of the module, I moved > them to the function call just before the loop). Is finding things in globals slower than finding them in locals? Did this change in Python 2.2? > 5) I localized self.__source_id... source_id = self.__source_id > before using it in every loop iteration. > 6) I localized self.fix_date_range()... fix_date = > self.fix_date_range before using it in every loop iteration/ > 7) I changed my method that built the output string by changing... > > return self.val_a + self.value_b + etc.. > > ...to... > > return "%-10.10s%-200.200s (etc)" % (self.val_a, self.val_b, etc.) > > ...and those were basically the changes I made! They made a huge > difference! > > Mike J. Thanks in advance. - Dave -- Dave Kuhlman dkuhlman at rexx.com http://www.rexx.com/~dkuhlman From eric.brunel at pragmadev.com Thu Jun 13 10:40:41 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Thu, 13 Jun 2002 14:40:41 +0000 Subject: Question about asksaveasfilename References: Message-ID: Mike Callahan wrote: > I am using asksaveasfilename from tkFileDialog. I want to restrict my > users to save filenames with these extensions .unl or .sql. This is my > call: > > from tkFileDialog import asksaveasfilename > fn = asksaveasfilename(filetypes=[('Unloaded', '*.unl'), > ('Queries','*.sql')]) > > This gives me the correct dialog box, but how do I force the correct > extension on fn? Thanks. There's a defaultextension option, but it does not depend on the selected file type, i.e. you'll have to do either: fn = asksaveasfilename(filetypes=[('Unloaded', '*.unl'), ('Queries', '*.sql')], defaultextension='.unl') or: fn = asksaveasfilename(filetypes=[('Unloaded', '*.unl'), ('Queries', '*.sql')], defaultextension='.sql') which isn't what you're looking for, I fear... I don't know any means to force an extension depending on the selecetd file type with asksaveasfilename, so my advice would be to split the two save options: one "Save unloaded" and one "Save query"... But if there's another solution, I'm interested too ;-). HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From marklists at mceahern.com Sat Jun 29 12:00:30 2002 From: marklists at mceahern.com (Mark McEahern) Date: Sat, 29 Jun 2002 11:00:30 -0500 Subject: exception handing In-Reply-To: Message-ID: > >>> ex1 = "spam" > >>> try: > ... raise ex1 > ... except ex1: > ... print 'got it' The problem is that you are using strings as exceptions--that is discouraged. Instead, raise a built-in exception or subclass the Exception object. class ex1(Exception):pass class ex2(ex1):pass try: raise ex2("some ex2 error") except ex1, e: print e // m - From peter at engcorp.com Sun Jun 9 13:38:13 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 09 Jun 2002 13:38:13 -0400 Subject: How to capture stdout into a string? References: <2YLM8.905$Yw3.119357@news20.bellglobal.com> Message-ID: <3D039285.72DFC71D@engcorp.com> Michael Davis wrote: > > Hi, > > I'm using libftp. The FTP.dir() function gets the remote directory listing > and prints it to standard out. How can I capture that in a string? > > If I were using an external process, I know I could open a pipe to it. But > it's not an external process. > > I'm sure there's a tricky way of doing it by getting the file descriptor for > stdout and reading from it directly, but I was hoping to avoid going that > low-level. I will if I must though. The best option by far (and really the easiest) to figure out stuff like this is to check the source. In this case, you can see that dir() calls retrlines() with the LIST argument and no callback function. As the notes say, this directs the output to stdout. You must specify a callback function of some kind. The best is probably a small class with a __call__ method, but this little baby seems to work too, although it may not be quite enough to work in the general case yet. It grabs lines that are passed to it into a list, until it is called with an empty argument, at which point it returns the saved list and deletes it, ready for another bunch of lines: >>> def grablines(line='', lines=[]): ... if line: ... lines.append(line) ... else: ... result = lines[:] ... del lines[:] ... return result ... >>> grablines() [] >>> grablines('test') >>> grablines('test') >>> grablines('test') >>> grablines() ['test', 'test', 'test'] >>> ftp.dir(grablines) >>> grablines() ['total 62', '-rw-r--r-- 1 engcorp netdial 0 Jan 11 2000 .addressbook', '-rw------- 1 engcorp netdial 2285 Jan 11 2000 .addressbook.lu', '-rw------ - 1 engcorp netdial 6459 May 21 23:42 .bash_history', '-rw-r--r-- 1 engcorp netdial 29 Jun 17 2001 .forward', '-rw------- 1 engcorp netdial 12221 .............] -Peter From dom at edgereport.put_a_c_o_m_here Wed Jun 5 05:18:34 2002 From: dom at edgereport.put_a_c_o_m_here (Domenic R. Merenda) Date: Wed, 05 Jun 2002 09:18:34 GMT Subject: Medium to Large Scale Python Deployments Message-ID: Greetings, I am running a home-grown Enterprise Resource Planning system, written entirely in Python, to manage the operations and manufacturing aspects of a medium ($100,000,000 annual sales) manufacturing organization. I would be interested in hearing from other individuals who are likewise "betting the farm" on Python as an ERP or MRP solution, and some of the experiences they may have had. We have found Python to be a robust solution for the problems we've encountered to date, and pass approximately half a gigabyte of daily data through our custom systems. We have merged the AS/400 (Python 2.1, soon to go to 2.2.1) with midrange (PIII700) PC's to create an interesting heterogenous environment. Cheers! -- Domenic R. Merenda Editor, The Edge Report http://www.edgereport.com From never at mind.info Sun Jun 2 16:54:29 2002 From: never at mind.info (G. Willoughby) Date: Sun, 2 Jun 2002 21:54:29 +0100 Subject: Python Turing machine References: Message-ID: > hint: post some URLs of those implementations to the list. that way we > don't need to look up what it is and people here have fun trying to solve > things pythonic... I belive he means a chat bot that tries to fool humans into beliving its a real person. --G. Willoughby From jadestar at idiom.com Tue Jun 11 05:28:58 2002 From: jadestar at idiom.com (James T. Dennis) Date: 11 Jun 2002 09:28:58 GMT Subject: python, shell, environment variable References: Message-ID: oliver wrote: > hi, folks, > I am trying to get a set of python and bash scripts to work, and I > constantly run into trouble with environment variables: > First, my python script need to modify environment variable, say, > PATH, and want to keep the modification even after the script is done. > os.environ["PATH"]= ... doesn't seem to work, any idea? Yes. You seem to have a fundamental misunderstanding about how environment variables work (under UNIX and UNIX-like OSes, at least). The environment is a region of your process' memory that is not overwritten by an exec*() system call. Thus it is an efficient way for a parent process to pass some (textual or textually encoded) data to its children. The environment is *NOT* a share memory mechanism. To execute Python your shell performed a fork() and then an exec*() (some form of exec; it's not important which one). fork() creates a new private address space for your new process, and address space that is initially an (almost) exact copy of the parent's memory (except for the portion of the stack or heap that's holding the return value to the fork() call itself). [Please understand that this is a new "virtual" address space; the actual physical memory pages are usually shared through page table aliasing on modern processors/architectures running modern kernels --- using a technique called CoW: copy on write]. So your assignments to os.environ["PATH"]=something are just happening to your address space. They can't affect your parent's memory (that would be a SEGV, segmentation violation; or it would require some form of shared memory). The assignments would be visible in any processes you created *under* your python process (os.popen('printenv') and search for the PATH entry for one way to demonstrate that), and they should remain set in that process (that was python) if you finish your script with one of the os.exec*() functions (except for the exec*e() which require you to explicitly prepare and pass a new environment to them). > Second, it would be better if my python script can call bash shell and > still keep the environment variable modification done by bash. I tried > os.popen("source some_shell"), it doesn't work. ? os.popen is creating yet another process; and the source command therein is modifying popen's memory. > Thanks for help. > -oliver This is a fundamental consequence of UNIX' fork()/exec*() and memory management/protection model. It is a basic principle that leads to several FAQs. It is something I have to emphasize at considerable length in my shell scripting classes. It is also one of the best examples of how important it is to understand the big picture, the "model" of an architecture, an OS, a language, or any other technology that one must control and use in any but the most trivial ways. Once you understand how fork(), exec*() and *NIX memory management works then you'd never have this question --- because the answer would be so obvious. (When my son tattoos his arm, why can't my grandpa read it off *his* arm? Because it's a different skin that's being modified!). From mcherm at destiny.com Mon Jun 3 15:29:39 2002 From: mcherm at destiny.com (Michael Chermside) Date: Mon, 03 Jun 2002 15:29:39 -0400 Subject: Is there a Text to HTML conversion module? Message-ID: <3CFBC3A3.8090806@destiny.com> > Does anyone know of a module that converts a text file to html? Sure! def textToHtml(text): return '
%s
' % text (sorry... couldn't resist) -- Michael Chermside From martin at strakt.com Thu Jun 13 05:40:26 2002 From: martin at strakt.com (Martin =?iso-8859-1?Q?Sj=F6gren?=) Date: Thu, 13 Jun 2002 11:40:26 +0200 Subject: Extension objects in Python 1.5 and 2.2 In-Reply-To: References: <20020613071813.GA16764@strakt.com> <15624.19045.700125.215173@12-248-41-177.client.attbi.com> Message-ID: <20020613094026.GA22933@strakt.com> On Thu, Jun 13, 2002 at 09:20:53AM +0000, Michael Hudson wrote: > Martin Sj?gren writes: > > > On Thu, Jun 13, 2002 at 02:31:49AM -0500, Skip Montanaro wrote: > > > > > > Martin> How do I write extension objects so that they work in both > > > Martin> Python 1.5 and the 2.x series? > > > > > > Michael Hudson has been working on a new include file named pymemcompat.h. > > > Since it's only used for backward compatibility it's in the Misc directory. > > > You can grab it from CVS: > > > > > > http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Misc/pymemcompat.h > > > > > > The idea is that you should be able to include it and program to the 2.3 > > > memory api in code that runs under 1.5.2 or newer versions of the > > > interpreter. > > > > Cool. Thanks a lot! > > Pleasure! Be sure to complain if it doesn't work, won't you? So far it's looking good. I still had to ifdef on the Python version since I'd used PyModule_AddObject, but that was easily fixed. Regards, Martin -- Martin Sj?gren martin at strakt.com ICQ : 41245059 Phone: +46 (0)31 7710870 Cell: +46 (0)739 169191 GPG key: http://www.strakt.com/~martin/gpg.html From johnroth at ameritech.net Tue Jun 4 20:15:49 2002 From: johnroth at ameritech.net (John Roth) Date: Tue, 4 Jun 2002 20:15:49 -0400 Subject: Behavior of += (was Re: [Python-Dev] Customization docs) References: Message-ID: "Huaiyu Zhu" wrote in message news:slrnafps1c.4ea.huaiyu at gauss.almadan.ibm.com... > John Roth wrote: > > > >"Huaiyu Zhu" wrote in message > >news:slrnafo7qv.37c.huaiyu at gauss.almadan.ibm.com... > >> Gustavo Cordova wrote: > > > >> > >> Great explanation! The problem stems from the fact that the current > >+= > >> operator implements two semantically distinct operations, chosen > >according > >> to some properties of the operands. This is not unlike the situation > >of the > >> division operator with distinct behaviors on floats and ints. > > > >This is not an issue with '+='. It's an issue with assignment, > >regardless > >of whether it is standalone or combined with some other operation. > > The point is that += does not have to contain any assignment at all. In > most cases for mutable objects, the result is the same object (mutated). > This was the motivation for introducing += into Python in the first place. > The need for assignment only comes from immutable objects, but its > implementational implication extends to mutable objects as well, producing > this spurious exception. It is spurious because the last assignment step is > not necessary. > > > > >And I disagree that assignment implements two distinct operations. > >Assignment always rebinds. Always. In the examples cited, it > >attempted to rebind into a tuple, because that's what was asked > >for when the left hand side had a subscript. > > This missed the point. In-place operations should not contain assigments. I think you're mistaken. To consider the example at the top of the thread in more detail, you would argue that the only operation is the append operation against the second list which is the second operand of the tuple. The assignment occurs because the pointer to the list has to be changed to point to the (possibly) new location of the list in memory. In other words, the second element of the tuple has to be rebound. There is no way of avoiding this, since objects are known internally by their location in memory, and if you change the object, you may (not necessarilly will) change that object's location. Therefore, the pointer to the object must also be changed in this instance. That is what causes the exception. John Roth From dreed at capital.edu Sat Jun 29 16:21:41 2002 From: dreed at capital.edu (Dave Reed) Date: Sat, 29 Jun 2002 16:21:41 -0400 Subject: private In-Reply-To: <3D1DE132.4A890D9D@engcorp.com> (message from Peter Hansen on Sat, 29 Jun 2002 12:32:50 -0400) References: <3D1DE132.4A890D9D@engcorp.com> Message-ID: <200206292021.g5TKLf928740@localhost.localdomain> > From: Peter Hansen > X-Accept-Language: en > Newsgroups: comp.lang.python > Xref: news.baymountain.net comp.lang.python:170296 > Sender: python-list-admin at python.org > Date: Sat, 29 Jun 2002 12:32:50 -0400 > > Rhymes wrote: > > > > Is there any possibility to build up a _real_ private attribute? > > Please define what "_real_" means to you. It's not apparent. > > > Such as C++ private data members... > > You realize that it's quite possible to get at private data members > in C++, don't you? Kind of off-topic, but this got me curious. The only way I could think of is to assume (which I think is always true) that the private data members are in order from the starting address so based on the offset from the address of the object you could access each one. Is there another way? Dave From nookieNO_SP_AM at online.no Wed Jun 5 12:02:26 2002 From: nookieNO_SP_AM at online.no (Erlend J. Leiknes) Date: Wed, 05 Jun 2002 16:02:26 GMT Subject: distutils and distributing "scripts" References: Message-ID: oh, sorry, didnt read your question good enough... =( "Erlend J. Leiknes" wrote in message news:nAqL8.10168$fG3.343408 at news2.ulv.nextra.no... > do not call the files .pyw, just use py > > when you then use py2exe, do the following > python setup.py py2exe -w > > the -w means --window or --windows (dont remember), anyway, this will use > the pythonw.exe. > > > "Hugo van der Merwe % str (33) >" < wrote in > message news:adl4e4$19ep$1 at news.adamastor.ac.za... > > I have recently started using distutils. I have a .pyw file for the > windows > > users, how do I get this to be a part of my ... sdist, for example? > > > > I have added this to the scripts list passed to "setup()", this seems to > me > > the "correct" place for it (I want to eventually play with py2exe). > > > > It seems "python setup.py sdist" does not add "scripts" by default though, > > just the py_modules. The docs seem to confirm this. How do I get my .pyw > > file distributed, do I really have to go and do all that MANIFEST.in > stuff, > > just for this one file? > > > > Thanks, > > Hugo van der Merwe > > From robin at jessikat.fsnet.co.uk Sat Jun 29 14:12:46 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sat, 29 Jun 2002 19:12:46 +0100 Subject: yield equivalent in C/JavaScript? Message-ID: Is there any way to do yielding easily in C? I have a bunch of programs which are normally connected together using unix pipes. I would like to merge them and the problem is then how to get them to communicate nicely using a single process. the typical process currently looks like initialise(); while((c=getc(stdin))>=0){ process(c); putc(c,stdout); } so if the inputs are reasonable I could just run each to completion before proceeding with the next by replacing the file streams with memory ones. That could get messy if the inputs are large. Is there a neat way to simulate the yield idea? In C I can just about consider doing some longjump madness, but that wont wash in the other possible environment which has JavaScript for implementation. -- Robin Becker From SSchukat at dspace.de Tue Jun 4 10:43:19 2002 From: SSchukat at dspace.de (Stefan Schukat) Date: Tue, 4 Jun 2002 15:43:19 +0100 Subject: Creating explorer link on Win32 Message-ID: <84257D042AA7D411B3F700D0B7DB9B7C13B17F@PDC-DSPACE> Use the standard windows functions or look at the Python Cookbook http://aspn.ActiveState.com/ASPN/Python/Cookbook/ Stefan -----Original Message----- From: Florian Fredegar Haftmann [mailto:fredegar at haftmann-online.de] Sent: Tuesday, June 04, 2002 1:49 PM To: python-list at python.org Subject: Creating explorer link on Win32 Hi! I'm searching for a possibility to create an explorer link (*.lnk) to a file on Win32. Has anyne heard of a python module able to do that in a simple way? Thanks, FFH -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- A non-text attachment was scrubbed... Name: CreateShortCut.py Type: application/octet-stream Size: 5310 bytes Desc: not available URL: From ark at research.att.com Thu Jun 13 15:33:34 2002 From: ark at research.att.com (Andrew Koenig) Date: Thu, 13 Jun 2002 19:33:34 GMT Subject: dictionary: keys() and values() References: Message-ID: John> keys = m.keys() John> values = m.values() John> Do we know if the values come out in the same order, that is does John> m[keys[i]] necessarily equal values[i] ? >From the library reference, 2.2.7, footnote 3: If keys() and values() are called with no intervening modifications to the dictionary, the two lists will directly correspond. This allows the creation of (value, key) pairs using zip(): "pairs = zip(a.values(), a.keys())". -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From logiplexsoftware at earthlink.net Thu Jun 20 15:47:15 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Thu, 20 Jun 2002 19:47:15 GMT Subject: How to represent the infinite ? References: <3d11ee9b$1@news.swissonline.ch> Message-ID: <20020620.124436.1266235189.32516@software1.logiplex.internal> In article , "Cliff Wells" wrote: > On Thu, 20 Jun 2002 17:02:33 +0200 > erreur wrote: > >> Will somebody have an idea, to represent the infinite one? I have >> variables to initialize with is +inf (or - inf). To be sure that >> later, all will be smaller (or larger) than my variables. I tried to >> redefine the operators on an object. It goes for Inf>10 but I do not >> arrive for 10>Inf (because that takes > of Int). -------------------- >> def __gt__(self, val): >> >> return 1 >> -------------------- > Hm, for some reason, my last two posts on this thread didn't seem to go > through... one more try (with a couple of little enhancements): Odd, the newsgroup -> mailing list transfer must be really slow (or down) today, I pulled up Pan and lo, my posts are there, they just haven't made it to the mailing list yet (after almost 2 hours). Or maybe I accidentally killfiled myself ;) From mhammond at skippinet.com.au Thu Jun 6 18:55:56 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Thu, 06 Jun 2002 22:55:56 GMT Subject: win32com problem: No Such Interface Supported References: Message-ID: <3CFFE8F8.1010404@skippinet.com.au> Unfortunately, win32com does not support calling arbitary vtable interfaces - only IDispatch is guaranteed. This may be fixed sometime this year, but is not at the moment - just one person offering to help may tip this over ;) Mark. Lindsey Smith wrote: > I'm having trouble using a COM object from Python 2.2.1 using the > win32all-143 extensions. I want to access ISubscriptionMgr, which is > implemented by webcheck.dll, a part of Internet Explorer 5+. > ISubscriptionMgr is defined by subsmgr.idl and subsmgr.h in the MS Visual C > vc98\include directory. > > What I did was: > ] midl subsmgr.idl > > which yields subsmgr.tlb, then > ] python makepy.py -i path\subsmgr.tlb > > which yields: > {C54FD88A-FFA1-11D0-BC5E-00C04FD929DB}, lcid=0, major=1, minor=0 > >>>># Use these commands in Python code to auto generate .py support >>>>from win32com.client import gencache >>>>gencache.EnsureModule('{C54FD88A-FFA1-11D0-BC5E-00C04FD929DB}', 0, 1, 0) >>> > > > then making test.py: > > from win32com.client import gencache > mod = gencache.EnsureModule('{C54FD88A-FFA1-11D0-BC5E-00C04FD929DB}', 0, 1, > 0) > > o = mod.SubscriptionMgr() > print o > > > but test.py bombs out in this way: > > Traceback (most recent call last): > File "test.py", line 5, in ? > o = mod.SubscriptionMgr() > File > "D:\DEV\PYTHON22\lib\site-packages\win32com\gen_py\C54FD88A-FFA1-11D0-BC5E-0 > 0C04FD929DBx0x1x0.py", line 37, in __init__ > if oobj is None: oobj = pythoncom.new(self.CLSID) > pywintypes.com_error: (-2147467262, 'No such interface supported', None, > None) > > Any ideas on what I'm doing wrong? > > thanks, > Lindsey > > > From observer at NOSPAM.space.pl Thu Jun 13 06:41:03 2002 From: observer at NOSPAM.space.pl (Johann) Date: Thu, 13 Jun 2002 12:41:03 +0200 Subject: How to check version of Python under CGI References: <873cvrin1q.fsf@tux.ntw23.fr> <87y9djh6tg.fsf@tux.ntw23.fr> <87ptyvh6g7.fsf@tux.ntw23.fr> Message-ID: On 13 Jun 2002 11:30:00 +0200, Sylvain Thenault wrote: >I didn't see the solution on the newsgroup, could you share it ? source: http://snakefarm.org/snakecharmer.tar.gz #!/usr/bin/env python # # SnakeCharmer v1.3, Carsten Gaebler (cg at snakefarm.org) # # SnakeCharmer gives you the location of your Python interpreter, # your path to Sendmail, your environment variables and a list of the # Python modules that are installed on your web server. # import glob, os, string, sys, traceback from stat import * def is_executable(path): return (os.stat(path)[ST_MODE] & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 def get_toplevel_libdirs(): libdirs = sys.path[1:] libdirs.sort() tlds = {} for i in range(len(libdirs) - 1): cp = os.path.commonprefix(libdirs[i:i+2]) if cp == "/": tlds[libdirs[i]] = None continue if cp[-1] == "/": cp = cp[:-1] if os.path.isdir(cp): tlds[cp] = None else: tlds[libdirs[i]] = None libdirs = tlds.keys() libdirs.sort() return libdirs def listmodules(arg, dirname, names): has_init_py = '__init__.py' in names if has_init_py: for p in sys_path: if dirname[:len(p)] == p: dirname = dirname[len(p):] break if dirname[:1] == '/': dirname = dirname[1:] if dirname[:4] == 'test': return dirname = string.replace(dirname, "/", ".") installedmodules.append(dirname) for mod in names: if (mod[0] != "_") and (mod[:4] != 'test'): ext = mod[-3:] if ext == '.py': mod = mod[:-3] elif ext == '.so': if mod[-9:-3] == 'module': mod = mod[:-9] else: mod = mod[:-3] else: continue if has_init_py: installedmodules.append(dirname + "." + mod) else: installedmodules.append(mod) print "Content-Type: text/html" print "X-Powered-By: Python %s" % string.join(string.split(sys.version), " ") print '''

snakefarm.org

Snake Charmer 1.3

''' try: sys_path = sys.path[1:] sys_path.sort(lambda a, b: cmp(len(b), len(a))) installedmodules = list(sys.builtin_module_names) for dir in get_toplevel_libdirs(): os.path.walk(dir, listmodules, None) installedmodules.sort() for i in range(len(installedmodules) % 3): installedmodules.append('') py = {} py["version"] = string.split(sys.version)[0] py["platform"]= sys.platform location = string.split(os.popen("whereis python", "r").read()) location = filter(lambda p: p[0] == '/', location) location.sort() for i in range(len(location)): if os.path.islink(location[i]): location[i] = location[i] + " -> " + os.readlink(location[i]) py["location"] = string.join(location, "
\n") location = string.split(os.popen("whereis sendmail", "r").read()) location = filter(lambda p: p[0] == '/', location) location.sort() location = filter(is_executable, location) py["sendmail"] = string.join(location, "
\n") libdirs = sys.path if libdirs[0] == '': libdirs[0] = './' py["libdirs"] = string.join(libdirs, "
\n") font = '' py["font"] = font print '' print """ """ % py print "
%(font)sProgram Paths
%(font)sPython version%(font)s%(version)s
%(font)sPython OS platform%(font)s%(platform)s
%(font)sLocation of Python%(font)s%(location)s
%(font)sLocation of Sendmail%(font)s%(sendmail)s
%(font)sDirectories searched for Python modules%(font)s%(libdirs)s
" print ''' ''' % font envvars = os.environ.keys() envvars.sort() for envvar in envvars: value = os.environ[envvar] print '' % (font, envvar, font, value) print "
%sEnvironment Variables
%s%s%s%s
" print '''
%sInstalled Modules
    ''' % font

    rows = len(installedmodules) / 3
    mods = [ [], [], [] ]
    maxlen = max(map(len, installedmodules))

    for i in range(rows):
            s = "%%-%ds %%-%ds %%s" % (maxlen, maxlen)
            print s % (installedmodules[i], installedmodules[rows +
i], installedmodules[2*rows + i])

    print """
    
""" except: tb = traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback) tb = string.join(tb, "") print '''
    %s
    
''' % tb From eric.brunel at pragmadev.com Fri Jun 7 13:52:19 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Fri, 7 Jun 2002 17:52:19 +0000 Subject: positional modifiers in python? References: Message-ID: fuf wrote: > hello everyone, > > does python support positional parameters in the print method? ie. > something like: > print "there %2$s something %1$s" % ("there", "is") > it doesn't work but maybe there's some other way? There's an utterly ugly way to do this: def toPosDict(l): d = {} map(lambda k,v,d=d: d.update({str(k):v}), range(len(l)), l) return d print "there %(1)s something %(0)s" % toPosDict(("there", "is")) For post-Python 2.2 users (I'm still 2.1, sorry), the "map" line may certainly be replaced by: map(d.__setitem__, [str(i) for i in range(len(l))], l) but it may be less efficient than the code above (one map + one list comprehension instead of a single map in the first solution). Maybe the second's a little more readable (or a little less unreadable ;-). HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From lhudson at geminidataloggers.com Thu Jun 27 11:22:49 2002 From: lhudson at geminidataloggers.com (Lawrence Hudson) Date: Thu, 27 Jun 2002 16:22:49 +0100 Subject: How to find out operating system References: Message-ID: <3D1B2DC9.30504@geminidataloggers.com> If you have PyWin32, try this: d:\>python Python 2.0 (#8, Jun 12 2002, 10:20:16) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> import win32api >>> win32api.GetVersionEx() (5, 0, 2195, 2, 'Service Pack 2') >>> majorVersion: Identifies the major version number of the operating system. minorVersion: Identifies the minor version number of the operating system. buildNumber: Identifies the build number of the operating system in the low-order word. (The high-order word contains the major and minor version numbers.) platformId: Identifies the platform supported by the operating system. May be one of VER_PLATFORM_WIN32s, VER_PLATFORM_WIN32_WINDOWS or VER_PLATFORM_WIN32_NT version: Contains arbitrary additional information about the operating system. Thanks, Lawrence A wrote: > Hi, > What is the best way of finding out the kind operating system? > I can use os.name but if the system is Windows I would like also > know if the system is Windows98 or Windows ME or W2K or > Windows XP. > Thanks for help. > Ladislav > > > > From saint at ghost.lt Thu Jun 20 12:08:52 2002 From: saint at ghost.lt (martynas sklizmantas) Date: 20 Jun 2002 18:08:52 +0200 Subject: Function to add commas in numbers? In-Reply-To: References: Message-ID: <1024589333.15471.82.camel@naked> hello, On Thu, 2002-06-20 at 17:17, mdk wrote: > Hello, > > Is there a function that will take, for example, 1234567 and return > 1,234,567? you could use locale module (http://www.python.org/doc/current/lib/module-locale.html ) for more interesting solutions look - http://mail.python.org/pipermail/python-list/2002-June/thread.html#108787 btw, i have some problems with locale module on debian sid: Python 2.1.3 (#1, Apr 20 2002, 10:14:34) [GCC 2.95.4 20011002 (Debian prerelease)] on linux2 Type "copyright", "credits" or "license" for more information. >>> import locale >>> locale.setlocale(locale.LC_NUMERIC, 'da_DK') Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.1/locale.py", line 374, in setlocale return _setlocale(category, locale) locale.Error: locale setting not supported am i missing something in my installation? best regards, ms -- You fill a much-needed gap. From cjw at sympatico.ca Sat Jun 15 08:25:59 2002 From: cjw at sympatico.ca (Colin J. Williams) Date: Sat, 15 Jun 2002 08:25:59 -0400 Subject: Integer conversion Message-ID: <3D0B3257.E8572AE5@sympatico.ca> int(string, base) => integer For int('127', 8), I had expected this function to deliver 87. The example below correctly gives errors at the top and bottom of the range and for int('127', 10) delivers 127. The other cases are not what I expected. I would appreciate any suggestions. Colin W. for b in range(2,38): try: print b, '[', int('127', b), ']' except: pass print 'error' From wilson at visi.com Thu Jun 20 21:41:04 2002 From: wilson at visi.com (Tim Wilson) Date: Thu, 20 Jun 2002 20:41:04 -0500 Subject: Generating SWFs using Ming via CGI Message-ID: <2wvQ8.19$eH2.59629@ruti.visi.com> Hi everyone, I'm finishing up a class on building Flash animations. For my final project, I thought it would be cool to build a SWF (the Flash output file) using input from a Web form and processed using the Ming library (http://ming.sourceforge.net/) through CGI. Ming is "an SWF output library and PHP module" that also provides a Python wrapper. There is a function reference at http://ming.sourceforge.net/docs/index.php?mode=py and examples at http://ming.sourceforge.net/examples/index.html I'm having trouble getting a simple example to work via cgi on my Web server. (I know it's not a cgi configuration problem. There are other CGI scripts that work fine.) I'm not sure how to set the Content-type header and then output the SWF movie. Here's a short PHP script followed by my Python translation. setLine(4, 0x7f, 0, 0); $s->setRightFill($s->addFill(0xff, 0, 0)); $s->movePenTo(10, 10); $s->drawLineTo(310, 10); $s->drawLineTo(310, 230); $s->drawCurveTo(10, 230, 10, 10); $m = new SWFMovie(); $m->setDimension(320, 240); $m->setRate(12.0); $m->add($s); $m->nextFrame(); header('Content-type: application/x-shockwave-flash'); $m->output(); ?> This script is found at http://ming.sourceforge.net/examples/example.php?name=shape Here's my Python translation. #!/usr/bin/python from ming import * s = SWFShape() s.setLine(4, 0x7f, 0, 0) s.setRightFill(s.addFill(0xff, 0, 0)) s.movePenTo(10, 10) s.drawLineTo(310, 10) s.drawLineTo(310, 230) s.drawCurveTo(10, 230, 10, 10) m = SWFMovie() m.setDimension(320, 240) m.setRate(12.0) m.add(s) m.nextFrame() print "Content-type: applicaton/x-shockwave.flash\n" m.output() Note, I can substitute m.save('shape.swf') for m.output() and the script works fine. But I want the swf to be viewed immediately in the browser. BTW, running the Python version listed above produces the following in my Web server's error log: [Thu Jun 20 20:08:15 2002] [error] [client 208.42.140.222] malformed header from script. Bad header=FWSQ: /home/wilson/public_html/cgi-bin/shape.py Running the shape.py script from the server's command line produces: wilson at beethoven:~/public_html/cgi-bin$ python shape.py Content-type: applicaton/x-shockwave.flash FWSQp ?? C???p 0@???P?5,?G????&Q h?@wilson at beethoven:~/public_html/cgi-bin$ Can anyone provide a hint about how I can make this work? -Tim -- Tim Wilson | Visit Sibley online: | Check out: Henry Sibley HS | http://www.isd197.k12.mn.us/ | http://www.zope.org/ W. St. Paul, MN | | http://slashdot.org/ wilson at visi.com | | http://linux.com/ From edream at tds.net Thu Jun 20 19:49:36 2002 From: edream at tds.net (Edward K. Ream) Date: Thu, 20 Jun 2002 23:49:36 GMT Subject: tkinter font picker? References: <3D122BB6.92593026@tds.net> Message-ID: <3D126A11.172D2565@tds.net> > >Does anyone know of tkinter code that will put up a font chooser > >dialog? There are a number of such packages written in tk/tcl. I'm > >wondering if anyone knows of a port to tkinter. > > I have a simple one that is part of a Tkinter-based preferences package. > You can find it at in the > Util.zip package; unpack and look in the Prefs folder. Thanks for this link :-) Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From nookieNO_SP_AM at online.no Sun Jun 9 17:56:28 2002 From: nookieNO_SP_AM at online.no (Erlend J. Leiknes) Date: Sun, 09 Jun 2002 21:56:28 GMT Subject: import problem References: <2se7guc3kkmm3bgooj776j55igpkmgpst4@4ax.com> Message-ID: if you have the debugging application strace (its most likely you have it) write a small application who only does: from qt import * save it, run it like this: strace python your_app.py 1> log1.txt 2>log2.txt wait for it to finnish, and edit log2 (or log1).txt, scroll to the bottom, and look for io signales that tries to open libsub.so.* now you should find out what your filename should be. "Michael Eager" wrote in message news:2se7guc3kkmm3bgooj776j55igpkmgpst4 at 4ax.com... > I'm trying to use Python 2.2 and PyQt on a RedHat-7.2 system. > > I get an error when I execute "from qt import *" -- there is a failure > in qt.py when it executes "import libsup". The error is "No module > named libsup". > > libsup.so.9 is a link to libsup.so.9.0.3 and is in > /usr/lib/python2.2/site-packages. If I enter "import libsup", I get > the same error message. > > Any suggestions? > > -- Mike Eager, eager at eagercon.com From gerhard at bigfoot.de Fri Jun 28 11:00:13 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 28 Jun 2002 15:00:13 GMT Subject: distutils/boost question References: Message-ID: In article , Uwe Schmitt wrote: > Hi, > > I used the Boost.Python library to write some python-extension. > How can I distribute the generated (binary) .so-file with distutils ? > I don't want to distribute the sources, only the binaries. > In detail: I have to distribute the libbpl.so from boost and > my own .so-file. One problem is, that I have to add the > path of libbpl.so to $LD_LIBRARY_PATH. When I only copy it > to the extension-folder of python, it does not work... The easiest solution is to statically link in the Boost.Python library. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From reason5000 at yahoo.com Wed Jun 19 10:35:44 2002 From: reason5000 at yahoo.com (Rod G) Date: 19 Jun 2002 07:35:44 -0700 Subject: web based e-mail Message-ID: <83e21f2.0206190635.14617b0a@posting.google.com> Hello. Does anyone know of a tutorial or how-to on creating a web based e-mail system using Python? I'm wanting to develop my own system as a learning project and need a starting point. Thanks, Rod From Chris.Barker at noaa.gov Thu Jun 20 13:46:12 2002 From: Chris.Barker at noaa.gov (Chris Barker) Date: Thu, 20 Jun 2002 10:46:12 -0700 Subject: Windows versions of Python---pros and cons? References: <3D110B55.4D8AD7FA@astro.cornell.edu> Message-ID: <3D1214B6.E9BB77D2@noaa.gov> Fernando P?rez wrote: > If you're an old unix hand and want to preserve your sanity, you have two > options: > > 1- put linux on that laptop and be happy. I have to concur. I am mostly a Linux user, but when I use Python on Windows, I really have a hard time with it. It's nothing to do with Python, and everything to do with Windows. Windows simply does not provide a programing enviroment that will feel at all productive to someone used to *nix. I run Linux on a Dell laptop, and am very happy with it. On that note: does anyone know if there is a way to turn a Python script into something that acts like an application on Windows...without resorting to Py2exe and the like. What I want is something just like: chmod +x scriptname and a #! line at the top on Unix. I want it to work on the windows command line. -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From gerhard.haering at gmx.de Wed Jun 19 21:18:33 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 20 Jun 2002 01:18:33 GMT Subject: My Python/MySQL code is too slow References: Message-ID: Duncan Smith wrote in comp.lang.python: > I have already posted this problem on mailing.database.mysql as I see it as > a problem with my lack of knowledge of SQL. But no responses so far, and > maybe Python could do more of the work. Doing work in Python that the db can do is not generally advisabele for performance reasons. MySQL, however, is a rather limited RDBMS. If you want better SQL support, I'd recommend to take a look at PostgreSQL. Outer joins and subselects are missing from MySQL, but available in PostgreSQL and it looks like they could be useful in your case. > I repost the original question below (SQL easier to follow), and the > Python code below that. Any help appreciated. TIA. > > --------------------------------------------------------------------- > I have two tables (say dbA and dbB) and need to find the number of rows in > dbB which have exactly 2 matching rows in dbA (on the selected columns). > I'm using Python/MySQL, but the relevant SQL is below. This is slow, and > I'm sure it's possible without creating the temporary table and without the > join. But everything I try fails (because of my limited knowledge of SQL). > Can anyone show me an efficient way of getting the answer? All I need is > the number of rows in dbB which have exactly 2 matching rows in dbA. Thanks > in advance. > > CREATE TEMPORARY TABLE tmp SELECT var1, var2, var3 FROM dbA GROUP BY var1, > var2, var3 HAVING COUNT(*)=2; > > SELECT dbB.var1, dbB.var2, dbB.var3, tmp.var1, tmp.var2, tmp.var3 FROM dbB, > tmp WHERE dbB.var1=tmp.var1 AND dbB.var2=tmp.var2 AND dbB.var3=tmp.var3; I have no idea what dbA and dbB contain, but it looks like they contain the same sort of data. This is not good db design, but that's normal for SQL newbies. I'm not very good at explaining the theory, but you could take a look at one of these links: http://www.google.com/search?hl=en&lr=&q=relational+database+normalization ("normalization" is the basic concept of good relational db design) It's very likely that reorganizing your db schema into a one-to-many relationship between two tables, and thus unifiying dbA and dbB will simpify your problem. > [...] > conn = MySQLdb.connect() > curs = conn.cursor() > curs.execute('USE %s' % (dbname,)) conn = MySQLdb.connect(db=dbname) HTH, Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From gcordova at hebmex.com Fri Jun 7 17:44:38 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Fri, 7 Jun 2002 16:44:38 -0500 Subject: direct output to printer Message-ID: > > Hi, > > I'd like to print barcodes with a special barcode printer. > Therefore I have to send raw ASCII data to the printer. > How can I do this using Python under Windows ??? > > Greetings, Uwe. > Same way you'd do it in MSDOS (if you have it connected to a parallel port): >>> lpt = open("lpt1:", "w") >>> lpt.write(BarcodeDataString) >>> lpt.close() You can also use "prn:" instead of "lpt1:" :-) -gustavo pd: Win's just MSDOS with icing on top. ;-) From metaliu at yahoo.com Fri Jun 7 20:01:21 2002 From: metaliu at yahoo.com (Bill) Date: Fri, 7 Jun 2002 17:01:21 -0700 Subject: Getting pixel values under cursor Message-ID: I'm using Tkinter right now for a GUI. Is there a way for me to get, in real time or when the user clicks the mouse button on a pixel, the pixel intensity value? Currently, I have a tkinter label which is showing a large grey scale image. I would like the user to move the mouse cursor over the image and show the pixel intensity under the cursor. Is there a way to do this? Perhaps some kind of event binding with the mouse and the image? Would putting the image in a canvas instead provide more flexibility? Thanks in advance, Bill From mertz at gnosis.cx Wed Jun 5 15:54:44 2002 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Wed, 05 Jun 2002 15:54:44 -0400 Subject: ANN: Gnosis (XML) Utils 1.0.2 Message-ID: This release contains one major bugfix, and one new XML module: * Added module gnosis.xml.validity. This module contains custom classes for creating a Python object that is constrained by XML validity rules (DTD or Schema). Taking its inspiration from the Haskell module HaXml, a programmer using gnosis.xml.validity can guarantee that no operation on an object will result in something that would be serialized as invalid XML. See gnosis/doc/xml_matters_20.txt for details. * Fixed bug with integer parsing in gnosis.xml.pickle (a single "0" was being treated as a failed octal number, rather than as...well, zero). It may be obtained at: http://gnosis.cx/download/Gnosis_Utils-1.0.2.tar.gz The current release is always available as: http://gnosis.cx/download/Gnosis_Utils-current.tar.gz Try it out, have fun, send feedback! David Mertz (mertz at gnosis.cx) Frank McIngvale (frankm at hiwaay.net) ------------------------------------------------------------------------ BACKGROUND: Gnosis Utilites contains a number of Python libraries, most (but not all) related to working with XML. These include: gnosis.xml.pickle (XML pickling of Python objects) gnosis.xml.objectify (Any XML to "native" Python objects) gnosis.xml.validity (Enforce validity constraints) gnosis.xml.indexer (XPATH indexing of XML documents) gnosis.indexer (Full-text indexing/searching) [...].convert.txt2html (Convert ASCII source files to HTML) gnosis.util.dtd2sql (DTD -> SQL 'CREATE TABLE' statements) gnosis.util.sql2dtd (SQL query -> DTD for query results) gnosis.util.xml2sql (XML -> SQL 'INSERT INTO' statements) gnosis.util.combinators (Combinatorial higher-order functions) gnosis.util.introspect (Introspect Python objects) ...and so much more! :-) SUMMARY:

Gnosis_XMLUtil 1.0.2 (6-June-02) -- _/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: Postmodern Enterprises _/_/_/ _/_/ ~~~~~~~~~~~~~~~~~~~~[mertz at gnosis.cx]~~~~~~~~~~~~~~~~~~~~~ _/_/ _/_/ The opinions expressed here must be those of my employer... _/_/ _/_/_/_/_/_/_/_/_/_/ Surely you don't think that *I* believe them! _/_/ From peter at engcorp.com Sat Jun 22 13:05:01 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 22 Jun 2002 13:05:01 -0400 Subject: urllib POST question References: <644f6688.0206200930.48110837@posting.google.com> <644f6688.0206210900.68dd930c@posting.google.com> <3D13D62B.D7AE6554@engcorp.com> <644f6688.0206220830.46583e8f@posting.google.com> Message-ID: <3D14AE3D.18BFBE55@engcorp.com> rdack wrote: > > Peter Hansen wrote in message news:<3D13D62B.D7AE6554 at engcorp.com>... > > > > In article <644f6688.0206200930.48110837 at posting.google.com>, rdack wrote: > > > > > i am doing a POST to a server using urllib and it works. > > > > > is there some way i can see exactly what is being posted? > > > > > a way to get the post object out of urllib - the exact lines it is sending? > > Howzabout this? > > > > >>> import httplib > > >>> httplib.HTTPConnection.debuglevel = 1 > > >>> import urllib > > >>> page = urllib.urlopen('yoururlhere').read() > > perfect! thanks. although i was able to install ethereal and see the > packet-it was the 100 megabyte solution. > this was the zero byte solution. > of course, now i have the roll royce of packet sniffers. > anyway - you are right - python-rocks - when you know which button to > push. :-). The right button was "Use the Source, Luke!". I found in urllib that it was doing an h = httplib.HTTP() so I went to httplib and found that the class had a debuglevel field which was used to control that feature. This button is available for most other Python modules, too. ;-) -Peter From cpbotha at i_triple_e.org Thu Jun 13 04:40:25 2002 From: cpbotha at i_triple_e.org (Charl P. Botha) Date: Thu, 13 Jun 2002 08:40:25 +0000 (UTC) Subject: py2exe 4 linux? References: <3D08563C.33D041E3@gol.ge> Message-ID: In article <3D08563C.33D041E3 at gol.ge>, Giorgi Lekishvili wrote: > Is there anything like py2exe for Linux? Try Gordon McMillan's Installer at http://www.mcmillan-inc.com/install1.html This works incredibly well and is cross-platform to boot! I've used it to make standalones of quite an extensive application that makes use of wxPython and VTK and was amazed at how little I had to do to get it working perfectly. HTH, Charl -- charl p. botha http://cpbotha.net/ http://visualisation.tudelft.nl/ From merkosh at hadiko.de Sun Jun 16 19:52:52 2002 From: merkosh at hadiko.de (Uwe Mayer) Date: Mon, 17 Jun 2002 01:52:52 +0200 Subject: what *is* a class? Message-ID: hi i've got an object 'Group'. i instanciate it by calling, f.e. g = Group() what actually does Group() return and is there any way to get hold of that again? i want to write a method which returns the instance, so that f.e. the following is possible: g = Group() g2 = g.foobar() g2 is g so that g2 is identical to g. any idea? thanks in advance Uwe From BPettersen at NAREX.com Mon Jun 24 12:31:37 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Mon, 24 Jun 2002 10:31:37 -0600 Subject: File Copying Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192158EF6@admin56.narex.com> > From: Rajat Chopra [mailto:rchopra at myrealbox.com] > > How do you copy a file from one directory to another. I have > looked all over and haven't found any documentation on it. > Essentially, I want to copy a file from $SRC_DIRECTORY to > $TARGET_DIRECTORY. > > Does anyone know which modules are used? Or does anyone have > some sample scripts? Look in the shutil module. -- bjorn From peter at engcorp.com Mon Jun 17 21:28:18 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 17 Jun 2002 21:28:18 -0400 Subject: symbolic python References: <3CEFAE4C.38A8022B@doc.ic.ac.uk> <3CEFD881.D7992095@doc.ic.ac.uk> <3cf8ce86$1@giga.realtime.net> <83sn46vkgi.fsf@panacea.canonical.org> <3CF942C7.2E4AA4CF@engcorp.com> <838z5xtcla.fsf@panacea.canonical.org> <6a625eea.0206161221.50d351ad@posting.google.com> Message-ID: <3D0E8CB2.E831F8AB@engcorp.com> Ira Baxter wrote: > > > > no support for Python is (yet) mentioned in the list of supported > > > languages. > > That's because our tools are designed to accept langauge definitions > easily. A Python grammar would take only a few days to develop. > > If you want to transform Python symbolically, DMS will do the > job very well, and I don't see many alternatives out there. "Will"? When? Or did you mean "could"? -Peter From mwh at python.net Wed Jun 19 11:47:11 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 19 Jun 2002 15:47:11 GMT Subject: procmail replacement in Python References: <20020619181953.E4127@phd.pp.ru> Message-ID: Gerhard H?ring writes: > > Fetchmail also has good GUI configuration program, written in Python > > and Tkinter. > > Pointless. fetchmail (and getmail even more) configuration is very easy. > If there were a GUI tool to write procmail rules, now that would make > sense. But even then only if it included a regex-wizard ;-) What *I* want is a tool that will subscribe you to a mailman mailing list, write an appropriate procmail rule to shove the messages into a new mail folder, send the confirmation and tell gnus about the folder. That would be neat. Cheers, M. -- The Internet is full. Go away. -- http://www.disobey.com/devilshat/ds011101.htm From jepler at unpythonic.net Tue Jun 4 12:20:26 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 4 Jun 2002 11:20:26 -0500 Subject: Python command line? In-Reply-To: References: Message-ID: <20020604112025.A24006@unpythonic.net> On Tue, Jun 04, 2002 at 10:59:18AM -0500, SA wrote: > Hi Everyone- > > I would like to run python code line by line using: > > python -c some line of code > > Will this work? Probably not. For instance, python -c 'def f(): return 3' python -c 'print f()' won't do the same thing as >>> def f(x): return 3 ... >>> print f(x) 3 You probably need to use 'eval' or 'exec': >>> gns = {'__builtins__': __builtins__} >>> lns = {} >>> exec "def f(): return 3" in gns, lns >>> exec "print f()" in gns, lns 3 >>> print lns['f']() # Or access items created in the local namespace 3 Jeff PS you escape all sorts of quoting and length-limit problems by avoiding the likes of os.system("python -c '%s'", cmdstr) too -- for instance, this won't work at all on NT (since ''-quoting doesn't exist in the shell afaik) and the cmdstr of "'; echo '0wn3d" will not do what you want on Unix. From logiplexsoftware at earthlink.net Tue Jun 18 14:07:16 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Tue, 18 Jun 2002 11:07:16 -0700 Subject: python version? In-Reply-To: <9YBP8.44418$GY.13865843@twister.nyroc.rr.com> References: <3tingu8psfmefoab93pl8gips8hg7sgpvp@4ax.com> <9YBP8.44418$GY.13865843@twister.nyroc.rr.com> Message-ID: <20020618110716.67cbf88f.logiplexsoftware@earthlink.net> On Tue, 18 Jun 2002 08:12:53 GMT George Hester wrote: > I think you guys don't how to do it. > > -- > George Hester You may in fact be correct. If I were you I'd email "Timothy Rue" as he would probably be able to give you a more direct answer. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From max at alcyone.com Thu Jun 20 00:59:18 2002 From: max at alcyone.com (Erik Max Francis) Date: Wed, 19 Jun 2002 21:59:18 -0700 Subject: can I call operator overloader in superclass? References: Message-ID: <3D116126.433AF0E4@alcyone.com> "Jon J. Morin" wrote: > TypeError: repr not string > > For one, I don't understand the error. For seconds, can I call > __repr__ in > the superclass from __repr__ in the subclass? I'm guessing you have an older version of Python. In Python 2.2 this is the error you'll get: TypeError: __repr__ returned non-string (type NoneType) which I can only presume was changed to be a little more descriptive. The calling superclass methods in subclasses is actually leading you astray -- all the error is telling you is that your __repr__ method must return and yours isn't. Change the __repr__ method in your subclass so that it returns a string and you're off and running. To answer your other question (which really wasn't the issue here), you can certainly explicitly call a superclass method in a subclass, and you'd had the syntax right: Specify the superclass method is an unbound method and then explicitly pass in the self object: class Superclass: ... def method(self): ... class Subclass(Superclass): ... def method(self): ... Superclass.method(self) ... -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Who'd ever think it / Such a squalid little ending \__/ The American and Florence, _Chess_ Church / http://www.alcyone.com/pyos/church/ A lambda calculus explorer in Python. From ylee12 at uiuc.edu Fri Jun 7 14:22:54 2002 From: ylee12 at uiuc.edu (Young-Jin Lee) Date: Fri, 7 Jun 2002 13:22:54 -0500 Subject: About writing Jython tutorial... References: Message-ID: <%N6M8.12540$U7.145594@vixen.cso.uiuc.edu> It would be great to have a nice Jython tutorial. I have been looking for it quite a while, but had no luck. YJ. "Robert Hanlin" wrote in message news:c427d639.0206070612.4ea8ce0c at posting.google.com... > Hi all, > > I'm indoctrinating friends into the dark, beautiful world of Jython. > But I find there is no good online documentation, and I only have an > easy time because I happen to own the O'Reilly Jython Essentials book. > (For example, when you use jythonc to compile classes, if something > is missing on the classpath you're more likely to get a null pointer > exception than an appropriate class not found exception.) > > If I happened to write a walkthrough, is there a website where it > would be welcome? If not, maybe I should make a weblog... > > > Thanks! > findler From john_taylor_1973 at yahoo.com Sat Jun 22 01:35:22 2002 From: john_taylor_1973 at yahoo.com (John Taylor) Date: 21 Jun 2002 22:35:22 -0700 Subject: urllib POST question References: <644f6688.0206200930.48110837@posting.google.com> <644f6688.0206210900.68dd930c@posting.google.com> Message-ID: rdacker at pacbell.net (rdack) wrote in message news:<644f6688.0206210900.68dd930c at posting.google.com>... > Ben Beuchler wrote in message news:... > > In article <644f6688.0206200930.48110837 at posting.google.com>, rdack wrote: > > > i am doing a POST to a server using urllib and it works. > > > is there some way i can see exactly what is being posted? > > > a way to get the post object out of urllib - the exact lines it is sending? > > > > I'm a big fan of Ethereal... > > "Sniffing the glue that holds the internet together!" > > > > http://www.ethereal.com/ > > i am looking into it. seems overkill for wanting to see a few bytes > that python is generating. > No way within python to see what urllib intends to send out for the > POST? If you have the tcpdump program available (most likely on unix), then you can use the script below. The program is a wee bit on the slow side when processing large files, so any suggested speed ups would be appreciated. Also available at http://www.terry.uga.edu/~jft/ptd.py #!/usr/bin/env python # ptd - Print TcpDump # John Taylor 2002-06-03 # Requires Python 2, will not work on Python 1.5.2 # Example: # tcpdump -n -i eth0 -x -vv -t -s 4096 ip and not port 22 | ptd.py import sys # if set to 1, you will see a line count status on stderr VERBOSE = 1 VERBOSE_PERIOD = 2000 # # Main # def main(): line_count = 0 for line in sys.stdin.xreadlines(): line_count += 1 newline = " " hexdata = line.split("\t") if 4 == len(hexdata) : hexline = hexdata[3].split() for w in hexline: h1 = w[:2] h2 = w[2:] if( len(h1) ): i = int("0x"+h1,16) if i >= 32 and i <= 127: newline += chr(i) else: if " " == newline[-1] : newline += "%s " % (h1) else: newline += " %s " % (h1) if( len(h2) ): i = int("0x"+h2,16) if i >= 32 and i <= 127: newline += chr(i) else: if " " == newline[-1] : newline += "%s " % (h2) else: newline += " %s " % (h2) print newline else: one = line[0:1] if " " == line[1:2] and (">" == one or "<" == one or "B" == one): print print line, if 1 == VERBOSE and (0 == line_count % VERBOSE_PERIOD): sys.stderr.write("%d\n" % line_count) # # Program execution begins here # main() From whisper at oz.net Tue Jun 11 12:04:17 2002 From: whisper at oz.net (David LeBlanc) Date: Tue, 11 Jun 2002 09:04:17 -0700 Subject: compiling error: undefined symbol: __gxx_personality_v0 In-Reply-To: <93523ebb.0206110732.791e745@posting.google.com> Message-ID: You might get more help with a boost problem like this on http://mail.python.org/mailman/listinfo/c++-sig which is the mailing list for boost & python. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of mitsch > Sent: Tuesday, June 11, 2002 8:32 > To: python-list at python.org > Subject: compiling error: undefined symbol: __gxx_personality_v0 > > > Hi, > I try to wrap C functions in Python. > when I compile, here's the result: > Traceback (most recent call last): > File "./boost.py", line 2, in ? > import getting_started1 > ImportError: ./getting_started1.so: undefined symbol: > __gxx_personality_v0 > > > can somebody tell why this error? > > here's my files: > getting_stated!.cpp : > #include > namespace python = boost::python; > #include > > namespace { // Avoid cluttering the global namespace. > > // A couple of simple C++ functions that we want to expose to > Python. > std::string greet() { return "hello, world"; } > int square(int number) { return number * number; } > } > > BOOST_PYTHON_MODULE_INIT(getting_started1) > { > // Create an object representing this extension module. > python::module_builder this_module("getting_started1"); > > // Add regular functions to the module. > this_module.def(greet, "greet"); > this_module.def(square, "square"); > } > > > > > > my compile command: > g++3 -fpic -g -I/usr/include/python2.1 > -I/usr/local/lib/python/boost_1_28_0/ -c ./getting_started1.cpp > gcc -shared -lc getting_started1.o -o getting_started1.so > -- > http://mail.python.org/mailman/listinfo/python-list From zopestoller at thomas-guettler.de Tue Jun 25 10:36:54 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Tue, 25 Jun 2002 16:36:54 +0200 Subject: Parsing strings (\n and \\) Message-ID: <3D188006.7050202@thomas-guettler.de> Hi! Is there a function for parsing c-like strings? I need to parse strings containing '\n' and '\\' '\"'. thomas From gmcm at hypernet.com Sat Jun 1 11:17:30 2002 From: gmcm at hypernet.com (Gordon McMillan) Date: 01 Jun 2002 15:17:30 GMT Subject: Installer vs py2exe: Windows DLLs References: Message-ID: Paul Moore wrote: > When building a distribution for the same script using Gordon > McMillan's Installer and py2exe, I notice that Installer includes > PyWinTypes22.dll and win32api.pyd, whereas py2exe doesn't. [snip] > More to the point, in some ways, why does Installer think these files > are needed? Is there some situation in which py2exe generated > executables will fail because these files aren't there? David's answer was 100% correct. The specific call here is os.path.abspath(...). Before 2.2 and without win32api, this simply examined its argument. In some rare corner cases, it would yield an incorrect answer. -- Gordon http://www.mcmillan-inc.com/ From amckay at merlintechnologies.com Mon Jun 10 13:08:48 2002 From: amckay at merlintechnologies.com (Andy McKay) Date: Mon, 10 Jun 2002 10:08:48 -0700 Subject: Newby: How do I strip HTML tags? In-Reply-To: <3d0190e7.5774640@news.t-online.de> References: <3d00e1b1.47853937@news.t-online.de> <3d0190e7.5774640@news.t-online.de> Message-ID: <20020610170848.GA2228@mckay.merlintechnologies.com> > Standalone "<" and ">" indicate invalid HTML code, one should use < > and > instead. You are of course right, in the end a use of > predefined classes is almost always better than reinventing the wheel > yourself. Of course the main problem is there is a lot of invalid HTML out there ;) I cant remember where the article was, but I found a good one a while ago that showed a list of valid, but admittedly rare situations that can crop up a simple html parser. Should make set of unit tests for any parser actually... -- Andy McKay Merlin Technologies From tdelaney at avaya.com Thu Jun 13 20:40:33 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Fri, 14 Jun 2002 10:40:33 +1000 Subject: newbie: from .. import * Message-ID: > From: jseb at cs.mcgill.ca [mailto:jseb at cs.mcgill.ca] > > In the interactive mode, if I import the code above as: > >>> from test import * > 1 > 0 http://py-howto.sourceforge.net/doanddont/doanddont.html Look at 1.1 ... Tim Delaney From rnd at onego.ru Tue Jun 11 16:20:00 2002 From: rnd at onego.ru (Roman Suzi) Date: Wed, 12 Jun 2002 00:20:00 +0400 (MSD) Subject: Why does Python mix OO concepts and non OO concepts for operation s on basic types? In-Reply-To: <3D054A98.3090708@bgb.cc> Message-ID: On Tue, 11 Jun 2002, Don Garrett wrote: >Hans Nowak wrote: >> Besides, while Python is object-oriented, that isn't the only >> paradigm in the language. People coming from a functional >> background may find the len() function more natural than a >> method. >> >> YMMV, >> > > That's one thing I don't get. Why wasn't len() added as a member to the >various types during the recent rework that added so many other members to the >native types? ...and what for do we need all those funny slices, attribute assignments, ..? a.set(b, c) print a.get(b) a.set_b(c) is much nicer than: a[b] = c print a[b] a.b = c I also wonder why to contaminate a wonderful language with all those <, >, &, |, ..., +, - ? Look, how nice these examples are: a.add(b.multiply(c)) instead of ugly, Perlish, unOOPish: a + b * c ... I only forgot how will I do this: map(string.split, s) if GvR will deprecate string module... Sincerely yours, Roman Suzi -- \_ Russia \_ Karelia \_ Petrozavodsk \_ rnd at onego.ru \_ \_ Tuesday, June 11, 2002 \_ Powered by Linux RedHat 7.2 \_ \_ "I can't use Windows. The cat ate my mouse." \_ From jepler at unpythonic.net Fri Jun 14 09:48:58 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 14 Jun 2002 08:48:58 -0500 Subject: Why does Python mix OO concepts and non OO concepts for opera tion s on basic types? In-Reply-To: References: Message-ID: <20020614134857.GB30070@unpythonic.net> On Fri, Jun 14, 2002 at 09:57:12AM +1000, Delaney, Timothy wrote: > > From: holger krekel [mailto:pyth at devel.trillke.net] > > > > probably. With python 1.6 many methods of the string *module* were > > included included directly with the *type* string ('str'). Most > > python developers think that the string module should be deprecated > > I think "most" is a little bit strong. The general feeling that I get seems > to be pretty much split down the middle. > > I personally *don't* favour getting rid of the string module - there are > many things which lend themselves better to a non-object-oriented style - > and many of the string functions are included. > > Now, if the str type included *all* of this functionality, *and* was aliased > to string, then you may have a case ... although 'import string' would still > need to work (for backwards compatibility) until 3.0. There are other problems with using "str" instead of "string", even when the methods exist: >>> u = U" hi there " >>> str.rstrip(u) TypeError: descriptor 'rstrip' requires a 'str' object but received a 'unicode' >>> string.rstrip(u) u' hi there' Jeff From gerhard at bigfoot.de Wed Jun 12 10:52:11 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 12 Jun 2002 14:52:11 GMT Subject: (no subject) References: Message-ID: In article , Martin v. Loewis wrote: > [cgi programming with Python] > There are several strategies, but I recommend to use plain print > statements. I would recommend to write to a StringIO.StringIO instance for the http body instead, then, at the end, when you finally know that nothing exceptional happened, you know which HTTP header to write, and then just print the body. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From donn at u.washington.edu Mon Jun 24 18:52:52 2002 From: donn at u.washington.edu (Donn Cave) Date: 24 Jun 2002 22:52:52 GMT Subject: AF_UNIX + SOCK_DGRAM References: Message-ID: Quoth Chris Liechti : [quoting me] | >> Actually think you have run into a bug in Python's socket module. | >> If it's convenient for you to build your own socket module, change | >> it like this and see what happens (I'm looking at version 2.1 here.) | > | >> *** socketmodule.c.dist Sun Apr 15 17:21:33 2001 | >> --- socketmodule.c Thu Jun 20 10:10:12 2002 | >> *************** | >> *** 597,602 **** | >> --- 597,603 ---- | >> case AF_UNIX: | >> { | >> struct sockaddr_un *a = (struct sockaddr_un *) addr; | >> + a->sun_path[addrlen - (sizeof(*a) - | >> sizeof(a->sun_path))] = 0; | >> return PyString_FromString(a->sun_path); | >> } | >> #endif | | why not simply use PyString_FromStringAndSize(const char *v, int len)? | | couln't you just file a patch on SF? should i do it? PyString_FromStringAndSize is OK by me, and it's also fine with me if you would like to submit a patch to Sourceforge. Donn Cave, donn at u.washington.edu From talon34 at hotmail.com Wed Jun 26 10:49:34 2002 From: talon34 at hotmail.com (Talon) Date: Wed, 26 Jun 2002 14:49:34 GMT Subject: Installation problems DCOracle2 & W2000 References: <3D1934D1.3000707@nospam.majid.fm> Message-ID: In article <3D1934D1.3000707 at nospam.majid.fm>, Fazal Majid wrote: > Talon wrote: > > I am having a heck of a time getting DCOracle2 to funcion properly. I > > am running on a W2K machine, python2.1.3 and Zope 2.5.1, both of which > > run just fine. I installed DCOracle2 and the ZOracleDA under Zope and > > it works fine. But standalone python scripts don't see the dco2.py > > module. So I tried to install DCOracle2 in the python21/lib folder. I > > got that latest version from Zope.org and it said it installed properly. > > But it doesn't run. If you try to import it into a script, you get > > complaints that it can't find this or that module, all of which are part > > of the Zope path. > > I have gotten DCOracle2 to work correctly on my Windows 2000 setup with > 2.1.1 (but I haven't tried it with Zope). You do need to set your > Pythonpath environment variable correctly, as well as copy the correct > dco2.pyd (DLL) version for your Python and Oracle versions. > > -- Fazal Majid > > If you want to respond by email, take the nospam out of my email address. > Thanks for the response Fazal. I believe the python path is correct, as other python scripts run fine. The dco2.pyd file is copied to the correct directory by the latest version of install.py that comes with it. But when a script tries to import DCOracle2, I get an error saying it is looking for Buffer or DateTime, all of which are part of the Zope path. Mark From bokr at oz.net Wed Jun 12 14:56:38 2002 From: bokr at oz.net (Bengt Richter) Date: 12 Jun 2002 18:56:38 GMT Subject: Negative long literals (was Re: Does Python need a '>>>' operator?) References: Message-ID: On Mon, 10 Jun 2002 08:19:09 -0400, Tim Peters wrote: >[Beni Cherniavksy] >> I just got another idea: use 0x1234 for 0-filled numbers and 1xABCD for >> 1-filled ones. That way you impose no restrictions on what follows the >> prefix and keep backward compatibility. 0xFFFFFFFF stays a 2^n-1 >> _positive_ number, as it should be. The look of 1x is weird at first but >> it is very logical... > >Indeed, on both counts . I like it a lot! > >For the other points related to getting rid of machine long-size >assumptions, see PEP 237: . > It was too easy for me to grasp at first ;-) Now that I know that 1x7 == 1xf7 == 1xff7, I can relate it to my (with Greg mod) suggested format 0hf7. Mostly they're interchageable by substituting 0hf for 1x and 0h0 for 0x as prefixes, but I like Beni's better. (They'd be fully interchangable if 1x == 1xf ;-) In a private email Paul Foley joked about writing 042 for 42 and 942 for -58 (i.e., why limit it to radix 16), and protested that machine representation was being exposed. It was not my purpose to expose machine representation, and neither format (mine or Beni's) should be thought of as such IMO. I was actually going to suggest an analogous binary notation (0b...), so I'm happy not to limit it to radix 16. The following decoding routine shows that the formats are not about exposing machine representation, IMO: >>> def benidecode(s): ... if s[1].lower()=='x': return long(s[2:],16)-long(s[0])*16L**(len(s)-2) ... elif s[1].lower()=='b': return long(s[2:],2)-long(s[0])*2L**(len(s)-2) ... elif s[1].lower()=='d': return long(s[2:],10)-long(s[0])*10L**(len(s)-2) ... elif s[1].lower()=='o': return long(s[2:],8)-long(s[0])*8L**(len(s)-2) ... raise NotImplementedError, 'radix "%s" not implemented"' % s[1] ... >>> benidecode('1x7') -9L >>> benidecode('1b0111') -9L >>> benidecode('1o67') -9L >>> benidecode('0x7') 7L >>> benidecode('0b0111') 7L >>> benidecode('0o07') 7L >>> benidecode('0z07') Traceback (most recent call last): File "", line 1, in ? File "", line 6, in benidecode NotImplementedError: radix "z" not implemented" And for Paul ;-) >>> benidecode('0d42') 42L >>> benidecode('0d042') 42L >>> benidecode('1d42') -58L >>> benidecode('1d942') -58L >>> benidecode('1d9942') -58L Regards, Bengt Richter From gina02122000 at yahoo.com Fri Jun 28 13:44:36 2002 From: gina02122000 at yahoo.com (ginak) Date: Fri, 28 Jun 2002 17:44:36 +0000 (UTC) Subject: Is Grail alive? Message-ID: The links from http://grail.sourceforge.net/source/license.html seem to be invalid... Thanks, G. From BPettersen at NAREX.com Thu Jun 13 17:06:01 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Thu, 13 Jun 2002 15:06:01 -0600 Subject: Type subclassing: bug or feature Message-ID: <60FB8BB7F0EFC7409B75EEEC13E2019221519F@admin56.narex.com> > From: Aahz [mailto:aahz at pythoncraft.com] > > Consider the following code: > > class MyStr(str): > def contains(self, value): > return self.find(value) >= 0 > > s = MyStr("hello, world!") > s = s.capitalize() > if s.contains('Hello'): > print "Found it!" > > It fails with an AttributeError when it calls s.contains(), because > s.capitalize() returned a str instead of a MyStr. Anyone > want to take a whack at defending this as the correct behavior? Well, in e.g. C++ this would make perfect sense, since a base class method can't know the real type of self/this. In Python we can do better of course: >>> class A: ... def foo(self): ... return self.__class__() ... >>> class B(A): ... pass ... >>> b = B() >>> b.foo() <__main__.B instance at 0x00864CC0> which version is correct is mostly a religious question, but personally I think that if we _can_ do better than C++ we should . File a bug and see what Guido says... -- bjorn From bokr at oz.net Tue Jun 25 21:09:39 2002 From: bokr at oz.net (Bengt Richter) Date: 26 Jun 2002 01:09:39 GMT Subject: SOLVED (Re: Python hits the spot) References: Message-ID: On Tue, 25 Jun 2002 15:12:47 -0700, "Jimmy Retzlaff" wrote: >Bengt Richter wrote: >>>> Well, lucky guess on the heat. That _probably_ accounts for laptop >>>> going to 87% and then shutting down, but how about the other huge >>>> slowdowns in your big loop of 8? Did you get that diagnosed too? >>>> Just curious ;-) >>> >>>On my stationary machine definitely not. The 8 steps remain constant. >I=20 >> >>Still curious ;-) > >I believe that newer mobile CPUs will throttle back their clock speed in >response to heat. This could explain the slow down. Apparently the ^^^-- or "some of the" >lowest clock speed wasn't low enough to keep the CPU happy... > Yeah, I understood that (having introduced the concept into this thread, I think ;-) But it was not clear to me whether that explained _everything_ (see other post re two readings of "On my stationary machine definitely not. The 8 steps remain constant." ;-) Regards, Bengt Richter From pedro_rodriguez at club-internet.fr Sat Jun 29 15:27:52 2002 From: pedro_rodriguez at club-internet.fr (Pedro RODRIGUEZ) Date: Sat, 29 Jun 2002 21:27:52 +0200 Subject: aspect-oriented demo using metaclasses References: Message-ID: On Fri, 28 Jun 2002 17:31:06 +0200, Mark McEahern wrote: > I owe much to previous threads on AOP, in particular Pedro Rodriguez's > non-metaclass implementation: > Mark, If you really want something more consistent than my posting, I will recommend you to also check: - Pythius by Juergen Hermann where Frank J. Tobin has introduced an aop module http://pythius.sourceforge.net/ by Juergen Hermann - Transwarp by Phillip J. Eby this a more complex framework using in some way concepts of aop http://telecommunity.com/TransWarp/ http://www.zope.org/Members/pje/Wikis/TransWarp/HomePage > > We want to iterate through the class's dict and do something for each > method (I'm not worried about distinguishing staticmethod and > classmethod type methods for now): > You should . At least for the purpose of the exercise ;) (Honestly I didn't try either, it may end up with a two liner... but I wonder if they will take two minutes or two hours to be written ;) > Rather than importing types and using types.FunctionType, I just compare > the type of the item to the type of an anonymous function (via lambda). > Is that cool or what? ;-) > Even if deprecation of the types module have been discussed on the devel list, I think it is preferable. > Now we're starting to get somewhere! The next step is to create a > framework where multiple observers can plug into the before and after > events for any given method call. Rather than taking more baby steps to > get there, this is the complete implementation I have so far: > You went even further than that. In the next step, you start separating (at least ;) the aspect and the 'aspectified' object in a less intrusive way. > > import sys > > class wrapped_method(object): > > def __init__(self, cls, method): > self.class_name = cls.__name__ > self.method = method > self.method_name = method.func_name > self.observers = [] > > def __call__(self, *args, **kwargs): > self.before(*args, **kwargs) > self.method(self, *args, **kwargs) > self.after(*args, **kwargs) > Oops... Didn't I make the same mistake... ... forgetting about the returned value ;) Something like could be better: def __call__(self, *args, **kwargs): self.before(*args, **kwargs) ret = self.method(self, *args, **kwargs) self.after(*args, **kwargs) return ret > class Trace(Observer): > > def __init__(self, filename=None): > self.filename = filename > > def write(self, prefix, class_name, method_name, *args, **kwargs): > cls = class_name > s = "%s: %s.%s(%s, %s)" % (prefix, cls, method_name, args, > kwargs) if not self.filename: > f = sys.stdout > else: > f = file(self.filename) > f.write(s) > f.write("\n") > if self.filename: > f.close() > > def before(self, class_name, method_name, *args, **kwargs): > self.write("before", class_name, method_name, *args, **kwargs) > > def after(self, class_name, method_name, *args, **kwargs): > self.write("after", class_name, method_name, *args, **kwargs) > This Trace class is an aspect. > class Aspect(type): > > def __init__(cls, name, bases, dict): > super(Aspect, cls).__init__(name, bases, dict) for k,v in > dict.items(): > if type(v) == type(lambda x:x): > setattr(cls, k, wrapped_method(cls, v)) > This is not an Aspect. This is your way to implement method call interception. > ************ > Observations > ************ > > Obviously, Trace is designed so that I can specify a filename when > creating an instance of it and that would use that file rather than > sys.stdout. > > Observers should probably be able to register for particular events > (i.e., just before). They should be able to unregister. It should also > be possible to register for some classes, some methods, and not others. What about module functions ? Bounded methods ? Using metaclass for call interception is too restrictive I believe. > What is a good way to write the rules for enrolling in notifications? > (And what's the word for this that AspectJ uses?) Joinpoint... but you already found it ;) > > I explicitly pass self from the wrapped_method instance to the actual > wrapped method. However, this is not really the instance of the class, > it's the instance of the wrapped_method object. How do I pass the > actual instance to the wrapped method--whether explicitly or implicitly? > This is the trickier part. When you do : setattr(cls, k, wrapped_method(cls, v)) you substitute a function (actually an unbounded method) by a callable object. Unfortunately when you'll invoke this object with a classical method call, Python will not pass the instance as the first argument. I only know two ways to substitute an unbounded method by an object that will allow to retrieve the instance argument : - providing a function, and take benifit of nested_scopes to retrieve all the information from your context - create an object through the 'new' package (new.instancemethod) that was broken for new type objects in 2.2, and fixed in 2.2.1 So your wrapped_method class is not sufficient per se to achieve this goal. > I should probably explicitly set the metaclass for wrapped_method, > Trace, Observer, and even VirtualClassError to "type" (the default > metaclass) to avoid weird infinite loops where the members of the aspect > framework are themselves being aspected. > I don't think that metaclass'ing is the good thing to do, but that's just me. > I need to think more about how this would be used. My vague impression > of AspectJ is that you use it from an IDE, specifying different > conditions for filtering classes and methods (what's the word for that > again?). When you compile with aspect support turned on, the generated > code has the aspects weaved in. What are the equivalent developer use > cases for weaving aspects into Python code? The whole point it seems to > me is that when I author the classes to be aspected, I shouldn't have to > do a thing--no subclassing, no method definition. I just write my > classes, omitting entirely any consideration of the future aspects to be > weaved in. I mean, that's the whole point, right? To simplify the > code. > Yep. And this is why I consider the metaclass thing for being too intrusive. > In the example, foo doesn't know diddly about the fact that it's being > traced. And we could turn that tracing on or off simply by changing the > module-level __metaclass__ variable. > Too intrusive. I don't believe that you can do it dynamically, at least not for classes defined at module level. They will be created with the metaclass defined at compilation time. > It would be easy to add aspects for error handling. This is a very > quick and dirty example for error notification: > Yes. Interception of raised exception is a good (and easy ;) feature. Just try to go a step further with 'around' methods. Thanks, for this posting Mark. Reminds me that aop is my task list for the moment I will have some spare time (not so far I hope ;) Just to give some hints on aop, this is what I wrote as a reminder 6 months ago along with a more complete implementation of aop : Vocabulary pointcut an object identifying a set of joinpoints, and aggregating a set of advices joinpoint a callable function in Python (unbound method, bound method, function) advice a function that will be called when a joinpoint is reached. It may be triggered before the joinpoint is called, after, or when an exception occurs. An advice may also be set around a joinpoint, meaning that it will be able to do some job before and after the joinpoint runs, but it will have to call the joinpoint himself. aspect a class that contains poincuts and their related advices. And a UML'ish model : +-------------+ n +-------------+ 1 +-------------+ | PointCut | - - - -> | JoinPoint |-------->| Function + +-------------+ +-------------+ +-------------+ | | | | V 1 | +-------------+ n | | AdviceStack |<-----------+ +-------------+ | | V n +-------------+ | Advice | +-------------+ - A pointcut uses several joinpoints - Since a joinpoint may participate in several pointcuts, it will have to trigger several set of advices (AdviceStack) related to each of the pointcut it belongs to. - A joinpoint is related to a Python function. It will intercept calls to it. +-------------+ 1 +-------------+ | JoinPoint |---------->| Function | +-------------+ +-------------+ ^ n | | +-------------+ | CallableSet | +-------------+ A | +-----------------+-------+---------+----------------+ | | | | +--------------+ +-------------+ +-------------+ +-------------+ |ClassicalClass| | TypeClass | | Module | | Instance | +--------------+ +-------------+ +-------------+ +-------------+ - A Python function related to a joinpoint belongs to a CallableSet. - A CallableSet can be a classical python class, in which case the function is an unbound method. - A CallableSet can be a new python class, in which case the function is an unbound method. - A CallableSet can be a python instance, in which case the function is a bound method. - A CallableSet can be a python module, in which case the function is a standard method. Best regards, Pedro From Chris.Barker at noaa.gov Fri Jun 21 15:53:02 2002 From: Chris.Barker at noaa.gov (Chris Barker) Date: Fri, 21 Jun 2002 12:53:02 -0700 Subject: do...while References: Message-ID: <3D13841D.F3C9EB5B@noaa.gov> Bjorn Pettersen wrote: > Doing a quick search over our C++ libraries (~900KLoc), "do {} while()" > seems to be used in right around 3% of the loops (including while, for; > excluding recursion). I was surprised that it was used so rarely, but them I realized that in C/C++, assignment returns a value, so you can do the equivalent of: while line = file.readline(): .... which is used a lot, but can't be done in Python. That's still not a reason to add the construct, but it is a commonly occuring structure. -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From emile at fenx.com Thu Jun 27 21:56:08 2002 From: emile at fenx.com (Emile van Sebille) Date: Fri, 28 Jun 2002 01:56:08 GMT Subject: Most elegant python program to date. References: Message-ID: "Delaney, Timothy" wrote in message news:mailman.1025223937.24431.python-list at python.org... > > From: PoulsenL at capecon.com [mailto:PoulsenL at capecon.com] > > > > examples of its prose. Are there any nominations for the most elegant > > example of a python program to date. Not sure under what > > print 'Hello, world!' > Cool... except the the single/double quotes, that's pure BASIC! ;-) OK-so-maybe-the-case-of-print-is-wrong-too ly y'rs, -- Emile van Sebille emile at fenx.com --------- From bokr at oz.net Thu Jun 13 16:44:35 2002 From: bokr at oz.net (Bengt Richter) Date: 13 Jun 2002 20:44:35 GMT Subject: Type subclassing: bug or feature References: Message-ID: On 13 Jun 2002 16:08:40 -0400, aahz at pythoncraft.com (Aahz) wrote: >Consider the following code: > >class MyStr(str): > def contains(self, value): > return self.find(value) >= 0 > >s = MyStr("hello, world!") >s = s.capitalize() >if s.contains('Hello'): > print "Found it!" > >It fails with an AttributeError when it calls s.contains(), because >s.capitalize() returned a str instead of a MyStr. Anyone want to take a >whack at defending this as the correct behavior? I don't think you could generally coerce base class method results to subclass instances, so I think it has to be explicit. Maybe it could be done with a method list for a more compact way (using a metaclass?) Anyway: >>> class MyStr(str): ... def contains(self, value): ... return self.find(value) >= 0 ... def capitalize(self): ... return MyStr(str.capitalize(self)) ... >>> s = MyStr("hello, world!") >>> s = s.capitalize() >>> if s.contains('Hello'): ... print "Found it!" ... Found it! Regards, Bengt Richter From marklists at mceahern.com Thu Jun 13 08:56:22 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 13 Jun 2002 07:56:22 -0500 Subject: get a list of classes in this module In-Reply-To: Message-ID: [Christian Tanzer] > I'd recommend to use a custom metaclass to put the classes in question > into the dictionary -- this way some other module can add credit card > classes and it should still work. Hmm, putting the other credit card classes in other modules creates a new problem: I have to import those modules. Another way of looking at what I'm trying to do--that I failed to state explicitly--is that I'm trying to get a list of all the available classes at runtime, via introspection, without having to specify them explicitly. Having to import the other modules amounts to having to specify them explicitly. Here's another solution to the problem, fwiw, using classmethod to stick the factory method inside the base class: class CreditCardValidation(object): def factory(cls): classes = cls.__subclasses__() d = {} for c in classes: d[c.__name__] = c return d factory = classmethod(factory) def validate(self, card_number): raise NotImplementedError("Subclasses must override.") class Visa(CreditCardValidation): def validate(self, card_number): print "Visa: %s" % card_number class MasterCard(CreditCardValidation): def validate(self, card_number): print "MasterCard: %s" % card_number f = CreditCardValidation.factory() card_type = "Visa" card_number = "5105 1051 0510 5100" validator = f[card_type]() validator.validate(card_number) Thanks for the suggestion. I find it much easier to just utilize __subclasses__ than to peer into the mysteries of metaclass programming. Cheers, // mark - From jepler at unpythonic.net Thu Jun 27 12:00:15 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 27 Jun 2002 11:00:15 -0500 Subject: Var substitution In-Reply-To: References: Message-ID: <20020627160014.GE3710@unpythonic.net> Guy, "A good FORTRAN programmer can program FORTRAN in any language." -- Allen Brown. You're asking questions about how to do things in Python that, while possible, are not idiomatic. It sounds like you're probably coming from background in another language or trying to directly translate a program written in another language. While people are giving you good answers about how to do the things you're asking about, I suspect that you would be better off in the long run learning to write Python programs than to write programs for language XXX in Python. Jeff From claird at starbase.neosoft.com Tue Jun 25 08:33:14 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 25 Jun 2002 07:33:14 -0500 Subject: Python and Eclipse References: <3D17FAF4.35CC9F1B@earthlink.net> Message-ID: <81CC01E58BF2A99B.DFCD5EC6E4654907.32D731380951B9CA@lp.airnews.net> In article <3D17FAF4.35CC9F1B at earthlink.net>, Joseph A Knapka wrote: >Hi folks, > >I am interested in having Python support in >Eclipse - interested >enough to contribute code, or to tackle the >task myself, if need be. Of course, I'd like >the Python support to be at least as good as the >Java support, which is a pretty tall order, >'cause the Java support in Eclipse is awfully >damn good --- it nearly allows me to *enjoy* >writing Java code :-) > >Anyway, I know some other folks have expressed >interest in this as well, and I'd like to hook >up with them. If you're working on Python+Eclipse >and you've got code in any state of completion, >I'm willing to alpha- or beta-test, fix stuff, >add new stuff, etc. . . . Can you say a few more words about Eclipse? It ... well, I'm wary. I understand its marketing more than its technology, and on hostile days, I think it's *only* marketing. Maybe you can make it more appealing. "[It] nearly allows me to *enjoy* writing Java ..." is certainly a good start. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From sholden at holdenweb.com Mon Jun 17 20:11:09 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 17 Jun 2002 20:11:09 -0400 Subject: why not "'in' in 'in'"? References: Message-ID: "Grant Griffin" wrote ... [ ... ] > > just-because-guido-allows-it-doesn't-mean-you-should-use > -it-injudicious-ly y'rs, But you don't mind complaining about the rules he has painstakingly established for sequence membership. Characters have always been strings of length one in Python, and that *does* make strings slightly anomalous. Your arguments that sequence membership should differ between string and other sequences are unconvincing. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From rajarshi at presidency.com Tue Jun 11 12:35:29 2002 From: rajarshi at presidency.com (Rajarshi Guha) Date: Tue, 11 Jun 2002 12:35:29 -0400 Subject: sftp interface for python Message-ID: Hi, I need to Python'ize some scripts which involve sftp. Is there any sftp interface for Python? Or is the best way system (or popen et al)? TIA, Rajarshi Guha From sholden at holdenweb.com Tue Jun 4 12:47:54 2002 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 4 Jun 2002 12:47:54 -0400 Subject: Behavior of += (was Re: [Python-Dev] Customization docs) References: <9A5L8.232032$%u2.84870@atlpnn01.usenetserver.com> <20020604112824.B24006@unpythonic.net> Message-ID: <019301c20be7$933acb50$7201a8c0@holdenweb.com> ----- Original Message ----- From: "Jeff Epler" To: "Steve Holden" Cc: Sent: Tuesday, June 04, 2002 12:28 PM Subject: Re: Behavior of += (was Re: [Python-Dev] Customization docs) > On Tue, Jun 04, 2002 at 12:01:56PM -0400, Steve Holden wrote: > > >>> a = b = [1,2,3] > > >>> a += [4] > > >>> a, id(a), b, id(b) > > ([1, 2, 3, 4], 269472088, [1, 2, 3, 4], 269472088) > > >>> > > > > Where did the rebinding take place? ISTM that "a" is still bound to the same > > list, which has been modified in place. > > Sure it rebinds a (just to the same object formerly bound to it) .. > >>> class X: > ... def __setattr__(self, a, v): > ... print "rebinding %s, sucker" % a > ... self.__dict__[a] = v > ... > >>> x = X() > >>> x.a = b = [1,2,3] > rebinding a, sucker > >>> x.a += [4] > rebinding a, sucker > >>> x.a is b > True > Interesting. But there was no need to call me a sucker. > Or are you saying that in > a = b = [1,2,3] > a = b > the second statement isn't a rebinding operation? That seems like an > odd position to take.... > It wouldn't be the oddest I've ever taken, but now you have clarified your assertion I understand what you were saying. > > Clearly an explicit assignment to a tuple element is always going to fail, > > so I don't really see what this would tell you. > > But you're claiming that there *is* no binding, so it would be > surprising that this augmented assignment wouldn't work > >>> t = ([1]) > >>> t[0] += [2] > t[0] "isn't" being rebound (according to your above logic, since if the > operation could complete, the "is" relation would hold between old t[0] > and new t[0]) .. but, of course, this actually causes a traceback. > Indeed, I now understand exactly why the error occurs. I have to say I still think that the existing behavior is reasonable. > I hate augmented assignment more and more each day, but at least I think > I understand it. Your claim that there is no rebinding operation makes > me think that you may not. > Possibly. In fact it seems to me that it's only *because* a rebinding does in fact take place that the tuple element assignment fails, so it's just as well it does. There's no point hating augmented assignment. Just don't use it if you find it gives confusing results. happy-when-i-didn't-understand-and-happy-now-i-do'ly y'rs - steve ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From martin at v.loewis.de Sun Jun 9 15:50:02 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 09 Jun 2002 21:50:02 +0200 Subject: Embed python in multi-thread environment References: Message-ID: Arlo writes: > it seems i can't call PyObject_CallObject twice at the same process? You can, but you must hold the GIL while doing so. In each thread, allocate a thread state (perhaps just for the lifetime of the Python call), and allocate the GIL. Regards, Martin From romany at actimize.com Sun Jun 9 10:29:50 2002 From: romany at actimize.com (Roman Yakovenko) Date: Sun, 9 Jun 2002 16:29:50 +0200 Subject: Problem with wxPython Message-ID: <7647A9F4B298E74DB6793865DA67285004AD78@exchange.adrembi.com> Could you post small piece of code. I have some computer configuration and it works fine to me. Also try Boa IDE. It is very helpful. Roman -----Original Message----- From: Stephane Larouche [mailto:steph_lar at videotron.ca] Sent: Saturday, June 08, 2002 3:57 AM To: python-list at python.org Subject: Problem with wxPython I use wxPython 2.3.2.1 with Python 2.2.1 on multiple computers running WinNT 4.0 SP6. On one of those computers, which has a setup that is identical to the setup of the other computers (I think), wxPython software crashes when a wxFrame is initialized with any of the window styles wxMAXIMIZE_BOX, wxRESIZE_BOX or wxSYSTEM_MENU (or wxDEFAULT_FRAME_STYLE that includes those styles). Even the demo provided with wxPython crashes. According to DrWatson, the crash is caused by a stack overflow during the execution of the function wxTransformMatrix::operator-. Have your ever seen the same problem? Is there a workaround? Thank you for your help! Stephane Larouche steph_lar at videotron.ca -- http://mail.python.org/mailman/listinfo/python-list From woodsplitter at rocketmail.com Fri Jun 21 01:00:35 2002 From: woodsplitter at rocketmail.com (David Rushby) Date: 20 Jun 2002 22:00:35 -0700 Subject: C extension/multithreading question Message-ID: <7876a8ea.0206202100.b9d6383@posting.google.com> Is it safe to call PyThread_acquire_lock and PyThread_release_lock on a PyThread_type_lock from a native thread that: a) was not created by Python b) has no bootsrapped Python thread state c) does not have the GIL locked ? It appears that this is safe, since the GIL itself is of type PyThread_type_lock, but I want to make sure that I'm not missing some fatal subtlety. Thanks. From peter at engcorp.com Sun Jun 9 03:06:45 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 09 Jun 2002 03:06:45 -0400 Subject: Program mysteriously STOPS! References: Message-ID: <3D02FE85.EA48FBEA@engcorp.com> LJD wrote: > > Hi all: > > The following code is designed (at least thats my intent) to run forever. > The program should sit in a loop until it connects with the server. It > should just loop and loop and loop. > > It does, for a while, maybe five or ten minutes, but then the process just > seems to vanish. It's in the c1==0 loop when it quits. When I do a PS AUX, > the process is just gone. Obviously it quit, but more importantly WHY???, > and what can I do so it doesn't? You may need to investigate socket.shutdown() and socket.close() ... Especially on Windows, you have a finite number of sockets you can have open simultaneously. Since socket resources are not necessarily freed by the underlying OS immediately upon Python releasing the reference as it goes out of scope, you may need to be explicit. Haven't done this enough under Linux to help beyond that... -Peter From menucool at yahoo.com.cn Tue Jun 18 06:46:30 2002 From: menucool at yahoo.com.cn (coolmenu) Date: 18 Jun 2002 03:46:30 -0700 Subject: Can python have lib to display PDF ? Message-ID: i want a python application to display end edit pdf. where are the lib pdf for python? thank From elfinman at yahoo.com Wed Jun 26 17:50:25 2002 From: elfinman at yahoo.com (Timothy H) Date: Wed, 26 Jun 2002 17:50:25 -0400 Subject: Memory Monitor References: <3D1894B5.720EB7F7@bioreason.com> <200206252139.QAA88038@starbase.neosoft.com> <3D18E752.7A5A4EAC@bioreason.com> Message-ID: <20020626.175009.711845894.6390@yahoo.com> In article <3D18E752.7A5A4EAC at bioreason.com>, "Mitch Chapman" wrote: > Cameron Laird wrote: >> Mitch Chapman wrote: >> > os.system("cat /proc/self/status | grep VmSize") >> Rather than >> os.system("grep VmSize /proc/self/status") >> ? > > No, that's also concise =8) > Concise, but it doesn't work. Then /proc/self/status is reporting the memory usage for grep, not for the python interpreter+script. From cliechti at gmx.net Fri Jun 28 16:45:43 2002 From: cliechti at gmx.net (Chris Liechti) Date: 28 Jun 2002 22:45:43 +0200 Subject: Dialing out on MODEM References: Message-ID: "David McInnis" wrote in news:mailman.1025270142.10532.python-list at python.org: > This is my object > >>>> import serial >>>> modem = serial.Serial >>>> modem = serial.Serial(2) >>>> modem.write("atdt3120992\n") somtimes it it's a '\r\n' and maybe you need to send the escape sequence first, to enter the command mode. if i remember correctly thats 3 times ESC and then wait 100ms or so. either google or your modem manual should help. i had to do somthing like that to dial with pyserial, but unfortunately the code is on an other machine... chris -- Chris From donn at drizzle.com Mon Jun 10 22:34:58 2002 From: donn at drizzle.com (Donn Cave) Date: Tue, 11 Jun 2002 02:34:58 -0000 Subject: M2Crypto: select() behaves weird on SSL socket References: <3D04ECED.2030202@NOSPAMREMOVETHISxs4all.nl> <3D04FBF5.8090407@NOSPAMREMOVETHISxs4all.nl> <3D04FE2F.6070302@NOSPAMREMOVETHISxs4all.nl> Message-ID: <1023762896.869994@yasure> Quoth Irmen de Jong : ... | The manual page of select(2) says: | "select waits for a number of file descriptors to change status. | Three independent sets of descriptors are watched. Those | listed in readfds will be watched to see if characters | become available for reading (more precisely, to see if a | read will not block - in particular, a file descriptor is | also ready on end-of-file), those in writefds will be | watched to see if a write will not block, and those in | exceptfds will be watched for exceptions." | | The way I interpret this is that -buffering or not- select must | return a FD if there is more data available. In my case, the SSL | socket indeed has more data available, and a recv() on the socket | will not block. I therefore think that either M2Crypto or OpenSSL | is doing the wrong thing because select() doesn't behave as it should? | The recv() may read from a buffer, I don't care, but it doesn't | block on my next call and thus I expect select() to return the socket | as being ready for reading... am I wrong here? Wrong, I'd say. SSL's buffer, like the file object's stdio buffer, is user process storage. From select's point of view (the low level device) you have already read that data, and it doesn't know or care what you did with it. I see my reply earlier today followed up a separate thread, after you posted your initial question twice. If you haven't seen it, a hint: SSL_pending(self->ssl.) (I don't know much more than that, anyway.) Donn Cave, donn at drizzle.com From i.linkweiler at gmx.de Sun Jun 9 05:10:20 2002 From: i.linkweiler at gmx.de (Ingo Linkweiler) Date: Sun, 09 Jun 2002 11:10:20 +0200 Subject: Comparison: HTTP with Java, Perl or Python References: Message-ID: <3D031B7C.8010207@gmx.de> > > >WHat you want to do reminds me of this (open source) project: > >http://www.bagley.org/~doug/shootout/ > >- it already has a framework/examples for many things you >are measuring. (and for MUCH MUCH more languages). >The project seem to be frozen but everybody can >advance it further. > > thanks, that?s it! Ingo From sjmachin at lexicon.net Fri Jun 7 18:40:41 2002 From: sjmachin at lexicon.net (John Machin) Date: 7 Jun 2002 15:40:41 -0700 Subject: question on pattern References: <3D007E96.3010505@rmb.co.za> Message-ID: Ulrich Pfisterer wrote in message news:<3D007E96.3010505 at rmb.co.za>... > I want to do a pattern match on a string that spans multiple lines (c++ > style comments, re.match('(/\*.*?\*/)', filestring) > If I use the re.findall(pattern, string) method it only finds those > matches that are on a single line. If I use re.match(pattern, string, > DOTALL) it spans multiple lines but only finds the first match. > Any help on this one would be greatly appreciated. You have got an answer to your problem of how to get DOTALL behaviour with .findall(). However you should be aware that your pattern can match strings that are not syntactically C or C++ comments. Here is an example from page 172 of "Mastering Regular Expressions" by Jeffrey E. F. Friedl: const char *cstart = "/*", *cend = "*/"; I'd agree that it's a pathological case. I'm just pointing out that in most work on program source files, to be 100% correct you need to have a lexical analyser for the language in question. Regexes won't take you the whole distance. From timo at alum.mit.edu Fri Jun 28 00:09:52 2002 From: timo at alum.mit.edu (Timothy O'Malley) Date: Fri, 28 Jun 2002 00:09:52 -0400 Subject: explain this pickle issue to me... Message-ID: hola. Can someone explain why I can't seem to use Pickle (actually cPickle) in combination with execfile? Sample code: ----------------------------------- Python 2.2.1 (#1, 06/20/02, 11:40:06) [GCC Apple devkit-based CPP 6.0] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> d = {} >>> execfile("testme.py", d) >>> q = d["writeSimple"]() >>> print `q` "(i__builtin__\nSimple\np1\n(dp2\nS'a'\nS'a'\nsS'b'\nI2\nsb." >>> d["readSimple"](q) Traceback (most recent call last): File "", line 1, in ? File "testme.py", line 14, in readSimple s = cPickle.loads(ss) AttributeError: 'module' object has no attribute 'Simple' >>> d["readSimple"].func_globals.keys() ['__builtins__', 'Simple', 'cPickle', 'readSimple', 'writeSimple'] And the testme.py file used in execfile --------------------------------------- import cPickle class Simple: def __init__(self): self.a = "a" self.b = 2 # end class A def writeSimple(): s = Simple() return cPickle.dumps(s) # end writeSimple def readSimple(ss): s = cPickle.loads(ss) assert ininstance(s, A), "Not an instance of Simple" # end readSimple --------------- As I understand it from the docs, there is a restriction in Pickle that requires class definitions to be in the global namespace in order to be found. And, it appears, I am running afoul of that restriction. But -- the last two lines of the posted sample code shows that the class definition *is* in the global namespace of the readSimple function. What's the catch? TimO From claird at starbase.neosoft.com Tue Jun 25 16:02:53 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 25 Jun 2002 15:02:53 -0500 Subject: Python daemon References: Message-ID: <680C5E8D0C5D5E02.689CD98EE6CE4D7E.6018C29C8F1E8BF9@lp.airnews.net> In article , Emile van Sebille wrote: >Cameron Laird >> This is one of the great FMMs under Unix--the under-utilization > >FMMs ? . . . OK, I was being provocative. It's the Federation of Malaysian Manufacturers. No, wait; while it *is* that, the more pertinent reading appears at . -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From peter at engcorp.com Sat Jun 1 08:12:30 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 01 Jun 2002 08:12:30 -0400 Subject: Interactive socket connection References: <3CF88F9B.1080308@saudi.net.sa> Message-ID: <3CF8BA2E.A8C42539@engcorp.com> Rayed Al-Rashed wrote: > > Hello, > > I am trying to build POP3 proxy, I want it to run from "inetd" so it should > communicate with the user using regular stdin, stdout. > I built a small code that should run as general proxy for any protocol, but > I faced the following problem, it doesn't show any output from the server > until I pass it a command [...] Are you maybe in need of a sys.stdout.flush() to get the output to be sent after the sys.stdout.write()? -Peter From glyph at twistedmatrix.com Wed Jun 26 07:03:23 2002 From: glyph at twistedmatrix.com (Glyph Lefkowitz) Date: Wed, 26 Jun 2002 06:03:23 -0500 (CDT) Subject: Python 2.2 __slots__ Bug? Message-ID: <20020626.060323.78699939.glyph@twistedmatrix.com> I'm sorry if this is a known issue. I couldn't get through to the bugtracker at sourceforge.net; it's abysmally slow and I stopped waiting for the search to run after about 15 minutes. Searches on google yielded nothing similar for 'python __slots__ bug'. I think I have discovered a weird bug in the Python interpreter. Under Python2.2, when I run this script: class foo(object): def __init__(self, n): self.n = n __slots__ = ['n'] o = None for i in xrange(43550): o = foo(o) del o o = None print "I'm fine." for i in xrange(43551): o = foo(o) del o print "I'm dead." I get "I'm fine" and then a segmentation fault. This only happens when __slots__ is defined on a new-style class. Seriously, i'm not making those numbers up -- reliably, 43551 objects will crash the interpreter; fewer will not. I don't know the code here, but I'm willing to bet Python is smashing the stack because PyType_GenericAlloc() is recursive. I get a stacktrace from gdb that looks like this: #0 0x100a3fc4 in PyDict_New () #1 0x100244e8 in _PyType_Lookup () #2 0x100249d4 in _PyObject_SlotCompare () #3 0x1001a3d4 in PyType_GenericAlloc () #4 0x1001a4fc in PyType_GenericAlloc () #5 0x1001a5b8 in PyType_GenericAlloc () #6 0x1001a5b8 in PyType_GenericAlloc () #7 0x1001a5b8 in PyType_GenericAlloc () #8 0x1001a5b8 in PyType_GenericAlloc () #9 0x1001a5b8 in PyType_GenericAlloc () #10 0x1001a5b8 in PyType_GenericAlloc () #11 0x1001a5b8 in PyType_GenericAlloc () #12 0x1001a5b8 in PyType_GenericAlloc () #13 0x1001a5b8 in PyType_GenericAlloc () #14 0x1001a5b8 in PyType_GenericAlloc () ... and so on, and so on, for longer than I had the patience to page through. (I did get to about #400, though.) Version Information: % python2.2 Python 2.2.1 (#1, May 4 2002, 11:33:48) [GCC 2.95.4 20011002 (Debian prerelease)] on linux2 And since those arguments to xrange() above look like some weird magic to me, this may also be useful to know: % free total used free shared buffers cached Mem: 253968 146192 107776 0 8008 59184 -/+ buffers/cache: 79000 174968 Swap: 262136 3168 258968 % uname -a Linux zelda 2.4.18 #1 SMP Fri Apr 26 19:18:50 CDT 2002 ppc unknown Is there any in-development code I should try running? -- | <`'> | Glyph Lefkowitz: Traveling Sorcerer | | < _/ > | Lead Developer, the Twisted project | | < ___/ > | http://www.twistedmatrix.com | -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From prema at prema.co.nz Sun Jun 16 22:42:00 2002 From: prema at prema.co.nz (Prema) Date: 16 Jun 2002 19:42:00 -0700 Subject: MS Word -- finding text References: Message-ID: Hi Mike ! Excellent -- thanks very much for your time and sharing. Would have taken a while to work through that -- I can't wait to try it out! I'll post to this thread as to how I got on Kind regards Thanks again Mike Mike Brenner wrote in message news:... > The COM objects (like Project, Word, Excel, etc.) sometimes return stuff in Unicode format. When they do, the python str() function dies when converting non-ASCII unicode characters. > > To avoid this problem, I use the following conversion routine. After making the necessary check for None, it attempts a quick conversion str() first. When necessary, it slowly goes through each character, handling the exceptions that are raised. > > The default is a prime because that is the most common character that hits me in Word and Excel documents. Instead of coding it as an ASCII single-quote characters, these applications code it as a more "beautiful" character, so it kills the python str() function. > > You may or may not wish to change the return to eliminate the string.strip there, depending on your needs. > > You could make a separate function that has just the TRY and the EXCEPT in it, in order to use the MAP function instead of the for loop. > > Mike Brenner > > > def phrase_unicode2string(message): > """ > phrase_unicode2string works around the built-in function str(message) > which aborts when non-ASCII unicode characters are given to it. > """ > if type(message)==types.NoneType: > return "" > try: st=str(message) > except: # untranslatable unicode character > list=[] > for uc in message: > try: > c=str(uc) > except: > c="`" > list.append(c) > # Note: because it raises exception instead of returning > # a default characters, we cannot use map() here. > st=string.join(list,"") > return string.strip(st) > > ------------------------ > > Mike Prema wrote: > > ####### > from win32com.client import Dispatch > W=Dispatch('Word.Application') > D=W.Documents.Open('c:\\windows\\Desktop\\TOR.doc') ## Test Doc > FindRange=D.Content > F=FindRange.Find.Execute('Conman','True') > print FindRange.Text > ####### > str() doesn't seem to work in this case > I tried using the codecs library but I think I am missing something From neal at metaslash.com Sat Jun 8 20:07:54 2002 From: neal at metaslash.com (Neal Norwitz) Date: Sun, 09 Jun 2002 00:07:54 GMT Subject: Simple pychecker question References: Message-ID: On Fri, 07 Jun 2002 16:44:50 -0400, Michael Gilfix wrote: > Pychecker doesn't seem to like named arguments (such as def > f(f='blah'), or sometimes, it's handy in __init__). Why is that? Are > they considered bad style in some respects? How about use in __init__ > functions? Are you saying that there is a warning message? Or that the code breaks pychecker? In older versions, the default for this warning was turned on. It is off in more recent versions. I personally think that superfluous use of named args are bad, but that the feature is good when used properly. For example, with your code above, calling f(f=2) would be better written f(2). However for Tkinter, named args can be useful when there are a bunch of parameters and you only want to use the last. Neal From martin at v.loewis.de Sun Jun 9 16:00:18 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 09 Jun 2002 22:00:18 +0200 Subject: (no subject) References: Message-ID: Attila Horvath writes: > - provide [generic] CGI functionality > and if possible... Please have a look at the cgi module. > - generate dynamic (DHTML) responses to CGI input parameters There are several strategies, but I recommend to use plain print statements. You can use HTML templates by putting multiline strings into your scripts which offer %s or %(key)s interpolation. Regards, Martin From jepler at unpythonic.net Thu Jun 13 13:51:52 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 13 Jun 2002 12:51:52 -0500 Subject: Translating Tcl/Tk code into Python/Tkinter help please... In-Reply-To: References: Message-ID: <20020613175152.GE25416@unpythonic.net> If you're rewriting your tk into Python, don't use a sub-python to create this data. Otherwise, catch {exec echo hi} output puts "output was $output" and import os output = os.popen("echo hi").read() print "output was %s" % output seem to behave about the same. The reason for the use of of 'catch { ... } output' instead of 'set output [...]' is because a nonzero exit status from an 'exec' is an error in Tk. (Tk errors are similar to Python exceptions, with "if {[catch]} {...}" being similar to 'try/bare except' and "error" being similar to "raise". Jeff From tjreedy at udel.edu Mon Jun 3 09:54:45 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 03 Jun 2002 13:54:45 GMT Subject: Graph distances, how can I speed it up? References: <33803989.0206030235.4134d33e@posting.google.com> Message-ID: "Miki Tebeka" wrote in message news:33803989.0206030235.4134d33e at posting.google.com... > Hello All, > > I'm trying to calculate distances in a graph. (The ultimate goal is > to calculate the distances between verbs in WordNet) > > The graph is built edge after edge and each time I recalculate the > distances matrix. However this takes ages to complete. (will finish in ~50H). There is a reasonably efficient algorithm for computing the distance between vertices in a graph. I am sure that this is *much* more efficient than doing so incrementally. I am pretty sure that I would be available in the graphical algorithms section of the C-coded Boost package, which has a Python wrapper. (Don't know details.) > Distances are held in hash table of pairs (x,y) -> distance. A 2-d array would take about the same space and probably be quicker. A 2-d Numerical Python array, which you would want for a large graph, would be better both ways. > For each vertex a hash of all vertexes conncted to it is saved > to improve distance update. As near as I can tell, you only access the lists of neighbors as lists, so store them that way. > return self.forward.get(x, {}).keys() > return self.backwards.get(x, {}).keys() But biggest boost will come from using C-coded function. Terry J. Reedy From sadams123 at optushome.com.au Wed Jun 19 16:05:36 2002 From: sadams123 at optushome.com.au (Steven Adams) Date: Thu, 20 Jun 2002 06:05:36 +1000 Subject: How to Store Binary data in a *.py module References: <3D10E0E9.906DF517@noaa.gov> Message-ID: <3d10e411$0$31829$afc38c87@news.optusnet.com.au> > I know a Python string can contain an arbitrary set of bytes, but I > don't know how to express binary data as a literal. If I were to try to > use r" ..." and I happened to have a byte that matched the ", it would > be mis-parsed. I'm imaging that UUencoding or something might solve my > problem, but I don't know anything about that. > > Anyone have an idea?? I've stored GIFs using base64 encoding via the base64 module and it seemed to work fine. in the interpreter read in the file in binary mode base64 encode it copy and paste the encoded string to your module decode it when you want use it as binary data again Steven From max at alcyone.com Wed Jun 12 22:33:38 2002 From: max at alcyone.com (Erik Max Francis) Date: Wed, 12 Jun 2002 19:33:38 -0700 Subject: why not "'in' in 'in'"? References: Message-ID: <3D080482.7A7FD514@alcyone.com> Grant Griffin wrote: > So why is the "in" operator limited to single characters when used as > a > membership operator? This peculiar lack of generality seems a bit > (dare I say > it?) "non-Pythonic". On the contrary, it is exquisitely Pythonic. You used the magic word yourself: _membership_. A string is a sequence of characters, so when testing membership with the `in' operator, the left-hand side of the expression should be a character (really a string of length one). `in' tests membership, not for the existence of subsequences. Would you have expected [1, 2] in [1, 2, 3, 4] to evaluate to true? -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Who'd ever think it / Such a squalid little ending \__/ The American and Florence, _Chess_ Church / http://www.alcyone.com/pyos/church/ A lambda calculus explorer in Python. From peter at engcorp.com Mon Jun 17 21:32:33 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 17 Jun 2002 21:32:33 -0400 Subject: pychecker + XEmacs References: <3d0de483$0$3881$e4fe514c@dreader4.news.xs4all.nl> Message-ID: <3D0E8DB1.E67264A6@engcorp.com> Boudewijn Rempt wrote: > > Has anyone succeeded in combining pychecker and XEmacs (or emacs)? I'm > checking a large project I began in 1999, and which is full of the most > atrocious errors, and I'd like to click on the line that mention the error > and be transported there, just like when you run a python program from > XEmacs and get a stacktrace. Phlip's PyUnitBrowser (hope I got that right) seemed to be sporting or about to sport an interface with PyChecker.... might be a start. -Peter From emile at fenx.com Thu Jun 6 15:25:01 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 06 Jun 2002 19:25:01 GMT Subject: Efficient python programming... References: Message-ID: Shagshag13 > I'm looking for any state of art, optimizing techniques, tips, that a > python beginner couldn't know by itself, but should learn and > would be aware to write "efficient and good looking"python's code... > > (not the kind of thing which made you an obfuscated python nerd, > but that "map" should be preferred to "for in loop" if possible, that > dictionary are very well optimized, etc.) > I think the advise you'll generally get is to write first, then profile, then optimize where needed. Those optimizations may well involve using map, or numpy, or c-extensions, etc... But emphasis on optimization first is probably time mis-spent. -- Emile van Sebille emile at fenx.com --------- From pyth at devel.trillke.net Thu Jun 13 18:38:53 2002 From: pyth at devel.trillke.net (holger krekel) Date: Fri, 14 Jun 2002 00:38:53 +0200 Subject: returning traceback strings In-Reply-To: <20020613181109.A1019@gurthang.twcny.rr.com>; from mboedick@mboedick.org on Thu, Jun 13, 2002 at 06:11:09PM -0400 References: <20020613181109.A1019@gurthang.twcny.rr.com> Message-ID: <20020614003853.M6609@prim.han.de> Matthew Boedicker wrote: > Hello, > > I am looking for something exactly like traceback.print_exc(), but instead > of writing the traceback text to a filehandle, I want it to return it to > me as a string. I was unable to find any way to do this using the traceback > module, since everything there seems to be in terms of file handles being > passed around. > > The problem is I need to pass the entire multi-line traceback string to a > file-like object's write() method in one call, not line by line. > > This is the best workaround I was able to come up with: > > import cStringIO > import traceback > > def print_exc_str(): > buf = cStringIO.StringIO() > traceback.print_exc(file=buf) > return buf.getvalue() this is a straightforward solution. if you don't want cStringIO you could do: import traceback class fakefile(list): write=list.append def get_exception(): ff=fakefile() traceback.print_exc(file=ff) return "\n".join(ff) > Any suggestions for a better way? What about the traceback module using > strings internally, and wrapping another layer around that to write to files > and file-like objects? The traceback module seems to route every print through '_print' (look into traceback.py) but you can't just replace 'file' with a string, because strings are immutable. You have to use a mutable type like a list . holger From whisper at oz.net Thu Jun 27 19:55:03 2002 From: whisper at oz.net (David LeBlanc) Date: Thu, 27 Jun 2002 16:55:03 -0700 Subject: Pythoniac: Thoughts on a hardware Python processor In-Reply-To: <7xeletjxtm.fsf@ruckus.brouhaha.com> Message-ID: > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Paul Rubin > Sent: Wednesday, June 26, 2002 18:49 > To: python-list at python.org > Subject: Re: Pythoniac: Thoughts on a hardware Python processor > > > I don't think it makes sense to stick with existing Python bytecodes > for hardware execution. Take a look at the work done on Lisp machines > in the 70's and 80's instead. Ah yes, thanks for reminding me. The Self project claimed to have gotten Self to run in the mid 90's percentile of "C speed", largely by making as many primatives as possible actual machine ops of the host processor - not too good for portability. OTOH, Self has many of the complexities of Python, and if this is true, this is blazing speed. For anyone that's interested, there is still a Self website (and by darned, a new release this year!) at http://research.sun.com/self/index.html and there are some good papers there on their compiler techniques. http://research.sun.com/self/release/optionalFiles.html offers the sources to the Self VM (in C++ and "Sparc-asm") Of course, some of the Self guys went on to another project at Sun: Java. I've read somewhere that Java HotSpot JIT compiler tech came out of the Self work (oops, there it is on one of the Self pages). Actually, Java and this idea of hosting Python on Forth brings up an interesting question: If Sun can't make a VM that will run everywhere, why would a Forth based Python implementation do any better? Dave LeBlanc Seattle, WA USA From jdhunter at nitace.bsd.uchicago.edu Sat Jun 29 16:14:31 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Sat, 29 Jun 2002 15:14:31 -0500 Subject: can't import generators Message-ID: I am having trouble working with generators. Anyone know what might cause this behavior: > /usr/local/bin/python2.2 Python 2.2.1 (#1, Apr 22 2002, 21:20:54) [GCC 3.0.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from __future__ import generators Traceback (most recent call last): File "", line 1, in ? ImportError: cannot import name generators >>> Thanks, John Hunter From fperez528 at yahoo.com Thu Jun 20 15:43:48 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Thu, 20 Jun 2002 13:43:48 -0600 Subject: logical statements (in Python and Numeric) References: <3D11F1B2.21587F31@lanl.gov> <3D122C5D.C6985686@noaa.gov> Message-ID: Chris Barker wrote: > One solution is to use the bitwise operators instead: > y = y + (x >= -2. & x < 0.) * (x + 6.) > Are you sure? This is what I get: In [11]: x = arrayrange(-4.,2.+.001,.001, Float) In [12]: x >= -2. & x < 0. --------------------------------------------------------------------------- TypeError Traceback (most recent call last) ? TypeError: unsupported operand type(s) for &: 'float' and 'float' That's why I suggested logical_and() as a workaround. But maybe I'm missing something. Cheers, f. From mfranklin1 at gatwick.westerngeco.slb.com Wed Jun 26 15:51:46 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Wed, 26 Jun 2002 19:51:46 +0000 Subject: printing (again!!) In-Reply-To: References: Message-ID: <200206261855.g5QItRM21915@helios.gatwick.geco-prakla.slb.com> On Wednesday 26 Jun 2002 5:57 pm, Geoff Tarrant wrote: > I want to use Python as the language in a Computing course that I teach. > However, I can't find a way that is relatively straightforward to send data > to a printer in a Windows environment. If I can't find a way around this, > I will have to revert to Delphi or VB. Please help. I like the idea of > sending 20 or so Python programmers to University each year. > > Geoff Tarrant Geoff, Get hold of the excelent win32 extension for python (url????) Then somthing like this: (untested since I wrote it about a year or two ago!) import win32print printer_list=[] for p in win32print.EnumPrinters(win32print.PRINTER_ENUM_CONNECTIONS): printer_list.append(p[2]) for p in win32print.EnumPrinters(win32print.PRINTER_ENUM_LOCAL): printer_list.append(p[2]) default_printer=win32print.GetDefaultPrinter() printer = win32print.OpenPrinter(default_printer) jid = win32print.StartDocPrinter(printer, 1, ('Page %i' %copy, None, 'RAW')) bytes=win32print.WritePrinter(printer, open(file, 'rb').read()) win32print.EndDocPrinter(printer) win32print.ClosePrinter(printer) Please not this is sending a file's contents to the printer (as it happens a postscript file) Cheers Martin From steve.menard at vodeotron.ca Sat Jun 29 20:21:54 2002 From: steve.menard at vodeotron.ca (Steve Menard) Date: Sat, 29 Jun 2002 20:21:54 -0400 Subject: Is this a __slot__ bug? Message-ID: OK, this is probably me not understanding something, but then again, you never know. First things first, I love __slots__. For the paranoid programmer I am, knowing I will never again assing to a variable with a typo and then wonder ehat the hell is going wring is a godsend. However, I also love(need) private variables (those __X). It seems they dont work with slots. try the following simple example under ptyon 2.2 on linux : class O(object) : __slots__ = [ '__a' ] def __init__(self) : object.__init__(self); self.__a = 3 o = O() I get thoe following error : AttributeError: 'O' object has no attribute '_O__a' Now, I know I can easily work around this by manually obfuscating the private variables names in the __slots__, but I would rather not. Feels wrong somehow to rely on what should be a hidden way of generating private variables. So if this is by design, I will not agree but I will do the workaround. If not, well then seems I founda bug :) Steve From chouster at uclink4.berkeley.edu Wed Jun 19 15:51:16 2002 From: chouster at uclink4.berkeley.edu (Chris) Date: 19 Jun 2002 12:51:16 -0700 Subject: Writing to Excel Message-ID: <79b54d28.0206191151.52ee78a3@posting.google.com> Hi I'm using a Python cgi script to write the contents of a table to an Excel sheet. I retrieve all the information fine but it seems like Excel doesnt want to print more than one line for me. It prints 'headerLine' but nothing more. Why??? ... headerLine = "some crap" sys.stdout.write( Html.header( 'application/x-msexcel' ) ) print string.strip(headerLine) allText = "" ... # set allText = "some other crap" ... print allText Im dismayed that this only will print the first print line I specified to the Excel page. The Html module is a proven-to-work module I've obtained so I'm 99.99% sure that's not the problem. I'm using the latest version of python, winNT, and using IE Explorer 5.5. Chris Chris From skip at pobox.com Tue Jun 25 09:11:08 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 25 Jun 2002 08:11:08 -0500 Subject: Thread Memory Leak In-Reply-To: References: Message-ID: <15640.27628.444843.841517@12-248-8-148.client.attbi.com> Marco> while 1: Marco> listThread = [] Marco> for i in range(50): Marco> listThread.append( threading.Thread( None, runthread ) ) Marco> for i in listThread: Marco> i.start() Marco> for i in listThread: Marco> i.join() Marco> pid = os.getpid() Marco> print "===================================" Marco> os.system( "ps -o vsize,rss %d" % pid ) You never remove any thread objects from your listThread list. It fills up with completed threads. -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From ethanw at rediffmail.com Fri Jun 14 15:58:22 2002 From: ethanw at rediffmail.com (Ethan) Date: 14 Jun 2002 12:58:22 -0700 Subject: PythonWin Problem! References: <1a52c7f1.0206131455.6df50cf8@posting.google.com> <3D0973C5.60407@skippinet.com.au> Message-ID: <1a52c7f1.0206141158.1c03b3f5@posting.google.com> Thanks Mark. It worked like a charm. One thing though, the key I had to delete was in HKCU rather than in HKLM. The second method would not work with ME since like I said in my earlier post, I don't have a right click menu for items in the taskbar. Thanks again. > Pythonwin has probably somehow remembered it's screen location as off > the screen. > > Try deleting the "HKLM\Software\Python 2.1\Python for Win32" key from > the registry, and it should come back. > > Alternatively, from the task-bar select "Move", then use the arrow keys > to try and bring it back on screen (presumably with the "Left" and "Up" > keys) > > Mark. From amuys at shortech.com.au Tue Jun 4 21:25:51 2002 From: amuys at shortech.com.au (Andrae Muys) Date: 4 Jun 2002 18:25:51 -0700 Subject: prototyping good OOdesign in Python? References: Message-ID: <7934d084.0206041725.220fa6d3@posting.google.com> Roman Suzi wrote in message news:... > Maybe this was already discussed, but I'd liked to raise this topic again. > > Python has superb OOProgramming support. Lets not dispute this for a > moment. Now let's consider that we need to make well-designed OOP solution > first prototyped in Python. > > What troubles are there? Python is too dynamic and all that. And all > those nifty features need to be translated properly into, say, C++. > One thing I'm very interested in is knowing if anyone has any experience with Python/Jython -> Java? Many managers are now firm believers in the gospel of Scott, but selling them Python as prototyping support for their new favourite seems feasible. Andrae Muys From spahievi at vega.bg Thu Jun 6 15:43:32 2002 From: spahievi at vega.bg (Niki Spahiev) Date: Thu, 6 Jun 2002 22:43:32 +0300 Subject: [ANN] constraint-0.1 In-Reply-To: <20020606135835.GF26159@orion.logilab.fr> References: <20020606135835.GF26159@orion.logilab.fr> Message-ID: <1272291294.20020606224332@vega.bg> 6/6/2002, 16:58:35, Alexandre wrote: A> Hello, A> Logilab has released constraint-0.1. Is it usable as Geometry Solver? -- Best regards, Niki Spahiev ______________________________________ VEGA(TM) Internet Service Provider Scanned and protected by Inflex Tova pismo e provereno i zashtiteno ot programite "Inflex/Antivir". From marcus1 at marcus1.de Fri Jun 21 12:21:59 2002 From: marcus1 at marcus1.de (Marcus Klein) Date: Fri, 21 Jun 2002 18:21:59 +0200 Subject: Newbie-Question: Oberserving an directory Message-ID: <3d1352a7@news.piro.net> Hi there, I want to observe an directory to check if a new file has been put in, if that happens I want to start an event. Does anyone have a good idea how to start, I've tried it with signal, but either I am too stupid or it is the complete wrong way :-/ Thx in advance, marcus -- sick nature ? From emile at fenx.com Thu Jun 6 09:12:01 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 06 Jun 2002 13:12:01 GMT Subject: HttpServer help! References: <3CFF4C14.450850D8@millfilm.co.uk> Message-ID: Eric Texier [snip] > req.putrequest("POST", > "file:/usr/people/erict/python/srcToolskit/pythonXmlBook/c8/favquote.cgi ") > > . > . > . > > ##### That the Error after the ruprequest->"##### > Traceback (most recent call last): > File "post.py", line 25, in ? > req.putrequest("POST", > "file:/usr/people/erict/python/srcToolskit/pythonXmlBook/c8/favquote.cgi ") > > File "/usr/people/erict/bin//lib/python2.2/httplib.py", line 453, in > putrequest > self.send(str) > File "/usr/people/erict/bin//lib/python2.2/httplib.py", line 395, in > send > self.connect() > File "/usr/people/erict/bin//lib/python2.2/httplib.py", line 379, in > connect > raise socket.error, msg > socket.error: (111, 'Connection refused') > So, you've got 'Connection Refused' on req.putrequest() with a file... Permissions isssues on the server or file? -- Emile van Sebille emile at fenx.com --------- From rx.andrew at ieee.org Sat Jun 1 23:47:23 2002 From: rx.andrew at ieee.org (Rex K. Andrew) Date: Sun, 02 Jun 2002 03:47:23 GMT Subject: Newbie question: is there a python wrapper for a distributed task? Message-ID: <3cf99371.1554503@news.mindspring.com> Hi folks, So I'm totally new here. I'm considering several scientific/data crunching projects that need a lot of CPU hours. We have at hand several linux clusters, but we want to expand (and take over the world.) I was looking at FIDA from the Chemistry Dept at UW and the Cosm library from Mithral. These are ways to "glue" a server process to the client processes on the nodes. (i.e., all the distributed computers.) I got to wondering: has anybody used python as the "glue"? python works on lots of computers now, and an app can be compiled into it if necessary using SWIG. And the python community has lots of netware contributions. I dunno, just a troll, I guess. It seems like it might be a good marriage. Any pointers, URLs, flames, etc, appreciated. Thanks, Rex ************************************************ Rex K. Andrew rx dot andrew at ieee dot org (you know what to do) From occeanlinux at linuxmail.org Thu Jun 27 20:14:54 2002 From: occeanlinux at linuxmail.org (SiverFish) Date: Fri, 28 Jun 2002 00:14:54 +0000 Subject: How to get rid the new line References: <3D1AD534.A74EC9F4@ipm.fhg.de> <3D1B1A76.563E5394@engcorp.com> Message-ID: On Thu, 27 Jun 2002 14:00:22 +0000, Peter Hansen wrote: > Markus von Ehr wrote: >> >> f = open(filename, 'r') >> lines = f.readlines() >> line1 = lines[0] # exemplarily for first line line1 = >> line1[0:len(line1)-1] >> >> or: >> f = open(filename, 'r') >> lines = f.readlines() >> line1 = lines[0][0:len(line1)-1] # exemplarily for first line > > I believe this is unsafe. The final line may not be terminated with \n. > > -Peter Any method like chomp in perl I just one to cut read only the line that not empty into the list From peter at engcorp.com Thu Jun 27 19:52:21 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 27 Jun 2002 19:52:21 -0400 Subject: How to get rid the new line References: <3D1AD534.A74EC9F4@ipm.fhg.de> <3D1B1A76.563E5394@engcorp.com> Message-ID: <3D1BA535.1EE16646@engcorp.com> "James T. Dennis" wrote: > > Could try this: > > def chomp(line): > if line[-1]=='\n': > line=line[:-1] > return line Just make sure you pass chomp() only lines that are not equal to the empty string ''. >>> line = '' >>> line[-1] Traceback (most recent call last): File "", line 1, in ? IndexError: string index out of range -Peter From xsebbi at gmx.de Sun Jun 23 05:18:29 2002 From: xsebbi at gmx.de (Sebastian Roth) Date: Sun, 23 Jun 2002 11:18:29 +0200 Subject: Parsing In-Reply-To: <3D14CEBC.C6655F86@vip.fi> References: <3D14CEBC.C6655F86@vip.fi> Message-ID: <200206231115.37654@xsebbi.de> On Samstag, 22. Juni 2002 21:23, Pekka Niiranen wrote: > Has anybody used python's parser -module to parse user defined > text structure? It is possible ? do you mean regular expressions? If yes, 're' is your module ;) > -pekka- Sebastian From kragen at pobox.com Mon Jun 10 16:53:40 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 10 Jun 2002 16:53:40 -0400 Subject: Where is Berkeley DB on your system? Can you live without DB 1.85? References: Message-ID: <83wut6q2i3.fsf@panacea.canonical.org> "David LeBlanc" writes: > > I don't think anybody has proposed including a modern version of BSD > > DB in Python, only dropping support for an old version, which is also > > not included in Python. > > Hmmm... I have Python 2.2.1 binary installed from Sourceforge - what is that > bsddb.pyd file dated 4/9/2002 in the dlls directory? That itself is probably the Python module that interfaces to whatever version of Berkeley DB you have, not Berkeley DB itself (although it could be statically linked in there), but Tim Peters has asserted that a binary version of db 1.85 is included, regardless. So I was wrong. Certainly Berkeley DB is not included in the Python source tarball. > > "commercial for-sale" is misleading. The current license of BSD DB > > allows distribution in commercial for-sale apps with no further hassle > > unless said commercial for-sale apps are, approximately, free > > software, and it forbids inclusion in noncommercial not-for-sale apps > > unless said not-for-sale apps are, approximately, free software. > > This makes no sense, so I'll just pass on it. I think you got your facts > backwards. It makes no sense because I got the sense of my first clause backwards; thanks for the correction. It should read as follows: It allows distribution in commercial for-sale apps with no further hassle unless they are *not* free software. > > > prospects. It didn't work for Perl in it's early years and > > that's why the > > > Artistic License was change to allow "for fee" distributions > > that included > > > Perl. > > > > I thought the AL allowed this from the beginning. Certainly > > Sleepycat's license doesn't forbid it. > > IIRC, in the early days of Pearl, the "AL" had the same tainting as GPL. > Again, IIRC, some of the Pearl inner circle where the ones who agitated for > the change so they could make some money from all the time they where > pouring into Pearl. Today, the AL is more like the GLL. My experience with Perl doesn't go back to the days before its public release when it was spelled with an "a", so I'll take your word for it. > Sleepycat's license doesn't prohibit commercial for-fee distribution, it > simply requires that you negotiate a payment scheme with them for the use of > versions after 1.85. They don't charge for redistribution with free open > source apps like Python. This is self-contradictory. The second statement is accurate; the first statement is not. They don't require that you negotiate a payment scheme with them *unless your commercial for-fee distribution is a distribution of proprietary software*. For example, Red Hat doesn't have to negotiate a license to Berkeley DB to include it in their commercial for-free Linux distribution. > However, as I said in my last post (along with exerpts from > Sleepycat's FAQ on the subject), if a Python developer was to > include a Python distribution that included a version of bsddb after > 1.85 in a for-fee commercial program, then they would have to > negotiate a payment scheme with Sleepycat. Again, *only* if it was a *proprietary* for-fee commercial program. The same issue would come up if they were distributing a proprietary not-for-fee noncommercial program. > More to the point, they would have to know that they would have to > do that or risk copyright infringement. Yes, they would have to understand the licensing terms of the software they were redistributing. > > In any case, your irresponsible, alarmist accusation is a red herring, > > as you will no doubt agree once you understand the situation properly. > > Dropping support for db 1.85 will not require all Python apps to be > > free software or open source; it won't even require all distributions > > of Python to be free software or open source. It will only require > > distributions of Python with bsddb support to either link to an > > external BSD DB library (like the one included with glibc) or be free > > software. > > I don't think I'm the one not understanding the situation properly, nor > could anything I posted be reasonably construed as irresponsible, alarmest > or an accusation! You said: > If you want to change Python's market dynamics and require _all_ Python apps > to be free and open source, then you can include any version of Sleepycat > BSDDB you like. That was what I meant by "your irresponsible, alarmist accusation". It isn't true, and it sounds scary and accusatory to me. Only Python apps that use Berkeley DB would be affected, and then only if they're distributed in binary form, and then only if they're running on operating systems that don't ship with Berkeley DB. > > If it's not clear, I'm in favor of this change. It helps everyone > > everywhere. > > Whatever gets done, it would be nice to have some useful db shipped in the > standard Python distro. I have heard a rumor that gadfly is such a > candidate - and also that gadfly has bugs of it's own. I think dumbdbm and gdbm are more comparable to Berkeley DB than Gadfly is; either or both of them could be included in a standard Python distro with no licensing problems, even for proprietary software. > BTW, since you're so keen on the failings of the BSDDB that seems to ship > with standard Python, perhaps you'd like to contribute information on how to > use it and what it's pitfalls are and ways to avoid them to the pythondoc? I don't know what they are because I use sane versions of Berkeley DB. I seem to recall that hash-style db 1.85 files will fail after a lot of inserts, and Sleepycat has patches on their page that fixes a couple of core dumps and one case of lost updates in the BTree code, but ISTR that there are other problems, too. > Hell, you could even help maintain BSD DB 1.x! I think it's more cost-effective to just ship 4.0 in binary distributions of Python and require users to switch. If someone finds 4.0 (or 2.x or 3.x) unacceptable because they want to incorporate Berkeley DB functionality into proprietary software, I would be willing to work on 1.x for them at my regular contract rate, but increasing the profits of proprietary software companies who are too cheap to buy a license from Sleepycat isn't really my idea of a fun way to spend my spare time. Given that, it would probably be more cost-effective for such a company to just pay Sleepycat for a 4.0 license. From cpbotha at i_triple_e.org Tue Jun 11 05:43:21 2002 From: cpbotha at i_triple_e.org (Charl P. Botha) Date: Tue, 11 Jun 2002 09:43:21 +0000 (UTC) Subject: Sorting list (maybe stupid) References: Message-ID: In article , J?rvinen Petri wrote: > I have a problem and can't solve it: > > There is lines of text like: > > 2. Header2 > 1. Header1 > 102. Header102 > > and so on... > > And I need to sort them according to the number (1,2,3,4...) Put each line in a tuple, first element the number, second element the header. Make a list of these tuples, and then use list.sort() with a comp function that compares using the first element in the tuple. Here's some help: >>> print [].sort.__doc__ L.sort([cmpfunc]) -- sort *IN PLACE*; if given, cmpfunc(x, y) -> -1, 0, 1 -- charl p. botha http://cpbotha.net/ http://visualisation.tudelft.nl/ From peter at engcorp.com Sat Jun 29 20:23:28 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 29 Jun 2002 20:23:28 -0400 Subject: Newbie that don't understand References: <3d1e262f.3755054@news.clara.net> Message-ID: <3D1E4F80.D8EFBB3E@engcorp.com> Just a dude wrote: > > >how can 23 and -23 be equal? > > > To some this can be a hard concept to grasp. I can't grasp it either, because it's not possible. Only their absolute values are equal, not the numbers themselves. If the answers were unclear, it might be because we aren't sitting face to face reading body language and seeing confusion on your face. The Usenet medium can require a couple of abortive attempts before an answer works, as we experiment and try to find the proper level and manner of replying. > My son is an electronics > design engineer, and I still can't get my head around negative > voltages, how the hell do you get a -12 V supply... to him it's basic > but to me.............. With a 12V supply, the power supply is trying to push electrons out the negative terminal and into the positive terminal. If you have a -12V supply, it tries to push electrons out the positive terminal and into the negative terminal. -Peter From max at alcyone.com Thu Jun 13 01:50:16 2002 From: max at alcyone.com (Erik Max Francis) Date: Wed, 12 Jun 2002 22:50:16 -0700 Subject: why not "'in' in 'in'"? References: <3D080482.7A7FD514@alcyone.com> <3D082A62.CF800C75@seebelow.org> Message-ID: <3D083298.470850D0@alcyone.com> Grant Griffin wrote: > In that case, perhaps I should have thought of a better one . > In > any event, in the case of strings, I think one might stretch the > concept > of "membership" to include substrings. In fact, note that since > Python > has no actual character type (because a character is adequately > represented as a string of length one) the "in" operator actually > _does_ > test membership of strings in strings. But for some reason, it's > limited to testing strings of length one. Go figure! A string is a sequence of one-character strings. It's not a sequence of all the subsequences of a string. > Honest answer: although I can't see much use for that construct, I > can't > see much harm in it either. So although it's probably not worth > adding > to Python, I'm sure _somebody_ would find a use for it. But that's exactly the problem; if you want [1, 2] in [1, 2, 3, 4] to return true (i.e., for the `in' operator to test substrings, not just membership), then you have an ambiguity problem. A list can contain sublists as elements, after all. > But anyway, let's "just say no" to the tuple case rather than confuse > ourselves; let's just make the string version of "in" a special case. Why make a special case for it when string.find and S.find already exist and are included expressly for that purpose? -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Who'd ever think it / Such a squalid little ending \__/ The American and Florence, _Chess_ Church / http://www.alcyone.com/pyos/church/ A lambda calculus explorer in Python. From inkedmn at earthlink.net Fri Jun 7 22:59:38 2002 From: inkedmn at earthlink.net (inkedmn at earthlink.net) Date: Sat, 08 Jun 2002 02:59:38 GMT Subject: syntax error References: Message-ID: <3d0171be.530166419@news.earthlink.net> On Fri, 7 Jun 2002 11:48:45 +0200, "Marc Beyerlin" wrote: >hello pythons, >im new to python and have a strange error: >if have installed python 2.4 with treads on my openbsd3.0 box >with also installed zope. >zope works fine, but when i try to start an script like > >python ipcheck.py > >i get an error msg like syntax error at ..... > >but i m sure there is no error. > >what could be the problem? > >greetings, >marc > > > >------------------------------------------------------- >magic garden GmbH - Agentur f=FCr Informationsarchitektur > >Hermannstr. 15 - 70178 Stuttgart (Am Feuersee) > >www.magic-garden.de =A6 beyerlin at magic-garden.de > >Tel. (07 11) 619 57-42 =A6 Fax (07 11) 615 01 38 > > What's the exact error that's returned? Please also paste the culprit code :) ink From kragen at pobox.com Mon Jun 10 21:27:10 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 10 Jun 2002 20:27:10 -0500 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 10) Message-ID: QOTW: "I favour Kent Beck's aphorism: 'Make it work, make it right, make it fast.'" -- James Kew Programming Libraries: Logilab's 'constraint', a constraint satisfaction problem programming environment for Python, which lets you program in Prolog style in Python, has released version 0.2. http://groups.google.com/groups?selm=mailman.1023468735.788.python-list%40python.org Twisted, an event-based framework for Python applications, including network servers, has released version 0.18.0. http://groups.google.com/groups?selm=mailman.1023121326.9358.clpa-moderators%40python.org Rdflib, which includes a store for RDF triples and XML serialization facilities for them, has released version 0.9.0. http://redfoot.sf.net/ The proposed standard Python logging module has been released version 0.4.5. http://groups.google.com/groups?selm=mailman.1023398221.4689.clpa-moderators%40python.org http://www.red-dove.com/python_logging.html scgi, yet another FastCGI clone, with support in Apache and Python, has released verion 0.3. http://groups.google.com/groups?selm=mailman.1023213423.29409.clpa-moderators%40python.org Skunkweb, a web application framework for Python, has released version 3.2.1, which supports Apache 2, among other things. http://groups.google.com/groups?selm=mailman.1023380951.25710.python-list%40python.org Python Development News Oleg BroytMann posted glue that automatically moves vim users to the locations of syntax errors in their Python source code, much like C-c - in Emacs. mailman.1023368949.9130.python-list at python.org Google may not save the attachment, but pipermail does. http://mail.python.org/pipermail/python-list/2002-June/107625.html Skip Montanaro wants help making Python better at detecting where various pieces of BSD DB are installed, and also wants to know if it's OK to stop supporting obsolete versions of BSD DB. http://groups.google.com/groups?selm=mailman.1023479590.27892.python-list%40python.org IDE Studio, an enhanced version of IDLE, including features like a graphical class browser, pydoc integration, and method syntax tips, released version 1.6. http://starship.python.net/crew/mike/Tide/idledev/IDEStudio.html Discussion on Features of Python: Andrew Kuchling has written "What's new in Python 2.3?" http://www.python.org/dev/doc/devel/whatsnew/ eval and exec still need real dicts for variable lookup, which is a wart. This is not a new topic. http://groups.google.com/groups?selm=mailman.1023324129.19618.python-list%40python.org http://groups.google.com/groups?selm=mailman.1023322808.24525.python-list%40python.org http://groups.google.com/groups?th=2338421ec8397bec&seekm=mailman.1004338951.27778.python-list%40python.org The timbot described the implementation details of the built-in list type, how it struck a balance between efficient reallocation behavior and efficient space usage, and why simple benchmarks may not always reveal the whole truth. http://groups.google.com/groups?selm=mailman.1023657975.22641.python-list%40python.org Problems and Solutions: There's a new Python Cookbook recipe describing how to produce lazily-computed attributes in Python 2.2. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/131495 David Mertz wrote an article about how to use generators to get cooperative multithreading. It turns out that "yield" really does mean "yield" after all. http://www-106.ibm.com/developerworks/library/l-pythrd.html Vojin Jovanovic is building a system for describing systems of interdependent lazily computed nonscalar values in Python, and he's annoyed that his variable names all have to begin with "self.". This is a little different from the standard "Python is different from C++ and therefore bad" thread. Holger Krekel, among others, suggested a solution, but it was not sufficient. http://groups.google.com/groups?selm=mailman.1023224648.434.python-list%40python.org Thomas Heller posted a sort of emulation of classmethod that works in Python 2.1. http://groups.google.com/groups?selm=ado5v8$uih9$1%40ID-59885.news.dfncis.de Uwe Schmitt wanted help talking to his barcode printer directly on Microsoft Windows. http://groups.google.com/groups?selm=Xns9226F1A931224cliechtigmxnet%4062.2.16.82 Cimarron Taylor posted his procedure for building a Python interpreter with Tkinter and Pmw. http://groups.google.com/groups?selm=29e28c51.0206090021.72466d4b%40posting.google.com Miscellaneous: ONLamp.com interviewed Guido van Rossum about Python. http://www.onlamp.com/pub/a/python/2002/06/04/guido.html EuroPython has posted some more interviews, including one with Steve Alexander and Stephan Richter, in which they talk about Zope's place in the world and Zope 3. http://europython.zope.nl/interviews/entries/steve_stephan_zope ActiveState continues its annual sponsorship of Active Awards for toilers in the vineyards of its supported languages. Voting closes on the 26th of this month. http://www.activestate.com/Corporate/Communications/Releases/Press1023137709.html Domenic Merenda, who used to work at BeOpen, is running a home-grown ERP system written entirely in Python on an AS/400 to manage the operations of a hundred-million-dollar manufacturing company. He hopes to release it as open source. He's looking for other people who have done this. http://groups.google.com/groups?selm=KHkL8.21383$eD2.2399923271%40newssvr10.news.prodigy.com The discussion about ERP systems generalized to large Python projects --- more than a few tens of thousands of lines. Michael Chermside posted a summary of a few such systems. http://groups.google.com/groups?selm=mailman.1023460091.14067.python-list%40python.org Domenic Merenda posted a list of several dozen large Python projects that BeOpen had compiled in 2000. http://groups.google.com/groups?selm=QX8M8.21882$EP.2548532334%40newssvr10.news.prodigy.com Tim Churches answered a question about how to compute confidence intervals in Python with an overview of available statistical software for Python, including SciPy, RPy, Gary Strangman's stats module, and NumPy's MLab. http://groups.google.com/groups?selm=mailman.1023574153.24062.python-list%40python.org Chris Armstrong is developing a Python-source serialization module for arbitrary object instances that works along the same lines as pickle, but is human-readable and human-editable. http://groups.google.com/groups?selm=mailman.1023668414.25769.python-list%40python.org Dean Goodmanson described what features of Python he avoided when trying to write Python that would be easy to translate into C++. http://groups.google.com/groups?selm=e81be8b2.0206022315.3a0bf9a9%40posting.google.com Peter Hansen eloquently praised test-first development. http://groups.google.com/groups?selm=3D02FB3B.CF75E925%40engcorp.com Dave Cole wrote about why he wrote Albatross, a web application framework for Python, when there were already so many web application frameworks for Python. http://groups.google.com/groups?selm=mailman.1023539113.15573.python-list%40python.org ======================================================================== Everything you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Michael Hudson continued Andrew Kuchling's marvelous tradition of summarizing action on the python-dev mailing list once every other week, into July 2001. Any volunteers to re-start this valuable series? http://starship.python.net/crew/mwh/summaries/ http://www.amk.ca/python/dev The Vaults of Parnassus ambitiously collect Python resources http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Links2Go is a new semi-automated link collection; it's impressive what AI can generate http://www.links2go.com/search?search=python Tenth International Python Conference http://www.python10.org Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. [http://www.egroups.com/list/python-url-leads/ is hibernating. Just e-mail us ideas directly.] To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From yidaki2 at excite.com Tue Jun 4 19:47:55 2002 From: yidaki2 at excite.com (Brent Miller) Date: Tue, 04 Jun 2002 23:47:55 GMT Subject: Fastest way to read / procsess / write text? Message-ID: <3CFD5229.2060803@excite.com> I'm somewhat new to python and programing in general and I trying to write a simple script that I can use to format large text files so that they are suitable for importing into MySQL. So far, I have came up with this: #!/usr/bin/python2 import sys, re infile = sys.stdin data = infile.read() infile.close() data = re.sub('[.](?=\d\d\d\d\d\d)|[.](?=\w+[ ][<|>])|[.](?=\w+[:])|[ ](?!0x)', '\t', data) outfile = open("/mnt/storage/output.txt", "w") outfile.write(data) outfile.close() This works beautifully most of the time (it's super fast), except when I pipe large files (>50megs) to it and then it usually dies half way through complaining of memory errors because it ran out of ram. Short of buying more ram, is there a way I can make this more effecient without taking a big peformance hit? I tried the above where I used a "for line in data:" loop so it would only process one line at a time but this seemed to take forever! I'm imagining there's a way to process the data in something like 1 meg chunks, but I'm not too sure how to do that. I'm using python 2.2.1 on a RH linux 7.2 system with 256 ram and a Athlon XP1700 if it makes any diffrence. Any suggestions? TIA, Brent From phd at phd.pp.ru Thu Jun 27 17:43:41 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Fri, 28 Jun 2002 01:43:41 +0400 Subject: Python crashed on me In-Reply-To: ; from bokr@oz.net on Thu, Jun 27, 2002 at 08:45:16PM +0000 References: Message-ID: <20020628014341.B22132@phd.pp.ru> On Thu, Jun 27, 2002 at 08:45:16PM +0000, Bengt Richter wrote: > To eliminate pickle, you could substitute a dump pickle. > If it's happening in pickle, you could substite a file object of your own, > to get a clue what it died on Aha, that's good point, thank you. I'll try your code. Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From rganesan at myrealbox.com Tue Jun 18 07:19:50 2002 From: rganesan at myrealbox.com (Ganesan R) Date: 18 Jun 2002 16:49:50 +0530 Subject: python version? References: Message-ID: >>>>> "George" == George Hester writes: > "If you can't get an answer, please don't take it personally that we don't > feel we can help you. Sometimes the members of the asked group may simply > not know the answer." Yeah, right. Nobody in the group knows the answer to your question. We would really appreciate if you do some research and figure it out for yourself. We would be even more happy when you come back and enlighten us with your knowledge. Thank you. Ganesan -- Ganesan R From gerhard at bigfoot.de Wed Jun 12 12:23:07 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 12 Jun 2002 16:23:07 GMT Subject: Extending distutils? References: Message-ID: Martin Sjoegren wrote: > There is so far no chapter in the distutils manual about extending distutils. > [...] I can't answer your question, but if you want to look into a setup.py that overrides a lot of the defaults, you can look into the one from the mxExtensions. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From fperez528 at yahoo.com Thu Jun 13 15:37:25 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Thu, 13 Jun 2002 13:37:25 -0600 Subject: filter2 References: Message-ID: Oleg Broytmann wrote: > I want to have new python builtin - filter2. It is exactly like filter, > but it returns also a list of items that didn't pass the test. > Why not instead propose that a new keyword parameter be added to filter? Something like filter(fn,seq,rejected=1) which would then behave as you want it? By default, rejected would be false and the current behavior would be maintained. This sounds like somehting you could put in a pep quickly. f. From res04ft9 at gte.net Fri Jun 28 19:33:31 2002 From: res04ft9 at gte.net (Erv Young) Date: Fri, 28 Jun 2002 19:33:31 -0400 Subject: Why the colon? In-Reply-To: Message-ID: <4.3.2.7.2.20020628190712.02450328@mail.gte.net> I've come a long way, baby! Four days ago, I posted an inquiry on a MS Developer mailing list, to the following effect: "How do I get MS Visual C++ 6.0 to act like good old non-visual, nonplussed (forgive me) plain old C?" and got back a response to the effect that I should forget C and use Perl. And now here I am, having read the entire thread "Python vs. Perl: which one to learn?" and having identified the pieces of Python that I need for the job at hand. I will omit several intermediate steps on the journey. But I have a question. Let me set it in the context of the first code snippet in section 4.7.1 (http://www.python.org/doc/current/tut/node6.html#SECTION006710000000000000000) of the on-line tutorial 1. def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): 2. while 1: 3. ok = raw_input(prompt) 4. if ok in ('y', 'ye', 'yes'): return 1 5. if ok in ('n', 'no', 'nop', 'nope'): return 0 6. retries = retries - 1 7. if retries < 0: raise IOError, 'refusenik user' 8. print complaint where I have added line numbers for the sake of the discussion. I understand the colons in the middle of lines 4, 5, and 7 as statement separators. Makes perfect sense. Then what am I to make of the colons at the end of lines 1 and 2? "Yoo-hoo, interpreter! I'm about to start indenting now!" Hmmm.... Maybe one of you can help me understand this syntactic convention a little better. An invitation to continue RTFM would be quite in order, if it were accompanied by a specific URL or section number. (An invitation to read the whole thing like a novel would be a bit un-Python-like, as near as I can tell.) Thanks. --erv From op73418 at mail.telepac.pt Wed Jun 26 13:45:25 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Wed, 26 Jun 2002 18:45:25 +0100 Subject: question od default args Message-ID: Hi, When I want default args I usually do def (arg = None): ... But what if I want to make None a reasonable argument too? That is, I want to know if the user has in fact passed an argument, and if not to do something special, with None (or whatever object) being a reasonable arg to be passed. All the best, Gon?alo Rodrigues From rapskat at hotmail.com Fri Jun 7 00:16:38 2002 From: rapskat at hotmail.com (rapskat) Date: Fri, 07 Jun 2002 00:16:38 -0400 Subject: Help with Black Adder... Message-ID: Greetings All. I'm just getting started with python and I chose Black Adder as a RAD IDE. Since my background is (ugh!) VB, I'm used to the whole Top Down IDE thing. My questions are: 1) I am having problems with BA not finding the PyQT libs. I installed both from the rpm's (I'm using RH 7.3). But when I start BA it gives me an error that it couldn't find the PyQT modules and that they won't be available for the session. I've tried removing them and reinstalling to no avail. I've run ldconfig as well. Has anyone ele seen anything like this and any ideas on how to resolve it? 2) Are there any good printed books out there for development swith BA and PyQT? I have Deitel's "Python - How To Program" which is really excellent and comprehensive, however I was looking for something more specific to development within BA itself. I have briefly parsed the documentation, but it seems to be more of a generic compilation of the different elemnts than product specific instructions. Any assistance that anyone could give I would really appreciate it. I already have like 3 projects that I want to tackle with this puppy, so I'm really eager to get started. Thanks in advance! :-) -- rapskat - 12:05am up 3 days, 3:04, 5 users, load average: 1.19, 1.09, 1.11 drop the hot to mail me lovin' livin' the linux life From tim.one at comcast.net Wed Jun 12 18:46:01 2002 From: tim.one at comcast.net (Tim Peters) Date: Wed, 12 Jun 2002 18:46:01 -0400 Subject: map -> class instance In-Reply-To: Message-ID: [John Hunter] > I want to convert dictionary instances to instances of a class that > has the keys of the map as attributes. ... Hmm. Nobody gave the obvious way yet: class Map2Class: def __init__(self, amap): self.__dict__.update(amap) That's it. Then >>> m = {'first': 'John', ... 'last': 'Hunter', ... 'age': 34} >>> c = Map2Class(m) >>> print c.first, c.last, c.age John Hunter 34 >>> at-34-life-can-be-unclear-ly y'rs - tim From donn at u.washington.edu Thu Jun 20 13:27:46 2002 From: donn at u.washington.edu (Donn Cave) Date: 20 Jun 2002 17:27:46 GMT Subject: AF_UNIX + SOCK_DGRAM References: Message-ID: Quoth "James T. Dennis" : | I was playing with the socket module and Unix domain sockets, | trying to make it work with SOCK_DGRAM. I could get messages | recvfrom() but any attempt to send responses was failing, | complaining about the return address. | | Now I think I understand the problem. The recvfrom() tuple | does contain two parts (which WOULD BE address and data in UDP) | but I'm guessing that the address is meaningless for Unix | domain sockets. It occurs to me that the "return" address | must be the same socket (filesystem node of type 's') as the | one that I did a .bind() to. Actually think you have run into a bug in Python's socket module. If it's convenient for you to build your own socket module, change it like this and see what happens (I'm looking at version 2.1 here.) *** socketmodule.c.dist Sun Apr 15 17:21:33 2001 --- socketmodule.c Thu Jun 20 10:10:12 2002 *************** *** 597,602 **** --- 597,603 ---- case AF_UNIX: { struct sockaddr_un *a = (struct sockaddr_un *) addr; + a->sun_path[addrlen - (sizeof(*a) - sizeof(a->sun_path))] = 0; return PyString_FromString(a->sun_path); } #endif The address returned from recvfrom is (addr, len), but we've been ignoring len on the theory that the string would be NUL-terminated. It isn't, so there can be some garbage on the end. | This is academic curiosity, and I'll read through the C sources | to see what I can glean therefrom, eventually. I'd like to know | how I can tell what process has opened a connection to my | AF_UNIX socket and I'd love to know how to pass an open file | descriptor through an AF_UNIX socket (in Python). I've read that | this is possible in C and that it is one of the few features of | AF_UNIX sockets which is NOT available via other address/protocol | families. Yes, AF_UNIX supports that (SOCK_DGRAM or SOCK_STREAM.) See man 2 sendmsg. That would have to be added to the socket module. Probably easy enough to do, as long as you confine yourself to support for this one particular thing (passing file descriptors.) | ... I've also heard that this can be used as a way for a | client to request read-only or append-only access to a file | --- since the UNIX APIs (in C) apparently offer ways for the server | to obtain credential information about the requesting process as | well as passing open file descriptors (which are then roughly akin | to "capabilities" since their access mode can't be changed) Don't know, right off hand I can't think what API function you might be thinking of there. Donn Cave, donn at u.washington.edu From martin at v.loewis.de Wed Jun 19 01:47:06 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 19 Jun 2002 07:47:06 +0200 Subject: how i use '=?iso-8859-15?q?=E3?=' in python??? References: <3D0F6623000017AA@www.zipmail.com.br> Message-ID: Gerhard H?ring writes: > You need to give more details than "doesn't work". Most probably there > is no problem with the statement > > s='?' > > but a problem occurs when you try to print a string that contains a > non-ASCII character, right? I guess the error occurs when entering that statement into IDLE. In that case, I can only recommend to use a different editor, at the moment. Regards, Martin From fperez528 at yahoo.com Fri Jun 7 15:24:47 2002 From: fperez528 at yahoo.com (Fernando Perez) Date: Fri, 07 Jun 2002 13:24:47 -0600 Subject: map References: <3D007666.2B6D3582@gol.ge> Message-ID: Giorgi Lekishvili wrote: > Hi all! > > Is there a way to map a function with several arguments to a list? E.g., > >>>>import math >>>>import MLab >>>>a=MLab.rand(3,5) >>>>b=map(math.pow,a) > > of course, this doesn't work. > > What to do? My task is to optimize the power (i.e., y in pow(x,y)) to > achieve maximal performance. > > > thanx, > Giorgi > > PS: Perhaps I have missed the needed functionality, that's presented in > NumPy? It's hard to tell what you're trying to do, since a 3x5 array doesn't have an 'obvious' way to be used as an argument to pow. But anyway, for 'maximal performance' you should use NumPy the way it was meant to be used. It already overloads ** so you can just write: In [1]: import MLab In [2]: a=MLab.rand(3,5) In [3]: a Out[3]: array([[ 0.7906459 , 0.9962979 , 0.59841698, 0.13870062, 0.93503422], [ 0.03783634, 0.68916065, 0.79217309, 0.23443535, 0.87729597], [ 0.04226565, 0.4821128 , 0.8859337 , 0.45935223, 0.47994375]]) In [4]: a**3 Out[4]: array([[ 4.94249303e-01, 9.88934754e-01, 2.14294850e-01, 2.66830335e-03, 8.17490114e-01], [ 5.41660550e-05, 3.27311607e-01, 4.97118874e-01, 1.28845512e-02, 6.75209283e-01], [ 7.55027297e-05, 1.12058801e-01, 6.95350325e-01, 9.69253713e-02, 1.10553126e-01]]) As a rule of thumb, in Numeric NEVER roll your own loops (even using map). Right there you kill all of the speed advantage of NumPy. If you can't find a way to write things with Numeric's functions and absolutely need to loop by hand, it will be dog slow. At that point, your only option is to write the tight loops in C, which is actually extremely easy to do using weave (http://scipy.org) Here's a quick comparison showing the disaster you're heading into if you try to use loops/map instead of properly using numeric: In [1]: import MLab, Numeric In [2]: def loop_pow3(arr): ...: out = Numeric.zeros(len(arr),arr.typecode()) ...: for i in xrange(len(arr)): ...: out[i] = arr[i]**3 ...: return out ...: In [3]: numpow3 = lambda x:x**3 In [4]: pow3=lambda x: pow(x,3) In [5]: a=MLab.rand(100000) In [6]: time_test (1,numpow3,a) Out[6]: 0.070000000000000062 In [7]: time_test (1,map,pow3,a) Out[7]: 1.1199999999999999 In [8]: time_test (1,loop_pow3,a) Out[8]: 0.54000000000000004 In [9]: _7/_6 Out[9]: 15.999999999999984 In [10]: _8/_6 Out[10]: 7.7142857142857082 So in summary, using map is a factor of 16 slower than using Numeric's builtin operators (or rather its natural overloading of **) and using loops is a factor of 8 slower. Unless you have a lot of time to sit around and wait, I'd recommmend spending an hour or two cuddled up with the Numeric documentation. It's a complete (if 'creatively' organized ;) reference. Cheers, f. From news at lindbergs.org Sat Jun 1 12:53:48 2002 From: news at lindbergs.org (VanL) Date: Sat, 01 Jun 2002 10:53:48 -0600 Subject: Generating unique numbers? References: <3CF7EBC8.4080802@verio.net> Message-ID: <3CF8FC1C.7060903@lindbergs.org> Hi, I appreciate the various answers which have been proffered. My application is thus: I am writing an outliner. TANGENT: Yes, I am aware of several other python outliner projects. While each is good for various things, 1. none so far have the exact featureset that I want/need and 2. I thought it would be fun to try to write a GUI application. I have written several 1000+ line scripts, but those were in a completely different problem domain. END TANGENT I am using these IDs as keys to various nodes, all held within a B-Tree (I to O Btree) that is contained within a standalone ZODB. The reason why I am wanting keys that are more likely to be globally unique is because I will be building in hooks to make this outliner network transparent (using ZEO), making it possible for multiple outliners to be used together as a real-time collaborative tool. I want to be able to be able to have people merge stuctures that people have made in the standalone instance into a shared instance without tromping on another nodes data. Based on what people have said, I was thinking of using some combination of DateTime.gmticks and the id of the obj, making it (I think) extremely unlikely that there would be a collision. Any comments on this, or the project in general would be appreciated. Thanks, VanL From BPettersen at NAREX.com Wed Jun 26 13:23:38 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Wed, 26 Jun 2002 11:23:38 -0600 Subject: Problems using samples Message-ID: <60FB8BB7F0EFC7409B75EEEC13E201922151B2@admin56.narex.com> > From: Raphael Ribeiro [mailto:gusraan at terra.com.br] > > 1 x = 8 > 2 y = 4 > 3 v = x - y > 4 > 5 print v > 6 if x = y: > 7 print "Eles s?o o mesmo valor" > 8 else: > print "Eles n?o s?o iguais , manja?" > > this is my code, it says there's an error in line 6, but i > can't find what **** error is that, can anyone help me? Generally, it's easier to figure out what is going wrong if you give us the stacktrace. In this case: >>> if x = y: File "", line 1 if x = y: ^ SyntaxError: invalid syntax Note that the ^ is pointing to where in the source the error is. x = y is an assignment, assigning the value of y to x. Assignments are not allowed as a test. I'm guessing you wanted to compare the two values to see if they were equal, in that case you need to say if x == y: note the equality operator is spelled ==. A better error message would probably have been helpful... -- bjorn From tim.one at comcast.net Mon Jun 3 18:56:13 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 03 Jun 2002 18:56:13 -0400 Subject: New win32all versions for Python 2.1 and 2.2 In-Reply-To: <3CFBF2BE.6020508@skippinet.com.au> Message-ID: [Mark Hammond] > I have released new win32all builds. > ... > These binaries are new (and have been built with WISE 8 - thanks Tim!) Tim who? Thank Wise. I have no idea what you're talking about. > so are still considered experimental. They seem to work wekk though :) I'm sure they work as wekk as Python itself . congratulating!-ly y'rs - tim From dbasch at yahoo.com Sat Jun 29 18:39:08 2002 From: dbasch at yahoo.com (Derek Basch) Date: Sat, 29 Jun 2002 15:39:08 -0700 (PDT) Subject: Win32/Python serial port event character problem In-Reply-To: <200206292038.g5TKcHu10071@smtp.swissonline.ch> Message-ID: <20020629223908.78455.qmail@web20808.mail.yahoo.com> Chris, It is funny that you wrote me. I just spent the last hour looking at pySerial. I dug into it some more and I think that using the event character is only usefull for driving the serial port polling function ('ReadFile' in this case). It is not usefull for breaking the serial data into logical units (ie..lines that end with '\n'). http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwbgen/html/msdn_serial.asp The 'caveat' section of this paper almost answers my question. > and read the characters in a separate receiver > thread. that thread can then > trigger on any character or sequence (e.g. using a > Queue to communicate > with other threads) Yeah, I think that is what will work best as a solution. Thanks for the suggestion. Also, I have been using the 'cbInQue' member of the COMSTAT structure returned by 'ClearCommError' to figure out how many characters are waiting in the serial buffer. I see that you are pre-allocating a buffer, using 'win32file.AllocateReadBuffer', based upon the size of 'cbInQue' for the subsequent 'ReadFile' operation. According to Mark Hammond I should be doing the same too.: http://starship.python.net/crew/mhammond/win32/RecentChangeHistory.html (section 108) If anyone reads this and can show me a better way to work with serial event characters in win32 please feel free to :) Thanks for the help, Derek Basch > > Sorry to post this again but it didn't get any > > responses. Maybe better luck this time. > > well 14hrs isn't that much time on a weekend... some > people only look into > news once per week. > > > I use the following code to read data from the > serial > > port when a certain event character ('\n') is > > received: > ... > > Has anyone ever dealt with this? Is using the > event > > character not a reliable method in windows? > > no sorry, i haven't used the event mode. > > .... > > This is driving me batty so any help is greatly > > appreciated. > > > my tip is: use http://pyserial.sf.net > > and read the characters in a separate receiver > thread. that thread can then > trigger on any character or sequence (e.g. using a > Queue to communicate > with other threads) > __________________________________________________ Do You Yahoo!? Yahoo! - Official partner of 2002 FIFA World Cup http://fifaworldcup.yahoo.com From skip at pobox.com Mon Jun 24 18:39:13 2002 From: skip at pobox.com (Skip Montanaro) Date: Mon, 24 Jun 2002 17:39:13 -0500 Subject: embedded Python - optimization for creating/destroying many small objects In-Reply-To: <3D174EEA.EFAE79C@fxtech.com> References: <3D174EEA.EFAE79C@fxtech.com> Message-ID: <15639.40849.865213.135766@12-248-11-90.client.attbi.com> Paul> I would like to simply create ONE of these objects and reuse it Paul> for the entire loop, so I am not paying for the memory Paul> allocation/deallocation overhead. Define your object to have something akin to a __setstate__ method, create a single instance of it before the loop, then set its state during each pass of the loop: holder = MyContainer() while 1: holder.setstate(data) dosomething(holder) -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From kragen at pobox.com Sat Jun 15 15:02:28 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 15 Jun 2002 15:02:28 -0400 Subject: Numeric module won't load on Debian Woody References: Message-ID: <83ofectlff.fsf@panacea.canonical.org> synthespian writes: > Numeric Python o Woody does not work, even though I did apt-get install > python-numeric without any problem.Theoretically, it's installed. > > Has anyone experienced problems with the Numeric module on Debian Woody? > What should I check? > Is there a workaround? > > I have Python2.2 installed woth no problem. Is your Python 2.2 a Woody package? Last I recall, Woody had Python 2.1, and there were two Numeric packages: one for 1.5.2 and one for 2.1. Neither of these will install files in /usr/lib/python22. HTH. FWIW, I'm running potato. You are allowed to call me lame now. From jdhunter at nitace.bsd.uchicago.edu Mon Jun 17 10:55:12 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Mon, 17 Jun 2002 09:55:12 -0500 Subject: MySQL database location References: Message-ID: >>>>> "Pawel" == Pawel Lewicki writes: Pawel> Hi, Is is possible to get the physical path to the MySQL Pawel> database file using MySQLdb or any other pythonous way? Depending on your platform, you could parse /etc/my.cnf. for line in open('/etc/my.cnf').readlines(): if line.find('datadir=')==0: dataDir = line[8:-1] print dataDir From fredrik at pythonware.com Wed Jun 26 06:29:44 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 Jun 2002 10:29:44 GMT Subject: Parsing strings (\n and \\) References: <3D19753C.9070104@thomas-guettler.de> Message-ID: Thomas Guettler wrote: > Look at the two functoins quote and unquote. I wrote them > without regular expression because I think it faster. faster to write, perhaps. and faster to run, if you only use them on strings with no more than 2-3 characters. but if you use a different set of test strings with more ordinary characters than escaped characters, e.g. strings = ['foo', '', '\\', ' ', '"', '\\"', '\\\\'] strings = [(x+"spamspamspamspamspam")*10 for x in strings] you'll find that a RE approach can be much faster. the following version is about four times faster than your code, under 2.2: def re_quote(string, sub=re.compile(r"[\\\"]").sub): def fixup(m): return "\\" + m.group(0) return sub(fixup, string) def re_unquote(string, sub=re.compile(r"(?s)\\(.)|\\").sub): def fixup(m): ch = m.group(1) if ch is None: raise 'Parse Error: Backslash at end of string' if ch not in r"\\\"": raise 'Parse Error: unsupported character after backslash' return ch return sub(fixup, string) ::: note the use of callbacks instead of substitution templates. it's usually faster (and in my opinion, also more pythonic) to use e.g. def fixup(m): return "spam %s %s" % m.group(1, 2) re.sub(pattern, fixup, string) or, if you prefer lambdas: re.sub(pattern, lambda m: "spam %s %s" % m.group(1, 2), string) than the re.sub non-standard interpolation syntax: re.sub(pattern, "spam \\1 \\2", string) (and where possible, it's also slightly faster to use m.groups() instead of enumerating all the groups in m.group(...)) ymmv, as usual. From jknapka at earthlink.net Tue Jun 25 16:24:39 2002 From: jknapka at earthlink.net (Joseph A Knapka) Date: Tue, 25 Jun 2002 20:24:39 GMT Subject: Python and Eclipse References: <3D17FAF4.35CC9F1B@earthlink.net> <81CC01E58BF2A99B.DFCD5EC6E4654907.32D731380951B9CA@lp.airnews.net> <3D189A8A.577C8186@earthlink.net> <3D18A6D2.5080404@dmsware.com> Message-ID: <3D18D159.2F66A9E8@earthlink.net> Paolo Invernizzi wrote: > Concerning elipse and python, I think there are 2 roads. > The first one is using jpe (http://sourceforge.net/projects/jpe) the > python-java framework. I've tried it some time ago... and I managed to > execute python code from a java VM (a jython prompt in reality! ;) but > I stopped there. Perhaps Frederic Giacometti and jython folks can give > some help! > > The second one is to use socket (is possible?) to connect to a python > server application... (with the plus that switching various python > versions is very easy)... and move some logic in python (fast > development times ;) > > The problem, as usual It's that I have no time ;( I think the latter is the best way. It's not clear, though, that these are the only two roads. But in any case, we must IMO be able to debug code under any Python version, preferably selectable among a number of different installed versions on the same machine (Eclipse allows this with the JVM, so I don't see why it would be a problem for Python). That way we could support CPython and Jython equally well. Another poster suggests that the Ruby Eclipse plug-in would be a good place to start, and I'm going to have a look at that later this week. -- Joe "Many ways to get what you want / I use the best / I use the rest!" -- Sex Pistols, "Anarchy in the UK" From ftobin at neverending.org Sun Jun 30 16:48:00 2002 From: ftobin at neverending.org (Frank Tobin) Date: Sun, 30 Jun 2002 16:48:00 -0400 Subject: Python needs better error reporting In-Reply-To: References: Message-ID: Brian Quinlan, on 2002-06-29, wrote: > There are a lot more tokens than that allowed. What about "+", "*", "\", > etc? Gadfly does this with its SQL parsing, and it helps a lot. -- Frank Tobin http://www.neverending.org/~ftobin/ From owen at nospam.invalid Thu Jun 20 18:20:52 2002 From: owen at nospam.invalid (Russell E. Owen) Date: Thu, 20 Jun 2002 15:20:52 -0700 Subject: tkinter font picker? References: <3D122BB6.92593026@tds.net> Message-ID: In article <3D122BB6.92593026 at tds.net>, "Edward K. Ream" wrote: >Does anyone know of tkinter code that will put up a font chooser >dialog? There are a number of such packages written in tk/tcl. I'm >wondering if anyone knows of a port to tkinter. I have a simple one that is part of a Tkinter-based preferences package. You can find it at in the Util.zip package; unpack and look in the Prefs folder. If you hear of a better one, please post. I'd also like a better color picker than the basic one included with Tkinter. -- Russell From sholden at holdenweb.com Fri Jun 28 08:56:10 2002 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 28 Jun 2002 08:56:10 -0400 Subject: M2Crypto: select() behaves weird on SSL sockets References: <3D04ED17.5070606@NOSPAMREMOVETHISxs4all.nl> <3D066E77.4070901@NOSPAMREMOVETHISxs4all.nl> <3D0790E1.9080904@NOSPAMREMOVETHISxs4all.nl> <831ybavprx.fsf@panacea.canonical.org> <3D0919AF.7050903@NOSPAMREMOVETHISxs4all.nl> <83it45lxfb.fsf@panacea.canonical.org> <3D1B92A2.7030605@NOSPAMREMOVETHISxs4all.nl> Message-ID: "Irmen de Jong" wrote in message news:3D1B92A2.7030605 at NOSPAMREMOVETHISxs4all.nl... > Kragen Sitaker wrote: > > > There are many pieces of middle ground between complete threading (two > > threads per connection) and complete event-loop-drivenness with just > > one thread --- as you're obviously aware, since you're using select() > > in a threaded program. > > Um, yeah. I have 1 loop using select() that waits for new incoming > connections. Every thread that is started for a connection just > recv()s data off the socket. > > > What I guess you're not aware of is that asyncore supports the middle > > ground (middle colors?) as well as the event-loop-driven end of the > > spectrum. For example, Zope has an asyncore thread that handles I/O, > > but actually processes requests and produces results in some child > > threads. > > You're probably right. I don't know a lot about the workings of asyncore. > Perhaps if I finally squash the bug that is still in Pyro 3 > -- *blushes* it's probably a threading race condition -- I'll spend > some time looking at it. > I understand that Zope used the asyncore code as a basis for development rather than adopting it outright, but I haven't actually checked the source to ensure this is so. > Doing stuff the Zope way, the worker threads must have some way to > get to the input and output streams that are handled in asyncore, right? > Well, it's a relatively simple matter: when an asyncore channel's handle-connect() method is called, one fo the arguments is the socket that was created by the connection. handle_connect() simply uses this socket to create another channel, which is added to the map used by the asynchronous select() loop. This new channel then starts to fire handle_read() method calls, which you service by doing something with the data. If the something you do includes putting data in an output buffer then handle_write() events also start to occur. asyncore/asynchat really repay the effort of study, so I would advise you to take a fresh look when you get time. To assist you, I plan to add documentation for asynchat for 2.3. when-sourceforge-stops-playing-silly-buggers-ly y'rs - steve ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From larooy at xtar.co.nz Sun Jun 16 03:02:40 2002 From: larooy at xtar.co.nz (John La Rooy) Date: Sun, 16 Jun 2002 19:02:40 +1200 Subject: a possibly foolish question about slices References: Message-ID: <20020616190240.5c3cc72e.larooy@xtar.co.nz> On Fri, 14 Jun 2002 17:50:09 GMT Andrew Koenig wrote: > Suppose x is a string or list, and I want to refer to > a subsequence of x with length n starting at position p. > under the assumption that this subsequence is entirely > > To do so, I can use x[p:p+n] in all circumstances but one, > namely when p < 0 and p == -n. Is there a similarly concise > expression that works even in this special case? > > -- > Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark x[p:][:n] John From matt at clondiag.com Tue Jun 4 11:01:39 2002 From: matt at clondiag.com (Matthias Kirst) Date: Tue, 4 Jun 2002 17:01:39 +0200 Subject: Win32 Decimal point/comma Message-ID: <3cfcd2e5$1@post.newsfeed.com> *** post for FREE via your newsreader at post.newsfeed.com *** Hi Kaci, This little problem caused continious annoyances to me until I found the locale module: import locale locale.setlocale( locale.LC_ALL, 'C' ) # sets portable locale -> point is decimal separator Matt -----= Posted via Newsfeed.Com, Uncensored Usenet News =----- http://www.newsfeed.com - The #1 Newsgroup Service in the World! -----== 100,000 Groups! - 19 Servers! - Unlimited Download! =----- From tatebll at aol.com Sun Jun 23 10:36:58 2002 From: tatebll at aol.com (Bill Tate) Date: 23 Jun 2002 07:36:58 -0700 Subject: Python hits the spot References: <3D1482AE.8FA299D8@kfunigraz.ac.at> Message-ID: Siegfried Gonzi wrote in message news:<3D1482AE.8FA299D8 at kfunigraz.ac.at>... > My conclusion: I will rewrite my simulation in Fortran 90 and will > abadon Python. Python is maybe good for some small scripts but not > appropiate for serious programming. The hydrodynamic and sediment transport models I used to run had simulation periods that required at least a week on a high-end computer. I wouldn't for a moment conclude that python is an appropriate numerical engine for computing the hydrodynamics in an estuary. However, python worked great for preprocessing large input data sets, post-processing very large binary output files and visualizing results. While that may not rise to your level of what constitutes "serious" programming, nevertheless, python performed an important purpose for my work and made my life a hell of alot easier. As far as python being appropriate for "small scripts but not appropriate for serious programming" I don't see where your particular application of python is sufficiently encompassing enough to make such a blanket assertion to the language's application as a whole. It didn't work for you in the problem domain to which you used python, so be it. There are more than a few examples where python rises to the level of performing mission-critical work outside of your particular area of focus. From roffe at aqualene.uio.no Sat Jun 22 09:47:40 2002 From: roffe at aqualene.uio.no (Rolf Marvin Bøe Lindgren) Date: Sat, 22 Jun 2002 15:47:40 +0200 Subject: [Q] numeric entry in boa constructor Message-ID: I've created a simple app in boa constructor. I would like to add a feature that does not seem to come with a pre-made component: the user hits a number on the numeric keypad. the number is displayed in a field. the user hits another number, the previous number is erased and the new number appears. any clues? -- Rolf Lindgren http://www.roffe.com/ roffe at tag.uio.no From jubafre at zipmail.com.br Fri Jun 21 01:24:06 2002 From: jubafre at zipmail.com.br (jubafre at zipmail.com.br) Date: Fri, 21 Jun 2002 02:24:06 -0300 Subject: =?iso-8859-1?Q?text=20search=3F=3F?= Message-ID: <3D12657900000468@www.zipmail.com.br> a have one componnent Entry, i put a string in Entry and search in the text your position to select it, but the searck doesn?t find a Upper letter W if a put lower, how i can serch in the text a W puting w?????? string='winzip' i want to find WinZip How i can find WinZip putting the string in lower?????? Juliano Freitas www.gebrasil.hpg.com.br ------------------------------------------ Use o melhor sistema de busca da Internet Radar UOL - http://www.radaruol.com.br From insyte-clp at emt-p.org Thu Jun 20 00:50:06 2002 From: insyte-clp at emt-p.org (Ben Beuchler) Date: 20 Jun 2002 04:50:06 GMT Subject: M2Crypto / SimpleXMLRPCServer Message-ID: I'm trying to set up an SSL SimpleXMLRPCServer instance. I've successfully used the xmlrpc_srv.py demo script from the M2 distro, but would like access to the convenience of .register_function() and .register_instance(). It looks to me like SSL.SSLServer and its various derivatives (Threading, Forking) *should* be a drop-in replacement for SocketServer.TCPServer when instantiating SimpleXMLRPCServer. I attempted to derive a SimpleSSLXMLRPCServer class like this (after setting up an appropriate ssl_context): class SimpleSSLXMLRPCServer(SSL.SSLServer, SimpleXMLRPCServer): def __init__(self, ssl_context, address, RequestHandler=SimpleXMLRPCRequestHandler, logRequests=1): SSL.SSLServer.__init__(self, address, RequestHandler, ssl_context) self.funcs{} # These three lines are copied from self.logRequests = logRequests # SimpleXMLRPCServer's __init__, as self.instance = None # calling it would create non-ssl # sockets. My understanding is that the methods in SSL.SSLServer would override the methods inherited by SimpleXMLRPCServer from SocketServer.TCPServer. It appears that the SSL part, at least, works great. I'm able to make a connection using xmlrpclib.ServerProxy("https://blah") but the actual remote method call hangs indefinitely. Is my basic premise flawed? Or just my implementation? Here's the output on the server side: >>> ctx = init_context('server.pem', 'ca.pem', SSL.verify_none) >>> bob = SimpleSSLXMLRPCServer(ctx, ('216.243.168.40', 9090)) >>> def q(a,b): ... return a + b ... >>> bob.register_function(q) >>> bob.serve_forever() LOOP: SSL accept: before/accept initialization LOOP: SSL accept: SSLv3 read client hello A LOOP: SSL accept: SSLv3 write server hello A LOOP: SSL accept: SSLv3 write certificate A LOOP: SSL accept: SSLv3 write server done A LOOP: SSL accept: SSLv3 flush data LOOP: SSL accept: SSLv3 read client key exchange A LOOP: SSL accept: SSLv3 read finished A LOOP: SSL accept: SSLv3 write change cipher spec A LOOP: SSL accept: SSLv3 write finished A LOOP: SSL accept: SSLv3 flush data INFO: SSL accept: SSL negotiation finished successfully petra.bitstream.net - - [19/Jun/2002 22:27:55] "POST /RPC2 HTTP/1.0" 200 - The client side is unremarkable. I instantiate a ServerProxy and attempt to make a remote call. It hangs. Very boring. Any thoughts? -Ben -- Ben Beuchler There is no spoon. insyte at emt-p.org -- The Matrix From dom at edgereport.put_a_c_o_m_here Thu Jun 6 15:33:00 2002 From: dom at edgereport.put_a_c_o_m_here (Domenic R. Merenda) Date: Thu, 06 Jun 2002 19:33:00 GMT Subject: Medium to Large Scale Python Deployments References: <82afc355.0206060043.d26564e@posting.google.com> Message-ID: Sure, Pedro. The database server is homegrown C and RPG II code running on the AS/400 for the majority of our "archived" data. The live database is mySQL on a PC. User interface is PC/400 by IBM, and communcation is handled over IPX through twisted pair cabling. Kludgy, but it works so far. :-) OS/400 is a wacky operating system. -- Domenic R. Merenda Editor, The Edge Report http://www.edgereport.com "Pedro Vale Lima" wrote in message news:82afc355.0206060043.d26564e at posting.google.com... > "Domenic R. Merenda" wrote in message > > > > I am running a home-grown Enterprise Resource Planning system, written > > entirely in Python > > Hello, > > Could you tell us more information about your system (Database Server, > User Interface, Communication protocol, etc)? I am running an ABAP > based ERP but I'm pretty sure your is better :-) > > regards, > > Pedro Lima From peter at engcorp.com Thu Jun 6 21:08:00 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 06 Jun 2002 21:08:00 -0400 Subject: Interfacing to 1-Wire LAN, especially Dallas temperature sensors? References: <3CF82E8E.23C6FA10@engcorp.com> <3cfb83e2$1_4@goliath.newsgroups.com> <3CFC226B.B6CB8995@engcorp.com> Message-ID: <3D000770.84B25F29@engcorp.com> Peter Hansen wrote: > > Brad Clements wrote: > > > > There is a technique where you can use a UART at some whacky baud rate and > > bits/byte setting to communicate. There's an APPNOTE somewhere, I don't have > > it handy. > > If someone can dig that out (I searched before and couldn't find it > in all the noise) I'd appreciate it. I would also be happy to try > to implement it under Python, since we'd have some uses for such a > beast. > > (But I still don't believe it can be done reliably. Maybe I'm wrong. > Would be cool.) I stand corrected, by private email. And now by Dave Moor's posting elsewhere in the thread. Sometimes it's _good_ to be wrong. :) -Peter From phil at river-bank.demon.co.uk Thu Jun 20 15:50:55 2002 From: phil at river-bank.demon.co.uk (Phil Thompson) Date: Thu, 20 Jun 2002 20:50:55 +0100 Subject: PyQT Complie problems References: Message-ID: <3D12321F.9090100@river-bank.demon.co.uk> ANdrew wrote: > First off, > > using: > > Windows 2000 > > MSVC 6.0 service pack 5 > QT eval 3.0.4 > Active State Python 2.2 > PyQt-3.2.4 (source) > > > I am trying to compile for Qt 3.0.4 eval. Following the win32 > instructions, i am able to compile the first makefile > (sip_helper.exe). However, when i change dir to the "qt" dir and > modify the makefile for the correct version of the .lib file and fix > the one type-o in the sipqtDeclqt.h file ( changed #include > to #include ) Why do you think there is a typo? There is no file sipQtQT.h. > i get a synatx error followed by an > unexpected end of file error. This is stated as being in the file > "sipqtQPaintDevice.h". The error is "sipqtQPaintDevice.h(44) : error > C2146: syntax error : missing ';' before identifier 'sipLazyAttrDef'" > > I have downloaded the latest snapshot (PyQt-snapshot-20020619.zip)and > there is nothing in there about the qt section. I am at a loss and > any help would be greatly appreciated. What do you mean by "the qt section"? The build system in the snapshots is completely different to v3.2.4 - the C++ code is now generated as part of the configuration process. Phil From dyoo at hkn.eecs.berkeley.edu Sat Jun 15 02:02:51 2002 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Sat, 15 Jun 2002 06:02:51 +0000 (UTC) Subject: PyArg_Parse() & review for memory leaks References: Message-ID: Anton Graph <""aglyportat\"@n-o.spa__mmm.yahoo dott com> wrote: [some code cut] : char *pstr; : if(!PyArg_Parse(result, "s", &pstr)) { // the plug-in just : // builds a string containing tag : return 0; : } : int st=strlen(pstr); : if(st>=len) { : delete [] *res; : len=st+1; : *res = new char[len]; : } : astrncpy(*res, pstr, len); : Py_DECREF(result); : return st; : } : do I leak pstr here? Sample code I've googled up seems similar, but I : don't understand how does PyArg_Parse allocate enough space without : going to the heap? I don't believe so: PyArg_Parse()ing a string shouldn't be doing any allocation because pstr is simply directed to the string pointer that Python is using internally to store that String object --- no string copying is involved. Section 5.5 of the Python/C API document explains more about PyArg_Parse(): http://python.org/doc/api/arg-parsing.html Good luck to you! From phd at phd.pp.ru Wed Jun 19 10:19:53 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Wed, 19 Jun 2002 18:19:53 +0400 Subject: procmail replacement in Python In-Reply-To: ; from marklists@mceahern.com on Wed, Jun 19, 2002 at 09:08:53AM -0500 References: Message-ID: <20020619181953.E4127@phd.pp.ru> On Wed, Jun 19, 2002 at 09:08:53AM -0500, Mark McEahern wrote: > http://www.qcc.sk.ca/~charlesc/software/getmail-2.0/ "A POP3 mail retriever..." Hence, it is not fetchmail replacement, as fetchamil also does IMAP, and does it very well. Fetchmail also has good GUI configuration program, written in Python and Tkinter. Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From fredrik at pythonware.com Tue Jun 11 17:01:39 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 11 Jun 2002 21:01:39 GMT Subject: frame.bind ? References: <3d05fff1$0$8149$ba620e4c@news.skynet.be> Message-ID: "kemu" wrote: > frame.bind("", callback) > > I don't understand what .bind does ? > I know button-1 is the first mouse button and he calls the function callback > but what does bind do ?? tell Tkinter that it should call the function callback when the first mouse button is pressed, if the mouse pointer is inside the frame widget. more here: http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm From peter at engcorp.com Sun Jun 23 21:42:11 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 23 Jun 2002 21:42:11 -0400 Subject: Redirecting StdOut References: <1024856420.145085@seux119> <1024860416.580309@seux119> <3D163550.E525D840@engcorp.com> <1024873013.652528@seux119> Message-ID: <3D1678F3.AD9B059B@engcorp.com> "Ugo Garc?a" wrote: > > "Peter Hansen" escribi? en el mensaje > > Why would you bother with C for a game that relies on simple print > > statements for its interface? > > What I'm making is a engine to make Graphical Adventures. > > Can't you implement the game entirely in Python? > Probably it would be implemented entirely in Python. Why not? SPEED. I'm > familiarized with C and prefer to make the core of the engine in C, which is > faster and more reliable for this kind of things, and leave Python be ONLY > the script language of the engine. You'll doubtless get other replies on this, including pointers to PyGame. I just want to ask a few more questions (yes, all just to make my point... please forgive me :-). What makes you think a game implemented in Python will not have enough speed? You certainly would not be writing the low level graphics routines in Python, but then you aren't about to do that in C, either (I sincerely hope). Python can call on libraries which have already been written *in C* (usually) to do the grunt work, so it is quite fast enough. As for reliable, I have to most vigorously object to anyone characterizing C as "reliable". C code is notoriously difficult to make reliable, generally being strewn with pointer bugs, memory allocation problems, and so forth. C was really written only as a somewhat more human-readable Assembly language substitute and has been supplanted by many more suitable alternatives for something as sophisticated as the engine of a game. Or to put it another way: don't knock it till you've tried it! Python is quite possibly a far more suitable solution for the entire application, not just for the scripting language. -Peter From david.abrahams at rcn.com Sat Jun 29 18:52:29 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Sat, 29 Jun 2002 18:52:29 -0400 Subject: SSE With Swig References: Message-ID: "Andrew Wilkinson" wrote in message news:uhs5g8hos5og51 at corp.supernews.com... > I'm trying to develop a Vector class that uses Intel's SSE extension. It > works very well when called using c or c++, but when I wrap the class with > Swig I get a privileged instruction exception error (this is under Windows > 2000 using MSVC++ 6sp5 with the processor pack installed). > > I've included the code below, any suggestions would be greatly appreciated > Andrew Wilkinson 1. Get rid of the virtual destructor 2. Get a copy of Scott Meyers' Effective C++ CD and read about operator overloads. Then write operator+ as a free function: vector operator+(vector const&, vector const&); 3. None of these are the reason for your crash, though. I don't know anything about SSE, but don't you have to tell it how many doubles it's going to operate on? > swig.i > %module Vector > %{ > #include "Vector.h" > %} > class Vector > { > public: > Vector(); > virtual ~Vector(); > Vector* operator+(const Vector *other); > float x; > float y; > float z; > float w; > }; > __ > vector.h > class Vector > { > public: > Vector(); > virtual ~Vector(); > > Vector* operator+(const Vector *other); > > __declspec(align(16)) union { > __m128 v; > struct { > float x; > float y; > float z; > float w; > }; > }; > }; > --- > vector.cpp > #include "Vector.h" > #include > > Vector::Vector() > { > x = 0.0f; y = 0.0f; z = 0.0f; w = 0.0f; > } > > Vector::~Vector() > { > > } > > Vector* Vector::operator +(const Vector *other) > { > Vector* r = new Vector; > > r->v = _mm_add_ps(v, (other->v)); // The exception occurs here. > > return r; > } > > -- > --- > Ditch The Decimal System! > Lets Use Hex - http://www.intuitor.com/hex/switch.html > > From martim.oberhuber at no-spam.org Thu Jun 20 15:09:46 2002 From: martim.oberhuber at no-spam.org (Martin Oberhuber) Date: Thu, 20 Jun 2002 21:09:46 +0200 Subject: Java to Python converter? References: Message-ID: <%LpQ8.55$g32.1762@nreader1.kpnqwest.net> Hi Gerhard, thanks a lot for your answer. The reason why I want to convert Java into Python is this: We are selling a programmer's IDE (SNiFF+) that is written in C++ but has an embedded python interpreter for scripting it. I'd like to write an import filter for importing project info from an external tool. We have a reader for the project files of that external tool, but the reader is written in Java. If I could easily do a "no-brain" conversion from Java syntax to python syntax, this would make the "brain-1.0" porting work a lot easier for me. I don't expect the Java -> Python converter to produce 100% correct code; it should just convert the syntax (i.e. classes + methods into "def" lines, braces {} into indentation) -- that's it. Thanks anyway, Martin -- martin oberhuber windriver.com "Gerhard H?ring" wrote in message news:mailman.1024575575.2971.python-list at python.org... > * Martin Oberhuber [2002-06-20 13:58 +0200]: > > Hi all, > > > > I've got some Java source code that I would like to convert into Python. > > Why? > > > Does anybody know of a converter that can do this? > > Brain 1.0. > > Btw. the Jython incarnation of Python can use Java libraries. > > Gerhard > -- > mail: gerhard bigfoot de registered Linux user #64239 > web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 > public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 > reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) > > From tony at sentienc.co.yuk Wed Jun 12 08:32:34 2002 From: tony at sentienc.co.yuk (Tony B) Date: Wed, 12 Jun 2002 13:32:34 +0100 Subject: Zope Newbie query Message-ID: Apologies if this is an innaproprate newsgroup - it's the closest I could find. I have been playing with zope and would like to use it properly now the problem I'm encountering is: How do I remotely install zope on a raq4 on which I am not the main raq4 administrator (i.e I have a subdirectory on which my site is hosted).? Do I have to have root priveliges to install and run zope? Has anyone done this who can point me in the right direction? Cheers T From campbells4 at ozemail.com.au Thu Jun 27 07:00:49 2002 From: campbells4 at ozemail.com.au (Alistair Campbell) Date: Thu, 27 Jun 2002 21:00:49 +1000 Subject: speech synthesis Message-ID: Hiya, I am a newbie with Python so any response to this may be way over my head. Basically, I am wanting to know whether there are any python modules that allow you to write programs which include voice synthesis. The sort of thing I am wanting to look at is an augmentive communication program for disabled people with speech and language disorders. So, I want to be able to convert typed text and stored blocks of text into audible speech using standard sound card interfaces. The application would be event driven and, at this stage, I would probably look at building the GUI using Tkinter. I am using Python 2.2 on a Windows OS. I have a Linux OS as well but I am not at all proficient with the file management on this so I don't really want to get into learning that interface just yet. If there is not a simple solution to this would there be a group of people around who would be interested in porting the Festival speech synthesis engine to the Windows OS and then writing the wrappers(is that the right term?) to be able to call it from Python. Alistair Campbell Qld, Australia t = ("Our 2 main weapons are...", "fear", "surpise", "and a fiendish devotion to the Pope!", "Oh Damn.") From ken at hotmail.com Sat Jun 1 08:28:34 2002 From: ken at hotmail.com (Ken) Date: Sat, 1 Jun 2002 22:28:34 +1000 Subject: How to open a HTML file when the python cgi program is executing? References: <9m6ada.31b.ln@10.0.0.1> Message-ID: > If you realize this before you've output anything, you can use one of the > redirection / refresh headers, such as "Location". > > print """Content-type: text/html > Location: http://replacement-url > >

Click here

Doesn't seem to work... :( > """ > > Theoretically it should be sufficient to just give the Location, but put in > a human-readable redirection just in case. > > Otherwise, if you've already started, you must continue. Just open the file > and print it. > > > As for frames, there's the main document, which decides which frames get > shown; and then the server gets separate requests for each of the frames. > You might want to browse a few pages with telnet to get a feel for how > things work. Where can I find this document? Thanks From christophe.chappet at silogic.fr Wed Jun 5 10:21:01 2002 From: christophe.chappet at silogic.fr (Christophe Chappet) Date: Wed, 5 Jun 2002 16:21:01 +0200 Subject: Extending inline help utility of IDLE Message-ID: <02b801c20c9c$38b36e70$01000001@TAKAROA> Hi to all, Is it possible to extend the inline help utility of the IDLE program to document my owns modules and functions ? Many thanks, Agence Scientifique & Industrielle Christophe CHAPPET Charg? d'Affaires T?l. : +33 534 619 246 - Fax : +33 534 619 222 e-mail : christophe.chappet at silogic.fr 6, rue Roger Camboulives - BP 1133 - 31036 Toulouse Cedex 01 - FRANCE -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: p3uilogo.gif Type: application/octet-stream Size: 2923 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: Christophe Chappet.vcf Type: text/x-vcard Size: 563 bytes Desc: not available URL: From gleki at gol.ge Fri Jun 28 04:34:10 2002 From: gleki at gol.ge (Giorgi Lekishvili) Date: Fri, 28 Jun 2002 10:34:10 +0200 Subject: Packages +reload() References: Message-ID: <3D1C1F82.443F22CC@gol.ge> Hi! It would be nice, if you shell (trace) send the output as well. Few questions: Do you import eNact prior to import what's inside? E.g., >From eNAct import * ir import eNAct J?rvinen Petri wrote: > Hey, > > I feel like complite lost. I have created nice package structure, > but I encountered lot's of troubles when using it with IIS and ASP. > > Structure is: > > eNAct\ > documents\ > listDocuments\ > showPage() > enactXML() > > -> main package eNAct and sub-packages eg. documents and it's > sub-packages eg. listDocuments > > The problem is that I can't reload the modules. > > I have tried various ways of importing listDocuments but IT doesn't > get reloaded. > > eg. > from eNAct.documents import listDocuments > reload(listDocuments) > > listDocuments.showPage() > > or > > import eNAct > reload (enact) You surely remember that enact!=eNAct, don't you? > > > eNAct.documents.listDocuments.showPage() > > Questions: > > 1. How should the structure be? > 2. Is it possible that I only reload the eNAct and all sub-modules > get reloaded. > 3. What does reload(eNAct.documents) reload? > > - Petri J?rvinen Grtz, Giorgi From egbert at bork.demon.nl Thu Jun 6 06:12:00 2002 From: egbert at bork.demon.nl (Egbert Bouwman) Date: Thu, 6 Jun 2002 12:12:00 +0200 Subject: Program to an interface, not an implementation Message-ID: <20020606121159.A975@bork.demon.nl> Hello, Can someone shed some light on the GoF adagium: 'program to an interface, not an implementation' and especially what it means for programming in Python ? GoF is not easy. egbert -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From ngiven at lanl.gov Thu Jun 20 12:20:06 2002 From: ngiven at lanl.gov (Nathan Given) Date: Thu, 20 Jun 2002 10:20:06 -0600 Subject: changing the viewing area with gnuplot in python Message-ID: <3D1200B6.639CEBE5@lanl.gov> right now gnuplot auto scales everything (I don't have control over the viewing area)... How do I change it? (I want to view from -4 to 2 on the x axis, and 0 to 10 on the y axis.... right now gnuplot automatically chooses -4 as xmin, 2 as xmax, 4 as ymin, and 10 as ymax) thanks -- Nathan -- From occeanlinux at linuxmail.org Sun Jun 2 09:49:37 2002 From: occeanlinux at linuxmail.org (Gold Fish) Date: Sun, 02 Jun 2002 13:49:37 GMT Subject: Question on time module Message-ID: <3cfa2287_1@news.iprimus.com.au> Can anyone tell me how to sort the file in the directory according to their modification time. Then if i want to look up a find say python.txt Mar 04 2002 in the directory can i use glob.glob to do it. I using time.localtime(time.time()) to get the current time in, how can i display only the file in the directory 5 days agos from the current time. Please help me to solve this problem. I tried to use os.stat to seperate the file time but it couldn't work. From candiazoo at attbi.com Thu Jun 27 10:09:09 2002 From: candiazoo at attbi.com (candiazoo at attbi.com) Date: Thu, 27 Jun 2002 14:09:09 GMT Subject: Most efficient way to write data out to a text file? References: <3d1a6993.248534625@netnews.attbi.com> <3D1A8CD9.C8B8EC28@engcorp.com> Message-ID: <3d1b1bd7.294171125@netnews.attbi.com> I am a newbie... this is my first Python "project" so I am probably writing horribly inefficient code... I have never used the profiler but I'll try it! I am not opening/closing the file each time. I am extracting 700000 rows from a mysql database, extracting additional data from our primary, Oracle database per row, then stuffing each piece of data into a class which preformats the data (I need to output the data into a fixed format string/record for another application which reads them) and returns a single string... which I write out to the file. Mike On Wed, 26 Jun 2002 23:56:09 -0400, Peter Hansen wrote: >candiazoo at attbi.com wrote: >> >> I assume some sort of block i/o or preallocating a large block of file space >> would be the best way to do it? I am outputting about 700,000 records to a text >> file and my program only spits out about 20 records per second. This is using >> standard file open and write... > >You're not opening and closing the file for each record that is written, are you? > >Can you post more detail on the amount of data in a record, and the format? > >Why not profile the code using the profile.py module and actually see >where the problem is? > >-Peter From Dick.Zantow at lexisnexis.com Tue Jun 25 12:09:31 2002 From: Dick.Zantow at lexisnexis.com (rzed) Date: Tue, 25 Jun 2002 12:09:31 -0400 Subject: Parsing strings (\n and \\) References: <3D188006.7050202@thomas-guettler.de> Message-ID: "Fredrik Lundh" wrote in message news:lt0S8.45025$n4.10623651 at newsc.telia.net... > Fran?ois Pinard wrote: > > > A simple avenue is to get Python itself to evaluate the string as a constant > > (you ensure this by removing evaluation context). Something like this: > > > > PARSED = eval(UNPARSED, {}, {}) > > >>> UNPARSED = "__import__('os').system('echo dream on!')" > >>> PARSED = eval(UNPARSED, {}, {}) > dream on! > Even if you use from __far_future__ import * ? From shalehperry at attbi.com Mon Jun 24 18:55:06 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Mon, 24 Jun 2002 15:55:06 -0700 (PDT) Subject: Suggestions for good programming practices? In-Reply-To: Message-ID: On 24-Jun-2002 Dianne van Dulken wrote: > Hi, > > I'm fairly new to python, coming from a perl background, and was wondering > if anyone has a list of things that they consider as good programming > practice in Python (I thought this might be an interesting topic for > discussion, anyway) > > For example, in perl you obviously are always encouraged to use strict, and > we always use eval around our main code to pick up any unexpected errors. I > presume the equivalent in python is the try statement. Would you suggest > that this should be used, or would that be redundant here? Any other tips > that you would suggest a new python user should be always doing as a good > programming practice? > one of the mantras you will hear on this list is: the simpler the code the better you hear this on style issues, on optimization issues, and well practically everywhere. Usually the simple, clean approach yields the best possible python -- both in your time and in runtime. So if you find yourself saying "man, why is this so complex" you should stop and rethink the problem. As a side item, tutor at python.org is a GREAT place to hang out and read about other people learning python. You can really pick up a lot of the niceties and sublties of the language there. From nospam at bigfoot.com Mon Jun 24 11:10:07 2002 From: nospam at bigfoot.com (Gillou) Date: Mon, 24 Jun 2002 17:10:07 +0200 Subject: Subclass of array References: <3d1714c3_7@news.newsgroups.com> Message-ID: The UserList package is your friend... --Gilles "JB" a ?crit dans le message news: 3d1714c3_7 at news.newsgroups.com... > Can I derive an own class from array? (I use 2.2.) > -- > Janos Blazi > > > -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- > http://www.newsfeed.com The #1 Newsgroup Service in the World! > -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From xsebbi at gmx.de Sun Jun 23 05:18:22 2002 From: xsebbi at gmx.de (Sebastian Roth) Date: Sun, 23 Jun 2002 11:18:22 +0200 Subject: bloody freshman question regarding strings In-Reply-To: <1024821351.3424.12.camel@dorian.blaue-elise.net> References: <1024821351.3424.12.camel@dorian.blaue-elise.net> Message-ID: <200206231118.22619@xsebbi.de> On Sonntag, 23. Juni 2002 10:35, Christian Guenther wrote: > My biggest question at the moment is why can't I do something like > this: > > def mailmsg(severity message opts target recipient): > # first create the message body > msgbody="computer: " + COMPUTER + "\n > system: " + SYSTEMTYPE + "\n > cpu: " + CPUTYPE + "\n > kernel: " + KERNELVER + "\n > date: " + DATE + "\n > \n > severity: " + severity + "\n > message: " + message + "\n\n" > a single " means that your string goes over one line in your interpreter. If you want to write over more than one line, try """ instead of ". > chris Sebastian From amuys at shortech.com.au Mon Jun 3 20:36:46 2002 From: amuys at shortech.com.au (Andrae Muys) Date: 3 Jun 2002 17:36:46 -0700 Subject: 'for every' and 'for any' References: <20020526135944.A32690@hishome.net> <20020526091742.A987@unpythonic.net> Message-ID: <7934d084.0206031636.5c29b31f@posting.google.com> Oren Tirosh wrote in message news:... > I don't have a personal utility library. It's on purpose. I don't have > personalized key bindings. I try to avoid customization. Customization is > a big part of what makes one programmer's code difficult to maintain by > another programmer, what makes on programmers's workstation unusable by > another and makes combining code from several sources difficult. > > Just one little example: I hate it when different parts of the code use > their own customized constants for ints from specific sizes. Is it > u_int32_t, uint32_t or guint32? I hate it when a big project starts and the > programmers all start to waste their time on writing a yet another library > with all this stuff. > Now I just don't understand how this position can possibly make sense? C dosn't have any 32-bit int types standardised, so what do _you_ use when you need one? Please don't tell me you don't use int, or I'll have to hunt you down and put you out of your misery ;). I personally have absolutely no problem with any of the 3 examples you gave above: sometimes-the-word-length-is-important-ly yours Andrae Muys From phawkins at connact.com Mon Jun 24 18:58:24 2002 From: phawkins at connact.com (Patricia J. Hawkins) Date: 24 Jun 2002 18:58:24 -0400 Subject: Tkinter and threads References: <3D0DCC8F.9A6D3B81@ipm.fhg.de> Message-ID: >>>>> "A" == Aahz writes: A> In article , A> Patricia J. Hawkins wrote: >> >> Also be aware that the early code examples aren't intended as models, >> just as teaching tools -- you don't hit the really useful stuff till >> page 48. And the format makes it tough to flip back and forth (not to >> mention, tiny amounts of information per page drives me nuts, but >> perhaps that's just me) -- and at 84 pages, I'm not going to print it >> out to take it downstairs to an armchair and mark it up, which is what >> I want to do. And skimming for what you don't know already is >> impossible. A> Yeah, I know. Last summer, I was negotiating with O'Reilly to A> write a whole book on the subject (their idea). Last November, they A> canned the project. I haven't had the time/energy to rewrite the slides A> into a real tutorial, and I'm working on a completely different book now. I hate those old projects. But in this case, just having an all-on-one page version in smaller fonts would help a lot. -- Patricia J. Hawkins Hawkins Internet Applications, LLC From penguin at bredband.no Wed Jun 12 20:08:59 2002 From: penguin at bredband.no (penguin) Date: Thu, 13 Jun 2002 02:08:59 +0200 Subject: fileupload error! Message-ID: <002c01c2126e$84925400$6e00a8c0@arcticpenguin02> Hi I try to upload a picture with a python cgi script. Tried many versions of the code, this is the current. Here's the code and error! The error: Traceback (most recent call last): File "C:\cgi-bin\upload.py", line 179, in ? xmldokument = skjema['dok'].value File "C:\Python22\lib\cgi.py", line 550, in __getitem__ raise KeyError, key KeyError: dok The code: #!c:\python22\python.exe # FileTransfer.py - CGI file transfer, may require Python 1.5 or higher # Author: JeffBauer at bigfoot.com # Prior art: Aaron Watters, Jim Fulton import xml.dom import xml.dom.minidom import xml.parsers import os, sys, traceback import httplib import tempfile from whrandom import randint from string import joinfields from time import time import cgi test = 0 FileUploadRequestException="Dette gikk ikke :" def parseDok(xmlstreng): s=[] pars = xml.dom.minidom.parseString(xmlstreng) elementene = pars.getElementsByTagName('element') for element in elementene: ss={} ss['dataid'] = element.getAttribute('dataid').encode('iso_8859_1') ss['type'] = element.getAttribute('type').encode('iso_8859_1') ss['format'] = element.getAttribute('format').encode('iso_8859_1') s += [ss] return s def lagFilblokk(elementliste,xmldokument): #path = "http://192.168.0.32/upload/" path = "http://192.168.0.32/upload/" #path = "O:\\" #Ting skal vist hete userfile og attach1 o.s.v. s = [{'fieldname':'userfile','filename':xmldokument}] att = 0 for element in elementliste: att += 1 ss={} ss['fieldname'] = "attach%s" % att ss['filename'] = path + element['dataid'] + filending(element['type'],element['format']) s += [ss] return s def filending(type,format): #Dette skal gj?res bedre if format == 'jpeg': return '.jpg' if format == 'jpg': return '.jpg' return '.txt' class FileUploadRequest: """ File upload modul, og sender en liste filer, i med gitte feltnavn. """ def __init__(self, uri, host, port): self.uri = uri self.host = host self.port = port self.queryString = '' self.teller = 1 #self.boundary= '%s%s_%s' % ('-tr--', int(time()), randint(1,10000)) self.boundary= '%s%s_%s' % ('rrrr', time(), randint(1,10000)) #print self.boundary def load(self, filenames, headerDict=None): for filename in filenames: if not '?' in filename['filename']: #Dette er ikke et xml dokument (som jo begynner med From huaiyu at gauss.almadan.ibm.com Wed Jun 19 14:57:22 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Wed, 19 Jun 2002 18:57:22 +0000 (UTC) Subject: python version? References: <3D0E8AC8.6C5C96EE@engcorp.com> <37TP8.47886$GY.15021139@twister.nyroc.rr.com> <3D1010C3.C321F8B0@engcorp.com> <3D107948.B3FEE4BB@engcorp.com> Message-ID: George Hester wrote: > But the reason I >mentioned is that I hoped that my students would take an interest in the subject >and learn the concept. They were not interested but they needed the credit to >graduate. In my case I was not necessarily interested in learning Python. But >I did want to determine my version of Python in ASP. I suppose I was like my >students and ya'll were like the teacher. Yes basically I wanted it handed to >me on a platter. What I did with the platter may have surprised you. So just >becasue somebody wants something handed to them on a platter does not mean the >contribution has less value. Being able to communicate effectively in Usenet may be an important skill for your students to master. You may want to teach them some lessons you have learned yourself. Here's a mini multiple choice questionair to get you started: 1. Suppose you want to get an answer to a question handed down on a platter, which would be the more effective question? a) What is the simplest script to get Python version? b) I know nothing about Python. I just want to know its version from ASP, what's the easiest way to get it? 2. Suppose you are given an answer that is all Greek to you, which would be the more effective response? a) I don't think you guys know anything about this. b) I think I need a script to do this. c) This is well over my head. I'm newbie. Please explain the details, keeping in mind that I only want to get the version from ASP. 3. If someone tells you that you are going about it the wrong way and gives you some advice which sounds like a detour to you, do you judge it based on a) whether he is your daddy. b) whether the advice has merits. 4. Once you realize that all the answers people gave you were real, some much simpler than you imagined before, and that your accusations earlier were largely based on arogance, do you a) Say: Hey, you guys didn't gave me the answers the way I wanted, and your tones were derogotory. b) Go away quietly. c) Say: Thanks for all the answers. Even though I didn't ask the question clearly, one of answer was exacted what I wanted. Sorry for the tone of my earlier posts, which was largely because I didn't recognize the answers. No doubt others can add more lessons learned from this episode. Huaiyu From fredrik at pythonware.com Wed Jun 19 17:58:32 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 19 Jun 2002 21:58:32 GMT Subject: file .seek() under MS-Windows References: <4169349c.0206191318.7f0d99d9@posting.google.com> Message-ID: Frank Schaefer wrote: > The following code: > > fh = open("myfile.pot", "r") > ... > fh.seek(-1,1) > ... > > produces an error: > [IOError 22] Invalid Argument > > under MS Windows (XP). It works fine under Unix, though > (for years). really? $ uname -sr Linux 2.4.7-10 $ python >>> fh = open("somefile") >>> fh.seek(-1, 1) Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 22] Invalid argument > uname -sr SunOS 5.8 >>> fh = open("somefile") >>> fh.seek(-1, 1) Traceback (innermost last): File "", line 1, in ? IOError: [Errno 22] Invalid argument > uname -sr OSF1 V4.0 >>> fh = open("somefile") >>> fh.seek(-1, 1) Traceback (innermost last): File "", line 1, in ? IOError: [Errno 22] Invalid argument (etc) according to the Unix specification, the underlying fseek operation is supposed to generate this error if you attempt to set the file pointer to a negative value. what did you expect it to do? From jadestar at idiom.com Mon Jun 10 19:19:13 2002 From: jadestar at idiom.com (James T. Dennis) Date: Mon, 10 Jun 2002 16:19:13 -0700 Subject: Why does Python mix OO concepts and non OO concepts for operation s on basic types? In-Reply-To: <60FB8BB7F0EFC7409B75EEEC13E20192158EBD@admin56.narex.com>; from Bjorn Pettersen on Mon, Jun 10, 2002 at 05:00:30PM -0600 References: <60FB8BB7F0EFC7409B75EEEC13E20192158EBD@admin56.narex.com> Message-ID: <20020610161913.B34334@idiom.com> On Mon, Jun 10, 2002 at 05:00:30PM -0600, Bjorn Pettersen wrote: >> From: James T. Dennis [mailto:jadestar at idiom.com] > > > Your wish is granted: > >>> x = [] > >>> list.append(x, 5) > >>> x > [5] > >>> str.join(' ', ['a', 'b', 'c']) > 'a b c' > >>> > > not-that-I-would-ever-do-something-like-that'ly y'rs > -- bjorn Doh! Thanks. should-have-tried-that-before-I-posted'ly y'rs Jim. From brueckd at tbye.com Wed Jun 26 11:03:54 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Wed, 26 Jun 2002 08:03:54 -0700 (PDT) Subject: Suggestions for good programming practices? In-Reply-To: Message-ID: On Tue, 25 Jun 2002, Carl Banks wrote: > So why did you ask what kind of teacher calls a newbie's attention to > eval? You seemed (not to be confused with "I have concluded") to have > been advocating ignorance. Nope. Just like on the first day of a C programming class, a lousy teacher would say, "Avoid pointers to pointers!" - it doesn't help at all to bring that up so early in the learning process, it's confusing, and those types of problems are furthest from the students' minds (they're interesting in *doing* something with this new language). There's a host of other things that are more useful to a newbie, whether experienced in other languages or not. But *if* you do bring it up, then you should take the time to explain why it's potentially bad. Likewise, it doesn't really help a newbie much to bring up eval/exec right away and say, "don't use this!" because there's tons of other things that will help them so much more, and in the early learning stages they're not going to be hurt by using those functions anyway. But *if* you do bring those functions up and advise against using them, you should explain why. And if your code will be running in an environment where it might be used maliciously, you need more than "don't use exec/eval" anyway - you really need to take some time to learn about basic program security as there are plenty of other potential security holes (at the very least you need a security mini-FAQ or checkoff list in which exec/eval would be listed along with many other things). With that knowledge you'd discover the risk of eval/exec on your own - they'd jump right out at you with even just a quick security audit. -Dave From financing at cfswebmail.com Tue Jun 18 06:19:01 2002 From: financing at cfswebmail.com (Canadian Subsidy Directory) Date: Tue, 18 Jun 2002 06:19:01 -0400 Subject: Available; Subsidies, Grants, Loans, Financing and General help. Message-ID: <200206180527.g5I5RO726262@plugngo.travelnet.ca> MG PUBLISHING 4865 HWY 138,R.R 1 ST-ANDREWS WEST ONTARIO, KOC 2A0 PRESS RELEASE CANADIAN SUBSIDY DIRECTORY YEAR 2002 EDITION Legal Deposit-National Library of Canada ISBN 2-922870-02-02 (2002) ISBN 2-922870-01-4 (2001) M.G. Publishing is offering to the public a revised edition of the Canadian Subsidy Directory, a guide containing more than 2800 direct and indirect financial subsidies, grants and loans offered by government departments and agencies, foundations, associations and organizations. In this new 2002 edition all programs are well described. The Canadian Subsidy Directory is the most comprehensive tool to start up a business, improve existent activities, set up a business plan, or obtain assistance from experts in fields such as: Industry, transport, agriculture, communications, municipal infrastructure, education, import-export, labor, construction and renovation, the service sector, hi-tech industries, research and development, joint ventures, arts, cinema, theatre, music and recording industry, the self employed, contests, and new talents. Assistance from and for foundations and associations, guidance to prepare a business plan, market surveys, computers, and much more! The Canadian Subsidy Directory is sold $ 49.95, to obtain a copy please call one of the following distributors: Canadian Business Ressource Center: (250)381-4822, 8am-4pm pacific time. Fureteur bookstore: (450)465-5597 Fax (450)465-8144 (credit card orders only). From ken at hotmail.com Sun Jun 2 01:41:33 2002 From: ken at hotmail.com (Ken) Date: Sun, 2 Jun 2002 15:41:33 +1000 Subject: What does sys.exit(1) means? Message-ID: What does sys.exit(1) means? Thanks From kragen at pobox.com Mon Jun 10 08:05:42 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 10 Jun 2002 08:05:42 -0400 Subject: Looking for a list subclassing example... References: <83bsaj4kgn.fsf@panacea.canonical.org> <3D04684C.BA67E64F@alcyone.com> Message-ID: <83r8jf1gq1.fsf@panacea.canonical.org> Erik Max Francis writes: > Kragen Sitaker wrote: > > Why do you think it's a good idea to subclass 'list'? > > > > I don't have one to show, but I think it's generally not a good idea. > > Why do you think it was made possible in 2.2, then? As an experiment. In October, Guido said: Subclassing list and dictionary etc. should be seen as an experimental feature; I don't want to fully fix the semantics yet in all cases. . . . Subclassing a built-in type is appropriate when either (a) you want to use it in a context where a genuine list/dictionary/file/etc.; or (b) you want the speed advantage of the built-in type. In both cases you have to live with some restrictions. Remapping the fundamental accessors (like __getitem__) is probably not a good idea in either case. Adding new state and behavior is fine. [from ] I'm tempted to be flippant and say "to confuse new users" or "as a sick joke", but as Guido points out, there are at least two valid reasons to do it: to optimize your code and to work around breakage --- well, let's say inconsistent, inflexible behavior --- caused by other people's optimizations. From duncan at NOSPAMrcp.co.uk Thu Jun 13 04:29:53 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Thu, 13 Jun 2002 08:29:53 +0000 (UTC) Subject: Python Virtual File System: A spike test References: Message-ID: "Mike C. Fletcher" wrote in news:mailman.1023900618.26500.python-list at python.org: > Equality-testing is useful for: I think the important thing is that all these scenarios use equality to optimise something, so it isn't the end of the world if they occasionally fail to detect equality, although it could be nasty if they returned two paths as equal when they were actually different. > it definitely is tricky, but it's one of the major things I want in > the package (and, after all, if there's no tricky code in the system, > why is someone going to use it instead of rolling their own). I wind > up with code to > do this stuff all over my packages otherwise, I'd like to localise it > somewhere. > Oh good, you want to do some tricky things. :-) > Will need to add special-casing for "local machine" unc, though > I don't see how to do it with cases other than \\.\ given that the > local machine name isn't immediately available as far as I know. I'm not sure I have even seen any good documentation that completely specifies UNC filenames on windows. You may have to handle \\? as well as \\., if you want completeness, but I suspect the law of diminishing returns kicks in somewhere. IF you have the win32 extensions around you can always call win32net.NetWkstaGetInfo to get the machine name, although I must admit that the last time I wanted to get the machine name I used os.popen('NET NAME') and parsed the output. Another option would be to read the appropriate registry keys, which doesn't require the win32 stuff. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From zaka07 at hotmail.com Wed Jun 19 06:33:32 2002 From: zaka07 at hotmail.com (Rad) Date: 19 Jun 2002 03:33:32 -0700 Subject: CPU Usage Windows Message-ID: Hi, I've noticed that when I run Python script on Windows 2k Pro Dual Intel Xeon (2.2GHz) CPU Usage for pythonw.exe is only 50%?! Nothing else is running on the machine (apart form the OS). Some of the python programs are running for hours (large data sets) and even though python shell freeze's (doesn't refresh) CPU usage is still only 50%. System Idle Process is about 40%-50% Any ideas why is this and can I do anything about it? Is it something to do with python not being able to use the power of both processors? thanks, From brueckd at tbye.com Wed Jun 26 11:17:41 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Wed, 26 Jun 2002 08:17:41 -0700 (PDT) Subject: Installation problems DCOracle2 & W2000 In-Reply-To: Message-ID: On Wed, 26 Jun 2002, Talon wrote: > I am having a heck of a time getting DCOracle2 to funcion properly. I > am running on a W2K machine, python2.1.3 and Zope 2.5.1, both of which > run just fine. I installed DCOracle2 and the ZOracleDA under Zope and > it works fine. But standalone python scripts don't see the dco2.py > module. So I tried to install DCOracle2 in the python21/lib folder. I > got that latest version from Zope.org and it said it installed properly. > But it doesn't run. If you try to import it into a script, you get > complaints that it can't find this or that module, all of which are part > of the Zope path. Hi Talon, Some of our development machines use the same configuration you list above. You're probably _very_ close, so I'd stick with DCOracle2 if you can. Would you mind posting the specific error messages you're getting? Also, you mentioned that standalone scripts don't work, but just to be clear, using DCOracle2 in Zope _does_ work without problems? (your connection object is open, you can browse the database, you can run test queries, ZSQL methods, etc.) If it's working for Zope, then standalone scripts should be able to use DCO2 if you include the right directory in your PYTHONPATH environment variable, so please tell us what your PYTHONPATH is too. Good luck, Dave From idbaxter at semdesigns.com Sat Jun 1 09:49:19 2002 From: idbaxter at semdesigns.com (Ira Baxter) Date: Sat, 1 Jun 2002 08:49:19 -0500 Subject: symbolic python References: <3CEFAE4C.38A8022B@doc.ic.ac.uk> <3CEFD881.D7992095@doc.ic.ac.uk> Message-ID: <3cf8ce86$1@giga.realtime.net> If you want program transformation capability, you can get it in the form the of DMS Software Reengineering Toolkit. See http://www.semdesigns.com/Products/DMS/DMSToolkit.html. -- Ira Baxter, Ph.D. CTO Semantic Designs www.semdesigns.com 512-250-1018 "Benjamin Tai" wrote in message news:3CEFD881.D7992095 at doc.ic.ac.uk... > > Hi, Benjamin. Not as you say it. > > > > However, I often met needs that could have been resolved as you say in > > some other languages, and that were easily addressed using more Pythonic > > paradigms. My belief if that Python is very flexible for such problems, > > if you accept to "negotiate" with the language. > > > > If you explain a bit more precisely what is the problem you are trying to > > solve, it is likely that many members of the Python list will have ideas > > or solutions to offer, that you might find workable and even elegant. > > This is my guess, do not take it as a promise :-). > > > I am afriad it is only simple (stupid + abstract) question out of > cuirosity. It does sound like some simple form of program transformation > (although I am not try to achieve any optimisation or static checking > here). > > > > Example 1): > > Could it be possible to have a parser to rewrite my derived class: > > class base: > def b_fun(self): > pass > > def overloaded(self): > print "base" > > > class derived(base): > def overloaded(self): > print "derived" > > > > into something like: > > class derived(base): > def b_fun(self): > pass > > def overloaded(self): > print "derived" > > > such that methods inherited from the base class is also written inside > the derived class. > > > > > Example 2): > > Could it be possible to have a parser to rewrite my derived class: > > class base: > def b_fun(self): > pass > > class derived(base): > def d_fun(self): > self.b_fun() > > > > into something like: > > class derived(base): > def d_fun(self): > self.b_fun() > > def b_fun(self): > pass > > > such that methods called from the base class is also written inside the > derived class. > > > > > > Simply speaking, I can look up a module to find out name of the > functions located inside. Could I also find out their function body? > I can get Python to evaluate the function, but is it possible to return > the source code of the funciton body at the same time? > > In a symbolic language, I would imagine there should be direct access > towards the body of the function. Could it be possible for Python to > have a similar behaviour? > > > > Thanks > > Ben > From pyth at devel.trillke.net Wed Jun 5 20:28:15 2002 From: pyth at devel.trillke.net (holger krekel) Date: Thu, 6 Jun 2002 02:28:15 +0200 Subject: self In-Reply-To: ; from vjovanov@stevens-tech.edu on Wed, Jun 05, 2002 at 02:40:45PM -0400 References: <0%hL8.22575$tK.5490038@news02.optonline.net> <_zpL8.81$pq2.4342892@newnews.cc.stevens-tech.edu> Message-ID: <20020606022815.F30696@prim.han.de> Vojin Jovanovic wrote: > [me] > > The next best solution IMO is to preprend a namescope like 'self.' > > to every name in an expression. > > But you may have to parse the expression to > > do this. > > I have been thinking about this for some time, and realized that there some > tricky cases that one has to deal with, and I am not sure that the whole > business of appending self. will be error free in every case. > For example in 'x + Geometry.x' the correct result should > be 'self.x + self.Geometry.x' where Geometry is an instance of Geometry > class that is bound to self.Geometry. with a small modification to my previously posted class you *can* do this: class Evaluator: def __init__(self, eqs={}): self.__dict__['equations']=eqs def __getattr__(self, name): value = self.equations[name] if type(value)!=str: return value # if it's not a string, just give it back scope={} while 1: try: return eval(value, scope) except Namerror, n: var=str(n).split("'")[1] scope[var]=getattr(self, var) def __setattr__(self, name, value): self.equations[name]=value class Berta: a=5 >>> e=Evaluator({'a':'3']) >>> e.berta=Berta() >>> e.g='berta.a*a' >>> e.g 15 This is hopefully what you want. This version doesn't detect cycles in equation definitions, though. Shouldn't be too difficult to add but requires some more thought. ask again if you are having problems with it. have fun, holger From mdtorre at freemail.it Thu Jun 13 05:30:38 2002 From: mdtorre at freemail.it (Matteo) Date: 13 Jun 2002 02:30:38 -0700 Subject: What language - platform use to data acquisiton/numerical work? Message-ID: <1c849ea9.0206130130.6cdaa36f@posting.google.com> I'm a programmer, I've worked with C, Java, Perl, Matlab, PHP, and a bit of almost every widespread language. I love OO programming. I have recently doscovered Python thanks to the great enthusuasm of its supporters. I love Java for its elegance and OO-ness, and Perl for its raw power. I don't like C++ for its long developng time and complexity and hate Visual C++ for being the worst (most complex, most slow, most ... ugly) develop environment on the earth. I have to do (from scratch and alone) a work without any language restriction. The system will have to work under MSWin2000 and maybe that, for stability, we will port it to unix-likes. The work involve: - a system of data acquisition (and control) from (of) a PLC via serial port. The data acquisition is in real time with low frequency (about 1 - 2 hz) - a big system of data analisys, pattern recognition, data visualization and heavy user interaction mostly for experiment with algorithms and for diagnostics - a end user system, mostly a wrapping of siplified GUI to the previous two subsystems. I think Python would be suitable for my work. What do you think? I think I will handle serial port comm vith small C libraries, I don't know if Python is suited to the problem. Having the base drivers should not be a problem ro realize the data acquisition system in Python Or not? The data analisys numerical procedures have to be done in matlab due to their complexity and specialization, and I fear even the plotting will have to be done in Matlab. I have seen there are some bridges from Phyton to Matlab, how they are? My problem here is where to start developing in Pyyhon and where to stop in ML. ML has a very simple and good sistem of building GUIs, how is Pithon? Finallly I hope to develop the wrapping GUI layer in Phyton. Again, has Python some simple and good GUI support? I've seen that the most widely used GUI module is something in tcl/tk (which I don't know at all). Considering that I don't know python nor tcl/tk, how is the learnig and developing curve? Thank you all. Matteo Della Torre From b_mcerlean at yahoo.com Fri Jun 7 10:10:59 2002 From: b_mcerlean at yahoo.com (Brian McErlean) Date: 7 Jun 2002 07:10:59 -0700 Subject: Efficient python programming... References: <20020606215349.GA13474@node1.opengeometry.net> Message-ID: gabor wrote in message news:... > > for file in directory: > file.printsize() > > > ran = range(len(directory)) > for r in ran: > directory[r].printsize() > > [file.printsize() for file in directory] > > they're the same, and everyone would recommend you the last one.. I wouldn't. The first one is better in this case. Using the list comprehension implys to me that you're interested in the result - while in fact you're discarding it. If there are a lot of files in the directory (And after all, thats the only reason to optimise it), then you'll end up with a large list of [None,None,None,...] that is completely unneeded. testing gives: [foo(i) for i in range(100000)] - took 0.240000009537 secs for i in range(100000): foo(i) - took 0.149999976158 secs (foo(i) is just an empty function) Using the list comprehension here is both misleading (because you are relying on a side-effect, not using the returned list), and less efficient. Using the for loop is better, because it makes clear that you're using an imperative technique, relying on the side-effect (printing the size) and are uninterested in building a list at all. On the other hand, if the code is: l=[] for file in directory: l.append(file.getsize()) It is both clearer, and more efficient if implemented as: l= [file.getsize() for file in directory] Brian. From peter at engcorp.com Mon Jun 17 20:56:57 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 17 Jun 2002 20:56:57 -0400 Subject: Zip makes sense! was: Re: why not "'in' in 'in'"? References: Message-ID: <3D0E8559.118C82CE@engcorp.com> "James T. Dennis" wrote: > > More over the term "yield" in English has a few distinct senses. I'd argue all the senses you've presented are extremely similar, perhaps identical in semantic meaning, but with distinct contexts which make them look a little different. > One (slightly archaic) is the imperative to "yield" to a conqueror > or authority as in: > "Yield, Sir knight!" > Another is a similar and common traffic imperative meaning to defer > to the rights-of-way for others (probably the inspiration for the > most common programming semantics associated with 'yield'). > Another is to refer to the product of a farm or manufacturing process > as in: the yield of the corn field last year was X bushells. > > It is clearly this last sense which inspires Python's use of the > term. The return operator "yields" a result *and* terminates an > execution contect. The yield operator also "yields" a result but > it leaves the production machinery or the "field" available for > future results. In exactly the same manner, if the knight yields he is still available for future results, such as another fight or, more usefully, joining the conqueror's own crusade. In all cases here, it looks like yielding involves producing an output of value while preserving the producer intact for future results. Were 't not so, the conqueror would but cry "Die, Sir Knight!" and despatch the hapless knave forthwith. ;-) -Peter From gustav at morpheus.demon.co.uk Fri Jun 7 09:41:10 2002 From: gustav at morpheus.demon.co.uk (Paul Moore) Date: Fri, 7 Jun 2002 15:41:10 +0200 Subject: Gordon McMillan's Installer - Data files in the archive References: Message-ID: Gordon McMillan writes: > [posted and mailed] > > Paul Moore wrote: > > [snip] > >> That worked remarkably easily. A trivial example: >> >> from carchive import CArchive >> me = CArchive(sys.executable) >> readme_file = me.extract('README')[1] >> >> One thought occurs - how "supported" is the CArchive class interface? > > I expect advanced users to do things like this. > I also expect them to manipulate TOCs and put > extra processing in their spec files. Installer's > only a black box if you don't open it :-). Fair enough. That sounds like a reasonable approach. Of course, whether *I* should do this boils down to whether I consider myself an "advanced user", or a "dumb blunderer who shouldn't be allowed near a computer" :-) pandora-opened-a-black-box-and-look-what-happened'ly y'rs Paul. From bt98 at doc.ic.ac.uk Sat Jun 8 11:47:51 2002 From: bt98 at doc.ic.ac.uk (Benjamin Tai) Date: Sat, 08 Jun 2002 16:47:51 +0100 Subject: PyCObject subtype PyObject Message-ID: <3D022727.2147C50E@doc.ic.ac.uk> Hi, Any comments to clarify my confusion would be appreciated. In Python/C API Reference Manual, section 7.5.9 CObjects, the document mentions that: "PyCObject This subtype of PyObject represents an opaque value, ..." 1) What does it mean by "subtype"? As a C interface, is the document talking about two structs which share some common fields? 2) For function "PyCObject_FromVoidPtr()", it takes in a "void*" as the first argument. For function "PyCObject_AsVoidPtr()", it returns a "void*". When implementing Python extension, what is the potential danger of casting pointers, of different size, to and from "void*"? 3) What if I can always determine the original type of the pointer? 4) Apart from exporting function between modules, are there any examples of using PyCObject? Thanks Ben From phawkins at connact.com Fri Jun 21 19:01:13 2002 From: phawkins at connact.com (Patricia J. Hawkins) Date: 21 Jun 2002 19:01:13 -0400 Subject: Tkinter and threads References: <3D0DCC8F.9A6D3B81@ipm.fhg.de> Message-ID: See Aahz's FibThreaded.py example that accompanies his slides for his thread talk. http://starship.python.net/crew/aahz/OSCON2001/index.html The whole thing is worth reading, but beware, it's really set up for a speech, not reading -- it's 84 pages with +/- 10 lines of text per page, and a lot of places where Aahz probably says a whole lot to the audience, but all you get is "Share external objects: Files, GUI, DB connections DON'T partial exception: print" so, um, why is print a _partial_ exception? Also be aware that the early code examples aren't intended as models, just as teaching tools -- you don't hit the really useful stuff till page 48. And the format makes it tough to flip back and forth (not to mention, tiny amounts of information per page drives me nuts, but perhaps that's just me) -- and at 84 pages, I'm not going to print it out to take it downstairs to an armchair and mark it up, which is what I want to do. And skimming for what you don't know already is impossible. Whinging aside, it's got a lot of meat, and useful solutions for a number of problems. -- Patricia J. Hawkins Hawkins Internet Applications, LLC From kragen at pobox.com Sun Jun 2 22:51:31 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 02 Jun 2002 22:51:31 -0400 Subject: HTML links in a GUI tkinter References: Message-ID: <83k7phrs5o.fsf@panacea.canonical.org> "G. Willoughby" writes: > import os > os.startfile(page.html) > > to execute the html file. os.startfile is nonportable. From martin at v.loewis.de Wed Jun 5 16:51:32 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 05 Jun 2002 22:51:32 +0200 Subject: Freeze questions References: Message-ID: "Sung H. Kim" writes: > Can the Freeze tool be used with C libraries? i.e. extensions? Sure. I recommend that you don't build the extensions as shared libraries, but as static object files - that allows you to incorporate them into the binary. The frozen binary cannot incorporate shared libraries - but it can still use them. > Will it create a truly standalone app (on Windows)? Not in the default configuration. If you build python as a static library (i.e. pythonxy.lib instead of pythonxy.dll), then you can create truly standalone binaries. It requires some manual work to create such a build process, though. > Does it support tk/tkinter apps yet? Depends on what you mean by "support". You can certainly freeze Tkinter applications, but that won't incorporate the Tcl libraries into the executable. To achieve that, you need - static versions of the Tcl libraries, - Tix - Tix Stand-Alone Modules (SAM) If you build Tix with SAM support, you get truly standalone Tkinter binaries. I did that five years ago, but haven't tried since. > Finally, is there a good how-to on the Windows platform? Sure. The Microsoft online documentation (press Start, then Help) includes quite reasonable Howtos for using Windows :-) Regards, Martin From martin at v.loewis.de Thu Jun 6 03:14:37 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 06 Jun 2002 09:14:37 +0200 Subject: minidom and encoding problem References: <17aafe08.0206051514.4af054d2@posting.google.com> Message-ID: ehab_teima at hotmail.com (Ehab Teima) writes: > I'm using Python 2.1. I wrote classes to create xml document from > scratch. The code worked fine until I hit an encoding problem. The > classes can read text and insert it as is to xml document using > creatTextNode. This text had characters > 127, and I got this error. This is a bug in your code. You must not insert (byte) string in a DOM tree; always use Unicode objects. > I know it's not possible to add an enconding attribute using writexml, > so the generated document only has . Is there any > way to get around this problem. Yes. Use Unicode strings when creating text nodes. When producing the serialized document through .toxml, you will find that it produces a Unicode string. Since (as you notice) the document has no encoding declaration, you need to .encode("UTF-8") that string before saving it into a file. > Does any body know how to get the rootnode of a document? If I know > the root node, I can add the proper header and then write the root > node using writexml. The document element is available through .documentElement on the Document. Regards, Martin From max at alcyone.com Sat Jun 15 05:03:43 2002 From: max at alcyone.com (Erik Max Francis) Date: Sat, 15 Jun 2002 02:03:43 -0700 Subject: Newbie deluxe References: Message-ID: <3D0B02EF.AA1AB471@alcyone.com> Zach wrote: > I've just started taking a look at Python (experienced in Delphi) and > so far > it looks very clean and comprehensible. My question is, what are the > fundamental differences and similarities between it and Perl? I hear > so > much about these two languages, especially in Linux circles and just > wondered what sets them apart. http://www.python.org/doc/Comparisons.html#perl > Can full fledged graphical applications be > built with Python or does it lean more towards scripting? Of course. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Who'd ever think it / Such a squalid little ending \__/ The American and Florence, _Chess_ Church / http://www.alcyone.com/pyos/church/ A lambda calculus explorer in Python. From tim at vegeta.ath.cx Thu Jun 13 05:13:13 2002 From: tim at vegeta.ath.cx (Tim Hammerquist) Date: Thu, 13 Jun 2002 09:13:13 GMT Subject: How to check version of Python under CGI References: Message-ID: Johann graced us by uttering: > I would like to write a simple CGI script to get as much info about > installed Python as possible. But I even don't know how to check > version of Python. :( From shell command it is easy, but how to do it > from CGI script? Eg. > > #!/usr/bin/env python > print "Content-type: text/html\n\n" > print "Python version: %s" %s (IDoNotKnowWhatToChoose(),) import sys print sys.version # version info in string print sys.version_info # version info in tuple HTH Tim Hammerquist -- Tools, of course, can be the subtlest of traps. -- Daniel, The Sandman From nomailhere at lookitup.yourself.com Sat Jun 22 12:01:01 2002 From: nomailhere at lookitup.yourself.com (Frihtiof Andreas Jensen) Date: Sat, 22 Jun 2002 18:01:01 +0200 Subject: Python hits the spot References: <3D1482AE.8FA299D8@kfunigraz.ac.at> Message-ID: <3d149f19$0$53133$edfadb0f@dspool01.news.tele.dk> "Siegfried Gonzi" skrev i en meddelelse news:3D1482AE.8FA299D8 at kfunigraz.ac.at... > A few weeks ago I complaint here that Python on Windows XP sucks. I had > a problem which would took theoretically about 1.5 hours; but in reality > it takes 6 hours on Windows XP and Python 2.2. After that 6 hours I must > reboot my system in order to work on. So, memory is leaking away somewhere... > In the following I got the advice to install a real user system on my > laptop. Okay, I bought Linux SuSE 8.0 and installed it on my laptop (256 > MB RAM, 1000 MHz Celeron). I also installed Python 2.2 (the ActivePython > version, otherwise I couldn't install idle due to the annoying > "free_software_garbage_2_weeks_installation_nightmare"). If you think the software others have spent time to develop for you to use as you please is "garbage" then why do you still use it and even whine about it to boot? I have no problem whatever installing the standard Python 2.2.x installs on ANY flavour of windows - even my win2k corporate install with restricted access is dealt with nicely by the install! I doubt many others had problems...it is about as easy as it possible gets. > My conclusion: I will rewrite my simulation in Fortran 90 and will > abadon Python. Python is maybe good for some small scripts but not > appropiate for serious programming. > *My conclusion: Lets look for Common Factors here: Python builds are *different* on Linux and WinXP, GUI's are *different*, in fact the common factors are YOU and YOUR Program....which leads me to believe that you have made a mistake, in your code. > Thank you Billy Boy for a forgiving user system Windows XP which in turn > relieves Python's "wreak havoc" behavior. Then write your software for MSC++ or C# - it is fine by me. > I cannot believe that Linux is responsible for Python's ill behavior > under Linux. Before you start ranting about note the following: In a > first step it has nothing to do with my programming style (admittedly > not very good and famous) it has to do that the same calculation cannot > be performed on Linux and Python 2.2! I think it has something to do with your coding style and everything to do with your attitude - you are using tools, which are working well for thousands of developers, yet when they do not work for you, it is the fault of the tool and not because you are doing something wrong! It is the hallmark of the neophyte programmer to consider oneself capable of *knowing* that ones code is flawless. Do you also blame the hammer, when you hit your thumb rather than the nail? Then you come out and slag off the very people who might be able to help, had you bothered to post a proper description of the problem, perhaps with some sample code, thus ensuring that nobody will care at all whether it really is a bug within Python, or not, just as long as it only affects your application. My bet is that once you cool off and sits down with some debugging tools like GDB, Boundschecker or Electric Fence you will indeed find the programming error and fix it. My bet is also that you will not tell anyone either. From jonathan at onegoodidea.com Fri Jun 28 16:20:26 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Fri, 28 Jun 2002 21:20:26 +0100 Subject: testing type of an object References: Message-ID: On 28/6/2002 20:00, in article afibp0$ekn25$1 at ID-76829.news.dfncis.de, "Russell Blau" wrote: > You can use > > if type(s) == type('abc'): > do something > > or, even better, import the types module (which you can look up in the > docs). Or, in Python 2.2, it's preferable to compare against the new type constructor builtins: >>> type('foo') is str 1 >>> type(5) is int 1 >>> or: >>> isinstance( 'foo', str ) 1 >>> isinstance( 5, int ) 1 >>> The other ones are: 'dict', 'long', 'list', and 'unicode'. Jonathan From gmcm at hypernet.com Wed Jun 26 08:20:51 2002 From: gmcm at hypernet.com (Gordon McMillan) Date: 26 Jun 2002 12:20:51 GMT Subject: import precedence References: Message-ID: Mark McEahern wrote: [snip] > Can I just assume that: > > from spam import foo > > will only import the foo.py module if the foo.dll and foo.so are not > found...? No. On any given installation, you could set things up so it would work, but it would be fragile and when it broke, it would be very mysterious. --Gordon http://www.mcmillan-inc.com/ From syver-en+usenet at online.no Wed Jun 26 21:33:08 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Thu, 27 Jun 2002 01:33:08 GMT Subject: python mode for emacs References: Message-ID: Alberto Griggio writes: > On Fri, 21 Jun 2002 18:02:14 +0200, Syver Enstad wrote: >> Is there a straight forward way of deciding how the >> py-pseudo-keyword-face >> should look? > (defun my-py-mode-hook () > (set-face-foreground 'py-pseudo-keyword-face "CadetBlue") > ;; ... and anything else you want > ) > (add-hook 'python-mode-hook 'my-py-mode-hook) > > Bye, > Alberto Thanks, I changed it to "Black" and (make-face-italic 'py-pseudo-keyword-face) Very nice, just gives self and the other pseudo keywords a little emphasis without being too "loud". -- Vennlig hilsen Syver Enstad From eddie at holyrood.ed.ac.uk Thu Jun 13 09:53:22 2002 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Thu, 13 Jun 2002 13:53:22 +0000 (UTC) Subject: parse tar file with python References: Message-ID: "Shagshag13" writes: >In fact, i don't want to tar/untar files, and especially not in main memory ! >I wish i could read the tar-ed file line by line (f.readline) and be able to check when i find the beginning of an "inside file" and >get some info about it like name, how and so on... (that's because my original files are plain text file, and i think that tar will >let them unchanged) >In my tar file there is, for example, a kind of separator like this (but with everything in one long line) with : >shag.py_0100744_0002033_0001750_00000004414_07500237361_0015314_0_ustar_00_shagshag_user_0000040_0000417_beginofmyfilehere >where _ stand for a variable amount of another ascii code that i can't cut/paste... >Do you kwow what each means (for example the first one is undoubtly the file name, but then...) ? >And what are the fixed position of each of theses ? >Have a clue ? A google search on 'tar file format directory header size' came up with this: http://www.mkssoftware.com/docs/man4/tar.4.asp I did write a tar program in Bliss10 many years (nay decades) ago and recall it was quite easy to deal with. Using tar is only useful if you know for certain that you're going to process each file in exact sequence. I think other solutions like making smaller directories would be easier. Surely if all you're doing is reading all files in sequence you can just concatenate them into one?, if you need to know where each ends add a unique seperator. Eddie From sholden at holdenweb.com Fri Jun 7 16:48:37 2002 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 7 Jun 2002 16:48:37 -0400 Subject: Creating Dynamic Web Pages (ZOPE) References: <46ca81a0.0206062016.789d3af6@posting.google.com> Message-ID: "Hugh Cowan" wrote ... > Hello, > > I am not exactly sure where to post this question -- the only > reference that I could find for ZOPE in the Newsgroups is here. I > appologize if this is not the correct place. > > I have the situation where I need to create a simple Intranet for my > company to display dynamic / data driven web-pages. We are running a > Windows NT network with MS-SQL Server and IIS. > > I had originally thought of using ASP (Server Side Scripting) to > generate the dynamic web-pages. While I know how to create the > Intranet using ASP, I have yet to find any RAD type Web-Tools that > will allow me to quickly and easily generate the ASP pages required, > and I don't fancy using the Notepad approach either. > > My scenario is typical where I need to put together a company Intranet > with a few front end Web-Pages where users can select information, > various links, and enter search criteria. The information is then > retrieved from the MS-SQL Server and the results are sent back to the > user. It's nothing fancy, no shopping carts, or remembering sessions > states, etc.. just really a simple front-end interface for > non-technical people to easily retrieve information. > > I don't know if ZOPE would fit my situation or not. I know that it is > / can be used to create complex E-commerce sites, but I am wondering > if it is overkill for what I need done. Would I be better off trying > to find some sort of RAD Web Tool instead (anyone have any good > suggestions) ? > At the risk of sounding like a heretic... I recently started to use DreamWeaver UltraDev (one of my clients mandated its use) and I've been relatively impressed. For a really small database-driven web created in DreamWeaver take a look at http://www.holdenweb.com/TinySite/ This web has precisely four pages, and I built it to explain to beginners how database contents can affect a site's navigation as well as its readable content. DreamWeaver MX is now out, and targets several more backends. It would be nice if it had one that drove some suitable Python framework -- possibly WebWare. If you are already familiar with ASP, this will get you up to speed on your tasks much more quickly than learning Zope. Won't be as much fun, though. regards Steve -- ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From eddie at holyrood.ed.ac.uk Fri Jun 14 13:17:21 2002 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Fri, 14 Jun 2002 17:17:21 +0000 (UTC) Subject: I feel stoopid ... this code is to verbose References: <3D0A1791.3060307@mxm.dk> Message-ID: Max M writes: >Hmm ... I am working on a problem. In Danish we have a number format >that looks like: >42.000.000,00 which is 42 millions >def stringSlicer(string, chunkSize=3): > chunkList = [] > reverseString = list(string) > reverseString.reverse() > for i in range(0, len(string), chunkSize): > chunk = reverseString[i:i+chunkSize] > chunk.reverse() > chunk = ''.join(chunk) > chunkList.append(chunk) > chunkList.reverse() > return '.'.join(chunkList) >I just find that it's a lot of code for such a little function an it >annoys my sense of aestetics. I have tried a lot of different approaches >including using zip on a list like ['','','.'], and other weird stuff :-) Recursion and remembering that you can avoid reverse by chopping off the tail end. My contribution: def commas (n,span=3,sep='.'): def chop (x, acc=[]): if not x: return acc return chop (x[:-span], [x[-span:]]+acc) return sep.join(chop(str(n))) I called it that because that's what the Icon command is called (and I misread the post first time through - eyesight must be going). Eddie From martin.stahl at telia.com Sat Jun 29 13:00:16 2002 From: martin.stahl at telia.com (Martin Ståhl) Date: Sat, 29 Jun 2002 17:00:16 GMT Subject: Newbie that don't understand Message-ID: I have never been programming before and now I am reading the "Non-Programmers Tutorial For Python" http://www.honors.montana.edu/~jjc/easytut/easytut/node9.html#SECTION0091000 0000000000000 And don't understand the following I quote "To start off this chapter I am going to give you a example of what you could do but shouldn't (so don't type it in): a = 23 b = -23 if a < 0: a = -a if b < 0: b = -b if a == b: print "The absolute values of", a,"and",b,"are equal" else: print "The absolute values of a and b are different" with the output being: The absolute values of 23 and 23 are equal" how can 23 and -23 be equal? From anton at vredegoor.doge.nl Sat Jun 29 13:43:40 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sat, 29 Jun 2002 19:43:40 +0200 Subject: [MODULE] rubiks cube simulation for visual python Message-ID: A very basic rubiks cube simulation written for visual python. Displays a 3D simulation of a rubiks cube. It is possible to view to cube from all sides, the cube can be zoomed, the layers can be rotated by typing single keystrokes and there is an undo function. http://home.hccnet.nl/a.vredegoor/rubik/rubik.py or (html-version) http://home.hccnet.nl/a.vredegoor/rubik/rubik.html From roelsch at comtrak.com Tue Jun 4 16:44:58 2002 From: roelsch at comtrak.com (Robert L. Oelschlaeger) Date: 4 Jun 2002 13:44:58 -0700 Subject: Version strings in executable created by Py2exe References: Message-ID: <4323edf0.0206041244.7c9b9b7a@posting.google.com> "Jimmy Retzlaff" wrote in message news:... > Probing a little deeper, it appears as if either - or should work. > From the part of distutils which parses setup.cfg: > > opt = string.replace(opt, '-', ' ') > > Here is a part of my setup.cfg (of course the word-wrapping is not in > the file): > > > Jimmy The problem was with the static name of the configuration file: setup.cfg. I am building several applications in the same directory (e.g., demo4, demo5) and have created separate demo4_setup.cfg and demo5_setup.cfg files (and corresponding demo4_setup.py and demo5_setup.py files). These .cfg files were not being used. The problem has been sidestepped by having the makefile copy the proper demo_setup.cfg to setup.cfg, generating the demo.exe file, and then deleting setup.cfg. Thanks for the help. Bob From carlca at dircon.co.uk Thu Jun 13 18:16:51 2002 From: carlca at dircon.co.uk (Carl Caulkett) Date: Thu, 13 Jun 2002 23:16:51 +0100 Subject: Python 2.2.1 References: Message-ID: <2v4igu4640ru57rv43kjrf43vvbn4h6btr@4ax.com> On Thu, 13 Jun 2002 20:58:58 GMT, "Dave" wrote: > Hi, I am 12 years old and would like to begin learning Python over the summer. I have Windows 98 SE. I have python 2.2.1 and all of its utilities on my computer. I am taking a tutorial from http://softwaredev.earthweb.com/sdopen/article/0,,12382_626311,00.html If you go to it and scroll down to the paragraph entitled Getting Started there is a paragraph that says, "You will need to cause the directory containing the file named python.exe to be listed in your system environment variable named path. If you already know how to set the path, go ahead and do it. If you don't already know how, you may need to get some help." > > > How do I set the path and what should the name of the path be? All help and information would be appreciated. Thanks.:) Hi Dave, Step 1 ... First of all you need to make a note of where Python is installed. If you used the default settings, I would think that it will be in C:\Python22 or something similar. The file python.exe should be in a sub-folder called "bin" underneath the C:\Python22 folder. So here you would note down C:\Python22\bin. Step 2 ... (*** VERY IMPORTANT ***) The next step is to make a backup of your autoexec.bat file (this will be in the root of your C: drive. Just use Windows Explorer to make a copy of it. Step 3 ... Then you will need to edit autoexec.bat by opening it in Notepad. Find the line which says something like PATH C:\WINDOWS;C:\WINDOWS\COMMAND. You then need to add the folder name that you noted in step 1 to the end of this line. If the line already ends with a ; character, then just add the folder name straight after. If there is no ; then you need to add one to the end of the existing path entry before adding the new folder name. Step 4 ... Save the edited autoexec.bat and close Notepad. Step 5 ... Reboot the machine. Step 6 ... Once the PC has rebooted, you can check that the path change is correct by doing Strat -> Run -> "command". This will bring up a DOS prompt. Just type in the word PATH and . You should see a line that shows your newly added Python folder at the end. Type EXIT and to leave the DOS prompt. That's it - you should be ready for Python now. By the way, well done for choosing Python. It's a remarkable language that will help you learn some good programming skills. Just as importantly, it's great fun because you can start to see useful results very quickly, which is a great way of motivating you to learn even more. Good luck . P.S. You might want to check your newsgroup settings and see if you can switch on the wordwrap option. Your message came through as one continuous line. -- Cheers, Carl From pyth at devel.trillke.net Sat Jun 15 07:44:10 2002 From: pyth at devel.trillke.net (holger krekel) Date: Sat, 15 Jun 2002 13:44:10 +0200 Subject: Pronouncing '__init__' In-Reply-To: <20020615132519.A14452@hishome.net>; from oren-py-l@hishome.net on Sat, Jun 15, 2002 at 01:25:19PM +0300 References: <20020615132519.A14452@hishome.net> Message-ID: <20020615134410.A15079@prim.han.de> Oren Tirosh wrote: > There has been a thread about this issue in the past. Below are some of the > proposals people made. I'd like to have an informal vote - how do *you* > say Python's magic names when talking with other Pythoneers? > > (all my Python-related communication is written) > double underscore init double underscore > under under init under under > double bar init double bar > bar bar init bar bar > unders init unders > under init under > bar init bar > magic init > pyinit > > Most of these pronounciations also have a shorter version with the trailing > part omitted. for oral language: init constructor and if the context allows init for written languange __init__ Isn't it obvious? :-) holger From dguo at ux1.cso.uiuc.edu Thu Jun 6 15:26:26 2002 From: dguo at ux1.cso.uiuc.edu (Carolyn Guo) Date: Thu, 6 Jun 2002 14:26:26 -0500 Subject: alignment excel written in Python In-Reply-To: References: <6bd9f01b.0206050736.f469082@posting.google.com> <3CFE9861.5090200@skippinet.com.au> Message-ID: Thank you very much. This time, it works well. Could you please tell me where I can get the detailed reference about writing Excel command from Python? I have worked out something like put color, borders in cells.But still I need more detailed information on this issue so that I can get a more clear picture of it. Thanks again. Carolyn On Wed, 5 Jun 2002, Raymond Hettinger wrote: > > I have a questions now: How can I deal with the alignment of Excel from > > Python? for example, put the value in a cell with alignment right, or > > center. > > xlLeft, xlRight, xlCenter = -4131, -4152, -4108 > from win32com.client.dynamic import Dispatch > xl = Dispatch('Excel.Application') > xl.Range('A1').HorizontalAlignment = xlRight > > > Raymond Hettinger > > > From kragen at pobox.com Mon Jun 10 17:49:21 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 10 Jun 2002 17:49:21 -0400 Subject: Interrupting a continuous script References: <_6JK8.1535$376.74360@newsfep1-win.server.ntli.net> Message-ID: <83k7p6pzxa.fsf@panacea.canonical.org> "Julian Gollop" writes: > I have a few programs continually processing text files on a Linux machine. > Occasionally I need to stop them, but I don't want to use a keyboard > interrupt because it may cause the script to stop in the middle of doing > something. > Does anyone know a simple way to allow me to stop the process by pressing a > key on the keyboard - without stopping inside something crucial? You could use select() to see if stdin is readable. My suggestion, though, would be to try to design the program so that it can be stopped at any point without anything bad happening. If the machine gets unplugged, after all... There are two general strategies for this: restartability, or idempotence, and atomicity. A restartable operation is one that, if interrupted in the middle and restarted from the beginning, will produce the same results as if it had been done once straight through. An atomic operation is one that is either completed or not and cannot be interrupted in the middle. On Linux, renaming a file and creating a directory are atomic operations. From mgerrans at mindspring.com Sun Jun 9 23:58:33 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Sun, 9 Jun 2002 20:58:33 -0700 Subject: How to capture stdout into a string? References: <2YLM8.905$Yw3.119357@news20.bellglobal.com> <3D039285.72DFC71D@engcorp.com> <3D039A73.210CDF7F@engcorp.com> Message-ID: > :-) Actually, I assumed you already had RTFM.... > Still helpful sometimes to read the source. Maybe you guys can coin (or have coined) a new acronym: RTFS From mfranklin1 at gatwick.westerngeco.slb.com Wed Jun 5 09:31:41 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Wed, 5 Jun 2002 13:31:41 +0000 Subject: Fastest way to read / procsess / write text? In-Reply-To: <3CFD5229.2060803@excite.com> References: <3CFD5229.2060803@excite.com> Message-ID: <200206051234.g55CYsB06651@helios.gatwick.geco-prakla.slb.com> On Tuesday 04 Jun 2002 11:47 pm, you wrote: > I'm somewhat new to python and programing in general and I trying to > write a simple script that I can use to format large text files so that > they are suitable for importing into MySQL. So far, I have came up with > this: > > #!/usr/bin/python2 > > import sys, re > > infile = sys.stdin > data = infile.read() > infile.close() This was the standard idiom (untill xreadlines came along I guess) while 1: data=infile.readlines(100000) # hint to readlines for 100000 bytes.... if not data: break ## EOF reached for line in data: ## process data > > data = re.sub('[.](?=\d\d\d\d\d\d)|[.](?=\w+[ ][<|>])|[.](?=\w+[:])|[ > ](?!0x)', '\t', data) > > outfile = open("/mnt/storage/output.txt", "w") > outfile.write(data) > outfile.close() > > > This works beautifully most of the time (it's super fast), except when I > pipe large files (>50megs) to it and then it usually dies half way > through complaining of memory errors because it ran out of ram. > > Short of buying more ram, is there a way I can make this more effecient > without taking a big peformance hit? I tried the above where I used a > "for line in data:" loop so it would only process one line at a time but > this seemed to take forever! I'm imagining there's a way to process the > data in something like 1 meg chunks, but I'm not too sure how to do that. > > I'm using python 2.2.1 on a RH linux 7.2 system with 256 ram and a > Athlon XP1700 if it makes any diffrence. > > Any suggestions? > > TIA, > Brent From jadestar at idiom.com Mon Jun 10 17:10:53 2002 From: jadestar at idiom.com (James T. Dennis) Date: 10 Jun 2002 21:10:53 GMT Subject: 'for every' and 'for any' References: <20020526135944.A32690@hishome.net> <20020526091742.A987@unpythonic.net> Message-ID: Oren Tirosh wrote: >> Then drop those functions into your personal utility library and use 'em >> as often as you want :) > I don't have a personal utility library. It's on purpose. I don't have > personalized key bindings. I try to avoid customization. Customization is > a big part of what makes one programmer's code difficult to maintain by > another programmer, what makes on programmers's workstation unusable by > another and makes combining code from several sources difficult. ... > One of the things I like about Python is that it comes with everything in > the box. > Oren Yet, this very discussion proves that "everything" is not already in the box. I'll grant that Python includes a very large set of batteries --- but I'd still say that there are many useful functions and classes that can still be added. Those should start as personal "utility" libraries, be discussed here and in PEPs, and (when their general utility is established) added to appropriate (standard or optional) libraries. Obviously you don't re-invent the wheel for each project that you join; you are re-using some code that you've used before, even if it's from "finger macros." I can see the argument in favor of adapting your functions to conform to local conventions and every programming team has to collaborate to find compatible conventions and standards for their projects. Any non-trivial project (non-trivial, in this case meaning "requires a *team* of programmers (> 3)) is going to find some elements of their project that go beyond established coding conventions. The alternative to "building a (domain/application specific) library" is to eschew code re-use. In this particular case the all() and every() functions that were presented are elegant and seem useful. As others have pointed out the implementations are trivial; so the questions become: "does it 'pollute the namespace' to add them to the core library?" and (if so) "where would we put them?" Personally I think that a language that support containers as first order data types should also include a reasonably comprehensive set of functions to operate on and/or support them. The in operator is good, the iteration protocol is great, the map(),zip(), and filter() functions are good. Notably zip() and filter() can be done with map() (trivially in most cases). I'd say that the inclusion of zip() and filter() argue *for* the (eventual/future) inclusion of (every() or all()) and (any() or some()). From tdelaney at avaya.com Wed Jun 26 00:21:44 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Wed, 26 Jun 2002 14:21:44 +1000 Subject: autocoder redux (was Re: Reminder of a python Project.) Message-ID: > From: Peter Hansen [mailto:peter at engcorp.com] > > Timothy Rue wrote: > > > > On 25-Jun-02 22:38:16 Peter Hansen wrote: > > >I'm afraid there is no longer any need for an autocoder. > > > > Geee, maybe you should tell that to NIST > > No need. They called me the other day and I let them know, but > it was too late to get it into the Computerworld article. > > Seriously, there's really no issue with software development any > more. The problems are solved. I guess if you've invented the > world's first autocoder, it kinda sux to be you then, eh? OK Peter - time to stop trolling. It's no fun when the bait is taken so easily ... ;) Tim (no - not *that* one) Delaney From peter at engcorp.com Sun Jun 23 14:55:06 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 23 Jun 2002 14:55:06 -0400 Subject: printing on the browser References: Message-ID: <3D16198A.B298D0CD@engcorp.com> "Ivan J." wrote: > > This is actually cgi quesion, but ... > Is there a way to print both HTML and IMAGE parts using: > >>>print "Conent-type: ...", > statement, if not is there any other way to create web page with text > and images without savingimages onto disk? > Thank you! The question is very unclear. Are you really talking about "printing" as in sending data to a printer, with real paper and all? It doesn't look that way... I guess you're talking about create a web page which has both text and images embedded in it. Basically, the answer is No, you cannot do that. (There are some sort of exceptions if you talk about leading edge stuff with embedded SVG graphics, but that's not relevant to your situation I think.) Can you clarify a little (actually, a lot :-)? -Peter From kosh at aesaeion.com Fri Jun 21 04:20:40 2002 From: kosh at aesaeion.com (kosh at aesaeion.com) Date: Fri, 21 Jun 2002 02:20:40 -0600 (MDT) Subject: compile python witout tkinter In-Reply-To: <20020621082846.GA933@lilith.my-fqdn.de> Message-ID: On Fri, 21 Jun 2002, Gerhard [iso-8859-15] H?ring wrote: > It looks like in Python 2.1.3, Tkinter gets built with distutils in > Python's setup.py. I fear I don't have a solution to your problem, as > detect_tkinter in Python 2.1.3's setup.py looks fine to me. Maybe you > have a very strange or broken Tcl/Tk setup on your machine. As a > temporary workaround, you could try to insert a return right at the > beginning of detect_tkinter in Python's setup.py. > > I sincerly hope some Tkinter expert here can come up with a better > solution and help finding the real reason behind this. The problem is that a lot of tk stuff is installed on the system but the xlib devel packages are not so it passes that test but there is no Xlib.h so it fails to compile. From dw133 at cs.york.ac.uk.go.away Thu Jun 6 19:34:30 2002 From: dw133 at cs.york.ac.uk.go.away (Darren Winsper) Date: Fri, 07 Jun 2002 00:34:30 +0100 Subject: Detecting OS and Window Manager References: Message-ID: In , Sean 'Shaleh' Perry wrote: > the only fool proof way to detect KDE, GNOME, etc is to check for X atoms. The > bigger question is why do you care? As long as they can display a GUI you > should not be bothered about which one it is. Especially under the X Window > System it was designed so that random applications DIDN'T know what they were > running under. As the person writing the KDE front-end to the mentioned application, let me answer your question. The idea is that if the user is running KDE, then they get a KDE front-end by default. I also hope that should somebody write a GTK/GNOME front-end, if the user was running GNOME they would get a GTK-based front-end by default. It's good UI design. > Also remember KDE is not a window manager, it is a desktop environment. It is > perfectly reasonable to run KDE and use fvwm (or even twm) as the window > manager. Same applies to GNOME. OK, Andrew meant DE instead of window manager, but it's still a valid question. > Also, what about someone who only runs say > Window Maker and never uses GNOME or KDE? Well, in that case we just choose a default. The thing is, we want to detect if PyKDE is installed. If it is, then we can do "import kdecore" without risk of it throwing an exception. If it isn't, I'd rather not have to try something along the lines of attempting "import kdecore" and then having to catch an exception if it's not found. -- ICQ: 8899775 Jabber ID: darren at rooter.dyndns.org Stop the EUCD before it's too late: http://uk.eurorights.org/issues/eucd/ http://www.tomchance.uklinux.net/articles/darkages.shtm From christophe.delord at free.fr Fri Jun 21 12:34:59 2002 From: christophe.delord at free.fr (Christophe Delord) Date: Fri, 21 Jun 2002 18:34:59 +0200 Subject: How to represent the infinite ? References: Message-ID: <20020621183459.63fe2e4d.christophe.delord@free.fr> On Fri, 21 Jun 2002 01:19:50 -0400 Tim Peters wrote: > It can, but it's a x-platform crapshoot as to exactly how. For example, > under current Windows CVS, this still "works": > > >>> 1e300 * 1e300 > 1.#INF > >>> > > Here's a clumsier way : > > >>> 1.6e308 + 1.6e308 > 1.#INF > >>> > > Both of those assume the user hasn't installed and enabled the fpectl > module, whose purpose in life is to cause even this to complain. > >>> 1e300 1.0000000000000001e+300 >>> 1e300*1e300 inf >>> 1e300**2 Traceback (most recent call last): File "", line 1, in ? 1e300**2 OverflowError: (34, 'Numerical result out of range') >>> (under Linux with yesterday CVS) So I was wrong. But addition, multiplication and exponentiation seem to be implemented differently (1e300+1e300 is inf and 1e300**2 is an overflow). Is there a reason for these different behaviours? Christophe. -- (o_ Christophe Delord _o) //\ http://christophe.delord.free.fr/ /\\ V_/_ mailto:christophe.delord at free.fr _\_V From jadestar at idiom.com Sun Jun 16 17:50:05 2002 From: jadestar at idiom.com (James T. Dennis) Date: 16 Jun 2002 21:50:05 GMT Subject: Zip makes sense! was: Re: why not "'in' in 'in'"? References: Message-ID: John Roth wrote: > "David LeBlanc" wrote in message > news:mailman.1024086417.5966.python-list at python.org... >> Aaaah, a logger. Obviously the first on his block to be a logger. The > joys >> of bravely loggin where no one has logged before! ;-> >> >> Perhaps if he was an english major, or english was his first language, > he >> could tell that the common meaning of yield isn't produce. I have no > idea >> what zip means beyond being a name for a compression utility or a verb >> meaning to exercise a zipper. > But that's what it is: exercising a zipper... > It puts two (or more) sequences together into a single > sequence, just like a zipper puts the two sides > together into one. > John Roth More over the term "yield" in English has a few distinct senses. One (slightly archaic) is the imperative to "yield" to a conqueror or authority as in: "Yield, Sir knight!" Another is a similar and common traffic imperative meaning to defer to the rights-of-way for others (probably the inspiration for the most common programming semantics associated with 'yield'). Another is to refer to the product of a farm or manufacturing process as in: the yield of the corn field last year was X bushells. It is clearly this last sense which inspires Python's use of the term. The return operator "yields" a result *and* terminates an execution contect. The yield operator also "yields" a result but it leaves the production machinery or the "field" available for future results. That is in keeping with the English semantics since saying that a field "yielded" a crop doesn't imply that I've taken out the field (building a shopping mall over it, perhaps). To say that my field "returned" a profit *could* mean that it was a "yield" or it could mean that I've sold it off (ROI, return on investment). Of course these nuances are not strictly part of the English usage. The are tendencies in usage since the terms can be used almost interchangeable in many cases. From catunda at pobox.com Tue Jun 25 08:14:07 2002 From: catunda at pobox.com (Marco Catunda) Date: Tue, 25 Jun 2002 09:14:07 -0300 Subject: Memory Monitor Message-ID: Hello, What is the best way to monitor usage memory? I have used "os.system( 'ps %d' % os.getpid() )" but I don't know if it is the best way? The function getusage of resource module returns only zero value. -- Marco Catunda From pyth at devel.trillke.net Sun Jun 16 09:27:31 2002 From: pyth at devel.trillke.net (holger krekel) Date: Sun, 16 Jun 2002 15:27:31 +0200 Subject: Snort alert tail... In-Reply-To: ; from jan.eric-enlund@multi.fi on Sun, Jun 16, 2002 at 03:51:45PM +0300 References: Message-ID: <20020616152731.I15079@prim.han.de> Jan-Eric wrote: > HEllo ! > I'm trying to write a dynamic firewall script in python that scans the Snort > alert file like 'tail -f' and takes action based on the infomation it gets > from that file. But I can't get the 'tail' function to work.It reads the > file, but any new information that Snort is writing to the file doesn't > show up to the script. > > ex. > file = open('/var/log/snort', 'r') > while 1: > file = file.read() > print file > .... > > Any suggestions??? yes, here's a snippet for unix/posix: import os tailoutputfile = os.popen('tail -f syslog') while 1: line = tailoutputfile.readline() if len(line)==0: break process_line(line) the regular popen call returns a file from which you can read. It's a blocking read while 'tail -f' has nothing to offer. the alternative is to implement the 'tail -f' algorithm yourself. basically you have to do (untested) lastsize=os.path.getsize('filename') while 1: size=os.path.getsize('filename') if size>lastsize: f=open('filename') f.seek(lastsize) part = f.read(size-lastsize) f.close() process_next_part(part) elif size==lastsize: time.sleep(0.2) # seconds to wait elif size>sys.stderr, "file filename got truncated" lastsize=size i guess you get the idea. regards, holger From phr-n2002b at NOSPAMnightsong.com Sun Jun 30 02:52:55 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 29 Jun 2002 23:52:55 -0700 Subject: yield equivalent in C/JavaScript? References: <60FB8BB7F0EFC7409B75EEEC13E201922151B8@admin56.narex.com> Message-ID: <7xelepi7g8.fsf@ruckus.brouhaha.com> Robin Becker writes: > thanks I know how to do this with threads, but I suspect I will end up > doing this in JavaScript and threading is a complete mystery there (if > it exists). If it's a Netscape browser or server you can reach the java.threads package from JS. I don't know what happens if you actually try using them though. From miracle at paradise.net.nz Thu Jun 27 16:50:16 2002 From: miracle at paradise.net.nz (Matthew Sherborne) Date: Fri, 28 Jun 2002 08:50:16 +1200 Subject: How to find out DNS ? References: <3D1B6186.3142.295959@localhost> Message-ID: <3D1B7A88.7030705@paradise.net.nz> A wrote: >Hi, >Is there a way how to find out, from Python , what primary or >secondary DNS I use when connecting to internet? >Thanks for help >Ladislav > >_______________________________________________ >ActivePython mailing list >ActivePython at listserv.ActiveState.com >To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs >Other options: http://listserv.ActiveState.com/mailman/listinfo/ActivePython > > > > > def getServersFromOS(self): if sys.platform in ('win32', 'nt'): return self.getServersFromWin32() elif sys.platform == 'posix': return self.getServersFromPosix() else: return [] def getServersFromWin32(self): import _winreg servers = [] x = _winreg.ConnectRegistry(None,_winreg.HKEY_LOCAL_MACHINE) try: y = _winreg.OpenKey(x, r'SYSTEM\CurrentControlSet\Services\Tcpip\Parameters') except EnvironmentError: # so it isn't NT/2000/XP # windows ME, perhaps? try: # for Windows ME y = _winreg.OpenKey(x, r'SYSTEM\CurrentControlSet\Services\VxD\MSTCP') nameserver = _winreg.QueryValueEx(y, 'NameServer')[0] if nameserver and not (nameserver in servers): servers += nameserver.split(',') except EnvironmentError: pass return servers def getServersFromPosix(self): """"Parses the /etc/resolv.conf file and sets defaults for name servers"""" lines = open('/etc/resolv.conf').readlines() servers = [] for line in lines: line = line.strip() if not line or line[0] == ';' or line[0] == '#': continue fields=string.split(line) if fields[0] == 'domain': defaults['domain'] = fields[1] elif fields[0] == 'search': pass elif fields[0] == 'options': pass elif fields[0] == 'sortlist': pass elif fields[0] == 'nameserver': servers.append(fields[1]) return servers GBU Matthew Sherborne From whisper at oz.net Fri Jun 28 22:10:11 2002 From: whisper at oz.net (David LeBlanc) Date: Fri, 28 Jun 2002 19:10:11 -0700 Subject: Python needs better error reporting In-Reply-To: Message-ID: That's not the point - I know that. David LeBlanc Seattle, WA USA > -----Original Message----- > From: kosh at aesaeion.com [mailto:kosh at aesaeion.com] > Sent: Friday, June 28, 2002 18:49 > To: David LeBlanc > Cc: Python-List at Python. Org > Subject: Re: Python needs better error reporting > > > On Fri, 28 Jun 2002, David LeBlanc wrote: > > > "Syntax Error: invalid syntax" isn't very informative, yet it's > tossed out > > frequently. HOW is the syntax invalid? For example: > > if s == ' ' > > > > That is supposed to start a new block so it should be > if s == ' ': > > From peter at engcorp.com Mon Jun 24 13:33:19 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 24 Jun 2002 13:33:19 -0400 Subject: How to stop a SocketServer? References: <7xhejv9af2.fsf_-_@ruckus.brouhaha.com> <3d1744d4$1_1@hpb10302.boi.hp.com> Message-ID: <3D1757DF.776A428F@engcorp.com> Daniel Fackrell wrote: > > I faced this problem with a simple chat server I wrote. I expected that > termination of the server with should have stopped it immediately, > but it instead waits until some communication is received from each thread > that was stopped at a read(). > > It appears that the current threading implementation does not provide for > termination of threads inside a single python statement (such as a > filelike.read()), so I am considering a move to character I/O, checking to > verify that a character is available before each read. The proper solution to this kind of problem is to use timeouts and select. There's generally no need to check for the data being available ahead of time by _polling_, which is inefficient. -Peter From jepler at unpythonic.net Thu Jun 13 13:42:59 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 13 Jun 2002 12:42:59 -0500 Subject: system command In-Reply-To: References: Message-ID: <20020613174258.GD25416@unpythonic.net> On Thu, Jun 13, 2002 at 07:19:48PM +0200, Thor wrote: > Having this code > > print "source "+root+".in" > os.system("source "+root+".in") > > the script does not run the root+".in" file, but copying and pasting the > output form teh 1st line work.. what i'm doing wrong? Thanks in advance It is not a Python problem. It is the difference between running something in a shell or a subshell. The former is like typing source $ROOT.in vs sh -c "source $ROOT.in" the latter will not make any changes to the environment of the parent shell. So setting environment variables, creating aliases, etc., won't work like you'd hoped. If you want to have a Python program that changes something in the parent shell's environment, you have to arrange to execute it in the shell. For instance, source `python print_name_of_file_to_source.py` or eval `python print_shell_code_to_execute.py` Jeff From sholden at holdenweb.com Tue Jun 4 16:41:44 2002 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 4 Jun 2002 16:41:44 -0400 Subject: DCOracle2 - Can't get cursor.execute to return data when SQL query involves datetimes. References: Message-ID: "Jim" wrote in message news:be0d725a.0206041139.1f8f6647 at posting.google.com... > Hello, > > I am trying to write a simple program to retrieve 2 colums from a > table. > I am running on Solaris 2.8, Python 2.1.1, DCOracle2 and Oracle > 8.1.7.3. > > > The columns are: > > acct_number ( one char long) > transaction_datestamp (oracle datetimestamp) > > Here is my program: > > import DCOracle2 > trandt = '19970110121212' > > db = DCOracle2.connect("uid/pwd") > c = db.cursor() > > dt = DCOracle2.Timestamp(int(tran_date[0:4]), int(tran_date[4:6]), > int(tran_date[6:8]), int(tran_date[8:10]), int(tran_date[10:12]), > int(tran_date[12:14])) > > results = c.execute,('select acct_nbr, trn_dt from testtable where > ACCT_NBR = :1 and TRN_DT = :2',"1",dt) > > aaa = c.fetchone() > > print aaa > > > The execute never return any thing from query when the date timestamp > is part of the query. If I only query on the acct_nbr it returns the > expected row. > > What am I missing ??? > Possibly the cxOracle module from www.computronix.com :-) Otherwise, please go away and *copy and paste* the real code: I'll overlook the line wrapping, which your mailer probably inserted gratuitously, but you appear to be using tran_date where you should be using trandt, and trn_dt where you should be using transacttion_datestamp. Finally, doesn't the .execute() method call want two arguments [i.e., shouldn't your data be a tuple ("1", dt)], not three? regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From nhodgson at bigpond.net.au Fri Jun 28 06:50:48 2002 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Fri, 28 Jun 2002 10:50:48 GMT Subject: Module Help References: Message-ID: Juan M. Casillas: > I want to create an empty module from C, and then add > functions and definitions stored in another file, and > some code that I will create on-the-fly, from C. Here is some Python code by Michael Hudson to create a new module and add some code to it: newm = new.module(name) sys.modules[name] = newm newm.__file__ = filepath exec compile(open(filepath).read(), filepath, "exec") in \ newm.__dict__ You can change the open(filepath).read() to provide the code text in ay way you want. I think you can use empty strings for the filepath variable. Now you just have to work out how to call this from C which IIRC is well covered in the embedding part of the "Extending and Embedding the Python Interpreter" manual. Neil From parker at gol.com Thu Jun 13 21:00:56 2002 From: parker at gol.com (Ian Parker) Date: Fri, 14 Jun 2002 01:00:56 GMT Subject: Medium to Large Scale Python Deployments References: <38C31EBA-79A4-11D6-9A7D-003065B33450@intersight.com> <3D003EC7.C72D27BE@engcorp.com> <3D006320.5040805@web.de> <3D00A209.EC24F671@engcorp.com> <3D0140BF.A239E39E@engcorp.com> <7hUN8.529345$%u2.28370@atlpnn01.usenetserver.com> Message-ID: In article <7hUN8.529345$%u2.28370 at atlpnn01.usenetserver.com>, Steve Holden writes >"Peter Hansen" wrote in message >news:3D0140BF.A239E39E at engcorp.com... >> Bengt Richter wrote: >> > >> > Is the "comments" number a count of _pure_ comment lines, >> > # (like this one) ? >> >> I believe so. I haven't examined the pycount code yet. >> >> > I think it would be interesting to analyze comments further, >> > to see what the relative comment byte count is overall, >> > and for lines with both code and comments, >> > """like this line:""" # (this has code and comment). >> >> I consider it a mild stylistic no-no to use line-ending >> comments, personally. I believe it's almost always better >> to put a block-comment of one or more lines above a block >> of code with related purpose. A good comment there tends to >> be more maintainable, and useful, than lots of little comments >> on each line. >> >I wouldn't necessarily disagree, but I used (when programming (gulp) Basic >Plus) to make the line-end comments into a free-form narrative that rough;y >parallelled the code. > >[...] >regards >----------------------------------------------------------------------- >Steve Holden http://www.holdenweb.com/ >Python Web Programming http://pydish.holdenweb.com/pwp/ >----------------------------------------------------------------------- > > > > > I did the same on assemblers (double gulp) and possibly FORTRAN. I think it's an effective technique on languages where the statements are relatively short compared to the window width. Regards Ian -- Ian Parker From opengeometry at yahoo.ca Wed Jun 26 17:06:00 2002 From: opengeometry at yahoo.ca (William Park) Date: Wed, 26 Jun 2002 17:06:00 -0400 Subject: Help with an algorithm wanted In-Reply-To: References: Message-ID: <20020626210600.GA2890@node1.opengeometry.net> On Wed, Jun 26, 2002 at 01:02:02PM -0700, Russell E. Owen wrote: > For instance, an object with A as the given would return D by solving > A->C->D. > The real issue is creating such objects without hand coding each one > (since in the real world I have more representations and the number of > casese proliferates badly). If pairing (ie. mapping between 2 objects) occurs randomly, then it's virtually impossible, because you don't know which direction to go from any one object. It would be travelling from city to city, without knowing which state or county. -- William Park, Open Geometry Consulting, 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin From Chris.Barker at noaa.gov Thu Jun 20 15:42:09 2002 From: Chris.Barker at noaa.gov (Chris Barker) Date: Thu, 20 Jun 2002 12:42:09 -0700 Subject: Windows versions of Python---pros and cons? References: <3D110B55.4D8AD7FA@astro.cornell.edu> <3D122E79.A189C72E@astro.cornell.edu> Message-ID: <3D122FDF.D64181DA@noaa.gov> Tom Loredo wrote: > Redhat > uses Python, but does their reliance on an old version still cause > problems?. They use 1.5, and all their scripts use "python" on the #! line, so if you use a more recent version, you need to put python2 (or python2.2 or whatever) on your #! lines. Nat a big deal, really, but a little annoying. I'd love to see RedHat put python1.5 on THEIR #! lines, which you wouldn't think would be difficult. Maybe RedHat 8.*, they have been getting complaints. > Actually, I need to develop stuff that other Win32 users can use, > some probably distributed via the McMillan installer (which I presume > works as well with Active State as with the python.org version). > So I'm stuck here.... I'd do most of your coding under Linux, and just use Windows to test an package it up, unless you're doing com or something Windows only. > The fact that Dell shipped it with a defective > install of Win98 did not help its cause. Is there such a thing an a non defective Win98? Seriously, use Win2k if you can, I still don't like it, but it provides a modicum of stability and a almost usable command line. -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From tim.one at comcast.net Sat Jun 29 07:25:58 2002 From: tim.one at comcast.net (Tim Peters) Date: Sat, 29 Jun 2002 07:25:58 -0400 Subject: Python needs better error reporting In-Reply-To: Message-ID: [David LeBlanc] > Cute anthropomorphism is lots of fun, but doesn't _quite_ obscure the fact > that computers don't really "tell" anybody anything, programmers do. When we ship Guido with every compiler, the world will be a better place for sure. > IIRC, Python throws this "Syntax Error: invalid syntax" in a number of > places. Yes. Study the code a little and you'll soon discover why. > In the place that I used as an example, looking at the language > reference, an appropriate error would be more like: > Syntax Error: expected "and", "or", "xor" or ":" Well, "xor" isn't legit there, but other tokens that are OK after if s == ' ' include ' " ''' """ == != <> < <= > >= + - / * ** and \ Call me prophetic, but you wouldn't be happy with a list of all possibilities either. Collapse oodles of them into "binary operator" and you lose half the people you're trying to help. Etc. > This would at least narrow down what should be looked at to resolve the > problem. Not really. Such lists tend to baffle more than clarify. I once used a Pascal compiler whose favorite trick was to point a caret at a trailing semicolon, and then complain "semicolon expected"; the message was always correct when it appeared, while appearing dead wrong, and was useless in determining the *real* problem regardless. It did appear friendlier than "syntax error" the first 719 times I saw it, though . > Vague error reporting doesn't help new user's self confidance or > acceptance of the language. > > I really DO have a point! Error-reporting in parsers has been the subject of intense research. Do a little digging and come back when you can make a case that your point can be addressed effectively. Keep in mind that most consumer-grade computers still don't have telepathy chips . From mcalla at insightbb.com Sun Jun 16 16:13:24 2002 From: mcalla at insightbb.com (Mike Callahan) Date: Sun, 16 Jun 2002 20:13:24 GMT Subject: Question about asksaveasfilename References: Message-ID: I did find defaultextension, but as you pointed out, it only works with a single string and does not pay attention to the user's choice in the file type listbox. I guess I could make my own dialog but I thought that built-in one would do the trick. Since no one else has responded, I guess it cannot. Mike C. "Eric Brunel" wrote in message news:aea3ha$lv$1 at wanadoo.fr... > Mike Callahan wrote: > > > I am using asksaveasfilename from tkFileDialog. I want to restrict my > > users to save filenames with these extensions .unl or .sql. This is my > > call: > > > > from tkFileDialog import asksaveasfilename > > fn = asksaveasfilename(filetypes=[('Unloaded', '*.unl'), > > ('Queries','*.sql')]) > > > > This gives me the correct dialog box, but how do I force the correct > > extension on fn? Thanks. > > There's a defaultextension option, but it does not depend on the selected > file type, i.e. you'll have to do either: > > fn = asksaveasfilename(filetypes=[('Unloaded', '*.unl'), > ('Queries', '*.sql')], > defaultextension='.unl') > > or: > > fn = asksaveasfilename(filetypes=[('Unloaded', '*.unl'), > ('Queries', '*.sql')], > defaultextension='.sql') > > which isn't what you're looking for, I fear... > > I don't know any means to force an extension depending on the selecetd file > type with asksaveasfilename, so my advice would be to split the two save > options: one "Save unloaded" and one "Save query"... But if there's another > solution, I'm interested too ;-). > > HTH > -- > - Eric Brunel - > PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From R.Barrett at ftel.co.uk Tue Jun 11 13:09:53 2002 From: R.Barrett at ftel.co.uk (Richard Barrett) Date: Tue, 11 Jun 2002 18:09:53 +0100 Subject: Defining a method final In-Reply-To: References: <6glN8.35376$86.884025@twister1.libero.it> Message-ID: <5.1.0.14.2.20020611161524.0341a008@pop.ftel.co.uk> At 15:35 11/06/2002 +0000, Eric Brunel wrote: >Emile van Sebille wrote: > > Accepted practice is to use a single underscore for objects to be > > considered private. This does not prevent their use, but strongly > > signals that re-use ought not to be done. > > > >>>> class Test: > > ... def _private(self): pass > > ... > > > >Python now have an "official" means to make attributes private by prefixing >them with a double-underscore. And it *does* prevent their use or >overloading: I'm not criticising the double underscore prefix feature but it prevents neither, if you factor in the name mangling that supports the feature. See the following transcript from Python 2.2.1 command line: >>> class A: ... def __private(self): print "class A private" ... def printit(self): self.__private() ... >>> class B(A): ... pass ... >>> class C(A): ... def _A__private(self): print "class C private" ... >>> a1 = A() >>> a1.printit() class A private >>> a1._A__private() class A private >>> b1 = B() >>> b1.printit() class A private >>> b1._A__private() class A private >>> c1 = C() >>> c1.printit() class C private >>> c1._A__private() class C private From occeanlinux at linuxmail.org Thu Jun 27 10:36:03 2002 From: occeanlinux at linuxmail.org (SiverFish) Date: Thu, 27 Jun 2002 14:36:03 +0000 Subject: Questiion on list Message-ID: I got the list of words now i want to calculate how many word in that list which is the same word (insensitive case),can anyone show me how to do it for example ls = ['abc','cd','abc','adf',abc','dwc','cd'] it will show abc = 3 ,cd = 2, adf = 1, dwc=1 From quinn at retch.ugcs.caltech.edu Tue Jun 25 17:33:26 2002 From: quinn at retch.ugcs.caltech.edu (Quinn Dunkan) Date: 25 Jun 2002 21:33:26 GMT Subject: 'parent object'? References: <3d18228c$0$221$4d4ebb8e@news.nl.uu.net> <3D182662.CBC925DB@alcyone.com> <3D18AF67.2010207@nospam.free.fr> Message-ID: On Tue, 25 Jun 2002 13:59:03 -0400, laotseu wrote: >That's ok for 'parent/child' in the inheritence meaning. But the OP >asked about something else : a container instance (the 'parent'), and >the instances it contains (the 'childrens'). This has nothing to do with > subclassing. > > >You should define a 'container/child' interface. it may be very simple >in Python, something like > >class container: > def __init__(self): > self.childrens = [] > > def add_child(self, child): > if child not in self.childrens: > child.parent = self # create a 'parent' attribute > self.childrens.append(child) > > def remove_child(self, child): > if child in self.childrens: > del self.childrens[self.childrens.index(child)] > del child.parent > > >Now whatever class your child objects is an instance of, it gets a new >'parent' attribute when you add it to the container instance, and looses >this attribute when you remove it... This also introduces a cycle. In older pythons, discarded containers would never deallocate their children. In newer pythons, the garbage will get cleaned eventually. As a random aside, I've found that almost always when I thought I needed to have a child know about its parent, it's turned out to be a design mistake. Cyclical dependency is messy to think about. Things can wind up getting called in weird ways, and getting in tricky infinite recursion. As another random aside, using __getitem__ and __setitem__ is usually more natural for this kind of thing. From BPettersen at NAREX.com Fri Jun 14 19:59:56 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Fri, 14 Jun 2002 17:59:56 -0600 Subject: why not "'in' in 'in'"? Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192F1A575@admin56.narex.com> > From: Tim Peters [mailto:tim.one at comcast.net] [snip] > So if somebody wants this change enough to submit a patch > (code, doc, + test suite changes), it's likely to be accepted > for 2.3. As code changes go, this one should be particularly > easy. We have an internal bet going as to whether this > invitation is enough to kill the idea . > > some-parts-of-this-were-actually-true-ly y'rs - tim Here are the code changes. (This patch is public domain, etc. etc.) I'm getting a two warnings: 1: "incompatible types - from 'struct _object*' to 'struct PyStringObject'" on the line result = string_find_internal(a, args, +1); 2: "incompatible types - from 'struct _object*' to 'struct PyUnicodeObject'" on the line findResult = (PyObject*) unicode_find(container, args); which I can't understand (anyone?) If anyone feels like writing the doc/test suite changes feel free to use my patch. -- bjorn *** stringobject.orig.c Fri Jun 14 16:46:58 2002 --- stringobject.c Fri Jun 14 17:51:16 2002 *************** *** 46,51 **** --- 46,56 ---- not counting the null terminating character, and is therefore equal to the `size' parameter. */ + + /* forward declarations */ + long + string_find_internal(PyStringObject *self, PyObject *args, int dir); + PyObject * PyString_FromStringAndSize(const char *str, int size) { *************** *** 824,848 **** static int string_contains(PyObject *a, PyObject *el) { ! register char *s, *end; ! register char c; #ifdef Py_USING_UNICODE ! if (PyUnicode_Check(el)) ! return PyUnicode_Contains(a, el); #endif ! if (!PyString_Check(el) || PyString_Size(el) != 1) { ! PyErr_SetString(PyExc_TypeError, ! "'in ' requires character as left operand"); ! return -1; ! } ! c = PyString_AsString(el)[0]; ! s = PyString_AsString(a); ! end = s + PyString_Size(a); ! while (s < end) { ! if (c == *s++) ! return 1; ! } ! return 0; } static PyObject * --- 829,855 ---- static int string_contains(PyObject *a, PyObject *el) { ! long result; ! PyObject* args; ! #ifdef Py_USING_UNICODE ! if (PyUnicode_Check(el)) ! return PyUnicode_Contains(a, el); #endif ! if (!PyString_Check(el)) { ! PyErr_SetString(PyExc_TypeError, ! "'in ' requires string as left operand"); ! return -1; ! } ! args = Py_BuildValue("(O)", el); ! result = string_find_internal(a, args, +1); ! Py_DECREF(args); ! if (result >= 0) { ! return 1; ! } ! else { ! return 0; ! } } static PyObject * *************** *** 1329,1335 **** return -1; } - static char find__doc__[] = "S.find(sub [,start [,end]]) -> int\n\ --- 1336,1341 ---- *** unicodeobject.orig.c Fri Jun 14 17:12:09 2002 --- unicodeobject.c Fri Jun 14 17:53:44 2002 *************** *** 76,81 **** --- 76,85 ---- # define BYTEORDER_IS_LITTLE_ENDIAN #endif + /* forward declaration */ + PyObject * + unicode_find(PyUnicodeObject *self, PyObject *args); + /* --- Globals ------------------------------------------------------------ The globals are initialized by the _PyUnicode_Init() API and should *************** *** 3789,3830 **** return -1; } ! int PyUnicode_Contains(PyObject *container, ! PyObject *element) { PyUnicodeObject *u = NULL, *v = NULL; int result; ! register const Py_UNICODE *p, *e; ! register Py_UNICODE ch; /* Coerce the two arguments */ v = (PyUnicodeObject *)PyUnicode_FromObject(element); if (v == NULL) { ! PyErr_SetString(PyExc_TypeError, ! "'in ' requires character as left operand"); ! goto onError; } u = (PyUnicodeObject *)PyUnicode_FromObject(container); if (u == NULL) { ! Py_DECREF(v); ! goto onError; } /* Check v in u */ ! if (PyUnicode_GET_SIZE(v) != 1) { ! PyErr_SetString(PyExc_TypeError, ! "'in ' requires character as left operand"); ! goto onError; } ! ch = *PyUnicode_AS_UNICODE(v); ! p = PyUnicode_AS_UNICODE(u); ! e = p + PyUnicode_GET_SIZE(u); ! result = 0; ! while (p < e) { ! if (*p++ == ch) { ! result = 1; ! break; ! } } Py_DECREF(u); --- 3793,3835 ---- return -1; } ! int PyUnicode_Contains(PyObject *container, PyObject *element) { PyUnicodeObject *u = NULL, *v = NULL; int result; ! long tmpresult; ! PyObject *args; ! PyObject *findResult = NULL; /* Coerce the two arguments */ v = (PyUnicodeObject *)PyUnicode_FromObject(element); if (v == NULL) { ! PyErr_SetString(PyExc_TypeError, ! "'in ' requires string as left operand"); ! goto onError; } u = (PyUnicodeObject *)PyUnicode_FromObject(container); if (u == NULL) { ! Py_DECREF(v); ! goto onError; } /* Check v in u */ ! args = Py_BuildValue("(O)", element); ! findResult = (PyObject*) unicode_find(container, args); ! Py_DECREF(args); ! if (findResult == NULL) { ! goto onError; } ! else { ! tmpresult = PyInt_AsLong(findResult); ! Py_DECREF(findResult); ! if (tmpresult >= 0) { ! result = 1; ! } ! else { ! result = 0; ! } } Py_DECREF(u); *************** *** 3832,3837 **** --- 3837,3843 ---- return result; onError: + Py_XDECREF(findResult); Py_XDECREF(u); Py_XDECREF(v); return -1; From james.kew at btinternet.com Tue Jun 11 18:52:06 2002 From: james.kew at btinternet.com (James Kew) Date: Tue, 11 Jun 2002 23:52:06 +0100 Subject: Sorting list (maybe stupid) References: <3D062B7C.FE6A4963@noaa.gov> Message-ID: "Chris Barker" wrote in message news:3D062B7C.FE6A4963 at noaa.gov... > Eric Brunel wrote: > > > l = [(102, 'foo'), (2, 'bar'), (1, 'baz')] > > l.sort() > > print l > > > > Apparently, the default sort function already sorts tuples according to > > their first element... > > Note that this only works if the rest of the elements in the tuples are > also sortable. In this case, they are strings, so they are. Although that does mean that, in the OP's problem, lines with identical numbers will be further sorted by the following string -- this might not be the behaviour he requires. Is sort() stable -- that is, is the relative order of elements which compare equal preserved? A quick shufti through the ActivePython docs wasn't illuminating. -- James Kew james.kew at btinternet.com From radix at twistedmatrix.com Wed Jun 12 11:36:02 2002 From: radix at twistedmatrix.com (Christopher Armstrong) Date: 12 Jun 2002 11:36:02 -0400 Subject: Bits and bytes? In-Reply-To: <3d0760ec$0$223$4d4ebb8e@news.nl.uu.net> References: <3d074e6d$0$224$4d4ebb8e@news.nl.uu.net> <3d0760ec$0$223$4d4ebb8e@news.nl.uu.net> Message-ID: <87adq0v7a5.fsf@twistedmatrix.com> >>>>> "Guyon" == Guyon Mor?e writes: Guyon> ok, thanx a lot. there's one thing i am missing though... how do i Guyon> write '011010110101' as 'binary bits' to a file? You can only write strings to a file. So use the unbinarify function to convert the bit-string to a "data" string, and write that. Guyon> "Christopher Armstrong" wrote in message Guyon> news:mailman.1023890477.2592.python-list at python.org... Guyon> http://twistedmatrix.com/users/moshez/binary.py Guyon> Moshe Zadka wrote this because he was annoyed at all the people in Guyon> #python asking how to do this ;-) -- Chris Armstrong << radix at twistedmatrix.com >> http://twistedmatrix.com/users/carmstro.twistd/ From gerhard at bigfoot.de Tue Jun 4 12:25:14 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 4 Jun 2002 16:25:14 GMT Subject: Python command line? References: Message-ID: In article , SA wrote: > Hi Everyone- > > I would like to run python code line by line using: > > python -c some line of code > > Will this work? You need to put your code into quotes, like in: python -c "print 5" Code spanning multiple lines will also work, just be sure to use ' instead of " in your code. Gerhard From peter at engcorp.com Fri Jun 28 18:39:29 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 28 Jun 2002 18:39:29 -0400 Subject: generate all combinations of a list (with variable output length) References: <3D1CBE6D.30002@huno.net> Message-ID: <3D1CE5A1.1A0F5E58@engcorp.com> thomas wrote: > > hi, > > i'm looking for a way to generate all possible combinations of all items > in a list. list = ["A","D","$","5","R"] > > but i also want it to use one item several times or not at all and in no > particular order. the length of the string is 1-10. so a possible output > would be: > > DD$ > A5RD$D555 > A > 5RR$$A > DRRR55$5$A > ... > > i find it particualy difficult to tell python to use one item several > times or not at all, and the variable length thing. i don't want to > reinvent the wheel so someone probably has already a soultion for that > :) and if not someone can probably push me in some direction. Why not post your best effort so far and we can critique it? That way you'll learn a lot more than if someone just hands you the answer on a silver platter. We'll also be happier helping when we know it's not just another homework question you're supposed to do on your own. ;-) -Peter From emile at fcfw.fenx.com Tue Jun 25 10:06:52 2002 From: emile at fcfw.fenx.com (Emile van Sebille) Date: Tue, 25 Jun 2002 07:06:52 -0700 Subject: Suggestions for good programming practices? References: <31575A892FF6D1118F5800600846864DCBD432@intrepid> Message-ID: <349201c21c51$eef186d0$0a06a8c0@FENX.COM> Simon Brunning > It isn't in the 2.2 series until 2.2.1, IIRC. > Am I missing something? F:\Python22>python Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import this The ... -- Emile van Sebille emile at fenx.com --------- From kragen at pobox.com Sun Jun 2 22:49:34 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 02 Jun 2002 22:49:34 -0400 Subject: Which is fastest dict or list.index() ? References: Message-ID: <83n0udrs8x.fsf@panacea.canonical.org> "Raymond Hettinger" writes: > There are a lot of ways to implement an OrderedDictionary. > Take a look at > http://home.arcor.de/wolfgang.grafen/Python/Modules/Modules.html > and http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/107747 > If you want a skiplist version, let me know and I'll send it. I'm curious how your skiplist version compares with the built-in Python dict type on performance; I'd been thinking about building a skiplist ordered dictionary extension type myself, but if you've already done it, maybe I should just use yours. From sanjay2kind at yahoo.com Wed Jun 26 07:45:28 2002 From: sanjay2kind at yahoo.com (sanjay) Date: 26 Jun 2002 04:45:28 -0700 Subject: how to remove HTML attributes from web pages ( HTML parseing) Message-ID: <63170f57.0206260345.5b9b3397@posting.google.com> Hi, New to python and doing one application. i would like to web page content after removing specific html tag, attribute etc. Like taking out color,bgcolor and ,

tag from the web pages. Which one will be helpful : regular expression or HTMLParser helpfully. Thx, From Norman_Shelley-RRDN60 at email.sps.mot.com Mon Jun 3 18:44:03 2002 From: Norman_Shelley-RRDN60 at email.sps.mot.com (Norman Shelley) Date: Mon, 03 Jun 2002 15:44:03 -0700 Subject: ?Tcl's embedded virtual filesystem and Scripted documents Message-ID: <3CFBF133.7DF60BA4@email.sps.mot.com> Tcl now has an embedded virtual filesystem that looks very useful. http://mini.net/tcl/2138.html Is there any motivation in the Python camp to have something similiar? Also, a "scripted document" like methodology looks to be very useful also. http://www.equi4.com/jcw/scripdoc.html Any work going on in this arena? Norman Shelley From mhammond at skippinet.com.au Sun Jun 30 03:53:50 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sun, 30 Jun 2002 07:53:50 GMT Subject: Python COM installation and NT Administrative rights. References: <3281a460.0206290652.51b800c9@posting.google.com> Message-ID: <3D1EB9C7.70901@skippinet.com.au> P Adhia wrote: > Hi, > > I'd like to install Python COM on my work PC - on which I don't have > administrative rights. Is there a Python COM installation available > that does not require administrative rights on NT ? (I don't know if > administrative rights is must for Python COM to install/work; but I > have installed some other softwares that detect current privilege > levels and install regitry entries reserved for per user instead of > system. I am hoping that Python COM can be made to do something > similar.) > Installing Python 2.2 + the latest win32all *should* work here - but I am sure there will be some problems. If you are willing, give it a try, then mail me with whatever problems you have. Mark. From Sarah_L at gmx.net Fri Jun 7 05:57:47 2002 From: Sarah_L at gmx.net (Sarah Mayer) Date: 7 Jun 2002 02:57:47 -0700 Subject: Memory leaks when embedding python (debug-version) ? Message-ID: <1eed5b9.0206070157.6d281f65@posting.google.com> Hi, maybe someone could help me, I just embedded python 2.2.1 into a dll , Program looks like: MyClass::MyClass() { Py_Initialize(); Py_Finalize(); } and after the program finishes I get a lot of memory-leaks. What is missing ??? Greetings Sarah Memorydump: Dumping objects -> {36193} normal block at 0x00936DE0, 52 bytes long. Data: < > B0 AC 15 1E 10 9A 92 00 CD CD CD CD CD CD CD CD {36182} normal block at 0x00936E40, 44 bytes long. Data: < o > 10 9A 92 00 00 6F 93 00 CD CD CD CD CD CD CD CD {36179} normal block at 0x00936EA0, 41 bytes long. Data: < o Pn > 10 6F 93 00 50 6E 93 00 04 00 00 00 88 F2 17 1E {36178} normal block at 0x00936F00, 44 bytes long. Data: <@n o > 40 6E 93 00 C0 6F 93 00 CD CD CD CD CD CD CD CD {36175} normal block at 0x00936F60, 45 bytes long. Data: < o o > D0 6F 93 00 10 6F 93 00 04 00 00 00 88 F2 17 1E {36174} normal block at 0x00936FC0, 44 bytes long. Data: < o 1 > 00 6F 93 00 00 31 93 00 CD CD CD CD CD CD CD CD {36170} normal block at 0x00933100, 44 bytes long. Data: < o `1 > C0 6F 93 00 60 31 93 00 CD CD CD CD CD CD CD CD {36166} normal block at 0x00933160, 44 bytes long. Data: < 1 R > 00 31 93 00 80 52 93 00 CD CD CD CD CD CD CD CD {36164} normal block at 0x00935070, 384 bytes long. Data: < $p0 M C) > 00 98 09 24 70 30 93 00 F0 4D 93 00 C0 43 29 1F {36162} normal block at 0x00935220, 41 bytes long. Data: < R p1 > 90 52 93 00 70 31 93 00 04 00 00 00 88 F2 17 1E {36161} normal block at 0x00935280, 44 bytes long. Data: <`1 V > 60 31 93 00 A0 56 93 00 CD CD CD CD CD CD CD CD {36158} normal block at 0x009352E0, 44 bytes long. Data: < V R > B0 56 93 00 90 52 93 00 04 00 00 00 88 F2 17 1E {36157} normal block at 0x009356A0, 44 bytes long. Data: < R W > 80 52 93 00 00 57 93 00 CD CD CD CD CD CD CD CD {36153} normal block at 0x00935700, 44 bytes long. Data: < V W > A0 56 93 00 C0 57 93 00 CD CD CD CD CD CD CD CD {36150} normal block at 0x00935760, 40 bytes long. Data: < W W > D0 57 93 00 10 57 93 00 04 00 00 00 88 F2 17 1E {36149} normal block at 0x009357C0, 44 bytes long. Data: < W M > 00 57 93 00 E0 4D 93 00 CD CD CD CD CD CD CD CD {36146} normal block at 0x00933070, 44 bytes long. Data: < M W > F0 4D 93 00 D0 57 93 00 04 00 00 00 88 F2 17 1E {36145} normal block at 0x00934DE0, 44 bytes long. Data: < W @N > C0 57 93 00 40 4E 93 00 CD CD CD CD CD CD CD CD {36141} normal block at 0x00934E40, 48 bytes long. Data: < M N > E0 4D 93 00 A0 4E 93 00 CD CD CD CD CD CD CD CD {36139} normal block at 0x00934EA0, 48 bytes long. Data: <@N D > 40 4E 93 00 C0 44 93 00 CD CD CD CD CD CD CD CD {36137} normal block at 0x009344C0, 48 bytes long. Data: < N E > A0 4E 93 00 20 45 93 00 CD CD CD CD CD CD CD CD {36135} normal block at 0x00934520, 48 bytes long. Data: < D E > C0 44 93 00 80 45 93 00 CD CD CD CD CD CD CD CD {36133} normal block at 0x00934580, 48 bytes long. Data: < E 6 > 20 45 93 00 A0 36 93 00 CD CD CD CD CD CD CD CD {36131} normal block at 0x009336A0, 48 bytes long. Data: < E $ > 80 45 93 00 F0 24 93 00 CD CD CD CD CD CD CD CD {36130} normal block at 0x009324F0, 148 bytes long. Data: < 6 I > A0 36 93 00 E0 49 93 00 CD CD CD CD CD CD CD CD {36124} normal block at 0x009349E0, 40 bytes long. Data: < $ ` > F0 24 93 00 60 CC 92 00 CD CD CD CD CD CD CD CD {35866} normal block at 0x00932F00, 41 bytes long. Data:

70 CC 92 00 F0 49 93 00 04 00 00 00 88 F2 17 1E {35297} normal block at 0x0092CC60, 52 bytes long. Data: < I > E0 49 93 00 B0 CB 92 00 CD CD CD CD CD CD CD CD {35295} normal block at 0x0092CAD0, 171 bytes long. Data: < p > C0 CB 92 00 70 CC 92 00 01 00 00 00 88 F2 17 1E {35293} normal block at 0x0092CBB0, 44 bytes long. Data: <` > 60 CC 92 00 20 CD 92 00 CD CD CD CD CD CD CD CD {35284} normal block at 0x0092CCC0, 42 bytes long. Data: <0 > 30 CD 92 00 C0 CB 92 00 04 00 00 00 88 F2 17 1E {35283} normal block at 0x0092CD20, 44 bytes long. Data: < > B0 CB 92 00 E0 CD 92 00 CD CD CD CD CD CD CD CD {35280} normal block at 0x0092CD80, 42 bytes long. Data: < 0 > F0 CD 92 00 30 CD 92 00 04 00 00 00 88 F2 17 1E {35279} normal block at 0x0092CDE0, 44 bytes long. Data: < > 20 CD 92 00 A0 CE 92 00 CD CD CD CD CD CD CD CD {35276} normal block at 0x0092CE40, 38 bytes long. Data: < > B0 CE 92 00 F0 CD 92 00 04 00 00 00 88 F2 17 1E {35275} normal block at 0x0092CEA0, 44 bytes long. Data: < ` > E0 CD 92 00 60 CF 92 00 CD CD CD CD CD CD CD CD {35272} normal block at 0x0092CF00, 38 bytes long. Data:

70 CF 92 00 B0 CE 92 00 04 00 00 00 88 F2 17 1E {35271} normal block at 0x0092CF60, 44 bytes long. Data: < ` > A0 CE 92 00 60 BC 92 00 CD CD CD CD CD CD CD CD {35268} normal block at 0x0092BC00, 38 bytes long. Data:

70 BC 92 00 70 CF 92 00 04 00 00 00 88 F2 17 1E {35267} normal block at 0x0092BC60, 44 bytes long. Data: <` > 60 CF 92 00 20 BD 92 00 CD CD CD CD CD CD CD CD {35264} normal block at 0x0092BCC0, 37 bytes long. Data: <0 p > 30 BD 92 00 70 BC 92 00 04 00 00 00 88 F2 17 1E {35263} normal block at 0x0092BD20, 44 bytes long. Data: <` > 60 BC 92 00 E0 BD 92 00 CD CD CD CD CD CD CD CD {35260} normal block at 0x0092BD80, 37 bytes long. Data: < 0 > F0 BD 92 00 30 BD 92 00 04 00 00 00 88 F2 17 1E {35259} normal block at 0x0092BDE0, 44 bytes long. Data: < > 20 BD 92 00 A0 BE 92 00 CD CD CD CD CD CD CD CD {35256} normal block at 0x0092BE40, 37 bytes long. Data: < > B0 BE 92 00 F0 BD 92 00 04 00 00 00 88 F2 17 1E {35255} normal block at 0x0092BEA0, 44 bytes long. Data: < 0 > E0 BD 92 00 30 B0 92 00 CD CD CD CD CD CD CD CD {35253} normal block at 0x01076FD0, 1536 bytes long. Data: < /> 00 00 00 00 00 00 00 00 00 00 00 00 81 A8 AB 2F {35251} normal block at 0x0107A018, 24576 bytes long. Data: < Op` > 00 E8 1E 4F 70 60 8C 00 00 00 00 00 00 00 00 00 {35250} normal block at 0x0092CFC0, 41 bytes long. Data: <@ > 40 B0 92 00 B0 BE 92 00 04 00 00 00 88 F2 17 1E {35249} normal block at 0x0092B030, 44 bytes long. Data: < > A0 BE 92 00 F0 B0 92 00 CD CD CD CD CD CD CD CD {35246} normal block at 0x0092B090, 40 bytes long. Data: < @ > 00 B1 92 00 40 B0 92 00 04 00 00 00 88 F2 17 1E {35245} normal block at 0x0092B0F0, 44 bytes long. Data: <0 > 30 B0 92 00 B0 B1 92 00 CD CD CD CD CD CD CD CD {35242} normal block at 0x0092B150, 37 bytes long. Data: < > C0 B1 92 00 00 B1 92 00 04 00 00 00 88 F2 17 1E {35241} normal block at 0x0092B1B0, 44 bytes long. Data: < > F0 B0 92 00 10 B2 92 00 CD CD CD CD CD CD CD CD {35237} normal block at 0x0092B210, 44 bytes long. Data: < > B0 B1 92 00 D0 B2 92 00 CD CD CD CD CD CD CD CD {35234} normal block at 0x0092B270, 38 bytes long. Data: < > E0 B2 92 00 20 B2 92 00 04 00 00 00 88 F2 17 1E {35233} normal block at 0x0092B2D0, 44 bytes long. Data: < > 10 B2 92 00 90 B3 92 00 CD CD CD CD CD CD CD CD {35230} normal block at 0x0092B330, 38 bytes long. Data: < > A0 B3 92 00 E0 B2 92 00 04 00 00 00 88 F2 17 1E {35229} normal block at 0x0092B390, 44 bytes long. Data: < P > D0 B2 92 00 50 B4 92 00 CD CD CD CD CD CD CD CD {35226} normal block at 0x0092B3F0, 37 bytes long. Data: <` > 60 B4 92 00 A0 B3 92 00 04 00 00 00 88 F2 17 1E {35225} normal block at 0x0092B450, 44 bytes long. Data: < > 90 B3 92 00 B0 B4 92 00 CD CD CD CD CD CD CD CD {35221} normal block at 0x0092B4B0, 44 bytes long. Data:

50 B4 92 00 70 B5 92 00 CD CD CD CD CD CD CD CD {35218} normal block at 0x0092B510, 38 bytes long. Data: < > 80 B5 92 00 C0 B4 92 00 04 00 00 00 88 F2 17 1E {35217} normal block at 0x0092B570, 44 bytes long. Data: < > B0 B4 92 00 D0 B5 92 00 CD CD CD CD CD CD CD CD {35213} normal block at 0x0092B5D0, 44 bytes long. Data:

70 B5 92 00 30 B6 92 00 CD CD CD CD CD CD CD CD {35209} normal block at 0x0092B630, 44 bytes long. Data: < > D0 B5 92 00 90 B6 92 00 CD CD CD CD CD CD CD CD {35205} normal block at 0x0092B690, 44 bytes long. Data: <0 > 30 B6 92 00 F0 B6 92 00 CD CD CD CD CD CD CD CD {35201} normal block at 0x0092B6F0, 44 bytes long. Data: < > 90 B6 92 00 B0 B7 92 00 CD CD CD CD CD CD CD CD {35198} normal block at 0x0092B750, 42 bytes long. Data: < > C0 B7 92 00 00 B7 92 00 04 00 00 00 88 F2 17 1E {35197} normal block at 0x0092B7B0, 44 bytes long. Data: < p > F0 B6 92 00 70 B8 92 00 CD CD CD CD CD CD CD CD {35194} normal block at 0x0092B810, 39 bytes long. Data: < > 80 B8 92 00 C0 B7 92 00 04 00 00 00 88 F2 17 1E {35193} normal block at 0x0092B870, 44 bytes long. Data: < 0 > B0 B7 92 00 30 B9 92 00 CD CD CD CD CD CD CD CD {35190} normal block at 0x0092B8D0, 39 bytes long. Data: <@ > 40 B9 92 00 80 B8 92 00 04 00 00 00 88 F2 17 1E {35189} normal block at 0x0092B930, 44 bytes long. Data:

70 B8 92 00 F0 B9 92 00 CD CD CD CD CD CD CD CD {35186} normal block at 0x0092B990, 39 bytes long. Data: < @ > 00 BA 92 00 40 B9 92 00 04 00 00 00 88 F2 17 1E {35185} normal block at 0x0092B9F0, 44 bytes long. Data: <0 > 30 B9 92 00 B0 BA 92 00 CD CD CD CD CD CD CD CD {35182} normal block at 0x0092BA50, 39 bytes long. Data: < > C0 BA 92 00 00 BA 92 00 04 00 00 00 88 F2 17 1E {35181} normal block at 0x0092BAB0, 44 bytes long. Data: < p > F0 B9 92 00 70 BB 92 00 CD CD CD CD CD CD CD CD {35178} normal block at 0x0092BB10, 39 bytes long. Data: < > 80 BB 92 00 C0 BA 92 00 04 00 00 00 88 F2 17 1E {35177} normal block at 0x0092BB70, 44 bytes long. Data: < > B0 BA 92 00 E0 A2 92 00 CD CD CD CD CD CD CD CD {35174} normal block at 0x0092A280, 39 bytes long. Data: < > F0 A2 92 00 80 BB 92 00 04 00 00 00 88 F2 17 1E {35173} normal block at 0x0092A2E0, 44 bytes long. Data:

70 BB 92 00 A0 A3 92 00 CD CD CD CD CD CD CD CD {35170} normal block at 0x0092A340, 39 bytes long. Data: < > B0 A3 92 00 F0 A2 92 00 04 00 00 00 88 F2 17 1E {35169} normal block at 0x0092A3A0, 44 bytes long. Data: < > E0 A2 92 00 00 BF 92 00 CD CD CD CD CD CD CD CD {35164} normal block at 0x0092BF00, 44 bytes long. Data: < ` > A0 A3 92 00 60 BF 92 00 CD CD CD CD CD CD CD CD {35160} normal block at 0x0092BF60, 44 bytes long. Data: < > 00 BF 92 00 C0 BF 92 00 CD CD CD CD CD CD CD CD {35156} normal block at 0x0092BFC0, 44 bytes long. Data: <` p > 60 BF 92 00 70 A0 92 00 CD CD CD CD CD CD CD CD {35152} normal block at 0x0092A070, 44 bytes long. Data: < > C0 BF 92 00 D0 A0 92 00 CD CD CD CD CD CD CD CD {35147} normal block at 0x0092A0D0, 48 bytes long. Data:

70 A0 92 00 30 A1 92 00 CD CD CD CD CD CD CD CD {35145} normal block at 0x0092A130, 48 bytes long. Data: < > D0 A0 92 00 90 A1 92 00 CD CD CD CD CD CD CD CD {35143} normal block at 0x0092A190, 48 bytes long. Data: <0 > 30 A1 92 00 F0 A1 92 00 CD CD CD CD CD CD CD CD {35141} normal block at 0x0092A1F0, 48 bytes long. Data: < > 90 A1 92 00 10 A6 92 00 CD CD CD CD CD CD CD CD {35139} normal block at 0x0092A610, 48 bytes long. Data: < p > F0 A1 92 00 70 A6 92 00 CD CD CD CD CD CD CD CD {35137} normal block at 0x0092A670, 48 bytes long. Data: < > 10 A6 92 00 00 A4 92 00 CD CD CD CD CD CD CD CD {35134} normal block at 0x0092A400, 48 bytes long. Data:

70 A6 92 00 60 A4 92 00 CD CD CD CD CD CD CD CD {35132} normal block at 0x0092A460, 48 bytes long. Data: < > 00 A4 92 00 C0 A4 92 00 CD CD CD CD CD CD CD CD {35130} normal block at 0x0092A4C0, 48 bytes long. Data: <` > 60 A4 92 00 20 A5 92 00 CD CD CD CD CD CD CD CD {35128} normal block at 0x0092A520, 48 bytes long. Data: < > C0 A4 92 00 80 A5 92 00 CD CD CD CD CD CD CD CD {35126} normal block at 0x0092A580, 48 bytes long. Data: < > 20 A5 92 00 D0 A6 92 00 CD CD CD CD CD CD CD CD {35123} normal block at 0x0092A6D0, 48 bytes long. Data: < 0 > 80 A5 92 00 30 A7 92 00 CD CD CD CD CD CD CD CD {35121} normal block at 0x0092A730, 48 bytes long. Data: < > D0 A6 92 00 90 A7 92 00 CD CD CD CD CD CD CD CD {35119} normal block at 0x0092A790, 48 bytes long. Data: <0 > 30 A7 92 00 F0 A7 92 00 CD CD CD CD CD CD CD CD {35117} normal block at 0x0092A7F0, 48 bytes long. Data: < P > 90 A7 92 00 50 A8 92 00 CD CD CD CD CD CD CD CD {35115} normal block at 0x0092A850, 48 bytes long. Data: < > F0 A7 92 00 B0 A8 92 00 CD CD CD CD CD CD CD CD {35113} normal block at 0x0092A8B0, 48 bytes long. Data:

50 A8 92 00 10 A9 92 00 CD CD CD CD CD CD CD CD {35112} normal block at 0x0092A910, 148 bytes long. Data: < > B0 A8 92 00 90 80 92 00 CD CD CD CD CD CD CD CD {35068} normal block at 0x00929A10, 44 bytes long. Data: < m @n > E0 6D 93 00 40 6E 93 00 CD CD CD CD CD CD CD CD {35056} normal block at 0x00928090, 40 bytes long. Data: < L > 10 A9 92 00 E0 4C 92 00 CD CD CD CD CD CD CD CD {34705} normal block at 0x00924CE0, 40 bytes long. Data: < > 90 80 92 00 B0 AC 15 1E CD CD CD CD CD CD CD CD {34589} normal block at 0x00922BF0, 39 bytes long. Data: < J L > F0 4A 90 00 F0 4C 92 00 03 00 00 00 88 F2 17 1E {34101} normal block at 0x00904AF0, 40 bytes long. Data:

50 E9 8F 00 F0 2B 92 00 04 00 00 00 88 F2 17 1E {33763} normal block at 0x008FE950, 36 bytes long. Data: < J > 10 C3 8F 00 F0 4A 90 00 04 00 00 00 88 F2 17 1E {33696} normal block at 0x008FC310, 37 bytes long. Data:

70 C3 8F 00 50 E9 8F 00 04 00 00 00 88 F2 17 1E {33695} normal block at 0x008FC370, 39 bytes long. Data: < > C0 20 8E 00 10 C3 8F 00 04 00 00 00 88 F2 17 1E {33048} normal block at 0x008E20C0, 55 bytes long. Data: <@% p > 40 25 8E 00 70 C3 8F 00 01 00 00 00 88 F2 17 1E {33043} normal block at 0x008E24E0, 24 bytes long. Data: < > E0 A0 92 00 80 A0 92 00 02 00 00 00 D0 D2 16 1E {36194} normal block at 0x008E22E0, 64 bytes long. Data: < ? ] @Z W > D0 3F 8C 00 90 5D 8B 00 40 5A 8B 00 F0 57 8B 00 {33041} normal block at 0x008E2530, 52 bytes long. Data:

70 1B 8E 00 70 23 8C 00 85 FF FF FF CD CD CD CD {33039} normal block at 0x008E2350, 255 bytes long. Data: < $ @% > 90 24 8E 00 40 25 8E 00 01 00 00 00 88 F2 17 1E {33037} normal block at 0x008E2480, 44 bytes long. Data:

50 08 8C 00 70 17 8E 00 85 FF FF FF CD CD CD CD {33028} normal block at 0x008E2590, 41 bytes long. Data: < & $ > 00 26 8E 00 90 24 8E 00 04 00 00 00 88 F2 17 1E {33027} normal block at 0x008E25F0, 44 bytes long. Data:

70 14 8E 00 70 27 8E 00 85 FF FF FF CD CD CD CD {33024} normal block at 0x008E2650, 42 bytes long. Data: < & & > C0 26 8E 00 00 26 8E 00 04 00 00 00 88 F2 17 1E {33023} normal block at 0x008E26B0, 44 bytes long. Data:

50 16 8E 00 B0 16 8E 00 85 FF FF FF CD CD CD CD {33020} normal block at 0x008E2710, 40 bytes long. Data: < ' & > 80 27 8E 00 C0 26 8E 00 04 00 00 00 88 F2 17 1E {33019} normal block at 0x008E2770, 44 bytes long. Data: < % P > F0 25 8E 00 50 16 8E 00 85 FF FF FF CD CD CD CD {33016} normal block at 0x008E27D0, 36 bytes long. Data: <0( ' > 30 28 8E 00 80 27 8E 00 04 00 00 00 88 F2 17 1E {33015} normal block at 0x008E2820, 44 bytes long. Data: < > 20 13 8E 00 E0 13 8E 00 85 FF FF FF CD CD CD CD {33012} normal block at 0x008E2880, 37 bytes long. Data: < ( 0( > F0 28 8E 00 30 28 8E 00 04 00 00 00 88 F2 17 1E {33011} normal block at 0x008E28E0, 44 bytes long. Data: <` > 60 12 8E 00 A0 11 8E 00 85 FF FF FF CD CD CD CD {33007} normal block at 0x008E10E0, 44 bytes long. Data: <`/ > 60 2F 8E 00 F0 15 8E 00 85 FF FF FF CD CD CD CD {33003} normal block at 0x008E1140, 44 bytes long. Data: < > B0 16 8E 00 80 13 8E 00 85 FF FF FF CD CD CD CD {32999} normal block at 0x008E11A0, 44 bytes long. Data: < ( > E0 28 8E 00 D0 14 8E 00 85 FF FF FF CD CD CD CD {32995} normal block at 0x008E1200, 44 bytes long. Data: < - > 90 15 8E 00 F0 2D 8E 00 85 FF FF FF CD CD CD CD {32993} normal block at 0x008E2940, 768 bytes long. Data: < g > 00 00 00 00 00 00 00 00 00 00 00 00 C1 06 67 CF {32991} normal block at 0x008E2C70, 39 bytes long. Data: < , > E0 2C 8E 00 10 12 8E 00 04 00 00 00 88 F2 17 1E {32990} normal block at 0x008E2CD0, 44 bytes long. Data: < P. > E0 13 8E 00 50 2E 8E 00 85 FF FF FF CD CD CD CD {32987} normal block at 0x008E2D30, 42 bytes long. Data: < - , > A0 2D 8E 00 E0 2C 8E 00 04 00 00 00 88 F2 17 1E {32986} normal block at 0x008E2D90, 44 bytes long. Data: < / P > 00 2F 8E 00 50 10 8E 00 85 FF FF FF CD CD CD CD {32982} normal block at 0x008E2DF0, 44 bytes long. Data: < / > 00 12 8E 00 C0 2F 8E 00 85 FF FF FF CD CD CD CD {32978} normal block at 0x008E2E50, 44 bytes long. Data: < , `/ > D0 2C 8E 00 60 2F 8E 00 85 FF FF FF CD CD CD CD {32975} normal block at 0x008E2EB0, 24 bytes long. Data: < / `. > 10 2F 8E 00 60 2E 8E 00 02 00 00 00 D0 D2 16 1E {32972} normal block at 0x008E2F00, 48 bytes long. Data: < - > D0 14 8E 00 90 2D 8E 00 85 FF FF FF CD CD CD CD {32970} normal block at 0x008E2F60, 48 bytes long. Data: 50 2E 8E 00 E0 10 8E 00 85 FF FF FF CD CD CD CD {32968} normal block at 0x008E2FC0, 48 bytes long. Data: < - 0 > F0 2D 8E 00 30 15 8E 00 85 FF FF FF CD CD CD CD {32966} normal block at 0x008E1470, 48 bytes long. Data: < % > C0 AC 15 1E F0 25 8E 00 85 FF FF FF CD CD CD CD {32964} normal block at 0x008E14D0, 48 bytes long. Data: < / > A0 11 8E 00 00 2F 8E 00 85 FF FF FF CD CD CD CD {32962} normal block at 0x008E1050, 48 bytes long. Data: < - > 90 2D 8E 00 20 13 8E 00 85 FF FF FF CD CD CD CD {32959} normal block at 0x008E1260, 48 bytes long. Data: < ( > 10 17 8E 00 E0 28 8E 00 85 FF FF FF CD CD CD CD {32957} normal block at 0x008E12C0, 48 bytes long. Data: <0 p > 30 15 8E 00 70 08 8E 00 85 FF FF FF CD CD CD CD {32955} normal block at 0x008E1320, 48 bytes long. Data:

50 10 8E 00 20 28 8E 00 85 FF FF FF CD CD CD CD {32953} normal block at 0x008E1380, 48 bytes long. Data: <@ > 40 11 8E 00 10 17 8E 00 85 FF FF FF CD CD CD CD {32951} normal block at 0x008E13E0, 48 bytes long. Data: < ( , > 20 28 8E 00 D0 2C 8E 00 85 FF FF FF CD CD CD CD From koancui at lucent.com Wed Jun 26 01:29:48 2002 From: koancui at lucent.com (Cui, Zhi Gang (Zhigang)) Date: Wed, 26 Jun 2002 13:29:48 +0800 Subject: subscriber Message-ID: <31C0F08B0D18D511ACC800508BAE7B470159B91F@CI0026EXCH001U> THX From msoulier at nortelnetworks.com_.nospam Thu Jun 13 11:19:21 2002 From: msoulier at nortelnetworks.com_.nospam (Michael P. Soulier) Date: 13 Jun 2002 15:19:21 GMT Subject: import problem References: <2se7guc3kkmm3bgooj776j55igpkmgpst4@4ax.com> Message-ID: On Sun, 09 Jun 2002 13:37:05 -0700, Michael Eager wrote: > I'm trying to use Python 2.2 and PyQt on a RedHat-7.2 system. > > I get an error when I execute "from qt import *" -- there is a failure > in qt.py when it executes "import libsup". The error is "No module > named libsup". > > libsup.so.9 is a link to libsup.so.9.0.3 and is in > /usr/lib/python2.2/site-packages. If I enter "import libsup", I get > the same error message. > > Any suggestions? Are you sure that you have the required dependencies for qt.py? Python does not import .so files directly, to my knowledge. Mike -- Michael P. Soulier, QX41, SKY Tel: 613-765-4699 (ESN: 39-54699) Optical Networks, Nortel Networks, SDE Pegasus "...the word HACK is used as a verb to indicate a massive amount of nerd-like effort." -Harley Hahn, A Student's Guide to Unix From walterm at parque.homelinux.net Tue Jun 18 09:32:06 2002 From: walterm at parque.homelinux.net (Walter Moreira) Date: Tue, 18 Jun 2002 10:32:06 -0300 Subject: __subclasses__ In-Reply-To: References: Message-ID: <20020618133206.GA19082@parque.homelinux.net> On Fri, Jun 14, 2002 at 10:09:31AM +0000, Michael Hudson wrote: > > class Foo(object): > > def __init__(self): > > object.__init__(self) > > > > class Bar(Foo): > > pass > > > > dir(Foo) # returns: > > > > ['__class__', '__delattr__', '__dict__', '__doc__', > > '__getattribute__', '__hash__', '__init__', '__module__', > > '__new__', '__reduce__', '__repr__', '__setattr__', > > '__str__', '__weakref__'] > > Whether things show up in dir() is a bit of a lottery (think about > __getattr__ methods!). Notice __bases__ isn't in there either, for > example. The __bases__ and __subclasses__ (and others) are listed in the 'type' object: >>> class Foo: ... pass ... >>> dir(type(type(Foo))) ['__base__', '__bases__', '__basicsize__', '__call__', '__class__', '__cmp__', '__delattr__', '__dict__', '__dictoffset__', '__doc__', '__flags__', '__getattribute__', '__hash__', '__init__', '__itemsize__', '__module__', '__mro__', '__name__', '__new__', '__reduce__', '__repr__', '__setattr__', '__str__', '__subclasses__', '__weakrefoffset__', 'mro'] Walter From jh at web.de Mon Jun 3 15:40:13 2002 From: jh at web.de (Jürgen Hermann) Date: Mon, 3 Jun 2002 21:40:13 +0200 Subject: python and windows and pydoc and favorite editor == True References: Message-ID: "Syver Enstad" schrieb im Newsbeitrag news:un0ugnxa3.fsf at online.no... > Post if there is any interest. OK, post. :) From sholden at holdenweb.com Thu Jun 13 22:50:54 2002 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 13 Jun 2002 22:50:54 -0400 Subject: libftp.size function gives wrong results! References: <3D038A19.D991A885@engcorp.com> <%ULM8.903$Yw3.118334@news20.bellglobal.com> Message-ID: "Michael Davis" wrote ... > Peter Hansen wrote: > > > Michael Davis wrote: > >> > >> I'm writing a python program which will upload or download files via ftp. > >> It's intended to be used to deploy a web site from a local machine to a > >> server. It tries to determine which files are modified on the local > >> machine by comparing file sizes and modification times. > >> > >> I try to compare files using os.stat for the local file and FTP.size for > >> the remote. The problem is, FTP.size is giving me incorrect results. If I > >> use the ftp command line client, and look at one of my files on the > >> server (the output looks like 'ls -l') then I can see that the file size, > >> is, say, 1200. But the FTP.size function returns, say, 1242. > > > > I think you'll find the number of lines in that file is 42. The > > difference > > is probably between CRLF and LF line terminations in the file. If you > > transfer files with FTP and want to preserve the line endings, you have > > to specify the binary type, not ascii. Don't know how to do this with > > ftplib, but from the ftp command line you would use 'type binary' or > > 'type ascii' to switch. > > Thanks Peter, > > I had already thought of that. Both my local and the remote systems are > unix, and so don't have CRs. But you're right - the difference in size is > the same as the number of lines, as though the ftp size command assumed > that I wanted to convert the end-of-lines to CRLF. I had specified binary > mode transfers. And if I do 'ftp size' on true binary files, the same > problem happens! > > Anyway, I just found out that one of the servers I need to talk to doesn't > allow me to use 'size' anyway, so I'm going to ask a different python > question in a different message. > You should take a look at "ftpmirror.py" in the Tools subdirectory of your Python distribution. Also, you might find it easier to use "make" to determoine what needs uploading to you web system. This has worked very well for me. regards -- ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From gerhard.haering at gmx.de Tue Jun 25 20:56:18 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Wed, 26 Jun 2002 02:56:18 +0200 Subject: Reminder of a python Project. In-Reply-To: <2218.941T781T12224051threeseas@earthlink.net> References: <2218.941T781T12224051threeseas@earthlink.net> Message-ID: <20020626005618.GA1145@lilith.my-fqdn.de> * Timothy Rue [2002-06-26 00:40 +0000]: > First off, it's ok that I got such a high level of resistance to my > initial posting here about this project. ACK. > Thanks to some research that /. That's an oxymoron. > had an article on, regarding the size of GPL project teams. ^^^^^^^^^^^^^^^^^ What's that? Somebody mistaking GPL with Free Software with Open Source? Again? > But anyway.... Remember the autocoding project I mentioned? Yes, unfortunately. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From kragen at pobox.com Sat Jun 1 02:17:33 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 01 Jun 2002 02:17:33 -0400 Subject: The email package and KLEZ mails References: Message-ID: <834rgnwmiq.fsf@panacea.canonical.org> pinard at iro.umontreal.ca (Fran?ois Pinard) writes: > For example, I expect compilers to raise diagnostics and help me at being > strict, because being overly liberal for a compiler is just not helpful. > Another example, a sad one, is the messy state of HTML all around us, > it comes from browsers having been by far too liberal, and for too long. If you had designed the early web browsers, the web never would have caught on, as indeed many other networked hypertext systems predating the Web did not; being liberal in what you accept is a crucial principle in building decentralized systems, and its embodiment in the Web made the Web possible. Having "bad HTML" warnings is, of course, extremely helpful. It makes it possible to be conservative in what you send. From jubafre at zipmail.com.br Mon Jun 24 07:45:52 2002 From: jubafre at zipmail.com.br (jubafre at zipmail.com.br) Date: Mon, 24 Jun 2002 08:45:52 -0300 Subject: =?iso-8859-1?Q?module=20py2exe?= Message-ID: <3D163E400000171F@www.zipmail.com.br> i don?t know how to use a py2exe module, i have made the download but i don?t know to install. the direcroty of installation is lib\site-packages. i have a program using tkinter module and i want to compile to .exe the name of the file is lfa.py, i read in http://starship.python.net/crew/theller/py2exe/, i have to make a setup.py, so doesn?t work, how i can make this rigth??????????????????? # setup.py from distutils.core import setup import py2exe setup(name="lfa", scripts=["lfa.py"], ) Juliano Freitas www.gebrasil.hpg.com.br ------------------------------------------ Use o melhor sistema de busca da Internet Radar UOL - http://www.radaruol.com.br From d2002xx at myrealbox.com Sun Jun 23 04:31:12 2002 From: d2002xx at myrealbox.com (d2002xx) Date: 23 Jun 2002 01:31:12 -0700 Subject: Python hits the spot References: <3D1482AE.8FA299D8@kfunigraz.ac.at> <3D148E71.2070201@kfunigraz.ac.at> Message-ID: <8d3f4438.0206230031.7838d0d7@posting.google.com> John Hunter wrote in message > unix> at now +6min > at> killall myprog > at> CTRL-d # Hit Control and D together > unix> ./myprog There is a faster method named SAK in linux, it can kill any processes in current console (i.e. also kill X-window) the document is in: 1.YOUR_LINUX_KERNEL_SOURCE_PATH/Docmentation/sysrq.txt 2.YOUR_LINUX_KERNEL_SOURCE_PATH/Docmentation/SAK.txt Be careful: The command is executed by kernel and send SIGKILL signal to kill processes, the signal can't be caught, so the process killed may lost some things such as working files which was not saved. And you can't use it with enabling the virtual screen in X-windows (I think few people use it, most people use virtual desktop instead). Also, if you start X-window in the first console, some daemons may be killed, it's something boring...... (although I have not tested) Good luck! From mhammond at skippinet.com.au Fri Jun 14 00:38:13 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Fri, 14 Jun 2002 04:38:13 GMT Subject: PythonWin Problem! References: <1a52c7f1.0206131455.6df50cf8@posting.google.com> Message-ID: <3D0973C5.60407@skippinet.com.au> Ethan wrote: > I have been using ActiveState's port of Python for a while. PythonWin > has been very helpful. Since a couple of days PythonWin developed a > problem. When I start it, it appears in the taskbar and tray but does > not appear on the screen. > > My Win98 did recently develop a problem which prevents me from getting > the right click menu on the taskbar entries. This was secondary to > some registry cleaning I did. I am not sure if this is related to > Pythonwin problem but all others apps are working fine. I do get the > menu for the tray icon and the "Close Program" window does not say > "not responding" > > I uninstalled Python - deleted the Python21 folder and reinstalled. It > did not help. Any suggestions? I really prefer PythonWin over IDLE. Pythonwin has probably somehow remembered it's screen location as off the screen. Try deleting the "HKLM\Software\Python 2.1\Python for Win32" key from the registry, and it should come back. Alternatively, from the task-bar select "Move", then use the arrow keys to try and bring it back on screen (presumably with the "Left" and "Up" keys) Mark. From rganesan at myrealbox.com Wed Jun 19 23:20:56 2002 From: rganesan at myrealbox.com (Ganesan R) Date: 20 Jun 2002 08:50:56 +0530 Subject: Variable Interpolation - status of PEP 215 Message-ID: Hi, I am a relative newbie to Python. I have a reasonably good perl background (don't worry I am not about to start a language flame war :-), and one of the things I really miss is variable interpolation in strings. I searched the net and found PEP 215 (http://www.python.org/peps/pep-0215.html). This seems to be exactly what I need. The proposal seems to be quite old, so I'd like to know if it's still in consideration or has it been dropped completely? Ganesan -- Ganesan R From cliechti at gmx.net Thu Jun 13 14:36:28 2002 From: cliechti at gmx.net (Chris Liechti) Date: 13 Jun 2002 20:36:28 +0200 Subject: Embedded systems References: Message-ID: "Stuart" wrote in news:aeaajv$5db01$1 at ID-17980.news.dfncis.de: > Is Python practical for embedded systems? I am working on a project > at the moment that uses a GSM/GPRS modem and a GPS receiver. I have > prototyped the whole thing in Visual Basic, and now I need to port it > over to a suitable processor (possibly on a 68000 device using Linux). python need some resources as its interpreted but there is a posrt for the palm (http://sourceforge.net/projects/pippy). as you have linux there shouldn't be a real problem. download the sources and try to compile it fo your target system. > I don't really want to get into C for this project, and was wondering > if Python was suitable? Are memory requirements an issue? i don't know any precise numbers, depending on project maybe starting at 100k RAM and 200k ROM? (pippy uses 137k in ROM) chris -- Chris From gerhard at bigfoot.de Wed Jun 19 04:38:47 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Wed, 19 Jun 2002 10:38:47 +0200 Subject: procmail replacement in Python In-Reply-To: <3u8pea.617.ln@127.0.0.1> References: <3u8pea.617.ln@127.0.0.1> Message-ID: <20020619083847.GA9664@lilith.my-fqdn.de> * Radovan Garabik [2002-06-19 08:38 +0200]: > Gerhard H?ring wrote: > : Does such a thing exist? I've recently looked into the procmail sources > > > http://melkor.dnp.fmph.uniba.sk/~garabik/pycmail.html > Whoa! _Exactly_ what I was searching. Would you mind registering it at Freshmeat, so other people can find it more easily? Looks like a good project for my next weekend to convert my fetchmail/procmail setup to getmail/pycmail. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 26.6 ?C Wind: 1.3 m/s From peter at engcorp.com Sun Jun 2 07:50:14 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 02 Jun 2002 07:50:14 -0400 Subject: Pop a list from beginning ? and memory saving... References: Message-ID: <3CFA0676.68F80DE6@engcorp.com> Shagshag13 wrote: > > I had a huge list containing consuming data, as i only need a one pass in a > for statement, i'm wondering if by doing this with a pop i could save memory ? Maybe, maybe not. The implementation _probably_ makes a copy of the entire list at some point as you shrink it. That would mean that at least at some interval, you would temporarily consume almost twice the memory of the original list as the original list is copied, then freed. You might end up with less memory used, but with double the memory needed. Of course, the same would have held true as you built the list in the first place... Why are you trying to save memory? Are you really working with such a large amount of data in one chunk that you will run out? Maybe there is some other approach you haven't thought of. This effort almost smells like premature optimization (the root of all evil). -Peter From oren-py-l at hishome.net Mon Jun 24 16:01:40 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Mon, 24 Jun 2002 23:01:40 +0300 Subject: PEP 294: Type Names in the types Module Message-ID: <20020624230140.B3555@hishome.net> PEP: 294 Title: Type Names in the types Module Version: $Revision: 1.1 $ Last-Modified: $Date: 2002/06/23 23:52:19 $ Author: oren at hishome.net (Oren Tirosh) Status: Draft Type: Standards track Created: 19-Jun-2002 Python-Version: 2.3 Post-History: Abstract This PEP proposes that symbols matching the type name should be added to the types module for all basic Python types in the types module: types.IntegerType -> types.int types.FunctionType -> types.function types.TracebackType -> types.traceback ... The long capitalized names currently in the types module will be deprecated. With this change the types module can serve as a replacement for the new module. The new module shall be deprecated and listed in PEP 4. Rationale Using two sets of names for the same objects is redundant and confusing. In Python versions prior to 2.2 the symbols matching many type names were taken by the factory functions for those types. Now all basic types have been unified with their factory functions and therefore the type names are available to be consistently used to refer to the type object. Most types are accessible as either builtins or in the new module but some types such as traceback and generator are only accssible through the types module under names which do not match the type name. This PEP provides a uniform way to access all basic types under a single set of names. Specification The types module shall pass the following test: import types for t in vars(types).values(): if type(t) is type: assert getattr(types, t.__name__) is t The types 'class', 'instance method' and 'dict-proxy' have already been renamed to the valid Python identifiers 'classobj', 'instancemethod' and 'dictproxy', making this possible. Backward compatibility Because of their widespread use it is not planned to actually remove the long names from the types module in some future version. However, the long names should be changed in documentation and library sources to discourage their use in new code. Reference Implementation A reference implementation is available in SourceForge patch #569328: http://www.python.org/sf/569328 Copyright This document has been placed in the public domain. From python at tykebsd.net Fri Jun 7 03:55:16 2002 From: python at tykebsd.net (Dave Moor) Date: 7 Jun 2002 00:55:16 -0700 Subject: Interfacing to 1-Wire LAN, especially Dallas temperature sensors? References: <1bf96e7f.0206060356.417a7394@posting.google.com> Message-ID: <1bf96e7f.0206062355.4718e1c1@posting.google.com> Hi Everyone Since one or two people are interested in this I have put a page on my website (http://www.tykebsd.net) with some info and some files to download. This module is only in its initial stages of developement so has limited functionality. There is a Linux and Windows version of the module. The module is currently only compiled against Python version 2.1 if you need a version for Python 2.2 you will have to wait until the middle of next week. I plan to upgrade but I don't think I'll have time before then. If you have any questions just drop me a line and I'll try to answer them. Dave Moor From irmen at NOSPAMREMOVETHISxs4all.nl Sun Jun 16 12:21:54 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Sun, 16 Jun 2002 18:21:54 +0200 Subject: ANN: pyro 3.0 beta 1 Message-ID: I've released the first beta of Pyro 3.0. It has some very exiting new features over the previous release (2.8); major speed increase, SSL support, safe XML pickling, authentication, timeouts, and much more. If you're interested in helping me improve Pyro 3.0, download it from http://www.sourceforge.net/projects/pyro Please read the change log carefully (available on request, but it's also in the manual in the distribution), and test it to the max! Please remember, it is still a beta release so there will be some rough edges, and there are still a few issues that need to be resolved for the final 3.0. Check the Pyro mailing list to stay up-to-date. Irmen de Jong - irmen(at)users.sourceforge.net What is Pyro?: Pyro is an acronym for PYthon Remote Objects. It is a basic Distributed Object Technology system written entirely in Python. With this, it closely resembles Java's Remote Method Invocation (RMI). Pyro is small, simple, fun and free! For more information, visit http://pyro.sourceforge.net From zopestoller at thomas-guettler.de Thu Jun 27 07:51:56 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Thu, 27 Jun 2002 13:51:56 +0200 Subject: print() with unicode strings Message-ID: <3D1AFC5C.2040708@thomas-guettler.de> Hi! >>>print '?' #(German Umlaut) works but >>>print u'?' does not. Is there a reason why print does not accept unicode? Why not default to a latin-1 encoding? Version: Python 2.2 (#1, Dec 31 2001, 15:21:18) [GCC 2.95.3-5 (cygwin special)] on cygwin thomas From phlip_cpp at yahoo.com Sun Jun 2 22:26:24 2002 From: phlip_cpp at yahoo.com (Phlip) Date: 03 Jun 2002 02:26:24 GMT Subject: cursors, etc References: <20020602221459.05355.00002083@mb-mm.aol.com> Message-ID: BCBOOKER wrote: > Is there any way for a user to actively move a cursor or some other marker > on a > plane? Not until you start naming specifics. What's this "plane"? Is it a window? If so, is it a Tkinter Canvas? Contrarily, is it a virtual terminal? such as the curses module addresses? > That is, if there is a 4x4 square with the cursor at (1,1), can > the > user press up, n, 1 or whatever and make the x increase? I tried making > something along the lines of this, but i had to go type in every situation > - that is, make the map for (2, 3) or (1, 2). So if you had variable row and col, could you let the Up key trigger a row -= 1, for example? -- Phlip http://www.c2.com/cgi/wiki?PhlIp -- Creationism: The belief that God is too stupid to be able to invent a Universe where life can spontaneously arise -- From jimmy at retzlaff.com Fri Jun 7 20:06:47 2002 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Fri, 7 Jun 2002 17:06:47 -0700 Subject: Efficient python programming... Message-ID: Peter Hansen [mailto:peter at engcorp.com] writes: > I disagree, if the tests are written first (and run, proving that > they will fail when the code is wrong or missing). I think the other perspective here is that the writing of the unit tests is design/coding, and hence subject to the same types of mistakes as the designing/writing of the code they test. A contrived example: def addEmUp(x, y): return x * y def testAddEmUp(): # try some limit cases and something in between for testCase in (0, 2, 1.79e+308): assert addEmUp(testCase, testCase) == testCase+testCase if __name__ == '__main__': testAddEmUp() print 'Success!!!' That test runs successfully on Python 2.2.1 on Windows despite the flawed implementation of the function the test is exercising. Having unit tests may make you more confident in correctness than not having them, but they are still prone to mistakes themselves. In order for unit tests to prove the code is correct, you'd need to prove the unit tests are correct and exhaustive (despite its correctness, the above unit test is not exhaustive which leads to a false validation). > The tests are executable requirement specifications. Running > them "proves" (yes, not 100%... nothing could) that the code > meets the specs. The specs could be wrong of course, but that > doesn't mean the code is broken... You can say the tests are your spec and hence your program is correct with regards to the spec, but that doesn't make the user any happier if your code costs them time, money, safety, etc. just because the part of the code you call the spec was also flawed or incomplete. Unit testing is just one of many important tools. On any significant project, it is important to have a well-rounded quality strategy that also employs things like design/code reviews, pair programming, user testing, etc. But if you're really after correctness, there may be only one true measure - let a sales person demo the product! Good old Murphy ensures that bugs are very good at exposing themselves during important sales presentations. :) Jimmy From merkosh at hadiko.de Fri Jun 14 22:39:37 2002 From: merkosh at hadiko.de (Uwe Mayer) Date: Sat, 15 Jun 2002 04:39:37 +0200 Subject: file.tell() -- obscure IOError References: Message-ID: In article , merkosh at hadiko.de says... > hi, > > i have an object which conforms to the file protocoll. while calling the > self.file.tell() method, i get the following error message: > > >>> s1 == s2 > Traceback (most recent call last): > File "", line 1, in ? > File "riff.py", line 153, in __cmp__ > data1 = self.read(self.value.step) > File "riff.py", line 205, in read > maxsize = len(self) -self.tell() > File "riff.py", line 234, in tell > return self.file.tell() -self.value.start > IOError: (0, 'Error') > more info: the tell() does not fail every time. what i do: i compare two files by reading count bytes and calling cmp() on both of them until end of file or cmp() != 0 the tell() failes for different numbers of 'count' bytes. f.e. count = 1 fails after 7 bytes count = 5 works count = 6 fails right at the beginning ...? any ideas? Ciao Uwe From janto_d at hotmail.com Sun Jun 30 10:30:01 2002 From: janto_d at hotmail.com (Janto Dreijer) Date: 30 Jun 2002 07:30:01 -0700 Subject: squared functions--most Pythonic way? References: Message-ID: I think that's a typo: >>> print AddNumbers(5) 5 How about: reduce(lambda a,b: a(b), range(10), addNumbers) or reduce(apply, [[i] for i in range(10)], addNumbers) "Opus" wrote in message news:... > Shouldn't addNumbers(5) equate to 5? In other words, it should evaluate that > as addNumbers(5)(0) or is that addNumbers(0)(5)? > > How would you send a list of numbers (or objects that represent numbers) to > this? > > On 30 Jun 2002 at 19:24, greg wrote: > > > Janto Dreijer wrote: > > > > > > def addNumbers(k): > > > def f(x): > > > a = addNumbers(x + k) > > > a.val = x+k > > > return a > > > return f > > > > > > >>> addNumbers(9)(5)(2)(4)(6).val > > > 26 > > > > > > Now if only I could figure out how to use __repr__() so I don't > > > need that ".val". It also fails when passed only one number. i.e > > > addNumbers(5). Help? > > > > class AddNumbers: > > > > def __init__(self, x): > > self.val = x > > > > def __call__(self, k): > > return AddNumbers(self.val + k) > > > > def __repr__(self): > > return repr(self.val) > > > > addNumbers = AddNumbers(0) > > > > >>> print addNumbers(9)(5)(2)(4)(6) > 26 > > >>> print addNumbers(5) > > 0 > > From whisper at oz.net Sun Jun 9 05:19:39 2002 From: whisper at oz.net (David LeBlanc) Date: Sun, 9 Jun 2002 02:19:39 -0700 Subject: Socket error problem Message-ID: I have this problem on windows where socket.socket(...) keeps returning 10022, 'Invalid argument'. It's actually dieing in the poplib.POP3.__init__(...) method. I have verified that host is reasonable (mymail.myisp.net or something like that ;)), and port is 110. If I use the test script in poplib.__main__(...) with the correct host, user and password, all is well, but if I call it from this other program i'm trying to get working I get the above error. I can't figure out what's wrong - any pointers? TIA, David LeBlanc Seattle, WA USA From loredo at astro.cornell.edu Thu Jun 20 15:35:21 2002 From: loredo at astro.cornell.edu (Tom Loredo) Date: Thu, 20 Jun 2002 15:35:21 -0400 Subject: Windows versions of Python---pros and cons? References: <3D110B55.4D8AD7FA@astro.cornell.edu> Message-ID: <3D122E79.A189C72E@astro.cornell.edu> Fernando P?rez wrote: > > If you're an old unix hand and want to preserve your sanity, you have two > options: > > 1- put linux on that laptop and be happy. Actually, I've reserved a big chunk of the disk for linux. Just gotta decide which version (is there a "best" one for Python? E.g., Redhat uses Python, but does their reliance on an old version still cause problems?). I'll stay there when I'm developing for *me* on it! > 2- if (1) is not an option for some reason, put cygwin on it. Actually, I need to develop stuff that other Win32 users can use, some probably distributed via the McMillan installer (which I presume works as well with Active State as with the python.org version). So I'm stuck here.... > If you have to work in the normal, > crippled windows environment, that laptop is going to suffer a painful death > after being hurled through the nearest window very soon :) I've only had it two weeks, and only the power cord to the battery charger has saved it! The fact that Dell shipped it with a defective install of Win98 did not help its cause. Thanks, to everyone! -Tom From fredrik at pythonware.com Thu Jun 6 18:57:31 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 06 Jun 2002 22:57:31 GMT Subject: minidom and encoding problem References: <17aafe08.0206051514.4af054d2@posting.google.com> <17aafe08.0206061419.6366b12b@posting.google.com> Message-ID: Ehab Teima wrote: > > This is a bug in your code. You must not insert (byte) string in a DOM > > tree; always use Unicode objects. > > I do not have control over the sent text. The issue started when some > bullets were copied from a word document and pasted into a file and > the whole file was passed to my classes. if you don't know what encoding the file is using, what makes you think Python can figure it out? > I tried to encode the string using different encodings but I could > not. the string is already encoded. you need to *decode* it. > Here is what I got when I tried .encode("UTF-8"): > UnicodeError: ASCII decoding error: ordinal not in range(128) this means that you have non-ASCII characters in an ASCII string. to convert this to a unicode string, use u = s.decode(encoding) where "encoding" is the source encoding (if you haven't the slightest idea, try "iso-8859-1") also see: http://effbot.org/guides/unicode-objects.htm From peter at engcorp.com Fri Jun 21 21:21:08 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 21 Jun 2002 21:21:08 -0400 Subject: [newbie] import fails first time, then works :-[ References: <3D1379D1.5020705@nospam.free.fr> <3D132C65.34B38F8C@engcorp.com> <3D138E31.4070409@nospam.free.fr> Message-ID: <3D13D104.A49AF73C@engcorp.com> laotseu wrote: > > Well... I added '/usr/local/lib/lib-dynload' to my PYTHONPATH and > 'import' does not complain anymore. Everything seems just fine now. But > that is puzzling me ! [being a python newbie,] I thought the > '/lib-dynload/' directorie, that is in the '/lib/python/' > directories, was automagically searched for external modules. Was I wrong ? Searching the executable with "strings" and "grep", I find references to /usr and /lib/python2.0 (in my case) and both /lib/lib-dynload and /lib-dynload. When I run python and check sys.path I get ['', '/usr/bin', '/usr/lib/python2.0', '/usr/lib/python2.0/plat-linux2', '/usr/lib/python2.0/lib-tk', '/usr/lib/python2.0/lib-dynload', '/usr/lib/python2.0/site-packages'] All with default values, under RedHat 7.1. Not sure why you've got troubles... Linux is still Black Magic much of the time to me. :) -Peter From mlh at vier.idi.ntnu.no Sat Jun 8 17:56:15 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Sat, 8 Jun 2002 21:56:15 +0000 (UTC) Subject: Removing ^M References: Message-ID: In article , Michael Hall wrote: > >I am trying remove ^M characters (some kind of newline character) from an >HTML file. I've tried all sorts of string.replace and sed possibilities >but the >things just won't go away. Does anyone have a way of removing such >characters? If you happen to run on a Windows system (including Cygwin) you could simply do this: open('outfile', 'wb').write(open('infile').read()) Python will then take care of the translation for you. >TIA > >Mick -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From theller at python.net Wed Jun 12 03:17:29 2002 From: theller at python.net (Thomas Heller) Date: Wed, 12 Jun 2002 09:17:29 +0200 Subject: Can Distutils include .pyd files directly? References: Message-ID: "Bjorn Pettersen" wrote in message news:mailman.1023837255.23228.python-list at python.org... > I've built my extension modules using the MS Devstudio IDE and now I > would like to use Distutils to create a Windows installer for me that > puts both the debug and release versions of the extension in the > python22\DLLs directory. Is this possible? If not, is there a way to > have Distutils build my extension in both debug and release mode and > install both? > > -- bjorn Sure. The 'build' command builds a 'pseudo installation tree' in the directory build\lib.win32-2.2, all of this will later be installed by the 'install' command. So you can python setup.py build to build the release version, python setup.py build -g to build the debug version, and python setup.py install will install all of this into Python22\lib\site-packages. python setup.py bdist_wininst will create a windows installer containing the debug _and_ the release version (everything that's in the build directory). Thomas From whisper at oz.net Mon Jun 3 18:30:11 2002 From: whisper at oz.net (David LeBlanc) Date: Mon, 3 Jun 2002 15:30:11 -0700 Subject: getting windows processes list In-Reply-To: Message-ID: I'm not sure that mere mortal programs are allowed access to that information due to Window's (NT's) arcane idea of what constitutes security. I think you're doing well to get your own PID. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Grant Griffin > Sent: Monday, June 03, 2002 10:53 > To: python-list at python.org > Subject: getting windows processes list > > > Hi Gang, > > Does anybody know offhand how to use Python to get the list of > processes that > are currently running on Windows? (I'm essentially trying to get the > information that appears in Window's Task Manager's "Processes" tab.) > > not-gifted-at-finding-needles-in-haystacks-ly y'rs, > > =g2 > > _________________________________________________________________________ > > Grant R. Griffin g2 at dspguru.com > Publisher of dspGuru http://www.dspguru.com > Iowegian International Corporation http://www.iowegian.com > > -- > http://mail.python.org/mailman/listinfo/python-list From peter at engcorp.com Mon Jun 17 21:25:58 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 17 Jun 2002 21:25:58 -0400 Subject: What If..... Strong Types References: <3D0C0F0D.4030900@bgb.cc> Message-ID: <3D0E8C26.7BF0772D@engcorp.com> Don Garrett wrote: > > I'm not suggesting any real changes to any, only proposing a thought > experiment. > > What if Python had been built from the start with strong types? And I mean > strong types, not strong typing. The distinction I am trying to draw is that > variables would not be typed, but that all types would have rigid interfaces. > > Primarily, what if classes always had rigidly defined interfaces. I mean > that public members had to be declared to exist, and that methods couldn't be > modified on an instance. Private members could exist but would be really private. It takes work to define those interfaces. In my opinion, unnecessary, inconvenient, and unreadable work... And Python does have private members, of course, for the right definition of private. Preventing modifying methods on an instance would make some of my automated testing really difficult, if not impossible. I don't understand the "must be declared to exist" part. If they are declared but not defined, they don't exist anyway. If they are defined, then they already exist and a declaration is redundant. Or were you using some other definitions of "define" and "declare"? > My belief is that almost all the convenience of Python would be maintained, > but that compilation, optimization, and automated code analysis would be simpler. Given that other languages have these things, but do not have nearly the maintainability and convenience of Python, I doubt that. > I'm just wondering if the change would be good or bad. Would it really > break anything important in Python today? Would it prevent any common errors? > Would it help with automated code analysis (compilation and optimization > included) as much as I think it would? Fork a branch of Python and experiment! I suppose, since Python is flexible and adding all these things to the language would tend to make it more restrictive and, well, brittle, you could probably call the language "Stick". :-) -Peter From mertz at gnosis.cx Sat Jun 8 13:14:04 2002 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Sat, 08 Jun 2002 13:14:04 -0400 Subject: Counting lines References: <3D000B36.5C7BCEBF@engcorp.com> Message-ID: Since this thread has drifted into line counts, I think it worth sharing a resource that a fellow-developer shared with me: SLOCCount: http://www.dwheeler.com/sloccount/ Take a look. It's not written in Python (I don't think), but it seems to do a large superset of what pycount.py does. SLOCCount counts the lines of code in a large number of different programming languages, using rather clever rules and heuristics both to identify what language a file actually is, and to discern which lines are code versus comments (including, e.g. Python docstrings). SLOCCount also reports some stuff about cost and development efforts. I would take that with a grain of salt, for lots of reasons. But it's fun seeing just how many kilodollars you -should- have been paid to write your open source application :-). Yours, Lulu... -- mertz@ | The specter of free information is haunting the `Net! All the gnosis | powers of IP- and crypto-tyranny have entered into an unholy .cx | alliance...ideas have nothing to lose but their chains. Unite | against "intellectual property" and anti-privacy regimes! ------------------------------------------------------------------------- From jonathan at onegoodidea.com Thu Jun 27 09:18:40 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Thu, 27 Jun 2002 14:18:40 +0100 Subject: Suggestions for good programming practices? References: Message-ID: On 26/6/2002 20:53, in article afd648$3b4$0 at 216.39.172.122, "Bengt Richter" wrote: > LOL ;-) It continually amazes me that Python is so backward as to require the programmer to explicitly note that a function takes arguments ;-) > ISTM caller-friendly is good, but the *args implementation of this overloading > is not as nice > as it could be. Is it better to allow foo(x,y,s) and foo(s) via overloaded > foo() than, e.g., > to use separate names like fooxy(x,y,s) and foo(s), and have foo() call > fooxy()? > (That, at least, is an OT question ;-) I'm of the opinion that when a function can take a sensible set of unrelated optional arguments they should be keyword arguments, and one should call the function with those keywords explicitly: >>> def writeString( s, x=0, y=0 ): ... pass ... >>> writeString( "Hello World" ) >>> writeString( "This is a test", x=10, y=35 ) >>> When the function can take a variable number of related arguments, I use *args: >>> def writeStrings( *strings ): ... for s in strings: ... writeString( s ) ... >>> writeStrings( "Hello World" ) >>> writeStrings( "This is a test", "I love tests" ) >>> These styles, of course, can be mixed. I'm not a big fan of the idea of distinguishing between not supplying an optional argument and supplying the equivalent default. I think a default should mean a default, not an indicator of no-argument. I don't much like: >>> def writeString( s, x=None, y=None ): ... if x is None: ... # do something else ... pass ... pass ... I think that calling a function with a default argument explicitly given should always make sense, i.e., read sensibly. So: >>> writeString( "This is a test", x=None, y=None ) >>> doesn't feel right to me since I'm not convinced that 'None' makes sense as a position. If the default is being used to indicate, for example, the current cursor position, then it should be explicitly named like: >>> class _CurrentPosition: pass ... >>> CurrentPosition = _CurrentPosition() >>> >>> def writeString( s, x=CurrentPosition, y=CurrentPosition ): ... if x is CurrentPosition: ... # obtain current x co-ordinate ... pass ... pass ... >>> writeString( "Hello World", x=CurrentPosition, y=CurrentPosition ) >>> The exception that proves the rule is where None really is a sensible default. Hoo hah. That's enough of that. Jonathan From mutsuura at mutsuura.com Thu Jun 13 11:25:49 2002 From: mutsuura at mutsuura.com (Attila Horvath) Date: Thu, 13 Jun 2002 11:25:49 -0400 (EDT) Subject: Poll: Readable languages In-Reply-To: <200206131409.JAA05450@scotland.k12.mo.us> Message-ID: On Thu, 13 Jun 2002, Chris Gonnerman wrote: > On Thu, 13 Jun 2002 09:36:06 -0400 (EDT), Attila Horvath wrote: > > > In my years of experience I have come across VERY readable assembler and > > very unreadable COBOL, PASCAL, FORTRAN, ADA, C/C++, JAVA, etc. So I > > suggest that a langauge does not inherently make resultant code readable. > > True, and false. It is possible to write bad code in any language; but in my > opinion, any programmer who has mastered Python (takes what, a couple of > weeks? :-) *tends* to write more readable code than an equivalently > accomplished programmer in any other language. Sorry. What I didn't say but meant to is that 'readability' is determined by several factors - 'structure' being only one. Clarity and simplicity in logic, nomenclature, packaging, comments, documentation [to mention a few] add greatly to readability. All these can be bastardized in ANY language. So my question/point to Ingo was, is 'readability' or 'fundamentals' of good programming at issue?! Either way, a survey will not answer that question: 'Good programming cannot be taught by preaching generalities. The way to learn to program well is by seeing, over and over, how real programs can be improved by the application of a few principles of good practice and a little common sense. Practice in critical reading leads to skills in rewriting, which in turn leads to better writing.' The above excerpt 'punch card' bookmarked in my copy of: "The Elements of Programming Style"; Brian W. Kernighan and P. J. Plauger Bell Telephone Laboratories 1974 If I understand the excerpt, I think it's saying that experience through practice from good examples makes for good programming skills. attila From kragen at pobox.com Mon Jun 3 00:03:52 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 03 Jun 2002 00:03:52 -0400 Subject: Why does this work: 5<"five" ? References: <3CF80435.689AE006@icc-computer.de> Message-ID: <831ybprot3.fsf@panacea.canonical.org> Jiri Baum writes: > It's documented that way. When comparing values of different types, you get > an arbitrary (but fixed) ordering. I think the docs say it can change from > version to version. > > You'll note that 5>"five" gives you a 0. > > This means you can do things like binary search trees without worrying > about how to sort disparate values. That's what I thought, too, but (in 2.1.1): >>> 1<1j Traceback (most recent call last): File "", line 1, in ? TypeError: cannot compare complex numbers using <, <=, >, >= So if you put complex numbers into your binary search tree, you will have problems. Oh, enjoy this: >>> (1,) < (2,) 1 >>> (1j,) < (1j,) 0 I'm not sure what's going on there. I thought maybe tuple comparison did an 'is' before doing an actual comparison, but timing suggests that it doesn't. From James_Althoff at i2.com Wed Jun 5 16:17:41 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Wed, 5 Jun 2002 13:17:41 -0700 Subject: Thought on PEP 204 and 276 Message-ID: [holger krekel ] >in many cases (where table is iterable that is). >I think that 'for i in 10:' is hardly ever used literally. >By far the most common case is: > > for i in xrange(len(somelist)): > item=somelist[i] > # use it > somelist[i]=newvalue > >which becomes: > > for i,item in enumerate(somelist): > # use item > somelist[i]=newvalue > >So i don't see many applications for PEP276 anymore. Except that tables -- GUI tables, Database tables, and other multi-dimensional structures -- *aren't* likely to be interable in the sense implied above (especially when they come from non-Python sources such as Swing/JDBC/Jython). As suggested in a previous thread, one might work around this limitation by writing wrappers that allow iteration across virtual rows and virtual columns of tables, for example. "enumerate" only helps (in the examples like the one above) if one is willing to write and use such wrappers. On the other hand, such wrappers often (like in the example above) make "enumerate" unnecessary. Jim From kragen at pobox.com Sat Jun 8 18:33:08 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 08 Jun 2002 18:33:08 -0400 Subject: How could i get execution times ? References: Message-ID: <83r8jh5rkr.fsf@panacea.canonical.org> "Shagshag13" writes: > I'm looking for a way to get execution time at different points of a program, by now i use the > code below, but i've seen in some post that time.clock() could be a better way to measure this, > > So my question, is how you pythoners do it ??? and to understand _why_ ? time.time() gives wallclock time; time.clock() gives CPU time. From tim.one at comcast.net Sun Jun 30 16:17:49 2002 From: tim.one at comcast.net (Tim Peters) Date: Sun, 30 Jun 2002 16:17:49 -0400 Subject: Python needs better error reporting In-Reply-To: Message-ID: [Tim] > Error-reporting in parsers has been the subject of intense > research. Do a little digging and come back when you can > make a case that your point can be addressed effectively. [/F] > fwiw, I've seen Lisp advocates argue that this may be > one of Lisp's greatest advantages... If so, the quality of Lisp advocacy has suffered a precipitous decline since my day . I spend less time puzzling over syntax errors in Python than I spent tracking down stuttered or missing parens in Lisp code, and in the presence of read macros errors in Lisp input can be arbitirarily difficult to spot. I routinely spend gobs of time trying to figure out what's wrong in C source, though -- e.g., forget a semicolon after a struct declaration and it's likely to take the next identifier as declaring a variable of the struct type, and the subsequent cascade of nonsensical error msgs is truly amazing. Lisp is mounds better than C in that respect -- but so is Python. don't-even-think-about-c++-ly y'rs - tim From ffjhenon at club-internet.fr Wed Jun 26 18:03:37 2002 From: ffjhenon at club-internet.fr (Fabien =?iso-8859-1?Q?H=E9non?=) Date: Thu, 27 Jun 2002 00:03:37 +0200 Subject: Embed terminal into a Tkinter application References: <3D1758B4.8FA63EBE@club-internet.fr> <653AB281E1346AA6.7E81367537EEC2BE.CF6BC8C39D83D26D@lp.airnews.net> Message-ID: <3D1A3A39.A63B1038@club-internet.fr> Thanks for the link. Yes that is what I want : Insert a terminal as Konsole or xterm into a Tkinter application instead of a Text (Tkinter widget) to which I never managed to redirect stdout and stderr of an external program. I have reposted a message about it today. Continuous redirection of stdout and stderr to a Tkinter app Fabien Cameron Laird a ?crit : > In article , > Chris Liechti wrote: > >Fabien H?non wrote in > >news:3D1758B4.8FA63EBE at club-internet.fr: > > > >> The title says it all. > >> Has someone already managed to include a Linux terminal into a Tkinter > >> GUI ? > >> > >> Redirecting the output of a console into the application does not do > >> what I want. > > > >well, what do you want? let us help you! > > > >there is also popen[2,3,4] - you can also redirect stdin. > > > >chris > > > >-- > >Chris > > > > My guess is he wants an xterm(-like thing) in a Tkinter frame. > > Information on the subject appears in . > I haven't made the time to translate this into idiomatic Python. Speak > up if you need help doing so. > -- > > Cameron Laird > Business: http://www.Phaseit.net > Personal: http://starbase.neosoft.com/~claird/home.html From logiplexsoftware at earthlink.net Fri Jun 21 03:39:20 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: 21 Jun 2002 00:39:20 -0700 Subject: Inhibiting duplicate apps in Windows? In-Reply-To: <3D12BCCA.3A0F7544@engcorp.com> References: <3D11F9E8.DFFFC8E4@tds.net> <3D1283EC.A28A45CB@engcorp.com> <3D12BCCA.3A0F7544@engcorp.com> Message-ID: <1024645162.10524.8.camel@localhost.localdomain> On Thu, 2002-06-20 at 22:42, Peter Hansen wrote: > Cliff Wells wrote: > > > [on locks 'n such] > > A fairly fool-proof/portable method is to open a socket. If the app is > > run a second time it will fail on the attempt. Even if the app crashes, > > the socket will be closed by the OS (although it may take a couple of > > seconds on occasion). > > Interesting, although I take it you mean "bind a socket to a port". Uh, yeah, sorry to be ambiguous. > Are there any complications with this? I created one and it's true > another instance could not be opened ("address already in us") but > the socket is listed with "netstat" as being LISTENING even though > I have not called listen() or accept(). Any problems with doing > that, if something connects to the socket? Could it cause the > socket to be held open for more than a couple of seconds after > closing? Sometimes sockets can take minutes to be cleaned up. You know, I haven't actually tested such a situation, but I don't think another program can connect to that socket without accept() being called (but I could be wrong). Probably best just to try it an find out. Cliff From dmitri.gouliaev at telkel.net Thu Jun 20 08:47:52 2002 From: dmitri.gouliaev at telkel.net (Dmitri I GOULIAEV) Date: Thu, 20 Jun 2002 07:47:52 -0500 Subject: latex-tex-packages In-Reply-To: <29A97D00F387D411AC7900902770E148058E5A11@lcoeexc01.coelce.net>; from "Alves, Carlos Alberto - Coelce" on Wed, Jun 19, 2002 at 04:24:36PM References: <29A97D00F387D411AC7900902770E148058E5A11@lcoeexc01.coelce.net> Message-ID: <20020620074752.A7257@lifebook> Hi, Alves, Carlos Alberto - Coelce ! On Wed, Jun 19, 2002 at 04:24:36PM -0300, Alves, Carlos Alberto - Coelce wrote: > You forgive me, c'os I know this issue it's not to this list; But, anybody > can tell me where can I get tex/latex packages to install. I just browse > some url but can't find'em. May I suggest to browse some more ?.. http://directory.google.com/Top/Computers/Software/Typesetting/TeX/ Best regards, -- DIG (Dmitri I GOULIAEV) From larooy at xtar.co.nz Thu Jun 13 03:50:38 2002 From: larooy at xtar.co.nz (John La Rooy) Date: Thu, 13 Jun 2002 19:50:38 +1200 Subject: Why does Python mix OO concepts and non OO concepts for operation s on basic types? References: <3D054A98.3090708@bgb.cc> Message-ID: <20020613195038.281d513d.larooy@xtar.co.nz> On Tue, 11 Jun 2002 22:28:44 +0200 holger krekel wrote: > Roman Suzi wrote: > > I only forgot how will I do this: > > > > map(string.split, s) > > > > if GvR will deprecate string module... > > what about > > map(str.split, s) > > :-) holger > > what about map(string.capwords, s) I'm guessing it's an oversight that there is no str.capwords?? John ;oP From sandeep182 at hotmail.com Thu Jun 20 11:12:48 2002 From: sandeep182 at hotmail.com (Sandeep Gupta) Date: Thu, 20 Jun 2002 15:12:48 GMT Subject: FreeTDS vs Inline TDS: Problem with Inline TDS Message-ID: I'm attempting to access a SQL Server 2000 DB from Linux using ODBC. My setup is Python --> mxODBC --> unixODBC --> --> SQL Server When I use the Inline TDS driver directly from unixODBC, all queries return the correct results, but the final line is always "-1 rows affected". The FreeTDS driver returns the correct results as well as the correct number of rows affected. The incorrect "rows affected" from Inline TDS seems to be causing problems with mxODBC. Has anyone experienced this same problem with Inline TDS's driver? Are there any other suggestions for querying against SQL Server 2000 from Python running on Linux? Thanks Sandeep From phd at phd.pp.ru Wed Jun 12 14:57:29 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Wed, 12 Jun 2002 22:57:29 +0400 Subject: dict = urllib.urldecode(string) ? In-Reply-To: ; from jjb5@cornell.edu on Wed, Jun 12, 2002 at 02:23:53PM -0400 References: Message-ID: <20020612225729.B642@phd.pp.ru> On Wed, Jun 12, 2002 at 02:23:53PM -0400, Joel Bender wrote: > I'm processing GET and POST data and I would like the functional > inverse of urllib.urlencode(). That is, split the string apart by > the '&' chars, split each of those by '=' and build a dict of the > results. The key and the value should be passed to unquote_plus(). > > Here is my solution, comments? > > >>> def urldecode(s): > ... rslt = {} > ... for item in s.split('&'): > ... keyValue = item.split('=') > ... rslt[ urllib.unquote_plus(keyValue[0]) ] = > urllib.unquote_plus(keyValue[1]) > ... return rslt > ... > > >>> urldecode('a=b+c&d%26e=%20f') > {'a': 'b c', 'd&e': ' f'} You cannot handle URLs like "city=London&city=Paris". BTW, modern urlencode accept a list of 2-lists, not only a dict. Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From pinard at iro.umontreal.ca Thu Jun 20 19:53:46 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 20 Jun 2002 19:53:46 -0400 Subject: do...while In-Reply-To: <60FB8BB7F0EFC7409B75EEEC13E20192158EEC@admin56.narex.com> References: <60FB8BB7F0EFC7409B75EEEC13E20192158EEC@admin56.narex.com> Message-ID: [Bjorn Pettersen] > Doing a quick search over our C++ libraries (~900KLoc), "do {} while()" > seems to be used in right around 3% of the loops (including while, for; > excluding recursion). Seems like overkill to add special syntax for a > feature used so rarely... Some of you might remember C.A.R. Hoare's axiomatisation of Pascal, which also gives good insight for many other languages. The `do {} while()' was called `repeat' in Pascal. The axiom for `while' is one of the simplest of the whole language, much simpler than the axiom for `repeat'. This taught me that there is a theoretical foundation for the popularity of the `while' construct. After all, program axiomatisation is nothing more than the formalisation of programmer's thought when s/he produces a program, and our intuition naturally drives our thoughts towards simpler concepts. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From bowman at montana.com Tue Jun 4 00:11:22 2002 From: bowman at montana.com (bowman) Date: Mon, 03 Jun 2002 22:11:22 -0600 Subject: getting windows processes list References: Message-ID: Grant Griffin wrote: > Does anybody know offhand how to use Python to get the list of processes > that are currently running on Windows???(I'm?essentially?trying?to?get?the > information that appears in Window's Task Manager's "Processes" tab.) Take a look at WSH/WMI. Probably the easiest way. From emile at fenx.com Sun Jun 30 11:42:57 2002 From: emile at fenx.com (Emile van Sebille) Date: Sun, 30 Jun 2002 15:42:57 GMT Subject: yield equivalent in C/JavaScript? References: <7xy9cxhlvx.fsf@ruckus.brouhaha.com> <7xit41i7i9.fsf@ruckus.brouhaha.com> <14ms5VAygsH9Eww2@jessikat.fsnet.co.uk> <7xelepnk84.fsf@ruckus.brouhaha.com> Message-ID: <5GFT8.369062$cQ3.24122@sccrnsc01> Robin Becker > The IE stuff seems to rely too much on the URL extension so provided it > thinks it's htm or html IE 5.x seems OK. > Cool... last time I looked into this it didn't work on IE, and I found this on msdn If the server-provided MIME type is either known or ambiguous, the buffer is scanned in an attempt to verify or obtain a MIME type from the actual content. ... that I read to mean 'if you tell it, it will make its own check anyway and ignore you' so I gave it up. Can you post an example url that causes IE to properly interpret Content-Encoding: x-gzip? Thanks, -- Emile van Sebille emile at fenx.com --------- From marklists at mceahern.com Thu Jun 13 12:11:52 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 13 Jun 2002 11:11:52 -0500 Subject: For and Dates In-Reply-To: <67F0CEAF5F0ED411B53900508BC5C8BC700195@admin.datacraft.com.br> Message-ID: > I need to do a loop that goes from 2002-6-1 to 2002-7-31, but I don't know > how to do that... > > Is there a way to do such range using for !? > > Do you have any suggestions !? Short answer: Use mx.DateTime + generators Demo: from __future__ import generators import mx.DateTime def date_span_gen(d1, d2): """Return an iterator for the dates between d1 and d2.""" if d2 <= d1: raise RuntimeError("d2 (%s) must be later than d1 (%s)." % (d2, d1)) diff = d2 - d1 for d in range(diff.days): yield (d1 + mx.DateTime.RelativeDateTime(days=d)) num_days = 30 d1 = mx.DateTime.now() d2 = d1 + mx.DateTime.RelativeDateTime(days=num_days) for d in date_span_gen(d1, d2): print d - From Bill.Scherer at VerizonWireless.com Wed Jun 12 11:27:09 2002 From: Bill.Scherer at VerizonWireless.com (Scherer, Bill) Date: Wed, 12 Jun 2002 11:27:09 -0400 (EDT) Subject: Bits and bytes? In-Reply-To: <3d0760ec$0$223$4d4ebb8e@news.nl.uu.net> Message-ID: On Wed, 12 Jun 2002, Guyon Mor?e wrote: > ok, thanx a lot. > > there's one thing i am missing though... how do i write '011010110101' as > 'binary bits' to a file? I've only had need for this once, but when I 'realized' that a byte was just eight bits, my problem was solved. For you that depends on if you're ok with writing bits in multiples of eight, and that you can create the proper 8 bit seqeunces for your needs. chr(0) through chr(255) should cover your needs, I think. chr(107) + chr(168) will give you '011010110101000' CAVEAT: I might be completely off my rocker on this. 8-) Good luck. > > > > > "Christopher Armstrong" wrote in message > news:mailman.1023890477.2592.python-list at python.org... > >>>>> "Guyon" == Guyon Moree writes: > > Guyon> ok, this might be a strange question.... but i was wondering: how > Guyon> can i read or write 'bits'? > > Guyon> if i have a string, how can i convert to it's basic 0's and 1's? > > Guyon> and offcourse, the other way around.... let's say i want to store > Guyon> some bit-sequence(0011101110) to a file. > > > Guyon> how do i do this? > > http://twistedmatrix.com/users/moshez/binary.py > > Moshe Zadka wrote this because he was annoyed at all the people in #python > asking how to do this ;-) > > > -- > Chris Armstrong > << radix at twistedmatrix.com >> > http://twistedmatrix.com/users/carmstro.twistd/ > > > > > > -- Bill.Scherer at Verizon Wireless RHCE 807101044903581 From wuhsinyee at hotmail.com Thu Jun 13 10:51:46 2002 From: wuhsinyee at hotmail.com (Mark Wu) Date: 13 Jun 2002 07:51:46 -0700 Subject: How to install BITS in zope? Message-ID: Hi All: Does any one successfully install Bug & Issues Tracking System on ZOPE? I already followed the installation guide, and installed 1. MySQLdb for python 2.1.1 2. ZMySQLDA in Zope 2.5.1 But when I want to install the sql script to create the table in my SQL, it not worked. It seems the script is only for Oracle. Can any one tell me how to change the script and make it suitable for mysql?? Best Regards, Mark ** My environment: OS: win2000 ZOPE: Zope 2.5.1 MySQL: 3.2.23 Python: 2.1.1 From mwh at python.net Wed Jun 12 06:24:05 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 12 Jun 2002 10:24:05 GMT Subject: unknown opcode Exception then AV References: Message-ID: "Geoff Bien" writes: > Found the problem. There is a known bug > in version 2.1 ?? when "continue" is used > within a try...except block Oh yeah, that. It's fixed in 2.1.something though, isn't it? Time for an upgrade perhaps. Cheers, M. -- C is not clean -- the language has _many_ gotchas and traps, and although its semantics are _simple_ in some sense, it is not any cleaner than the assembly-language design it is based on. -- Erik Naggum, comp.lang.lisp From TuxTrax at fortress.tuxnet.net Wed Jun 5 17:23:13 2002 From: TuxTrax at fortress.tuxnet.net (TuxTrax) Date: Wed, 05 Jun 2002 21:23:13 -0000 Subject: Compiling Python References: <3CFE23DB.994F8A6C@engcorp.com> Message-ID: On Wed, 05 Jun 2002 10:44:43 -0400, Peter Hansen wrote: > TuxTrax wrote: >> >> Hello all >> >> I am new to this forum, and to Python, please excuse the newbie question. >> >> I have started reading the o'reilly book, "learning python" and find python >> to be an amazing language so far. My first impression of it is a language that >> is easier than basic to learn and use, and more powerful than many other >> high level languages such as pascal. >> >> My question is this; I realize that Python compiles to bytecode automatically >> as part of the interpreters tokenization run, but is there a way to permanently >> compile python code outputting to an executable binary? > > Why do you want to do that? For presumably increased speed, or because > you don't want the hassle of multiple .py files all over the place (in > other words, better packaging)? > > -Peter Hi Peter I was more interested in if there were existing tools to do it, already available. I really don't care to "hide" my source code, as I hail from the open source Linux community (kind of like "I'm from star fleet, I never lie" ) and I would be releasing any source for any python app that I wrote (that was any good ) anyway. Besides, if you know others will be seeing your source you tend to write cleaner code . As I noted, it was a newbie question, a matter of curiousity. I am just starting to learn python and I really love it, and I am full of such questions that probably others have already gotten past. Packaging is a thought, but speed (so far) isn't an issue, as python is pretty fast IMHO. Cheers, Mathew -- TuxTrax (n.) An invincible, all terrain, Linux driven armored assault vehicle that can take as much fire as it gives ;-) ASSASINATION ANTHRAX PRESIDENT NUCLEAR TALIBAN AMMONIUM NITRATE Yes, I am a Penguin cult high priest. Fin readings upon request. ROT13 this email address to mail me: uvtuqrfregzna at lnubb.pbz From gerhard at bigfoot.de Fri Jun 14 21:47:31 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Sat, 15 Jun 2002 03:47:31 +0200 Subject: Using Python to script a game? In-Reply-To: References: Message-ID: <20020615014731.GA2856@lilith.my-fqdn.de> * Ben Blonder [2002-06-14 18:18 -0700]: > I'm writing a 3D naval tactics in C++ for the Mac. I'm planning on > having all the object behaviors, movements, and AI controlled through > a scripting layer. The scripts would be text files the game would > parse and then carry out actions. All the scripts would be read at > runtime, not compile time, so they'd all have to be interpreted. > > For example, I might have the C++ code > > class foo { > public: > int x; > void print() { > cout << x << endl; > } > }; > > In the scripting system, there would have to be some way to create a > new foo object, define x, and then call print() while the user was > playing. > > Can I use Python to accomplish this, Yes. And it would be a pretty good match, too. There's even been a commercial game that uses Python for internal scripting, its name escapes me, though. > and if so, can you point me to some tutorials on integratring Python > with my existing code? Python's documentation has (now) good documentation about it's C API. Python's API is _C_, though, not C++. There are several C++ wrappers for it than can simplify the integration a lot. My personal favourite is Boost::Python. http://www.boost.org/ As a C++ developer, you might be interested in the other free libraries from Boost, too. What these people accomplish is really amazing! Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From peter at engcorp.com Fri Jun 7 08:07:37 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 07 Jun 2002 08:07:37 -0400 Subject: Medium to Large Scale Python Deployments References: <38C31EBA-79A4-11D6-9A7D-003065B33450@intersight.com> <3D003EC7.C72D27BE@engcorp.com> <3D006320.5040805@web.de> Message-ID: <3D00A209.EC24F671@engcorp.com> J?rgen Hermann wrote: > > Peter Hansen wrote: > > How big is that when run through pycount? > > > > (I.e. comments and blank lines don't count!) > > Summary on "twisted" > ==================== > files 256 > lines 51654 > bytes 1728211 > comments 5993 > empty lines 10029 > non-commentary lines 29910 Thanks! Similar results to what I've seen over about 50000 lines in 235 files. Roughly 50-60% code content, and almost twenty percent blank lines. I suspect such numbers (perhaps excluding lines of comments) are more consistent for Python code, whoever wrote it, than for many other languages. -Peter From drew_csillag at yahoo.com Wed Jun 26 03:14:06 2002 From: drew_csillag at yahoo.com (Drew Csillag) Date: Wed, 26 Jun 2002 12:14:06 +0500 Subject: [ANN] SkunkWeb 3.2.3 Message-ID: <3D1969BE.2040901@yahoo.com> SkunkWeb 3.2.3 has just been released. The release is available from the SkunkWeb home page at http://skunkweb.sourceforge.net or directly from http://prdownloads.sourceforge.net/skunkweb/skunkweb-3.2.3.tgz This is mainly a bugfix release. Changes in 3.2.3 ======================================== * added support for the SCGI Protocol - http://www.mems-exchange.org/software/scgi/ * document updates/revamps (currently stmlrefer) * now is more persistant about the timeout exception (it's reraised each second after a timeout occurs) * now should build with non-GNU makes (specifically BSD make) * many fixes -- thanks to pychecker! * fixed error handling weirdnesses Drew Csillag From gh_pythonlist at gmx.de Tue Jun 4 03:48:51 2002 From: gh_pythonlist at gmx.de (Gerhard =?unknown-8bit?Q?H=E4ring?=) Date: Tue, 4 Jun 2002 09:48:51 +0200 Subject: 'for every' and 'for any' In-Reply-To: <7934d084.0206031636.5c29b31f@posting.google.com> References: <20020526135944.A32690@hishome.net> <20020526091742.A987@unpythonic.net> <7934d084.0206031636.5c29b31f@posting.google.com> Message-ID: <20020604074850.GC23780@gargamel.hqd-internal> * Andrae Muys [2002-06-03 17:36 -0700]: > C dosn't have any 32-bit int types standardised, so what do _you_ use > when you need one? Do you need 32 bit ints or >= 32 bit ints? I only know that Ada 95 and C++ with Boost can guarantee a certain bit length for ints. Dunno if that's what you wanted to hear :) Does Python run on any machine where ints are 16 bits long at all? Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 18.7 ?C Wind: 2.0 m/s From idbaxter at semdesigns.com Sun Jun 16 16:21:52 2002 From: idbaxter at semdesigns.com (Ira Baxter) Date: 16 Jun 2002 13:21:52 -0700 Subject: symbolic python References: <3CEFAE4C.38A8022B@doc.ic.ac.uk> <3CEFD881.D7992095@doc.ic.ac.uk> <3cf8ce86$1@giga.realtime.net> <83sn46vkgi.fsf@panacea.canonical.org> <3CF942C7.2E4AA4CF@engcorp.com> <838z5xtcla.fsf@panacea.canonical.org> Message-ID: <6a625eea.0206161221.50d351ad@posting.google.com> Kragen Sitaker wrote in message news:<838z5xtcla.fsf at panacea.canonical.org>... > Peter Hansen writes: > > Kragen Sitaker wrote: > > > "Ira Baxter" writes: > > > > DMS Software Reengineering Toolkit. > > > It sounds very interesting. How can I get a copy? > > > > No doubt by sending them a pile of money. :-) (Given the customer > > list mentioned, it would probably be a large pile.) It isn't cheap by most people's standards. But then, we don't sell tens of thousand of copies, and so the cost must reflect the engineering effort and volume. And we (at least) think it is well worth the price in terms of time saved for the tasks which it does well. > I looked around the web site for a while without finding any > information about how to do that, so I posted the above message. Ira > Baxter responded in private, saying it "was available commercially", > and suggesting that I look at the web site for more details. > > This all leaves a bad taste in my mouth; the Web site makes a point of > explaining that the information they would like to sell me was > developed with my tax dollars. And frankly, so was the basic VLSI technology that powers the computers you seem happy to pay for. Yes, we did get some tax dollars to help build an early, *demo* version of the technology. And, like most other beneficiaries of US Government Research grants, we have put a huge amount of effort into it above and beyond what the original grants provided. > > no support for Python is (yet) mentioned in the list of supported > > languages. That's because our tools are designed to accept langauge definitions easily. A Python grammar would take only a few days to develop. If you want to transform Python symbolically, DMS will do the job very well, and I don't see many alternatives out there. -- IDB From aahz at pythoncraft.com Mon Jun 10 12:15:34 2002 From: aahz at pythoncraft.com (Aahz) Date: 10 Jun 2002 12:15:34 -0400 Subject: Correct code/unit testing (was Re: Efficient python programming...) References: <3D02FB3B.CF75E925@engcorp.com> <3D03CDD2.78C01DE1@engcorp.com> Message-ID: In article <3D03CDD2.78C01DE1 at engcorp.com>, Peter Hansen wrote: > >The nastiest bugs were found by lots and lots of work, which usually >included repeated attempts to reproduce the problem, manual runs, >and sometimes using a debugger. Staring helped little. And then, >having found the bug, we look at the code and say "oh yeah, we >should have seen that." Not necessarily. >Better not to put the bugs in the code in the first place, however, >so staring or those other things won't be necessary. Writing the >tests and the code together, tests first, in small iterative steps, >tends not to lead to buggy code. The payback is high compared to >staring. Maybe. The most difficult bug I recall tracking down turned out to involved a web page created by a program that put a null character at the end of an URL, like this: Except, of course, that looking at the page's source in the obvious ways didn't display the damn thing. I finally used Python to download the page and display chunks of the pagestring. The problem was compounded by a bug in MS SQL Server that considered the null-ending and non-null-ending versions of the string to be either duplicate or unique, depending on the precise operation. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I had lots of reasonable theories about children myself, until I had some." --Michael Rios From tdelaney at avaya.com Mon Jun 24 20:29:31 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Tue, 25 Jun 2002 10:29:31 +1000 Subject: Redirecting StdOut Message-ID: > From: Ugo Garc?a [mailto:plugin at supercable.es] > > or, perhaps this is the right way to do it. Do u know many > games that are > made with an interpreted languaged? I don't. (I'm talking > about GAMES, not > little demos). Well, I known one: BLADE. It use Python to > define the world, > the behavour of the characters, and other things like the > save games... If u http://groups.google.com/groups?hl=en&lr=lang_en&ie=UTF-8&frame=right&th=54a 844b1ecd059e9&seekm=3D0D9317.6371F155%40del_cygnus-software_del.com In particular, look at Bruce Dawson's response. Tim Delaney From Mitch.Chapman at bioreason.com Tue Jun 25 12:05:09 2002 From: Mitch.Chapman at bioreason.com (Mitch Chapman) Date: Tue, 25 Jun 2002 10:05:09 -0600 Subject: Memory Monitor References: Message-ID: <3D1894B5.720EB7F7@bioreason.com> Marco Catunda wrote: > > Hello, > > What is the best way to monitor usage memory? > > I have used "os.system( 'ps %d' % os.getpid() )" but I > don't know if it is the best way? Can't tell if you're using Linux or some other *nix variant. If you are using Linux, this might do what you want: inf = open("/proc/self/status", "r") print inf.read() inf.close() 'course, you probably want more concise output, e.g.: os.system("cat /proc/self/status | grep VmSize") -- Mitch Chapman Mitch.Chapman at bioreason.com From mwh at python.net Sat Jun 8 12:50:36 2002 From: mwh at python.net (Michael Hudson) Date: Sat, 8 Jun 2002 16:50:36 GMT Subject: __imul__ broken for 'objects' in 2.2.1 References: Message-ID: Alexander Schmolck writes: > OK, after unsuccessfully trying for about half an hour to submit this to the > sf bug tracker, I gave up: > > class Breaky(object): > def __imul__(self, other): > print "imuling" > return self > sq = Breaky() > sq *=1. > > gives: > > Traceback (most recent call last):[...] line 10, in ? > sq *=1. > TypeError: can't multiply sequence to non-int > > Unless I'm overlooking something, this is a fairly serious bug and I > can't see a way to work around it (getattribute would presumably > work, but slow everything down unacceptably, so the only 'solution' > seems to be to have no inplace-multiplication). > > I had the same behavior on two different machines (running Mandrake 8.2 and > Suse 7.3). Hmm. You should file a bug on sf so this doesn't get forgotten (unless it's already been reported, but I don't think so). Cheers, M. -- 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 mertz at gnosis.cx Fri Jun 28 14:29:09 2002 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Fri, 28 Jun 2002 14:29:09 -0400 Subject: metaclasses vs. inheritance References: Message-ID: <1rKH9kKkX0cE092yn@gnosis.cx> |Can someone give an example of a problem that is solved with metaclasses, |which would be difficult or impossible to solve with inheritance? |I (very barely) understand metaclasses, but to me it just seems like |inheritance, where the classes who get the benefit of the meta-class get the |metaclass' features. Well... I am at the "barely" level also. But my Gnosis_Utils package contains a moderately useful example of a metaclass. By way of background, gnosis.xml.pickle pickles Python objects to XML. There are several ways to use it, but one is: # By inheritence from gnosis.xml.pickle import XML_Pickler class MyClass(XML_Pickler): # create some behavior and attributes for MyClass... o1 = MyClass() # o1 knows how to dump itself xml_str = o1.dumps() Good enough. But every class that wants to know how to serialize itself needs to inherit from XML_Pickler. Here's an alternate approach: """Perform black magic of unearthly and ungodly sorts Quick Example 1: Python 2.2 (#0, Dec 24 2001, 18:42:48) [EMX GCC 2.8.1] on os2emx Type "help", "copyright", "credits" or "license" for more information. >>> import gnosis.magic >>> __metaclass__ = gnosis.magic.MetaPickler >>> class Boring: ... def __init__(self): ... self.this = 'that' ... self.spam = 'eggs' ... def print_spam(self): ... print self.spam ... >>> boring = Boring() >>> boring.print_spam() eggs >>> print boring.dumps() """ from gnosis.xml.pickle import dumps class MetaPickler(type): def __init__(cls, name, bases, dict): super(MetaPickler, cls).__init__(name, bases, dict) setattr(cls, 'dumps', dumps) -- mertz@ | The specter of free information is haunting the `Net! All the gnosis | powers of IP- and crypto-tyranny have entered into an unholy .cx | alliance...ideas have nothing to lose but their chains. Unite | against "intellectual property" and anti-privacy regimes! ------------------------------------------------------------------------- From jeremy at jdyallop.freeserve.co.uk Sat Jun 15 04:44:15 2002 From: jeremy at jdyallop.freeserve.co.uk (Jeremy Yallop) Date: 15 Jun 2002 08:44:15 GMT Subject: html parser etc help References: <7fe97cc4.0206111445.43b196de@posting.google.com> <7fe97cc4.0206150003.65fe8821@posting.google.com> Message-ID: * Xah Lee | Thanks Jeremy Yallop for help. Some follow up questions... | | in the following code: | | import os | def visit(arg, dirname, fnames): | for file in fnames: | if file.endswith('.html'): | print file | print arg | os.path.walk('/export/home/xah/unixnotes/',visit,'---') | | | * in the os.path.walk, what's the third argument for? Here's what the interactive help says: >>> import os >>> help(os.path.walk) Help on function walk in module posixpath: walk(top, func, arg) Directory tree walk with callback function. [...] No semantics are defined for, or required of, arg, beyond that arg is always passed to func. It can be used, e.g., to pass a filename pattern, or a mutable object designed to accumulate statistics. Passing None for arg is common. | * what if i want to print the full path? Use os.path.join(): def visit(arg, dirname, fnames): for file in fnames: if file.endswith('.html'): print os.path.join(dirname, file) | * what if i want to print a particular type of file, for example only | directories. Use os.path.isdir() | * how to find out about a particular function or method, or what | modules are available? In python 2.2, type help() at a (python) prompt, and then 'modules' to give a list of all modules available on your system. You can use help() on a type or function to read its documentation (try 'help(file)' for example). The full current library reference is at: http://www.python.org/doc/current/lib/lib.html Jeremy. From jason at mastaler.com Tue Jun 25 17:53:06 2002 From: jason at mastaler.com (Jason R. Mastaler) Date: Tue, 25 Jun 2002 15:53:06 -0600 Subject: bug in os.getgroups? References: <1025033152.17806.TMDA@nightshade.la.mastaler.com> <20020625202442.GG4435@unpythonic.net> Message-ID: Jeff Epler writes: > This is liely to be because /tmp is "sticky": /tmp was a bad choice for my example. The problem is the same in a non-sticky directory such as /home. # python Python 2.2.1 (#1, Apr 22 2002, 10:19:01) [GCC 2.95.3 20010315 (release) [FreeBSD]] on freebsd4 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.setgid(31) >>> os.setuid(667) >>> os.getgroups() [31, 0, 2, 3, 4, 5, 20, 31] >>> os.unlink('/home/junk') Traceback (most recent call last): File "", line 1, in ? OSError: [Errno 13] Permission denied: '/home/junk' >>> -- (http://tmda.sourceforge.net/) From tdelaney at avaya.com Mon Jun 10 21:26:15 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Tue, 11 Jun 2002 11:26:15 +1000 Subject: Efficient python programming... Message-ID: > From: John J. Lee [mailto:jjl at pobox.com] > > On Sun, 9 Jun 2002, Peter Hansen wrote: > [...] > > What tests do, however, is vastly increase your confidence in the > > correctness of the code, and when written properly (in advance > > of each small morsel of code that is written, and having been > > shown to fail without that code) they are sufficient to deliver > [...] > > This point -- that tests should fail before they pass -- is > easy to forget > about. Thanks for reminding me. It's one of the things that you need to be veryt rigourous about. It's very tempting, upon receiving a bug report, to go charging into the code, finding where the problem is, "fixing" it, then realising you need to test it. Of course, by this time you can't write a test that *fails* with the previous behaviour unless you go back to a previous version. Always write a (correct ;) test that fails before "fixing" anything. Unit tests may include 100% code coverage, but they rarely cover all possible situations. When a new situation is found, the test should be written. Tim Delaney From tim.one at comcast.net Mon Jun 10 08:19:09 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 10 Jun 2002 08:19:09 -0400 Subject: Negative long literals (was Re: Does Python need a '>>>' operator?) In-Reply-To: Message-ID: [Beni Cherniavksy] > I just got another idea: use 0x1234 for 0-filled numbers and 1xABCD for > 1-filled ones. That way you impose no restrictions on what follows the > prefix and keep backward compatibility. 0xFFFFFFFF stays a 2^n-1 > _positive_ number, as it should be. The look of 1x is weird at first but > it is very logical... Indeed, on both counts . I like it a lot! For the other points related to getting rid of machine long-size assumptions, see PEP 237: . From peter at engcorp.com Fri Jun 7 21:01:37 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 07 Jun 2002 21:01:37 -0400 Subject: Efficient python programming... References: Message-ID: <3D015771.4BDCB22F@engcorp.com> Sean 'Shaleh' Perry wrote: > > > I disagree, if the tests are written first (and run, proving that > > they will fail when the code is wrong or missing). > > > > The tests are executable requirement specifications. Running > > them "proves" (yes, not 100%... nothing could) that the code > > meets the specs. The specs could be wrong of course, but that > > doesn't mean the code is broken... > > this also assumes the test covers every possible failure. this also assumes > one can write tests for that section of code. And all these sorts of things are the direct focus of test-driven development. For example, on the issue of testability: code developed this way is inherently testable because the test was written first, and the code had to be written to pass the test. Code developed in a more traditional way is much less likely to be testable and often ends up tightly coupled and very hard to test or maintain as a result. This, of course, tends to lead to having no tests at all, which is a terrible thing. I guess I was just taking a moment to point out there are some new approaches which are more useful than the traditional (and generally neglected) approach of writing a handful of tests after the fact. I was also rebelling momentarily against the idea of shipping code to a customer without having a suite of unit tests in place to give confidence in the code. I'll step back from any claim that unit tests really prove anything, but in a very Pythonic and pragmatic fashion they are Good Enough to make them a /necessity/ for anyone trying to deliver reliable software. -Peter From tjreedy at udel.edu Mon Jun 3 09:37:03 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 03 Jun 2002 13:37:03 GMT Subject: Efficient posting-list References: Message-ID: <3iKK8.99777$%y.10468246@bin4.nnrp.aus1.giganews.com> "Shagshag13" wrote in message news:adffdk$10mep9$1 at ID-146704.news.dfncis.de... > A posting list is something like that (hope i'm not too wrong) : > > [key_0] -> ... > ... > [key_i] -> [id_j, informations] -> [id_k, informations] -> ... > ... > [key_n] -> ... > > where in information retrieval : > - key are often words, > - id are document id (so we have key_i in document id_j and in document id_k and ...) > - informations are often in document frequency, but might be more... > > I'm looking for an efficient way of implementing this in full python, by now i use a dict > for keys and a python list containing node objects for [id_j, informations]. > But i have two troubles this is very slow to populate, and too memory consuming do you > have an idea for optimizing this ? > > (keep in mind that : there are more than 500,000 text keys ; id are numbered from 1 to > 150,000 ; length of a posting list might be from 1 to 500,000...) For English text, one would almost certainly reduce the number of text keys by deleting some suffixes, so that 'statistic', 'statistics', 'statistical', 'statistically', and maybe 'statistician' would be one key. But I have no idea of word structure of non-Indo-European languages and what one should do to reduce key number. By 'length of a posting list' do you mean number of text keys? Ie, size of key dict? The length of list attached to each key is at most number of documents. You do not specify 'node object'. This is crucial since these take up most of memory. (This a good reason not to index the 2000 or so most common keys.) For pure Python, tuple is most space efficient. If each node really is (integer id, integer count), one could devise a system using a pair of array (module) objects or 2-dimensional numerical python arrays; which store actual integers rather than pointers to int PyObjects. When filled, they would have to be copied to larger arrays in much the same manner as done automatically by Python lists. Terry J. Reedy From koenig at v-i-t.de Sat Jun 29 16:17:17 2002 From: koenig at v-i-t.de (Mirko Koenig) Date: Sat, 29 Jun 2002 22:17:17 +0200 Subject: dynamic buttons with tkinter Message-ID: Hi In my i want to make a button for every file in a special directory, so that i can load it. I did: for file in os.listdir( dir ): Button( load_dlg_frame, text=file, relief=GROOVE, command=load).pack() But how can i find out which button is pressed? Or another question: How can i pass a event funktion more than 1 parameter (the event and other things). I can't give any button a new event function, because it's dynamic, because of the number of files in the directory. thanx Mirko From seeger at sitewaerts.de Wed Jun 12 05:34:59 2002 From: seeger at sitewaerts.de (Felix Seeger) Date: Wed, 12 Jun 2002 11:34:59 +0200 Subject: SyntaxWarning: name 'mailcounter' is used prior to global declaration Message-ID: Hi I get this warning. I set mailcounter as a global var because I have to change it's value from a method in a class. This was the only way. How can I remove this warning ? Mailcounter is defined at the beginning of the script and "global mailcounter" is called in the method. thanks have fun Felix From vjovanov at stevens-tech.edu Wed Jun 5 10:51:59 2002 From: vjovanov at stevens-tech.edu (Vojin Jovanovic) Date: Wed, 5 Jun 2002 10:51:59 -0400 Subject: self References: <0%hL8.22575$tK.5490038@news02.optonline.net> Message-ID: <_zpL8.81$pq2.4342892@newnews.cc.stevens-tech.edu> > If you are going to always store the equation, never the value, what > happens when the user does > c.y = 37 > c.y = 'y+1' that is very simple, look at my response to Tim Peters and the method __setattr__ def __setattr__(self,arg,val): self.__dict__['Equations'][arg]=str(val) str(val) takes care of c.y=37 I suggets that you play with my Foo class to see how all that works. > Then you're left with detecting stuff like > c.x = "y" > c.y = "x+1" cycle staff can be taken care with a counter, I don't see a problem with that. > Well, good luck with your project -- and don't spring any more > requirements on us, it's getting harder each time to solve your problem. Sorry, but it is not that my problem is hard. It is that the concept of having to reference instance variables always through self. is making it hard and inconvenient which was my point in my original post. My opinion is that those points explained in FAQ are irrelevant. The only one relevant is ..... "When classes were added to Python, this was (again) the simplest way of implementing methods without too many changes to the interpreter. " This sentence says it all, everything after that is said in FAQ is of less importance and it looks like "well, we did it in the simplest way, but, you know, this way is really better for you, let us show you how ..." The consequence is that the simplest solution is not always the best one. Vojin Jovanovic From SteveC at nospam.innocent.com Fri Jun 21 15:10:29 2002 From: SteveC at nospam.innocent.com (Steven M. Castellotti) Date: Fri, 21 Jun 2002 19:10:29 GMT Subject: Dispatching a Win32 COM in the background? References: <3D132A7C.94CE4670@engcorp.com> Message-ID: On Fri, 21 Jun 2002 08:30:36 -0500, Peter Hansen wrote: > David LeBlanc wrote: >> >> Hmmm... if this is working for you, that's great - it just looks >> strange to me. >> >> If Background_TTS is the background speacher thread, shouldn't it have >> the queue.get() in it and the foreground have the queue.put()? >> >> It's also worth noting that self isn't used or needed at the global >> level, so self.speech is kind of different ;-) > > I'm pretty sure from previous postings he was going to call this from > within another object, so the "self." used elsewhere might refer to it. > > As near as I can tell, with that in mind, the .get() and .put() are in > exactly the right places. That's right, this object is getting called from another class object. All of this is part of a GPL'd program that allows children to create their own video games using drawings and pictures, without them having to learn how program. Since the program runs under Linux and Windows, there's separate objects loaded for each enviroment, both having a reference set to "self.speech" in order to abstract the exact implementation away from other parts of the program. Cheers, Steve Castellotti SteveC (at) innocent.com http://cogengine.sourceforge.net/ From emile at fenx.com Mon Jun 17 21:49:52 2002 From: emile at fenx.com (Emile van Sebille) Date: Tue, 18 Jun 2002 01:49:52 GMT Subject: PythonWorks Pro problem! References: Message-ID: <3lwP8.112157$pw3.6716@sccrnsc03> Johann > I registered some examples from above link. The problem is, I cannot > find this "small, coloured icon" , so I cannot cycle through avalable > settings. :-( > > I tried to clink on everything, but without results :( Anybody can > help? Hmmm... that icon appears to be missing from 1.3... It's there in 1.2 -- Emile van Sebille emile at fenx.com --------- From duncan at NOSPAMrcp.co.uk Tue Jun 18 07:34:28 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 18 Jun 2002 11:34:28 +0000 (UTC) Subject: python version? References: <3tingu8psfmefoab93pl8gips8hg7sgpvp@4ax.com> <9YBP8.44418$GY.13865843@twister.nyroc.rr.com> Message-ID: "George Hester" wrote in news:9YBP8.44418$GY.13865843 at twister.nyroc.rr.com: > I think you guys don't how to do it. And I think you are one of the most impolite posters we have seen around here. Try this: Python Version -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From daniel.dittmar at sap.com Fri Jun 21 09:36:49 2002 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Fri, 21 Jun 2002 15:36:49 +0200 Subject: RE strings (was: Variable Interpolation - status of PEP 215) References: <4PfQ8.44245$n4.10307683@newsc.telia.net> <29e28c51.0206201156.7e61a7f5@posting.google.com> <3D127B89.EE1C17F4@engcorp.com> <3D132ADC.D04B52EA@engcorp.com> Message-ID: >> The implementation could choose to cache the result of re.compile at >> module level, thus >> - speeding up the 'naive' re usage >> - freeing the programmer from doing the caching in code > > Any reason the re.match() method could not do the same, internally? The caching strategies would be different: using re"...": the compiler would know that there are only x literals in the module, thus he would store the re.compile results in an array for fast lookup. using module re: this requires a dictionary indexed by the patterns. And it wouldn't be wise to keep all patterns around, so it depends on the locality of pattern usage how well the cache performs. Daniel From mcfletch at rogers.com Mon Jun 3 17:19:53 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 03 Jun 2002 17:19:53 -0400 Subject: Guru advice needed for mxTextTools References: <3CFBCC68.D35A03D8@vip.fi> Message-ID: <3CFBDD79.5020809@rogers.com> I'm curious, if you have an EBNF grammar, why not just go ahead and use it with SimpleParse to generate the tag-table. As for the two-line parsing, just define the grammar such that a matched line is: file := (match/fail)+ match := properHeaderLine, properContentLine fail := -[\n]*,"\n",-[\n]*,"\n"? # two lines, second newline optional := whateveryouneedtotest properContentLine := (group/-("\n"/STOPCHAR))*, "\n"? group := STARTCHAR,(group/-("\n"/STOPCHAR))*,STOPCHAR (That's untested, of course ;) . Grouping code is always a pain to write without having corner cases fry you :) ). 2MB is a small file, so shouldn't take long to parse using mx.TextTools, and it's normally much faster to just slurp that size of file into memory and process the whole thing in the mx.TextTools C loop. I often worked with 5-6MB VRML files (far more complex grammar generating large numbers of in-memory nodes) and never had a problem with speed there. Note: the above grammar will silently ignore improperly formatted content lines after a properHeaderLine. Marc-Andre has added suport that would allow creating an error in that case, but I've been busy elsewhere and don't yet support it in SimpleParse. HTH, Mike Pekka Niiranen wrote: > I am trying to optimize a function that searches nested strings from > set of (allmost) flat files (about 2 MB each) . If I use regular > expressions, I must > fix the amount of nesting: > ... > > In the code above support two nested strings. If prefix is "?" and > suffix is "!" then > it will evaluate into: > > >>>>pattern = re.compile("(\?[^?!]+(\?[^?!]+\!)*[^?!]+\!)") >>>>Line = "?AA?BB!CC!?DD!ee?EE!ff?FF?GG!HH!" >>>>print re.findall(pattern, Line) >>> > [('?AA?BB!CC!', '?BB!'), ('?DD!', ''), ('?EE!', ''), ('?FF?GG!HH!', > '?GG!')] > ... > 2) The file is not flat: I also need to check the contents of the > previous line. If previous line > does not contain correct value, I do not have to run the regular > expression on the current line: > for i in range(1,len(lines),2): > test = lines[i-1].strip() > if (test == 'x' or test == 'y'): > matches = re.findall(pattern, > lines[i].strip()) > if matches: > # Remove empty results with filters > pars = > filter(operator.truth,reduce(operator.add, matches)) > > 3) Amount of nesting may vary in the future ... > I have thought of EBNF -notation that should be supported with > Simpleparse + mxtexttools > > Questions are: > > 1) What is the mxtexttool tagtable for the regular expression above > with additions of unlimited nesting. > If suffix is the same as prefix, no nesting is assumed > 2) Is it possible to parse the file without keeping the record of the > current line number since > values to be checked are allways on odd line numbers and regular > expression is allways run > on even line numbers. If I could read two lines at a time and > parsing them both simultaneously > (as a single line) with mxtexttools (with lookAhead or whatever > ), I could gain some speed ? > 3) Should I seek examples from XML -tools instead OR write my own > parser with C + SWIG ? ... _______________________________________ Mike C. Fletcher http://members.rogers.com/mcfletch/ From FooWeissBarMike at hotmail.com Fri Jun 7 14:33:45 2002 From: FooWeissBarMike at hotmail.com (Michael Weiss) Date: Fri, 7 Jun 2002 14:33:45 -0400 Subject: map References: <3D007666.2B6D3582@gol.ge> Message-ID: <3d00fe37@news.mhogaming.com> Would this work? ########## x = [1,2,3,4] y = 2 #this? print map(lambda z: pow(z,y), x) # or this? print map(pow, x, [y for z in xrange(len(x))]) ########## "Giorgi Lekishvili" wrote in message news:3D007666.2B6D3582 at gol.ge... > Hi all! > > Is there a way to map a function with several arguments to a list? E.g., > > >>>import math > >>>import MLab > >>>a=MLab.rand(3,5) > >>>b=map(math.pow,a) > > of course, this doesn't work. > > What to do? My task is to optimize the power (i.e., y in pow(x,y)) to > achieve maximal performance. > > > thanx, > Giorgi > > PS: Perhaps I have missed the needed functionality, that's presented in > NumPy? > > > From peter at engcorp.com Sun Jun 23 12:16:39 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 23 Jun 2002 12:16:39 -0400 Subject: Newbie question (anyone programming with curses?) References: Message-ID: <3D15F467.F66309EE@engcorp.com> hellboy wrote: > > I'm quite new to Python, but I'm positive that version 2.2 (for Windows) > comes without curses module, though documentation states it is included. > import curses gives me "Import Error: no module named curses" message. > Anyone knows where to download curses module (for Windows)? A quick google search (http://www.google.ca/search?q=python+curses+windows) brought up a number of results, including a link to the curses How-To by Kuchling and Raymond which has this to say: "No one has made a Windows port of the curses module. On a Windows platform, try the Console module written by Fredrik Lundh." -Peter From jonathan at onegoodidea.com Thu Jun 27 08:19:58 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Thu, 27 Jun 2002 13:19:58 +0100 Subject: Python 2.2 __slots__ Bug? References: Message-ID: On 27/6/2002 1:24, in article afdlv6$bu6$0 at 216.39.172.122, "Bengt Richter" wrote: > Wondering if there's any 12*n byte chunks involved, fitting > into some 2**n (-overhead) allocation space? Just noticing > >>>> divmod(2**19, 43551) > (12, 1676) >>>> divmod(2**16, 5430) > (12, 376) > > Sometimes these things mean something, sometimes they don't ;-) > Maybe it will jog someone's thought. E.g., a last-item index/limit > problem? It appears that GjR is on the case ;-) but I did some digging into the source out of curiosity and it's definitely a stack overrun problem. If anyone is interested, here's my analysis: At the moment the deallocators for the builtin container types pull a neat trick to stop the stack getting too deep. As they're recursively deallocating objects they keep a count of how deep deallocation has gotten so far. If this gets over a set limit then instead of deallocating the object it jams it onto a list and returns immediately. When the stack has unwound back to the top a new piece of magic is invoked that checks to see if anything was put onto the "delete later" list. If something was then it grabs the first thing off the list and starts recursively deleting at that point again. A hack is used to make this "delete later" list: The object's type is checked and, since this trick is only used by a few builtin object types, a numeric type code is stored in the reference count slot of the object (which is no longer interesting since it must be 0). The type object pointer slot is then re-used as a pointer to the next item in the "delete later" list. When the item is pulled off the list and actually deallocated the reverse trick is pulled to correct the type object pointer and reset the reference count to 0. This is all fine except that this trick is not pulled for __slots__ variables as these are not stored in a dict that can be added to the "delete later" list (the point of slots variables). In the case of Glyph's example, because the chain is made up entirely of slots pointers, there is never a dict, tuple, or list - the only* types that can take part in this trick - that can be added to the "delete later" list allowing the stack to be unwound, so the deallocation simply recurses until it runs out of stack. I can't see an easy way to fix this without changing the way that the "delete later" list is constructed. Chewy problem. Jonathan * OK, I lied slightly there. Actually frames and traceback objects take part in this crime as well, but they're not interesting here. From phr-n2002b at NOSPAMnightsong.com Sat Jun 22 00:58:41 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 21 Jun 2002 21:58:41 -0700 Subject: How to stop a SocketServer? Message-ID: <7xhejv9af2.fsf_-_@ruckus.brouhaha.com> I want to run a simple network server based on SocketServer.ThreadingTCPServer. I followed the docs and implemented a handler class which works fine. Then I instantiate the server and run the serve_forever() method. The server listens for connections, starts threads for them and handles them just like it should. Question: how do I shut down the server once it's running, besides doing something crude like killing the process? I'd like to be able to connect to the server and enter a "shutdown" command and have the server gracefully exit and free the port. I haven't been able to figure out how to do that. Suggestions? Thanks. From ljd at nospam.com Sun Jun 9 12:11:18 2002 From: ljd at nospam.com (LJD) Date: Sun, 09 Jun 2002 16:11:18 GMT Subject: Program mysteriously STOPS (Solved)! References: Message-ID: Thank you to all those who responded! The problem seemed to be that I was writing output to the console. When the program ran after I started it from a console session it worked fine because there was a place for the ouput to go. When I started the program from a startup script, the program would run, but I noticed I never saw any console output. Apparently, this output built up somewhere and eventually caused the program to stop. Once I took the PRINT statement out of the code, the program started via startup script and ran without quitting. I am very new to Linux and Python, so I am only surmising that this is what happened. All I know is the program now runs "forever" just like I wanted! Thanks again!!! Larry From tew at wiencko.com Sat Jun 1 22:35:23 2002 From: tew at wiencko.com (Tom Wiencko) Date: Sun, 02 Jun 2002 02:35:23 +0000 Subject: win32com under Cygwin Message-ID: <3CF9846B.579606ED@wiencko.com> There may be an easy answer for this, but I have not yet found it... I noticed that the Python distribution with Cygwin does not include the win32 extensions. The only distribution I can find for them is a Windows executible, which does not seem to know about Cygwin. Can these libraries be loaded under Cygwin? Do they even work under Cygwin? Can somebody point me toward how to load them if it is possible? Thanks in advance. Tom -- ------------------------------------------------------------------------ Tom Wiencko tew at wiencko.com President - Wiencko & Associates, Inc. (404) 255-2330 Telecom Consulting & Project Development -- Wireline, Wireless, Internet From chris.gonnerman at newcenturycomputers.net Sun Jun 16 09:12:00 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Sun, 16 Jun 2002 08:12:00 -0500 Subject: What If..... Strong Types References: <3D0C0F0D.4030900@bgb.cc> <332c7c11.0206160305.304b7cb3@posting.google.com> Message-ID: <001f01c21537$67b69a00$0101010a@local> ----- Original Message ----- From: "Benno" > Don Garrett wrote in message news:<3D0C0F0D.4030900 at bgb.cc>... > > I'm not suggesting any real changes to any, only proposing a thought > > experiment. > > > > What if Python had been built from the start with strong types? And I mean > > strong types, not strong typing. The distinction I am trying to draw is that > > variables would not be typed, but that all types would have rigid interfaces. > > > > > I'm just wondering if the change would be good or bad. Would it really > > break anything important in Python today? > > Well, it would break my stuff, which is pretty damned important to me :). > Dynamically creating/modifying things on the fly can produce nicer, cleaner > code than would otherwise be possible. Indeed. Those who truly grasp the Zen of Python never miss "strong typing" of any sort. Python is dynamic. Failure to follow interface rules usually results in raising an exception; in the cases where it is more subtle, it seems to me that Python takes less time to debug than strong-typed languages due to the parallel feature of introspection. > > Would it prevent any common errors? > > Possibly but not that many imho. I have rarely experienced errors related to an object's interface; usually if I have it has been a simple typo which raised an exception. What exactly would I gain therefor with strong typing? More typing (of the keyboard variety) for little gain. > > Would it help with automated code analysis (compilation and optimization > > included) as much as I think it would? > > Possibly, it is probably rather difficult to follow through all the > implications of such as change however. Exactly. Trust Guido... he knows far better than most of us. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From gerhard.haering at gmx.de Thu Jun 27 12:23:51 2002 From: gerhard.haering at gmx.de (=?ISO-8859-1?Q?Gerhard=20H=E4ring?=) Date: Thu, 27 Jun 2002 18:23:51 +0200 (CEST) Subject: "multi" zip In-Reply-To: References: Message-ID: <20020627162143.C13AC624@gargamel.hqd-internal> Am Thu, 27 Jun 2002 15:46:25 GMT schrieben Sie (Mark ): > So, > > Let line be a list of lists where the sublists are the same length. > > For example: > > line = [ [0,1,2], [3,4,5], [6,7,8] ] > > Now, I can do: > > zip(line[0], line[1], line[2]) > > to "invert" the array. Now, I'd like to do two different things: > > 1) instead of producing tuples, I'd like to produce lists. > > 2) I'd like to extend this to an arbitrary number of lists. If it were > possible, I'd do zip(line[0], line[1], ..., line[n]) but this doesn't seem to > compile :). > > Is there a way to make zip() do this, or should I stop trying to hammer with > a wrench? zip(*list) The *sequence form of calls is described in chapter 5.3.4 of the language reference: http://www.python.org/doc/current/ref/calls.html Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From dgallion1 at yahoo.com Tue Jun 4 20:35:32 2002 From: dgallion1 at yahoo.com (darrell) Date: Wed, 05 Jun 2002 00:35:32 GMT Subject: Looking for a list subclassing example... References: Message-ID: Thanks Jeff. I don't use this code now but I checked and it had a memory leak. Which the "del self[:-self.limit]" fixed. I didn't need support for slices. Guess I should have coded an assert into those other methods. --Darrell Jeff Epler wrote: > I don't think the line >> self = self[-self.limit:] > can do what you want (it only changes something about the locals in > the method). You almost certainly need to use slice deletion > del self[:-self.limit] > or > if diff > 0: del self[:diff] > (these seem to work in all cases, even when diff == 1). You also haven't > overridden the slice assignment method, extend(), __add__, or __mult__ > to make sure the length invariant is preserved in cases like > x[:0] = ['ha ha'] * 1000 > x = x + ['ha ha'] * 1000 > x = x * 1000 > > Jeff From tdelaney at avaya.com Mon Jun 3 02:53:55 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Mon, 3 Jun 2002 16:53:55 +1000 Subject: Why no open(f, "w").write()? Message-ID: > From: John La Rooy [mailto:larooy at xtar.co.nz.avaya.com] > > It's unlikely to be explicitly documented. from the docs... > > The file() constructor is new in Python 2.2. The previous > spelling, open(), > is retained for compatibility, and is an alias for file(). > > So you shouldn't be using open() in new programs anyway Yes - but *file objects* have been part of Python for a long time, and the docs do not state anywhere I could find (I may be wrong) that *file objects* have a destructor that closes the file. The name used to create a file object (be it file, open or wibble) is unimportant. Tim Delaney From rnd at onego.ru Thu Jun 27 15:59:26 2002 From: rnd at onego.ru (Roman Suzi) Date: Thu, 27 Jun 2002 23:59:26 +0400 (MSD) Subject: Pythoniac: Thoughts on a hardware Python processor In-Reply-To: Message-ID: On Thu, 27 Jun 2002, Gustavo Cordova wrote: >> The only route that has any chance of success is >> Python -> Forth -> stack engine --------------- ------- --- Fython by analogy of Jython ;-) >> which leverage works that has already gone into Forth area. >> But, my days of hand assembling 68000 or programming HP calculators >> are long gone... :-) Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by Linux RedHat 7.2 From thenault at nerim.net Mon Jun 17 07:12:36 2002 From: thenault at nerim.net (Sylvain Thenault) Date: 17 Jun 2002 13:12:36 +0200 Subject: [ANN] PyReverse 0.3.1 Message-ID: this release fixes a packaging problem which was broken the installation process of 0.3. What's new ? ------------ See the ChangeLog file for more information. What's PyReverse ? ------------------ Pyreverse is a set of utilities to reverse enginering Python code. So far, it features dependency analysis tools, unittest generation, and XMI generation for importation in a UML modeling tool. A special module can be used to generate files readable by Argo UML. It uses a representation of a Python project in a class hierarchy which can be used to extract any information (such as generating UML diagrams and make a few statistics from the Python code, as "pyargo" and "pystats") Home page --------- http://www.logilab.org/pyreverse/ Download -------- ftp://ftp.logilab.org/pub/pyreverse/ Mailing list ------------ mailto://xml-logilab at logilab.org -- Sylvain Th?nault From gerhard at bigfoot.de Thu Jun 13 10:08:34 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 13 Jun 2002 14:08:34 GMT Subject: Threading tutorial wanted. References: Message-ID: Alex Polite wrote in comp.lang.python: > Okidoki. My little webspider has reached the point where further > optimization won't pay off. But my DSL pipe is not saturated by > far. So I guess it's time for me to start looking into threads. You could take a look at the linkchecker source code. It uses threads for web spidering. > I few minutes of googling on python + threads doesn't yield a > lot. Maybe someone here can point me to a good primer. Maybe someone > here can write a good primer. Aahz has written a tutorial that you were already referred to. It's useful info, but nowhere near complete. Maybe you can write a tutorial yourself once you've mastered threading? ;-) Maybe there's a Python book that covers multithreading in depth? I'd be interested which one this is if so. > When is threading good, when is it bad? I've recently experimented myself with multitheading in Python. It can open a whole new can of worms for your app, that's for sure. > How much memory do they consume? Depends on the threading implementation - just try it out. I don't think it will be a problem unless start _lots_ (100+) of threads. > Is it safe to let multiple threads use the same db connection? Look into the DB-API specification for the threadsafety attribute of your respective DB module. The ones I use have threadsafety=1, which means you can't safely share the connection among threads, but it's ok if every thread opens its own connection. Alternatively, you could make the connection threadsafe by wrapping it with a proxy class like the one I yesterday proposed here in: Message-ID: <20020611205423.GA28113 at lilith.my-fqdn.de> RfD: Automagically making a class instance 'synchronized' (draft impl.) Or you could use a database connection pool. Webware includes one that you can borrow. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From usenet at thinkspot.net Sat Jun 1 12:20:06 2002 From: usenet at thinkspot.net (Sheila King) Date: Sat, 01 Jun 2002 09:20:06 -0700 Subject: How to open a HTML file when the python cgi program is executing? References: <9m6ada.31b.ln@10.0.0.1> Message-ID: On Sat, 1 Jun 2002 22:28:34 +1000, "Ken" wrote in comp.lang.python in article : > > If you realize this before you've output anything, you can use one of the > > redirection / refresh headers, such as "Location". > > > > print """Content-type: text/html > > Location: http://replacement-url > > > >

Click here

> > Doesn't seem to work... :( > > > > """ You must remove the line about Content-type. The Location header will essentially redirect to a different HTML page. When using the location header, your entire output that is printed should simply be: print "Location: http://replacement-url\n" You should have nothing before this, and there's no point in having anything after it, since the page is being redirected. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From rivers at cars.uchicago.edu Sun Jun 23 20:06:43 2002 From: rivers at cars.uchicago.edu (Mark Rivers) Date: Sun, 23 Jun 2002 19:06:43 -0500 Subject: Problems with Pmw.Blt Message-ID: Folks, I am having some problems with Pmw.Blt running Python 2.1.3 on Win32 and Python 2.1.1 on Linux. Pmw is version 0.8.5 and Blt is version 2.4. I found descriptions of the first problem in the newsgroup archives, but no solutions were posted. Here is a short script that demonstrates the problem: ################################# from Tkinter import * import Pmw t1 = Tk() g1 = Pmw.Blt.Graph(t1); g1.pack() t2 = Tk() #reload(Pmw.Blt) g2 = Pmw.Blt.Graph(t2); g2.pack() ################################# When this script is run right after starting Python, the following happens. The first Tk() window (t1) and the first Blt.Graph (g1) are created fine. The second Tk() window (t2) is created and then the following error occurs: Traceback (most recent call last): File "U:\Rivers\python\epics\testBlt1.py", line 7, in ? g2 = Pmw.Blt.Graph(t2); g2.pack() File "C:\PROGRA~1\Python21\Pmw\Pmw_0_8_5\lib\PmwBlt.py", line 260, in __init__ Tkinter.Widget.__init__(self, master, _graphCommand, cnf, kw) File "C:\PROGRA~1\Python21\lib\lib-tk\Tkinter.py", line 1756, in __init__ self.tk.call( TclError: invalid command name "::blt::graph" I can eliminate this error if I uncomment the line "reload(Pmw.Blt). I have been using this workaround in my applications with 99% success. Just before every call to create a Pmw.Blt.Graph I execute the statement "reload(Pmw.Blt)". However, this workaround cannot be the right way to do things, and it seems like it is occasionally creating problems, as evidenced in the next example. The second problem is illustrated in the following simple script: ######################################### from Tkinter import * import Pmw t1 = Tk() reload(Pmw.Blt) g1 = Pmw.Blt.Graph(t1); g1.pack() t2 = Tk() l = Label(t2, text='A label'); l.pack() b = Button(t2, text='Press me'); b.pack() e = Pmw.EntryField(t2, labelpos=W, label_text='Enter something') e.pack() ######################################### When this script is run, the first Tk() window (t1) and the Pmw.Blt.Graph (g1) appear OK. The second Tk() window (t2) is created, and the Label and Button widgets are created. However, when the Pmw.EntryField is being created the following error occurs: Traceback (most recent call last): File "U:\Rivers\python\epics\testBlt2.py", line 9, in ? e = Pmw.EntryField(t2, labelpos=W, label_text='Enter something') File "C:\PROGRA~1\Python21\Pmw\Pmw_0_8_5\lib\PmwEntryField.py", line 72, in __init__ sequences = root.bind_class(tag) File "C:\PROGRA~1\Python21\lib\lib-tk\Tkinter.py", line 923, in bind_class return self._bind(('bind', className), sequence, func, add, 0) File "C:\PROGRA~1\Python21\lib\lib-tk\Tkinter.py", line 858, in _bind return self.tk.splitlist(self.tk.call(what)) TclError: bad window path name ".45079580.45079148" Any suggestions will be most appreciated! Thanks, Mark Rivers Dept. of Geophysical Sciences, University of Chicago GSECARS, Advanced Photon Source, Argonne National Laboratory From bokr at oz.net Thu Jun 27 13:04:26 2002 From: bokr at oz.net (Bengt Richter) Date: 27 Jun 2002 17:04:26 GMT Subject: "multi" zip References: Message-ID: On Thu, 27 Jun 2002 16:05:01 GMT, "Emile van Sebille" wrote: >Mark >> 1) instead of producing tuples, I'd like to produce lists. >> >> 2) I'd like to extend this to an arbitrary number of lists. If it >were >> possible, I'd do zip(line[0], line[1], ..., line[n]) but this doesn't >seem >> to compile :). >> >> Is there a way to make zip() do this, or should I stop trying to >hammer with >> a wrench? >> > > >>>> line = [range(ii*10,11*10+5) for ii in range(5) ] ^^-- assuming you meant ii >>>> map (list,zip(*line)) > Nice. Regards, Bengt Richter From wweexxsseessssaa at telusplanet.net Sun Jun 30 23:12:39 2002 From: wweexxsseessssaa at telusplanet.net (John Hall) Date: Mon, 01 Jul 2002 03:12:39 GMT Subject: Q: Status of MySQL & Python? Message-ID: <69hvhu4otkrcncmu0d4vudfhv74o7maiul@4ax.com> I'm a python newbie, recently discovered PythonCard, and, perhaps unwisely with so little experience, am considering PythonCard & MySQL on Windows 2000 Pro for a small DB aplication. I have Python22, wxWindows, PythonCard & MySQL (just today) apparently working OK. When trying to run the dbBrowser from Samples, MySQLdb/__init__.py does a traceback in line #27 because _mysql is not found. Sure 'nuff, I don't have that. I do have souce C source: _mysql.c Q1: Do I need to do something to build _mysql from something? I can't find one ready to roll on the 'net. q2: I get the impression that support for MySQL with Python is less robust and up-to-date for Windows than Linux et al. Is it feasible and wise to persue this? -- John W Hall Calgary, Alberta, Canada. "Helping People Prosper in the Information Age" From jepler at unpythonic.net Wed Jun 5 08:37:07 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 5 Jun 2002 07:37:07 -0500 Subject: Pop a list from beginning ? and memory saving... In-Reply-To: <3CFD8747.4AA8D29F@engcorp.com> References: <3CFA0676.68F80DE6@engcorp.com> <3CFD5B60.90831F21@engcorp.com> <3CFD86D4.C4F81404@engcorp.com> <3CFD8747.4AA8D29F@engcorp.com> Message-ID: <20020605073707.B25640@unpythonic.net> On Tue, Jun 04, 2002 at 11:36:39PM -0400, Peter Hansen wrote: (speaking about this expression): >> l[:] = [] > > Oh, and in my opinion, that is obscure and deserves a > comment explaining how it works, and why it is being done. > I might not feel that way if I write that idiom a few times, > though. :) IMO del l[:] is clearer than l[:] = [] I'd accept the first one immediately, and puzzle over the second one for a short (or even long) time. Jeff From whisper at oz.net Thu Jun 13 17:14:49 2002 From: whisper at oz.net (David LeBlanc) Date: Thu, 13 Jun 2002 14:14:49 -0700 Subject: Type subclassing: bug or feature In-Reply-To: Message-ID: > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Aahz > Sent: Thursday, June 13, 2002 13:09 > To: python-list at python.org > Subject: Type subclassing: bug or feature > > > Consider the following code: > > class MyStr(str): > def contains(self, value): > return self.find(value) >= 0 > > s = MyStr("hello, world!") > s = s.capitalize() > if s.contains('Hello'): > print "Found it!" > > It fails with an AttributeError when it calls s.contains(), because > s.capitalize() returned a str instead of a MyStr. Anyone want to take a > whack at defending this as the correct behavior? > -- > Aahz (aahz at pythoncraft.com) <*> > http://www.pythoncraft.com/ Looks like a bug to me. How can self be something else then what it is? Should MySocket return a socket, thus stripping off any additional functionality added by my derived class? David LeBlanc Seattle, WA USA From ken at hotmail.com Tue Jun 4 09:37:32 2002 From: ken at hotmail.com (Ken) Date: Tue, 4 Jun 2002 23:37:32 +1000 Subject: Automated Email - What did I do wrong here? References: Message-ID: "Ken" wrote in message news:adg1do$10nmr5$1 at ID-49758.news.dfncis.de... > How to do automated emailing when results being processed? > > Thanks > What did I do wrong? It crash the program. Without these code, the cgi script works fine. Thanks fromaddr = 'ken at hotmail.com' toaddrs = 'ken at hotmail.com' msg = "testing\n" server = smtplib.SMTP('smtp.aol.com') server.sendmail(fromaddr, toaddrs, msg) server.quit() From kragen at pobox.com Mon Jun 10 04:16:40 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 10 Jun 2002 04:16:40 -0400 Subject: Looking for a list subclassing example... References: Message-ID: <83bsaj4kgn.fsf@panacea.canonical.org> "Shagshag13" writes: > I'm looking for a list subclassing example, and i can't find it... > > Do you have one to show ? Why do you think it's a good idea to subclass 'list'? I don't have one to show, but I think it's generally not a good idea. From pyth at devel.trillke.net Sun Jun 30 06:57:05 2002 From: pyth at devel.trillke.net (holger krekel) Date: Sun, 30 Jun 2002 12:57:05 +0200 Subject: Python needs better error reporting In-Reply-To: <3D1E7655.29975.167945D@localhost>; from opus@value.net on Sun, Jun 30, 2002 at 03:09:09AM -0700 References: <3D1E5376.32716.DF5C94@localhost>; <20020630095830.C20310@prim.han.de> <3D1E7655.29975.167945D@localhost> Message-ID: <20020630125705.A10625@prim.han.de> Opus wrote: > Interesting idea. Would these statistics be built from normal usage of the > language or from that person's usage? that'd certainly be a configuration option. But i guess common usage of python-expressions/tokens is not that different. My personal try would just pump the standard lib modules through the AST/Token-statistic profiler. holger From kemusoft at hotmail.com Tue Jun 11 09:49:38 2002 From: kemusoft at hotmail.com (kemu) Date: Tue, 11 Jun 2002 15:49:38 +0200 Subject: frame.bind ? Message-ID: <3d05fff1$0$8149$ba620e4c@news.skynet.be> frame.bind("", callback) I don't understand what .bind does ? I know button-1 is the first mouse button and he calls the function callback but what does bind do ?? __________________________________________________________________ jonas Geiregat ICQ#: 115695917 Current ICQ status: + More ways to contact me __________________________________________________________________ From bokr at oz.net Thu Jun 20 22:19:17 2002 From: bokr at oz.net (Bengt Richter) Date: 21 Jun 2002 02:19:17 GMT Subject: Raw String Output References: Message-ID: On Thu, 20 Jun 2002 19:09:41 -0400, "mike" wrote: >If I have a string variable with the value '\n' how do I output it to a file >with the value of '\012' instead ? > First, let me get straight what you mean vs what I think you might mean ;-) If you want to write a single line feed character with code value 012 (10 decimal), don't worry about it, just write the string (in binary on windows, or it will become \r\n in the file). Note that: >>> ord('\n'), ord('\012'), ord('\x0a') (10, 10, 10) and >>> 'one\ntwo\012three\x0a' 'one\ntwo\nthree\n' >>> print 'one\ntwo\012three\x0a' one two three To see the string in terms of the character sequence a file write would see, convert to a list: >>> list('one\ntwo\012three\x0a') ['o', 'n', 'e', '\n', 't', 'w', 'o', '\n', 't', 'h', 'r', 'e', 'e', '\n'] I.e., the actual internal \n, \012,and \x0a codes are the same single characters. OTOH, if you need to pass custom escaped strings to some other platform or software for evaluation there, that would be different. If you type s1 = '\n' You will get an internal string object with length one bound to the 's1' on the left. If you type s2 = '\012' or s3 = '\x0a' You will get string objects with the identical value (even sharing the identical immutable single-char string object in current Python, I believe), but bound to 's2'. The numeric character code will be 10 in decimal for all three, which you can verify with ord(): >>> s1='\n'; s2='\012'; s3='\x0a' When you inspect s1 or s2 by just typing the names interactively, the interactive loop will use the __repr__ methods of the respective strings and print the charaters returned. >>> s1,s2,s3 ('\n', '\n', '\n') It's the same character, so convential repr shows it as '\n' >>> ord(s1),ord(s2),ord(s3) (10, 10, 10) "'\n'" is a string literal, which if you evaluate it will give you a length-1 string whose single character will have a numerical code with value 10 decimal. If you write (in binary mode) any of the strings s1, s2 or s3 to a file, you will only write one character, and it will be the same character, with the ascii value 10. If for some reason you want to write a _representation_ of the internal encoded string, you have choices. The conventional representation is produced by repr(s) or s.__repr__, or `s`, and line feed will be represented as '\n' on the screen, which comes from two characters: '\\' and 'n'. To create an alternate _representation_ for the same internal character, using four characters (i.e., your '\\' '0','1','2') instead of two, you could produce the conventional representation and substitute '\\012' for '\\n'. ('\\012' and '\\n' can be written r'\012' and r'\n'). Here is an example of text with two line feeds: >>> s="""\ ... line 1 ... line 2 ... """ Triple quotes keeps the line feeds, and the convential string representation printed shows the \n characters escaped: >>> s 'line 1\nline 2\n' Backquotes are short for calling for a repr() or __repr__ representation string, which will have the actual backslash escape characters as such paired with the plain characters they are escaping. When shown on the screen, _that_ string with its back-slashes is repr'd and printed, so the backslashes are shown doubled: >>> sr1 = `s` >>> sr1 "'line 1\\nline 2\\n'" If you want to change the _representation_ r'\n' of chr(10) to _representation_ r'\012', you can split out the former and join in the latter: >>> sr1.split(r'\n') ["'line 1", 'line 2', "'"] >>> sr2 = r'\012'.join(sr1.split(r'\n')) >>> sr2 "'line 1\\012line 2\\012'" Now compare the conventional representation sr1 and your sr2: >>> print sr1 'line 1\nline 2\n' >>> print sr2 'line 1\012line 2\012' Note the single quotes printed. They are part of the repr string (though they could have been double quotes if the text included single quotes, so don't depend on the quoting character's being "'" or '"'. You might conceivably want to strip the outer quotes off, depending on the destination of your custom string representation. And note that if you evaluate the representation strings, you get the original identical string back: >>> eval(sr1) 'line 1\nline 2\n' >>> eval(sr2) 'line 1\nline 2\n' as the original >>> s 'line 1\nline 2\n' And naturally if you print them, they print the same: >>> print eval(sr1) line 1 line 2 >>> print eval(sr2) line 1 line 2 Now the question is, do you want to write a string to a file where it takes one character to represent EOL (or two if windows cooks it in text mode), or do you actually want to write a representation string that has to be eval'd to retrieve the original internal string? And if the latter, why would you want r'\012' instead of r'\n' ? Again, the issue of abstractions vs representations that play different and related roles is the key. >Thank you in advance! > HTH Regards, Bengt Richter From cliechti at gmx.net Thu Jun 13 17:33:33 2002 From: cliechti at gmx.net (Chris Liechti) Date: 13 Jun 2002 23:33:33 +0200 Subject: Shrinking Python References: Message-ID: "Mahrt, Dallas" wrote in news:mailman.1023999624.27508.python-list at python.org: > I am looking into using Python in a small device with limited space > for binaries. Due to this, I am both investigating creating a shared > library with the interpreter and shrinking the footprint of this > library. I have found many threads talking bout shared libraries, so I > am not too concerned about that aspect. > > I am concerned about shrinking the library's binary footprint. I did > find several links to a "Deeply Embedded Python" based on 1.5.1 which > has since vanished. I have stripped the library to improve size some > (to ~1.13 MB) but would like to reduce it further. Has anyone tackled > this or even attempted? Are there any links to resources that may help > me that I haven't found? http://pippy.sourceforge.net/ seems to use 137k (app) + 300k (lib, VM) on my palm. its a stripped down 1.5.2 chris -- Chris From tdelaney at avaya.com Thu Jun 27 20:24:29 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Fri, 28 Jun 2002 10:24:29 +1000 Subject: Most elegant python program to date. Message-ID: > From: PoulsenL at capecon.com [mailto:PoulsenL at capecon.com] > > examples of its prose. Are there any nominations for the most elegant > example of a python program to date. Not sure under what print 'Hello, world!' 1. Does what it is designed to do. 2. No extra cruft. 3. Does not suffer any performance penalties dues to poor algorithms. 4. Does not complicate itself by attempting to optimise algorithms which don't need to be. Of course, this is more a reflection of the elegance of Python itself ... public class HelloWorld { public static void main (String argv[] ) { System.out.println("Hello, world!"); } } Tim Delaney From gcordova at hebmex.com Thu Jun 27 16:41:53 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Thu, 27 Jun 2002 15:41:53 -0500 Subject: How to find out operating system Message-ID: > > C:\>python > Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import os > >>> os.environ.has_key('WINOS') > 1 > >>> os.environ['WINOS'] > 'WIN2000' > >>> > Why check if maybe "WINOS" is in the environment? I've personally never seen that variable. Better check for "WINDIR", or for "COMSPEC"; the first is, well, the directory under which Windows is installed, and I've seen that variable in all the versions I've used: Win95, 98, ME, NT, 2000; the other one points to the command shell for that version of windows. Good luck :-) -gus From lewy0lewy at poczta.onet.pl Mon Jun 17 05:41:35 2002 From: lewy0lewy at poczta.onet.pl (Pawel Lewicki) Date: Mon, 17 Jun 2002 11:41:35 +0200 Subject: MySQL database location Message-ID: Hi, Is is possible to get the physical path to the MySQL database file using MySQLdb or any other pythonous way? Pawel Lewicki From anthony at interlink.com.au Thu Jun 13 01:19:32 2002 From: anthony at interlink.com.au (Anthony Baxter) Date: Thu, 13 Jun 2002 15:19:32 +1000 Subject: using m2crypto to encrypt credit card numbers In-Reply-To: Message from Graham Ashton of "12 Jun 2002 10:52:48 +0100." <1023875569.603.44.camel@walter> Message-ID: <200206130519.g5D5JWO10417@localhost.localdomain> >>> Graham Ashton wrote > If you get too > much fraud (I think the limit was 40% fraud by value in the UK, but my > memory is hazy) going through your site you can get your merchant ID > status revoked by the banks (i.e. you get your transaction processing > account chopped). The stuff they get really shitty about is charge-backs. If you can detect the fraud and do the refunds yourself before the end-user notices, you can get away with it... I hate the credit card system. As designed, it's completely insecure, and the merchants end up copping it in the neck because of the appalling design. Since the banks and the card networks don't take any losses, they have little or no incentive to FIX the bloody problem. Anyone remember SET? It was going to save all our lives, make the world a good and great thing. And that was in 1996. Still waiting for it... Anthony -- Anthony Baxter It's never too late to have a happy childhood. From bokr at oz.net Sat Jun 29 05:16:44 2002 From: bokr at oz.net (Bengt Richter) Date: 29 Jun 2002 09:16:44 GMT Subject: I'm an idiot References: Message-ID: On Sat, 29 Jun 2002 01:00:22 GMT, David wrote: >OK, I am the first to admit it. I am an idiot. I have RTFM on this over >and over, and I can still not figure out what I am doing wrong. > IMHO the key thing to learn from all the responses is not the solution to the particular problem, but some hints as to how you can figure things out for yourself. That is one of the nice things about Python. You can effectively ask it what is happening as you walk through your problem interactively. >I think the intent of the code is obvious, but just to clarify, I want to >read every line in a file and write those lines back out to another file, >but with leading and training space removed. I also want to have some >elegant way to determine that I have reached the end of the file and >break out of the loop. > >And just to explain my stupidity, my reference langauge is BASIC. I >could have written this in BASIC in a minute, but I need to learn >something new. Any help would be appreciated. > >David > > >f=open('c:\\temp\\temp.txt', 'r') >g=open('c:\\temp\\temp1.txt', 'w') >while 1: > try: > s=f.readline > g.write(s.split()) > except IOError: > break > >g.close >f.close Ok, why doesn't that work, you probably asked yourself. First thing, did you have a known temp.txt file? You'd want one that will demonstrate that things are working, so make one up, and store it where you are specifying it to be e.g.: --< temp.txt >-- Three leading spaces and not trailing. Second line with four trailing spaces. Third line has no spaces around it, and has blank line following. Last line, with leading tab and ending with newline. -- So first thing is opening the file >>> f=open('c:\\temp\\temp.txt', 'r') Now what is f at this point? You can check to make sure: >>> f Well, that seems to have worked. Now before putting it in a loop, let's just try the read statement: >> s=f.readline You expect a string, so check to make sure: >>> s Aha. Not what you expected. Most built-in stuff has doc strings, so here you can print either s.__doc__ or f.readline.__doc__, since they both refer to the same thing at this point: >>> print f.readline.__doc__ readline([size]) -> next line from the file, as a string. Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then). Return an empty string at EOF. We want the whole line here, and we'll trust that input lines are reasonable length, so we'll want f.readline(), which we can test: (and we'll pretend we didn't see that bit about EOF) >>> s = f.readline() What did we get? >>> s ' Three leading spaces and not trailing.\n' Looks good so far. Now what about s.split() ? Let's see: >>> s.split() ['Three', 'leading', 'spaces', 'and', 'not', 'trailing.'] Hm, that doesn't look ready to write out. Must be another string method that does the job. dir(s) will tell us what other s.xxx methods there are associated with s (here s is bound to a string, so we'll see string methods): >>> dir(s) ['__add__', '__class__', '__contains__', '__delattr__', '__eq__', '__ge__', '__getattribut e__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__' , '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__repr__', '__rmul__', '__setat tr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expand tabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rst rip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upp er'] Whoa, that line wrapped. lstrip, rstrip, and strip look like the obvious candidates, with the last likely to do the job. So check it out: You can print the docstring info: >>> print s.strip.__doc__ S.strip() -> string Return a copy of the string S with leading and trailing whitespace removed. Or with >= version 2.1 you can: >>> help(s.strip) Help on built-in function strip: strip(...) S.strip() -> string Return a copy of the string S with leading and trailing whitespace removed. Ok, let's make sure it works: >>> s.strip Oops. We know about that one now. Need a () to execute the method ... >>> s.strip() 'Three leading spaces and not trailing.' s is still there for comparison, since we have not rebound it with s=s.strip() or something: >>> s ' Three leading spaces and not trailing.\n' Well, the leading spaces diasppeared ok, but note that the newline also disappeared with .strip(). The virtue of trying things out ;-) So if we want to write out the stripped strings as lines, we'll have to add the '\n' back on. Perhaps we are ready to try that: >>> g=open('c:\\temp\\temp1.txt', 'w') >>> g Make sure it's what we think: >>> s.strip()+'\n' 'Three leading spaces and not trailing.\n' Ok, write it >>> g.write(s.strip()+'\n') No complaint, so we might as well do the rest: >>> s = f.readline() >>> s 'Second line with four trailing spaces. \n' >>> s.strip()+'\n' 'Second line with four trailing spaces.\n' >>> g.write(s.strip()+'\n') >>> s = f.readline() >>> s 'Third line has no spaces around it, and has blank line following.\n' >>> s.strip()+'\n' 'Third line has no spaces around it, and has blank line following.\n' >>> g.write(s.strip()+'\n') >>> s = f.readline() >>> s '\n' >>> s.strip()+'\n' '\n' >>> g.write(s.strip()+'\n') >>> s = f.readline() >>> s '\tLast line, with leading tab and ending with newline.\n' >>> s.strip()+'\n' 'Last line, with leading tab and ending with newline.\n' >>> g.write(s.strip()+'\n') >>> s = f.readline() >>> s '' Oops, what was that? >>> help(f.readline) Help on built-in function readline: readline(...) readline([size]) -> next line from the file, as a string. Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then). Return an empty string at EOF. Aha. (we should've remembered about EOF from before ;-) >>> f.close ;-) >>> f.close() >>> g.close() Check results: >>> h=open('c:\\temp\\temp1.txt', 'r') >>> h.read() 'Three leading spaces and not trailing.\nSecond line with four trailing spaces.\nThird lin e has no spaces around it, and has blank line following.\n\nLast line, with leading tab an d ending with newline.\n' That wrapped, but looks ok, so now use the knowledge gained to revise your original. My point here is just to show that you need not be at a loss when a program as a whole doesn't work. Just break it down and check on what your code is actually doing. After a while, just a well-placed print statement or two to check on intermediate results will usually tell you enough. To do that, you probably want to use an editor to edit a file representing the program, and then either run it from the editor, if your editor supports that, or run it from a separate command line window, and switch back and forth between editor and cmd line window. When you want to be even more systematic about testing your code, you can set up automatic testing to verify expected results. This is prudent once things get past trivial and you need to make sure evolving improvements don't break existing functionality. There are modules to help with that (see doctest & unittest). You can always keep an extra console window open with python running to try little snippets and type out help docs etc. Python makes it easy to explore what's really happening. Then if you're stumped, you can post an excerpt from a session showing what you tried. ;-) HTH Regards, Bengt Richter From david.abrahams at rcn.com Tue Jun 18 18:36:29 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Tue, 18 Jun 2002 18:36:29 -0400 Subject: SWIG and Callbacks References: <3d0a8b6e@nntp.server.uni-frankfurt.de> <3d0b4fd6@nntp.server.uni-frankfurt.de> <3d0c6d67@nntp.server.uni-frankfurt.de> <3D0CE698.1050806@SPAMnwinternet.com> <3D0D3223.5070500@SPAMnwinternet.com> <3D0E2606.5050001@SPAMnwinternet.com> <3D0F807A.40203@SPAMnwinternet.com> Message-ID: "Jim" wrote in message news:3D0F807A.40203 at SPAMnwinternet.com... > David Abrahams wrote: > > "Jim" wrote in message > > >>Template-based code does require special treatment with sip. > >>In most cases where I've wrapped template-based types or > >>classes, I manually write C++ code for conversion C++ <-> Py > >>(sip has some functions that make that easier) and implement > >>it as a sip 'mapped type', which lets me refer to the same > >>conversion code from any return value or arg. > > > That's a given with Boost.Python; with v2 conversions are automatically > > registered in a global repository so they can be re-used automatically > > across extension modules. > > For C++ code with a lot of templates Boost.Python has an > advantage, particularly if you're early on the learning curve. Well, yes, but I wasn't talking about that. I was talking about re-usability of conversions. My point was that if you wrap a class X in one module, you can can wrap [member] functions that operate on X in another module. > Sure - you can extend sip in almost any way you want also > (the bindings generated are C++ code), but it may be a > little trickier fitting things in the binding's framework. > It's also possible to embed custom Python or C++ code in > sip description files and I do that when appropriate (rarely). > It kind of goes against the design philosophy of sip IMHO, > so I try to avoid it personally. Understood. > >>The real problem wouldn't seem to be C++ types as such, but > >>finding a useful (to the Python programmer) representation > >>via PyObject, and still maintaining the range of abilities > >>built into the C++ code (esp things like subclassing). > > > That's built-in to Boost.Python. V1 had to implement a complicated Python > > class look-alike itself; V2 uses Python's new-style classes so subclassing > > "just works". Making virtual functions overridable in Python requires a > > small amount of boilerplate on the part of the programmer. I often wish I > > had a good C++ parser front-end which I could use to automate that part. > > New-style classes lock you into Python 2.2+ though - I've > got users still at 1.5.2 and place a lot of emphasis on long > term version support. That didn't seem to be important to my users. The amount of code I was able to throw away when I started using new-style classes was really staggering (and gratifying!). If it was really important to some people, it should be possible to re-implement all of the Python 2.2+ features used by Boost.Python very much more cleanly in C++, for 1.5.2 compatibility... but it's not a job I want to spend time on. As they say, there will be many more people using future versions than have every used any existing version. Anyway, those who really need it can always get v1 out of its archive and dust it off. > sip does the virtual code boilerplate' > automatically, unless the method requires handwritten code > for some other reason (rare). On the stuff I do, I see a lot > more virtual code than templates, but that obviously varies > a lot. Yeah, that's important. Another area that Boost.Python could use some help from a parser with is in wrapping overloaded functions and those with default args. C++ is missing the ability to represent an overload set as a single object ;-) > > OK. The C++ code you're wrapping still has to get by with #ifdef, I > > suppose... > > Depends on the code I suppose. Qt and KDE just issue all > new files - no versioning in the C++ code. Ah. I guess if they were wrapped with Boost.Python, the wrapping code would be treated the same, then? > > There is no "resorting to C++" with Boost.Python -- Boost.Python *embraces* > > C++! Since you're coding the wrappers in C++ anyway, it's trivial to make a > > "thin wrapper function" which calls the function being wrapped if you want > > to change the interface somehow. Then you just wrap the thin wrapper. > > I finally went back to your website - I took your 'like an > IDL' comments a little too literally. IMHO, the fact that > Boost.Python *is* C++ is a big advantage for people who > want/need that. Personally, I don't want to write C++, > which is how I got into this in the first place. A lot of people seem to feel that way. > Thin wrappers are easily implementable with sip too. In > contrast to the very large packages like PyQt and PyKDE, > they tend to be very lightweight and quick to build. Sorry, I think you misunderstood what I meant by "thin wrapper". A classic trivial example might be used to wrap a function with default args: // function to wrap void f(int a, char* b = expression-1, Foo const& c = expression-2); Thin wrappers: void f1(int a, char* b) { f(a,b); } void f2(int a) { f(a); } wrapping code: module("my_module") .def("f", f) .def("f", f1) // overloads handle .def("f", f2) // default args ; Obviously you can do arbitrary pre- and post- processing inside a thin wrapper function. > >>Yes, but I don't write it - I just edit it mostly to correct > >>mistakes my description file generator creates and to handwrite > >>code where the generator has flagged that. Crude but effective (TM) > >>Even without automation, the process is easiest if you start by > >>saving the h file with a .sip extension and then (mostly) delete > >>the things that sip doesn't want/need, so it's still mostly > >>editing (sometimes A LOT of editing). > > > That seems to be the key difference. It's not clear wether it's really an > > advantage, but I suppose that time will tell. > > I doubt that it's ever clearly an advantage. Really? It seems like it should lower the barrier to entry and get people started with an iterative development process, at least. > It works very > well for PyQt and PyKDE because of the C++ style those projects > use generally - very consistent, That uniformity tends to be important to parser-based systems. I learned a lot about the wide range of code people needed to wrap during v1 development, and I'm trying hard to lift restrictions imposed by that kind of assumption for v2. > relatively small amount of > template usage, lots of enums and of course sip has features to > support Qt. sip has been used outside of the Qt/KDE area, but > perhaps not on anything available publicly yet. Probably the docs are the main obstacle there. It's amazing how many different wrapping tools there seems to be a market for; people will try anything once ! > There's certainly plenty of opportunities for something like > "benchmarketing". Let's not, please! > Either one of us could contrive examples to > make one or the other look clearly better, but like most things > it's probably more rational to look at what the user actually > needs to accomplish. I've avoided actual code comparisons, > because the simple cases tend to be one-sided one way or the > other. Well, code comparisons are important in showing the system's user-interface. > >>I should probably go back and review Boost. I had thought that > >>with Boost it was possible to wrap as much or as little of a > >>C++ library as you want to. > > > That's true. > > Big selling point IMHO. :-) > >>I had the impression SWIG was supposed to do most of that in a single > >>step. Just wondering if I could implement something like that with > Boost, > >>or need to code a line manually for each method/class/whatever. > > > If you have something which can mostly parse your headers, you can generate > > much of the wrapping code automatically. > > Yes - it looks like that should be possible. Virtual code > might require a little more work in generating Boost.Python > code automatically, but the tradeoff is probably less things > flagged as requiring handwritten code. Not sure what you mean here about the tradeoff. Example? > > Yep. BTW, Boost is much more than just my Python binding library, so please, > > for the sake of the other authors: "Boost.Python" when discussing my lib. > > Noted - I've tried to do better in this post. Thanks. > > Not sure that you'll find much to steal; they're so different in approach... > > I can be very creative when stealing other people's code :) > > Actually "under the hood" sip and Boost.Python have similarities. Yeah, well that page is slightly outdated, and doesn't really show much of what's going on other than the class data structure. There really aren't many other practical ways to make extension class wrappers. -Dave From cliechti at gmx.net Tue Jun 25 14:43:29 2002 From: cliechti at gmx.net (Chris Liechti) Date: 25 Jun 2002 20:43:29 +0200 Subject: import precedence References: Message-ID: "Mark McEahern" wrote in news:mailman.1025011774.28523.python-list at python.org: > Suppose I have a package like this: > > spam/ > __init__.py > setup.py > foo.py > > For cygwin, setup.py creates: > > foo.dll > > For linux2, setup.py creates: > > foo.so > > But for win32, setup.py is basically a no-op because I can do what I > need to do in foo.py using pythoncom. > > Here's the question: > > Can I just assume that: > > from spam import foo > > will only import the foo.py module if the foo.dll and foo.so are not > found--that is, if the import statement is executed on win32 (where > those extensions won't exist)? > > I looked at the documentation for import and it's not clear to me that > it addresses this issue. Perhaps because noone in their right mind > would consider this approach? ;-) why don't you add an underline to the C extension, it's pretty common to do that. then in foo.py you can do: try: from _foo import * except ImportError: #get python implementation... you could also choose the correct import by looking at os.name. example from pyserial: if os.name == 'nt': #sys.platform == 'win32': from serialwin32 import * elif os.name == 'posix': from serialposix import * elif os.name == 'java': from serialjava import * else: raise "Sorry no implementation for your platform available." chris -- Chris From gerhard at bigfoot.de Wed Jun 19 01:10:04 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Wed, 19 Jun 2002 07:10:04 +0200 Subject: how i use =?iso-8859-15?Q?'=E3?= =?iso-8859-15?Q?'?= in python??? In-Reply-To: <3D0F6623000017AA@www.zipmail.com.br> References: <3D0F6623000017AA@www.zipmail.com.br> Message-ID: <20020619051004.GA8897@lilith.my-fqdn.de> * jubafre at zipmail.com.br [2002-06-19 01:38 -0300]: > i?m brazilian, and in my laguage(Portguese) there are many other caracters > how ?, ?, ? and a string in python doesn?t support this > how i can use??? have a import module for this??? > > BRASILEIROS DA LISTA COMO VCS CONSEGUEM USAR ACENTO NO PYTHON?? > > for exmple: > s='?' > doesn?t work?why?? You need to give more details than "doesn't work". Most probably there is no problem with the statement s='?' but a problem occurs when you try to print a string that contains a non-ASCII character, right? Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From printers at sendme.cz Fri Jun 21 03:34:05 2002 From: printers at sendme.cz (A) Date: Fri, 21 Jun 2002 09:34:05 +0200 Subject: How to find all emails (on the same line) Message-ID: <3D12F30D.2071.204353@localhost> Hi, I need to find ALL emails in a file. I can use re module but I do not know how to find all emails if there are more emails on the same line because re module ( as far as I know )finds only one/first occurrence on that line. Thanks for help. Ladislav From whisper at oz.net Fri Jun 28 22:30:12 2002 From: whisper at oz.net (David LeBlanc) Date: Fri, 28 Jun 2002 19:30:12 -0700 Subject: I'm an idiot In-Reply-To: Message-ID: > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of David > Sent: Friday, June 28, 2002 18:00 > To: python-list at python.org > Subject: I'm an idiot > > > OK, I am the first to admit it. I am an idiot. I have RTFM on this over > and over, and I can still not figure out what I am doing wrong. > > I think the intent of the code is obvious, but just to clarify, I want to > read every line in a file and write those lines back out to another file, > but with leading and training space removed. I also want to have some > elegant way to determine that I have reached the end of the file and > break out of the loop. > > And just to explain my stupidity, my reference langauge is BASIC. I > could have written this in BASIC in a minute, but I need to learn > something new. Any help would be appreciated. > > David > > > f=open('c:\\temp\\temp.txt', 'r') > g=open('c:\\temp\\temp1.txt', 'w') > while 1: > try: > s=f.readline > g.write(s.split()) > except IOError: > break > > g.close > f.close Here's my version that also strips out blank lines: #lineio.py f=open('j:/python22/lineio.py', 'r') g=open('j:/python22/lineio.txt', 'w') for s in f: if s == '\n': continue g.write(s.strip() + '\n') g.close() f.close() If you want to keep blank lines: #lineio.py f=open('j:/python22/lineio.py', 'r') g=open('j:/python22/lineio.txt', 'w') for s in f: g.write(s.strip() + '\n') g.close() f.close() Dave LeBlanc Seattle, WA USA From uwe at rocksport.de Fri Jun 7 05:35:07 2002 From: uwe at rocksport.de (Uwe Schmitt) Date: 7 Jun 2002 09:35:07 GMT Subject: Distributing Packages / os independent installation folder References: Message-ID: Achim Domma wrote: | Hi, | - where should my package and shared librarie go to? On windows I put the | dll into python22/DLLs and the rest into a folder | python22/Lib/site-packages/ImageMagick. What to do on other plattforms? I | don't expect a DLLs folder on Linux. ;-) import sys echo sys.path ... this might help you. | - In my __init__.py I have to change one environment variable. Currently I | do it like this: | import os | os.environ['MAGICK_HOME'] = r'C:\Python22\Lib\site-packages\ImageMagick' | from _ImageMagick import * | Is there an plattform independent way to get the installation folder of my | package? On windows I can get the python folder from registry, but this will | also break on linux. maybe os.getcwd() in __init__.py does the job... Greetings, Uwe -- Dr. rer. nat. Uwe Schmitt ICQ# 159647634 Uwe.Schmitt at num.uni-sb.de From sholden at holdenweb.com Tue Jun 4 16:57:00 2002 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 4 Jun 2002 16:57:00 -0400 Subject: Thought on PEP 204 and 276 References: <6w4L8.229234$%u2.120502@atlpnn01.usenetserver.com> Message-ID: "Stephen Horne" wrote ... > On Tue, 4 Jun 2002 10:49:19 -0400, "Steve Holden" > wrote: > > >"phil hunt" wrote in message > >news:slrnaf7mo4.dfe.philh at comuno.freeserve.co.uk... > > >> I think they are essentially the same. A sequence tpye is just a > >> mapping type where the keys are restricted to the integers from > >> 0 to however many elements there are minus 1. > >> > >No matter what you think, they are essentially different. Insertion into a > >mapping doesn't alter the key to which other elements are mapped, but > >insertion into a sequence (potentially) does that. > > What is normally referred to as insertion in dictionaries is actually > more like overwriting a list element. This is why handling both with > the 'container [key] = value' syntax is natural. > aarrgghh. So we can completely ignore the fact that the len() of a dictionary will change after an insertion while the len() of a list won't after an element is overwritten? > Insertion with modification of existing keys to make room (ie list > insertion) simply does not exist in lists. The usefulness of list > insertion derives from the fact that a list is a very specialised type > of key-to-value mapping - in this respect, the type 'list' should > clearly inheret from and extend the more general key-to-value type > called a dictionary. > It might be clear to you. It certainly isn't to me. I believe you are looking to unify two fundamentally different semantics. Neither does it make sense in implementation terms. List insertion's usefulness is in fact limited to situations where performance isn't unduly degraded by the need to modify the representation too radically. Of course, where performance doesn't matter, it doesn't matter. > In essence, you are confusing the operations on the underlying data > structures with the operations on the conceptual types. These are two > separate concepts. The implementation is distinct from the > user-visible abstraction. > Fine. You write your programs to delete lists element-by-element from the front, and don't complain about performance -- that's just an aspect of the implementation. While I admire your attempt to maintain theoretical purity here, Python is a pragmatist's language. I don't think I'll be bothering to conceptualise dictionary insertion as overwriting a non-existent element, thank you very much. pragmatical-ly y'rs - steve -- ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From ken at hotmail.com Sat Jun 1 07:10:39 2002 From: ken at hotmail.com (Ken) Date: Sat, 1 Jun 2002 21:10:39 +1000 Subject: Python and HTML frames References: Message-ID: "Jiri Baum" wrote in message news:r08ada.b7b.ln at 10.0.0.1... > Ken: > > How do I output HTML onto frames? This code below doesn't work. Can > > someone help me? > > This isn't really a python question, it's a HTML question (or possibly > HTTP; are you ouputting the right headers?). However, I should note that > setting scrolling to "no" is a really, really bad idea unless the frame > contains just an image, because not all people have the same-sized fonts. > > I trust you've read the guidelines for using frames at www.useit.com ? > Briefly: don't, and if you have to, make all links TARGET="_top". Why you think it isn't python question? I want that HTML frame output from the python script. Can you tell me how? Thanks From K.Rdt at TU-Berlin.DE Fri Jun 28 01:12:09 2002 From: K.Rdt at TU-Berlin.DE (Klaus Reinhardt) Date: Fri, 28 Jun 2002 07:12:09 +0200 Subject: crypt for windows? In-Reply-To: Message-ID: <53VT85VUA6GBXVTQOOKPOIDWRJEQKTQ.3d1bf029@FRITZweb> Am 27.06.02 19:29:52, schrieb Gerhard H?ring : >> Is there a crypt for windows-python, so >> I can manage some password-files? > >Probably not. I believe Cygwin's Python has this module. Is that an >option for you? --------------------------------------------------------------------- Hi No, I dont like cygwin. I tried pgp, but it's to complicated. So I decided to aks me for password each session. For this I can use python in 'the next script'. K at Rdt --------------------------------------------------------------------- From peter at engcorp.com Sat Jun 22 20:33:34 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 22 Jun 2002 20:33:34 -0400 Subject: position of matches References: <653cf871.0206221452.6cb17ef2@posting.google.com> Message-ID: <3D15175E.74934C43@engcorp.com> les wrote: > > i am new to python and want to do the following: > given a string str='abcABCDefsgRSTVderDae' > i would like to find all the internal lowercase strings between 2 caps > i.e. pattern=re.compile(r'[A-Z]([a-z]+)[A-Z]') > > match_obj=pattern.search(str) > begin,end=match_obj.span() > > however i would like to get all the begining and end positions > of the pattern, > i.e. > efsg begin=7 end=10 > der begin=15 end 17 Try this: >>> for x in m.finditer(s): ... print '%s\tbegin=%s end=%s' % ((x.group(1),) + x.span(1)) ... efsg begin=7 end=11 der begin=15 end=18 Note that you might want to adjust the "end" index to fit Python's view of the world. Python generally uses the index of a "slice" made to the string *between* two characters rather than referring to the index of one of the characters. This lets you easily use the slice notation as below. (This explains why my code shows 11 and 18 instead of 10 and 17 for the end position.) A very recent thread explained this in more detail. >>> s[7:11] 'efsg' >>> s[15:18] 'der' (Note: I also used 's' above instead of 'str' since 'str' is a builtin in 2.2. Safer not to use it.) -Peter From tim.one at comcast.net Mon Jun 3 16:32:02 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 03 Jun 2002 16:32:02 -0400 Subject: encoding and decoding repr'd version of strings In-Reply-To: <1YNK8.9622$cE6.591635@wagner.videotron.net> Message-ID: [Daniel Parisien] > is there an codec that bundles with python so you can transform strings > into the repr'd (escaped) version and back? Not now; there may be in 2.3. Getting the escaped version is trivial, i.e. that's what repr(string) has always done. It's the other direction that's missing. > If not, how easy would it be to code? It's a matter of rearranging code that already exists (at C level). > I don't want to use eval(...) because I don't trust the source of the > string and I might mistakenly eval an expression like "' '*(2**30)" which > would allocate about 1 GB of data (eek!) Use eval anyway, but first pass the putative string literal through tokenize.py to ensure that it really is a string literal. From theller at python.net Wed Jun 26 06:57:19 2002 From: theller at python.net (Thomas Heller) Date: Wed, 26 Jun 2002 12:57:19 +0200 Subject: 'parent object'? References: <3d18228c$0$221$4d4ebb8e@news.nl.uu.net> Message-ID: > Is there, like 'self, also a 'parent' object of some sort? > > The problem i'm having is that i have a class, which contains a list of > instances of another class. How can i let this 'childclass' call a function > which is on the 'parent class'? > You could check out Environmental Acquisition: http://www.zope.org/Members/acquisition/ Thomas From tim.one at comcast.net Tue Jun 25 11:14:22 2002 From: tim.one at comcast.net (Tim Peters) Date: Tue, 25 Jun 2002 11:14:22 -0400 Subject: Thread Memory Leak In-Reply-To: Message-ID: [Marco Catunda] > I've developed a python program with some threads. > This program is a daemon server. I have seen the > memory of that program growing very fast in a short > period of time. So I decided to make a little program > to see what's happen. > ... Which version of Python, which OS, and which thread package? There's no leak evident when running your program on Win2K using any of Python 2.1.3, 2.2.1, or current CVS, so whatever you're seeing is specific to something you haven't told us. From jdhunter at nitace.bsd.uchicago.edu Wed Jun 12 17:49:32 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Wed, 12 Jun 2002 16:49:32 -0500 Subject: map -> class instance Message-ID: I want to convert dictionary instances to instances of a class that has the keys of the map as attributes. I naively tried this: class Map2Class: def __init__(self,m): self.m = m def __getattr__(self, key): return self.m[key] def __setattr__(self, key, val): self.m[key] = val def __delattr__(self, key): if self.m.has_key(key): del self.m[key] m = {'first' : 'John', 'last' : 'Hunter', 'age' : 34} c = Map2Class(m) print c.first, c.last, c.age But got an infinite recursion: ~/python/test $ python map_to_class.py Traceback (most recent call last): File "map_to_class.py", line 20, in ? c = Map2Class(m) File "map_to_class.py", line 3, in __init__ self.m = m File "map_to_class.py", line 8, in __setattr__ self.m[key] = val File "map_to_class.py", line 5, in __getattr__ return self.m[key] File "map_to_class.py", line 5, in __getattr__ return self.m[key] [snip ... lots more line fivers ] Is there a better/right way to do what I want? Thanks, John Hunter From chris.gonnerman at newcenturycomputers.net Thu Jun 13 10:09:20 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Thu, 13 Jun 2002 09:09:20 CDT Subject: Poll: Readable languages In-Reply-To: Message-ID: <200206131409.JAA05450@scotland.k12.mo.us> On Thu, 13 Jun 2002 09:36:06 -0400 (EDT), Attila Horvath wrote: > In my years of experience I have come across VERY readable assembler and > very unreadable COBOL, PASCAL, FORTRAN, ADA, C/C++, JAVA, etc. So I > suggest that a langauge does not inherently make resultant code readable. True, and false. It is possible to write bad code in any language; but in my opinion, any programmer who has mastered Python (takes what, a couple of weeks? :-) *tends* to write more readable code than an equivalently accomplished programmer in any other language. Those of us who have been here a while have learned from experience of the ease of writing Python code, and reading it again later. I have to admit, most of the Python I write is little stuff to do jobs I would have done with Bourne shell in the past... but I tend to save them for reuse as I would not have done with a command-line pipeline. From R.Barrett at ftel.co.uk Mon Jun 24 10:51:52 2002 From: R.Barrett at ftel.co.uk (Richard Barrett) Date: Mon, 24 Jun 2002 15:51:52 +0100 Subject: I'd give up Perl tomorrow if only... In-Reply-To: <3D17214F.5000902@destiny.com> Message-ID: <5.1.0.14.2.20020624152755.00ad2d88@pop.ftel.co.uk> At 09:40 24/06/2002 -0400, Michael Chermside wrote: >Michael Chermside wrote: > > Where can I find the pyperl module? > >Gerhard H?ring responded: >>Google - Enter "pyperl" - then hit "I feel lucky" :-) >>This will bring you to >>http://www.cpan.org/modules/by-module/LWP/GAAS/pyperl-1.0.readme which >>looks to >>a non-Perl guy like me that its available as a CPAN module. > >Well, I had tried that, but (not being a perl kind of guy) I'm not really >sure what a CPAN module is or how to obtain or download it. I DID find >some version of pyperl at ActiveState (yeah, ActiveState!), but couldn't >(in the brief amount of time I spent on it) figure out how to set it up. > >What I WAS able to figure out has been written up at >http://www.faqts.com/knowledge_base/view.phtml/aid/17202/fid/1102 >If anyone else can help more, let me know. > >-- Michael Chermside I was following this thread with interest. As a result I downloaded http://downloads.activestate.com//Zope-Perl/pyperl-1.0.1.tar.gz last Friday. Having unpacked the .tar.gz I did just what it said in the README: Build instructions: - make sure your PATH is set up so that 'perl' and 'python' reference the versions of the language interpreters that you want to use. - If you are using Python-1.5.2, then you need to install the Distutils package version 0.9 or better first. - Run these commands: (cd Python-Object; perl Makefile.PL; make install) python setup.py install - You should now be able to run the test.py test script. python test.py The only snag was quickly fixed by renaming the file MULTI_PERL to xMULTI_PERL to indicate that my Perl installation hadn't been build with -Dusethreads option. All working in less than half an hour on my Linux desktop with Python 2.2.1 and Perl 5.6.1. Say 'import perl' in your Python code and you have a pretty seamless way of using Perl modules from Python. Wonderful for using that legacy code and particularly for using a Perl module for which you cannot find a Python equivalent ready to hand. As an old Perl hand who these days much prefers Python but cannot always escape history, I am mightily impressed. That said both Python and more recently Perl are pretty good at embedding and extending so I should not be as impressed as I am that it works so nicely. While I've not given it a real thrashing yet, the implementation seemed pretty solid to me. Many thanks to the folks at ActiveState who I gather did the embedding work. Definitely recommended for the compleat script-writer's use. All I have to do now is see how it all interacts with Tk/Tcl :) From gumuz at looze.net Tue Jun 25 04:01:53 2002 From: gumuz at looze.net (Guyon Morée) Date: Tue, 25 Jun 2002 10:01:53 +0200 Subject: 'parent object'? Message-ID: <3d18228c$0$221$4d4ebb8e@news.nl.uu.net> Hi, Is there, like 'self, also a 'parent' object of some sort? The problem i'm having is that i have a class, which contains a list of instances of another class. How can i let this 'childclass' call a function which is on the 'parent class'? maybe i am thinking wrong and is there a better way to setup this class structure, please tell me if it's so. thanx, Guyon From rchopra at calypso.cs.brandeis.edu Mon Jun 17 00:16:36 2002 From: rchopra at calypso.cs.brandeis.edu (Rajat Chopra) Date: Mon, 17 Jun 2002 00:16:36 -0400 Subject: System Configuration Message-ID: I am looking to create a utility program that will query various aspects of my system, such as the hardware configuration and the software programs installed. I have looked into the Python module list but could not find much to do with system analysis. At the moment, I would like my program to function only on Windows 2000 systems. What modules can I use to determine such things as: -How much memory is installed in the system? -How much disk space is available on the system? -What is the processor speed of the system? -What is the bus speed? -Is Micrsoft Office installed on the system? -What version of Internet Explorer is on the system? -Certain registry actions, such as inserting a key, querying a key, etc. Thank you in advance for your help. Rajat From mdtorre at freemail.it Mon Jun 24 04:49:08 2002 From: mdtorre at freemail.it (Matteo) Date: 24 Jun 2002 01:49:08 -0700 Subject: What language - platform use to data acquisiton/numerical work? References: <1c849ea9.0206130130.6cdaa36f@posting.google.com> <1c849ea9.0206210457.36d494db@posting.google.com> Message-ID: <1c849ea9.0206240049.472b0d4a@posting.google.com> Alexander Schmolck wrote in message news:... > If you are interested I could send you > the code, but you'll need python2.2.1 and it might still have rough edges. I wold be grateful if you can send me the code, Thank you very much Matteo Della Torre From dev at newdeal.ch Fri Jun 28 09:19:11 2002 From: dev at newdeal.ch (erreur) Date: Fri, 28 Jun 2002 15:19:11 +0200 Subject: How to write accent in WinXP Command Prompt ? Message-ID: <3d1c628a@news.swissonline.ch> How to write accent in WinXP Command Prompt ? It's ok with the Python interpretor, but if I run sript <> write <> thanks From news at nospam.majid.fm Wed Jun 26 20:32:43 2002 From: news at nospam.majid.fm (Fazal Majid) Date: Wed, 26 Jun 2002 17:32:43 -0700 Subject: Installation problems DCOracle2 & W2000 References: Message-ID: <3D1A5D2B.1070906@nospam.majid.fm> brueckd at tbye.com wrote: > Aha! Here's what I think the problem is: the DCOracle2 bundle off the Zope > site comes all wrapped up in the Zope database adapter (ZOracleDA), so > your above script is actually trying to import the DA and not the > DCOracle2 package itself (I can see why this is confusing - both > directories are named DCOracle2 but one is a subdirectory of the other!). I just reinstalled Oracle 9.2.0.1 + Python 2.2 + DCOracle2 on a new computer so I can reproduce the steps to a correct install. I think Dave is right on track here, there is a name conflict between the module DCOracle2.py, which is standalone without Zope and that you want to use, and DCOracle2 the Zope database adapter package directory which is used only from within Zope. Here is my setup: PYTHONPATH=D:\Etc\DCOracle2 D:\Etc\DCOracle2>python Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import DCOracle2 >>> d=DCOracle2.connect('scott/tiger at database') >>> d.execute('select SYSDATE from dual') 1 >>> d.fetchall() [[OracleDate("2002-06-26 17:31:57")]] >>> ^Z D:\Etc\DCOracle2>dir Volume in drive D is MAJID Volume Serial Number is B8C2-4135 Directory of D:\Etc\DCOracle2 2002-06-11 14:47 . 2002-06-11 14:47 .. 2002-06-05 15:00 73,728 dco2.pyd 2002-06-05 12:16 56,957 DCOracle2.py 2002-06-05 15:00 180,304 win32-python-1.5.2-805-dco2.pyd 2002-06-05 15:00 73,728 win32-python-1.5.2-dco2.pyd 2002-06-05 15:00 180,298 win32-python-2.1-805-dco2.pyd 2002-06-05 15:00 73,728 win32-python-2.1-dco2.pyd 2002-06-05 15:00 73,728 win32-python-2.2-dco2.pyd 2002-06-05 12:16 1,725 __init__.py 2002-06-26 17:21 46,293 DCOracle2.pyc 9 File(s) 760,489 bytes 2 Dir(s) 6,778,052,608 bytes free From gerhard.haering at gmx.de Thu Jun 27 13:33:32 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 27 Jun 2002 17:33:32 GMT Subject: How to find out DNS ? References: Message-ID: A wrote in comp.lang.python: > Hi, > Is there a way how to find out, from Python , what primary or > secondary DNS I use when connecting to internet? I don't think so. There might be platform specific ways to get that info, though. On Unixen, for example, you can parse /etc/resolv.conf for lines starting with "nameserver". On Windows, your best bet is to read MSDN on how to do it and try to get that info with the win32 extensions. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From mbelanger_NOSPAM at NOSPAM_pixelsystems.com Tue Jun 25 12:05:53 2002 From: mbelanger_NOSPAM at NOSPAM_pixelsystems.com (Mathieu Belanger) Date: Tue, 25 Jun 2002 12:05:53 -0400 Subject: Switch from 2.1 to 2.2 References: <3D188302.1030109@thomas-guettler.de> Message-ID: > Plese send the stracktrace, too > Yeah, I know it will be easier, but I can't have a complete one for any reason !?! So here it is: Traceback (most recent call last): File "D:\WINNT\system32\RxScriptFile.py", line 551, in DCMgmtScript File "D:\Python22\Lib\site-packages\_xmlplus\dom\ext\__init__.py", line 82, in PrettyPrint Printer.PrintWalker(visitor, root).run() File "D:\Python22\Lib\site-packages\_xmlplus\dom\ext\Printer.py", line 385, in run return self.step() File "D:\Python22\Lib\site-packages\_xmlplus\dom\ext\Printer.py", line 381, in step self.visitor.visit(self.start_node) File "D:\Python22\Lib\site-packa Thanks From garrett at bgb.cc Wed Jun 19 01:27:30 2002 From: garrett at bgb.cc (Don Garrett) Date: Wed, 19 Jun 2002 05:27:30 GMT Subject: What If..... Strong Types References: <3D0C0F0D.4030900@bgb.cc> <20020616.175421.861584889.1250@localhost.localdomain> Message-ID: <3D1015B9.207@bgb.cc> Lamy Jean-Baptiste wrote: > I've done really nice hack by changing object class, adding method or > properties, and so on... ! Can you give some examples? I really would just like to understand what people use this stuff for. I'm not trying to imply that people shouldn't. I'd just like to have some concrete examples to help me understand. -- Don Garrett http://www.bgb.cc/garrett/ BGB Consulting garrett at bgb.cc From tdelaney at avaya.com Thu Jun 20 23:00:57 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Fri, 21 Jun 2002 13:00:57 +1000 Subject: GOTO w/ Python? Message-ID: > From: John Roth [mailto:johnroth at ameritech.net] > > "Max M" wrote in message news:3D11A21D.9010809 at mxm.dk... > > > > What do you mean??? > > > > Goto's are simple ;-) [Clever, silly, not real GOTO example snipped] > Those aren't goto's in the classical sense. For a real goto, > you need to think assembler: if it's a statement anywhere, > you can branch to it, and who cares about the execution > history! Having the compiler manage your flow control is > for sissys! Methinks someone missed something ... Tim Delaney From SBrunning at trisystems.co.uk Fri Jun 28 07:57:45 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Fri, 28 Jun 2002 12:57:45 +0100 Subject: GUI-Control for HTML Message-ID: <31575A892FF6D1118F5800600846864DCBD462@intrepid> > From: Thomas Guettler [SMTP:zopestoller at thomas-guettler.de] > Is there are GUI-control which can display HTML? > > The HTML that will be used will be simple, no javascript or > form support is needed. > > Is there are cross-plattform solution? (Unix + Win32) See . Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From dfackrell at DELETETHIS.linuxmail.org Thu Jun 20 11:46:26 2002 From: dfackrell at DELETETHIS.linuxmail.org (Daniel Fackrell) Date: Thu, 20 Jun 2002 09:46:26 -0600 Subject: Function to add commas in numbers? References: Message-ID: <3d11f8d2$1_1@hpb10302.boi.hp.com> mdk, The following thread is about formatting numbers for Danish, but it should give the info you need (paste it as one line): http://groups.google.com/groups?hl=en&lr=&ie=UTF8&oe=UTF8&threadm=3D0A1791.3 060307%40mxm.dk&rnum=5&prev=/groups%3Fas_q%3Dnumber%2520format%26ie%3DUTF8%2 6oe%3DUTF8%26as_ugroup%3Dcomp.lang.python%26lr%3D%26hl%3Den -- Daniel Fackrell (dfackrell at linuxmail.org) When we attempt the impossible, we can experience true growth. "mdk" wrote in message news:Xns923372EFBBC5Dmdkmdkmdkmdk at 130.133.1.4... > Hello, > > Is there a function that will take, for example, 1234567 and return > 1,234,567? > > Thanks From paul at boddie.net Tue Jun 25 06:57:01 2002 From: paul at boddie.net (Paul Boddie) Date: 25 Jun 2002 03:57:01 -0700 Subject: ? and %s placeholders, help? References: <3D178542.604@mxm.dk> Message-ID: <23891c90.0206250257.23d38d30@posting.google.com> "Duncan Smith" wrote in message news:... > Thanks both, > But I'm still having problems with this. I want to use > prepared statements to avoid unnecessary parsing, and I get the impression > (from what information I can find, eg Python Programming on Win32) that I > should (need to?) use the '?' placeholder to achieve this. But I cannot > come up with anything that works. First, check the paramstyle of the MySQLdb module. # This generally works with database modules. print MySQLdb.paramstyle The parameter notation to be used - informally known as the paramstyle - should be printed. Only if "?" is printed can you actually use that particular notation. (There's been some discussion about the merits of having loads of paramstyles on the DB-SIG mailing list, but it would arguably be a lot easier if "?" were in use throughout, just like with JDBC.) > >>> query = 'INSERT INTO %s (%s) VALUES (%s)' % (tblname, string.join(vars, > ', '), string.join(['%s']*len(vars), ', ')) > >>> query > 'INSERT INTO tbl (var1, var2, var3) VALUES (%s, %s, %s)' > >>> curs.execute(query % ("'a'", "'b'", "'c'")) > 1L > > #Hurray, but does this avoid parsing the statement on each INSERT? This isn't what you ought to be doing, since you're effectively doing Python string substitution to supply the values. Moreover, bad data could be used to "attack" your application or to "exploit" it, should you employ these methods. > >>> query = 'INSERT INTO %s (%s) VALUES (%s)' % (tblname, string.join(vars, > ', '), string.join(['?']*len(vars), ', ')) > >>> query > 'INSERT INTO tbl (var1, var2, var3) VALUES (?, ?, ?)' You're doing the right thing when building the query string, since the table and column names cannot be passed in as parameters - therefore you are right to substitute them in first. The only potential problem is whether the parameter notation is correct - check out the paramstyle to be sure, and modify the '?' to '%s' in the statement above if the paramstyle turns out to be '%s'. > >>> curs.execute(query, ("'a'", "'b'", "'c'")) > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python22\Lib\site-packages\MySQLdb\cursors.py", line 70, in > execute > raise ProgrammingError, m.args[0] > ProgrammingError: not all arguments converted > >>> Be aware that by supplying "'a'", the actual inserted value will be "'a'" and not "a" - you don't need to quote parameter values. Apart from this, the above looks correct, and I suspect that the cause of the error is the paramstyle that you've chosen being incorrect. To summarise: 1. Check the paramstyle. 2. Build the query (or statement, in this case). Put the table and column names in here, along with the parameter "placeholders" according to the paramstyle. 3. Execute the query (or statement) supplying the parameter values, remembering that you don't need to quote the parameter values. Paul From tom at huno.net Fri Jun 28 15:42:56 2002 From: tom at huno.net (thomas) Date: Fri, 28 Jun 2002 21:42:56 +0200 Subject: feeding a prompt with python References: <3D1C5341.9070001@huno.net> <3D1C7CA0.7060201@ivs.tu-berlin.de> Message-ID: <3D1CBC40.6090604@huno.net> Andreas Ulbrich wrote: > > What you actually want to do is using pipes. See os.popen and related > stuff for documentation. > thx! exactly what i was looking for. From pixie888 at hotmail.com Thu Jun 6 08:36:04 2002 From: pixie888 at hotmail.com (pixie888 at hotmail.com) Date: Thu, 06 Jun 2002 12:36:04 GMT Subject: check on numerical value? Message-ID: <3cff56b4.511834453@news.skynet.be> Hi, Is there any way to discover when a value is numerical or not in Python? I want a check in my code on a given value. If somebody enters or gives me something like "akjlvq?irq" this is surely not a numerical value. Thanks, Henk From johnroth at ameritech.net Sat Jun 29 18:28:38 2002 From: johnroth at ameritech.net (John Roth) Date: Sat, 29 Jun 2002 18:28:38 -0400 Subject: private References: <3D1DE132.4A890D9D@engcorp.com> Message-ID: "James Kew" wrote in message news:afl3e4$f8abc$1 at ID-71831.news.dfncis.de... > "Peter Hansen" wrote in message > news:3D1DE132.4A890D9D at engcorp.com... > > Rhymes wrote: > > > > > > Is there any possibility to build up a _real_ private attribute? > > > Such as C++ private data members... > > > > You realize that it's quite possible to get at private data members > > in C++, don't you? > > I can't help feeling this is overly dismissive! > > Yes, of course one can circumvent private in C++. But for me the main value > of the public and private specifiers is that they _document_ to the client > of the class what it should access and what it should not. > > I don't -- in my admittedly very limited experience -- find Python classes > as immediately self-documenting. It's not obvious from the class definition > what is intended to be called or modfied by the client and what is internal > to the implementation. > > I suspect I'm still in the crossover period from strictly declarative C/C++ > and the "anything goes" Pythonic way and that, given time, I'll find my > groove and feel comfortable. > > > This has been discussed about 479 times in the last decade. > > I'll bet. I'll shut up about it now. > > James > > > From fredrik at pythonware.com Sun Jun 16 16:06:16 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 16 Jun 2002 20:06:16 GMT Subject: PIL and miscolored images References: <3D09D25A.4C04E03@ipm.fhg.de> Message-ID: Markus von Ehr wrote: > I'd like to show a greylevel image as miscolored image, > anyone has an idea how i can do it and maybe adjust > the color scale? do you mean pseudocoloring? something like this should work: from PIL import Image im = Image.open("some grayscale image") im.load() # make sure it's loaded into memory assert im.mode == "L" # create a lookup table (r, g, b, r, g, b, r, g, b, ...) lut = [] for i in range(256): lut.extend([255-i, i/2, i]) im.putpalette(lut) assert im.mode == "P" # now has a palette im.save("out.gif") the "load" call is a workaround for a bug in 1.1.3 and earlier. without it, you will sometimes get a ValueError exception when attempting to save (or further process) the image. From fperez528 at yahoo.com Thu Jun 20 23:52:01 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Thu, 20 Jun 2002 21:52:01 -0600 Subject: newbie string question References: <3D129BB7.C7EA15D2@engcorp.com> Message-ID: Don Low wrote: > So if I understand, pystr[3] refers to the subscript index, but pystr[3:] > refers to the slice index. pystr[2:5] means slice at slice index 2 and 5, > not start at subscript index 2 and slice at slice index 5. > > I just want to understand this once and for all. The easiest way to understand this is to build a list which is a range. There you have a one-to-one mapping between list indices and elements. Then slice it to your heart's content and the behavior of : and friends will become second nature: In [1]: x=range(10) In [2]: x Out[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] In [3]: x[5] Out[3]: 5 In [4]: x[3:7] Out[4]: [3, 4, 5, 6] In [5]: x[:] Out[5]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] In [6]: x[5:] Out[6]: [5, 6, 7, 8, 9] In [7]: x[-1] Out[7]: 9 In [8]: x[-5] Out[8]: 5 In [9]: x[-5:] Out[9]: [5, 6, 7, 8, 9] cheers, f From xah at xahlee.org Sat Jun 15 04:03:33 2002 From: xah at xahlee.org (Xah Lee) Date: 15 Jun 2002 01:03:33 -0700 Subject: html parser etc help References: <7fe97cc4.0206111445.43b196de@posting.google.com> Message-ID: <7fe97cc4.0206150003.65fe8821@posting.google.com> Thanks Jeremy Yallop for help. Some follow up questions... in the following code: import os def visit(arg, dirname, fnames): for file in fnames: if file.endswith('.html'): print file print arg os.path.walk('/export/home/xah/unixnotes/',visit,'---') * in the os.path.walk, what's the third argument for? * what if i want to print the full path? * what if i want to print a particular type of file, for example only directories. * how to find out about a particular function or method, or what modules are available? in perl i'd do "perldoc -tf functionname" to find out about a particular function. Or , or in Java there's the API doc. http://java.sun.com/j2se/1.3/docs/api/index.html Thanks. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From ken at hotmail.com Sun Jun 2 06:01:19 2002 From: ken at hotmail.com (Ken) Date: Sun, 2 Jun 2002 20:01:19 +1000 Subject: How to call functions inside a cgi script from the html interface? References: <2bkcda.c25.ln@10.0.0.1> Message-ID: "Jiri Baum" wrote in message news:2bkcda.c25.ln at 10.0.0.1... > Ken: > > How to call functions inside a cgi script from the html interface? > > > Eg. If there is a link on the html display call "Search", how do I get it > > to call the function call "def search( )" inside the cgi script? > > You need to get yourself a CGI programming reference, or even a good HTML > book, and refer to them before you post questions on the (wrong) newsgroup. > > Also read the docs for the python cgi module (eg at www.python.org). > > HTTP doesn't have any facilities for doing this directly. Every time a user > selects a link, a request is made to the server for that page. This can > either be a completely different cgi script, or it can be the same script > with different parameters. Either way, it's a separate connection, so don't > expect variables to stay. Where can I find good references with both python and HTML explained in detail on how they work together? From cliechti at gmx.net Wed Jun 26 15:32:00 2002 From: cliechti at gmx.net (Chris Liechti) Date: 26 Jun 2002 21:32:00 +0200 Subject: printing (again!!) References: Message-ID: Martin Franklin wrote in news:mailman.1025117834.9485.python-list at python.org: > Get hold of the excelent win32 extension for python (url????) http://starship.python.net/crew/mhammond/ -- Chris From kragen at pobox.com Mon Jun 17 01:44:49 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 17 Jun 2002 01:44:49 -0400 Subject: Args not set in extension class References: <83sn3otlkf.fsf@panacea.canonical.org> Message-ID: <83bsaampbi.fsf@panacea.canonical.org> "Gorny" writes: > That doesn't seem to work as well for some vague reason... It complains > it's not a valid tuple I suspect you are overlooking something significant in your source code, but I don't know what it is without seeing the code. From kwokng at earthlink.net Sat Jun 1 12:37:57 2002 From: kwokng at earthlink.net (Billy Ng) Date: Sat, 01 Jun 2002 16:37:57 GMT Subject: Copying a database Message-ID: I need you guys help on mysql again. I need to push my python program to production now, but I don't want to recreate the mysql database on the production box. I want to copy the database from the development box to production box.. Would anybody please tell me how to do it, thanks! Billy Ng From kragen at pobox.com Sat Jun 1 15:59:41 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 01 Jun 2002 15:59:41 -0400 Subject: symbolic python References: <3CEFAE4C.38A8022B@doc.ic.ac.uk> <3CEFD881.D7992095@doc.ic.ac.uk> <3cf8ce86$1@giga.realtime.net> Message-ID: <83sn46vkgi.fsf@panacea.canonical.org> "Ira Baxter" writes: > If you want program transformation capability, > you can get it in the form the of DMS Software Reengineering > Toolkit. > See http://www.semdesigns.com/Products/DMS/DMSToolkit.html. It sounds very interesting. How can I get a copy? From fredrik at pythonware.com Thu Jun 20 03:50:23 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 20 Jun 2002 07:50:23 GMT Subject: SNIP IT: tk.Canvas Drag Items Around References: <63604d2.0206031518.2da29d3b@posting.google.com> <63604d2.0206050957.60a47f1@posting.google.com> Message-ID: <3PfQ8.44244$n4.10307657@newsc.telia.net> "Phlip" wrote: > points = event.widget.coords (tk.CURRENT) > anchors = copy.copy(points[:2]) > print points > > for idx in range(len(points)): > # print idx, xy[idx % 2], anchors[idx % 2] > mouse = xy[idx % 2] > zone = anchors[idx % 2] > points[idx] = points[idx] - zone + mouse > > print points > apply(event.widget.coords, [tk.CURRENT] + points) footnote: the canvas provides a nice little method called "move" that adds X and Y offsets to all coordinates of all matching items: dx = mouse[0] - anchors[0] dy = mouse[1] - anchors[1] event.widget.move(tk.CURRENT, dx, dy) for more info, see http://www.pythonware.com/library/tkinter/introduction/canvas.htm => Methods