From gagsl-py at yahoo.com.ar Tue Aug 22 13:13:29 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 22 Aug 2006 14:13:29 -0300 Subject: Need advice on how to improve this function In-Reply-To: References: Message-ID: <7.0.1.0.0.20060822141105.003ac9b0@yahoo.com.ar> At Monday 21/8/2006 12:03, Larry Bates wrote: > > I wrote a function that converts a tuple of tuples into html. For > > example: > > I'd like to know ways to make it better (more efficient, able to deal > > with enormous-size arguments, etc). How would I write this as a > > generator? >Before you put too much work into this you might want to take a look >at HTMLgen: http://www.python.net/crew/friedrich/HTMLgen/html/main.html Another very good library is (Don't be afraid of the date - it's just that HTML standards haven't changed very much lately :) ) Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From david_wahler at bic.ky Fri Aug 4 11:36:50 2006 From: david_wahler at bic.ky (david_wahler at bic.ky) Date: 4 Aug 2006 10:36:50 -0500 Subject: =?utf-8?Q?Re:_RELEASED_Python_2.5_=28beta_3=29?= Message-ID: <20060804153650.22032.qmail@BICSRV1011.bic.ky> I'll be out of the office until approximately August 20th. If you have any questions, please email support at bic.ky. -- David Wahler From me at privacy.net Tue Aug 15 20:41:45 2006 From: me at privacy.net (Dan Sommers) Date: Tue, 15 Aug 2006 20:41:45 -0400 Subject: Printing n elements per line in a list References: <1155685889.626881.37040@m73g2000cwd.googlegroups.com> Message-ID: On 15 Aug 2006 16:51:29 -0700, "unexpected" wrote: > If have a list from 1 to 100, what's the easiest, most elegant way to > print them out, so that there are only n elements per line. > So if n=5, the printed list would look like: > 1 2 3 4 5 > 6 7 8 9 10 > 11 12 13 14 15 > etc. > My search through the previous posts yields methods to print all the > values of the list on a single line, but that's not what I want. I feel > like there is an easy, pretty way to do this. I think it's possible to > hack it up using while loops and some ugly slicing, but hopefully I'm > missing something Perhaps not the prettiest, but I can't think of anything simpler to read six months from now: counter = 0 for an_element in the_list: print an_element, counter = counter + 1 if counter == n: print counter = 0 Regards, Dan -- Dan Sommers "I wish people would die in alphabetical order." -- My wife, the genealogist From bj_666 at gmx.net Mon Aug 14 02:32:37 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 14 Aug 2006 08:32:37 +0200 Subject: Python/Tk not working in Linux References: <1155354248.783487.217200@m79g2000cwm.googlegroups.com> <1155534034.779323.184130@m79g2000cwm.googlegroups.com> Message-ID: In <1155534034.779323.184130 at m79g2000cwm.googlegroups.com>, BinnyVA wrote: >> Some distributions move the `Tkinter` stuff into an own package. >> Search for a package called `python-tk` or `python-tkinter` or similar. > > I could use a 'python-tk' package - but the problem is the latest > version of python may not be available. That's always the problem with packaged software. But you gain fast and easy installation via the package system. > I am going to download Tcl/Tk and install it. Then I would try to > install Python once again. Just install the necessary development packages for your installed Tcl/Tk and compile the Python sources. Unless you really want to compile everything yourself. Ciao, Marc 'BlackJack' Rintsch From jyoti.chhabra at gmail.com Tue Aug 29 03:24:14 2006 From: jyoti.chhabra at gmail.com (JyotiC) Date: 29 Aug 2006 00:24:14 -0700 Subject: prob with tkinter Message-ID: <1156836253.948332.268200@i42g2000cwa.googlegroups.com> hi, i am making a GUI using tkinter i need to get lot of data from user, it's in form of a excel sheets(many rows n columns) what i am using is grid for foramating, frame is from Toplevel, data collected from Entry widget I can't see most of the columns. I am not able to add scroll bar, i want it to be added horizontally and vertically. thanx Jyoti From spam.noam at gmail.com Mon Aug 14 15:34:10 2006 From: spam.noam at gmail.com (spam.noam at gmail.com) Date: 14 Aug 2006 12:34:10 -0700 Subject: ANN: byteplay - a bytecode assembler/disassembler Message-ID: Hello, I would like to present a module that I have wrote, called byteplay. It's a Python bytecode assembler/disassembler, which means that you can take Python code object, disassemble them into equivalent objects which are easy to play with, play with them, and then assemble a new, modified, code object. I think it's pretty useful if you like to learn more about Python's bytecode - playing with things and seeing what happens is a nice way to learn, I think. Here's a quick example. We can define this stupid function: >>> def f(a, b): ... print (a, b) >>> f(3, 5) (3, 5) We can convert it to an equivalent object, and see how it stores the byte code: >>> from byteplay import * >>> c = Code.from_code(f.func_code) >>> from pprint import pprint; pprint(c.code) [(SetLineno, 2), (LOAD_FAST, 'a'), (LOAD_FAST, 'b'), (BUILD_TUPLE, 2), (PRINT_ITEM, None), (PRINT_NEWLINE, None), (LOAD_CONST, None), (RETURN_VALUE, None)] We can change the bytecode easily, and see what happens. Let's insert a ROT_TWO opcode, that will swap the two arguments: >>> c.code[3:3] = [(ROT_TWO, None)] >>> f.func_code = c.to_code() >>> f(3, 5) (5, 3) You can download byteplay from http://byteplay.googlecode.com/svn/trunk/byteplay.py and you can read (and edit) the documentation at http://wiki.python.org/moin/ByteplayDoc . I will be happy to hear if you find it useful, or if you have any comments or ideas. Have a good day, Noam Raphael From david at boddie.org.uk Tue Aug 15 14:54:06 2006 From: david at boddie.org.uk (David Boddie) Date: 15 Aug 2006 11:54:06 -0700 Subject: X windows and Python? In-Reply-To: <1155667686.196587.94250@p79g2000cwp.googlegroups.com> References: <7xy7tpyhbf.fsf_-_@ruckus.brouhaha.com> <1155667686.196587.94250@p79g2000cwp.googlegroups.com> Message-ID: <1155668046.277321.27570@i3g2000cwc.googlegroups.com> The usual follow-up to "fix" Google's "formatting". Maybe this does what you need: http://python-xlib.sourceforge.net/ From slawomir.nowaczyk.847 at student.lu.se Fri Aug 4 10:41:03 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Fri, 04 Aug 2006 16:41:03 +0200 Subject: Nested function scope problem In-Reply-To: <1okvniwl5zgqj.dlg@gelists.gmail.com> References: <20060804094245.A9AF.SLAWOMIR.NOWACZYK.847@student.lu.se> <1okvniwl5zgqj.dlg@gelists.gmail.com> Message-ID: <20060804155855.EE80.SLAWOMIR.NOWACZYK.847@student.lu.se> On Fri, 04 Aug 2006 10:10:45 -0300 Gerhard Fiedler wrote: #> On 2006-08-04 07:36:25, Slawomir Nowaczyk wrote: #> #> > #> The address operator is probably for a C programmer the closest to #> > #> what the id() function is to a Python programmer. #> > #> > I disagree. At least in my understanding, which, up to now, was #> > perfectly enough to explain everything about how Python variables #> > behave: #> > #> > The address operator in C is what textual representation (i.e. what #> > you type, like "a") is in Python. Equivalent of id() is a dereference #> > operator. #> #> But then you are not talking about C variables. I am. The fact that Python variables behave like C pointers isn't overly relevant. A pointer is perfectly good C variable to me. #> Using a normal C variable, this doesn't work: #> #> int c = 5; #> printf( "id(c)=%x", *c ); Depends on what do you expect. The above is kind of equivalent to, say: locals()[5] in Python. Of course, there is no object at memory address "5" (in C) and no object in locals() named "5" (in Python). I agree there is a difference between getting a segfault and getting an exception, but it doesn't have much to do, IMHO, with what a variable is. #> You can hardly claim that what gets printed is the "id" of the variable c. #> (Well, you can claim, but few C programmers would follow you.) That's possible. I wouldn't expect too many C programmers to have any notion of "id of a variable". I, for example, never thought about such thing before this thread. #> What would be analogous in Python to the textual representation of #> the variable in C? The address operator in C in analog to the #> textual representation in Python. The textual representation in C #> is analog to ??? in Python? There is no "textual representation" of variables in C -- at least not at runtime. Why should there be? There is, after all, no equivalent to "eval('a=1')" so why would anybody care what was variable named? #> You may be talking about C pointers and call the locations they point to #> "variables". Yes, I am talking about C pointers, but I call *them*, not what they point at, variables. #> That's a big difference; those are /not/ C variables. I agree, the locations are not variables. #> And they still are not the same. OK, sure, there is a number of things that you can do to/with C variable that you cannot to/with Python variable, so they are not "the same". I just feel the differences are not large enough to warrant #> What is analog in Python (using your analogy) to the address of the pointer #> variable in C (&a in your example)? Well, how about x='a'? It allows you to do locals()[x], #> Note that in standard C/C++ language, a and b in your example are variables #> (in fact the only variables), not *a and *b. Agreed. #> (three and four should have been declared as constants, to be #> analogous to Python.) True, but I didn't think it matters. #> So the only variables in your example (a and b) don't really behave #> according to your analogy. Sorry, I do not follow. #> What behaves somewhat like your analogy are *a and *b -- neither of #> which are C/C++ variables. (Well, they are in your example, but #> only because of sloppily applying your analogy. I never said *a is a variable. #> And they are not in the general case: pointers don't care whether #> they point to actual C/C++ variables, or to any other memory #> location.) I think I lost you, but Python names do? Does "a" in your *.py file "care" whether they are bound to any object? I just noticed that part of our disagreement comes from the fact that I am talking about C variables as they look at runtime, while you seem to also consider the source code to be relevant. Am I correct? -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) Science is a differential equation. Religion is a boundary condition. -- Alan Turing From paddy3118 at netscape.net Sun Aug 27 22:50:21 2006 From: paddy3118 at netscape.net (Paddy) Date: 27 Aug 2006 19:50:21 -0700 Subject: Middle matching - any Python library functions (besides re)? In-Reply-To: <1156722194.089832.282510@74g2000cwt.googlegroups.com> References: <1156722194.089832.282510@74g2000cwt.googlegroups.com> Message-ID: <1156733421.546282.257370@m73g2000cwd.googlegroups.com> EP wrote: > Hi, > > I'm a bit green in this area and wonder to what extent there may be > some existing Python tools (or if I have to scratch my head real hard > for an appropriate algorithm... ) I'd hate to build an inferior > solution to that someone has painstakingly built before me. > > I have some files which may have had the same origin, but some may have > had some cruft added to the front, and some may have had some cruft > added to the back; thus they may be of slightly different lengths, but > if they had the same origin, there will be a matching pattern of bytes > in the middle, though it may be offset relative to each other. I want > to find which files have in common with which other files the same > pattern of origin within them. The cruft portions should be a small % > of the overall file lengths. Are they source files? Is the cruft comments? Have you done an exhaustive search for info on the files and the histories? If they are systematically generated then there may be a way to systematically uncover the matching info from their histories, such as source code management histories, file pathnames, file dates? What more can you find out about cruft? Is there a way to strip the cruft by program? If so, file sizes and checksums could be compared on the stripped files. > > Given that I am looking for matches of all files against all other > files (of similar length) is there a better bet than using re.search? > The initial application concerns files in the 1,000's, and I could use > a good solution for a number of files in the 100,000's. Can you change the flow that creates these files so that the information you want is generated alongside the files? Can you use data later in the flow to more easily extract the info you want? > > TIA for bearing with my ignorance of the clear solution I'm surely > blind to... > > EP Just some questions that I woud ask myself if given the task. - Paddy. From phinsxiii at gmail.com Sun Aug 20 17:47:14 2006 From: phinsxiii at gmail.com (Bucco) Date: 20 Aug 2006 14:47:14 -0700 Subject: List comparison help please Message-ID: <1156110434.360601.102800@i3g2000cwc.googlegroups.com> I am trying to compare a list of items to the list of files generated by os.listdir. I am having trouble getting this to work and think I may be going down the wrong path. Please let me know if hter is a better way to do this. THis is what I have for my class so far: import os, sys class MatchList: def __init__(self, dir, file): self.dir = os.listdir(dir) self.flist = open(file, 'r').readlines() self.matches = [] def matcher(self): #~ matches = [] for fname in self.dir: #~ print fname if fname[-4] == '.': for item in self.flist: if item == fname[:-4]: pass else: self.matches.append(fname) #~ else: #~ break #~ if self.matches == '': #~ print "Sorry, there was no match." #~ else: #~ for item in matches: #~ print item def matchedFiles(self): for item in self.matches: print item if __name__ == '__main__': dir = sys.argv[1] file = sys.argv[2] list = open(file, 'r').readlines() test = MatchList(dir, file) test.matcher() test.matchedFiles() Thanks in advance for your help. :) SA From __peter__ at web.de Wed Aug 2 08:16:16 2006 From: __peter__ at web.de (Peter Otten) Date: Wed, 02 Aug 2006 14:16:16 +0200 Subject: Class definition within function References: Message-ID: Tomi Lindberg wrote: > With the following function definition, is it possible to > create an instance of class C outside the function f (and if > it is, how)? And yes, I think this is one of those times > when the real question is why :) > > ?>>>?def?f(): > ????????class C(object): > ????????????????def __init__(self): > ????????????????????????self.a = 'a' > ????????return C() > > ?>>>?x?=?f() > ?>>>?x.a > 'a' y = type(x)() By the way you get an instance of a different class C every time you call f, so that isinstance(f(), type(f()) is False. Peter From ldo at geek-central.gen.new_zealand Sat Aug 19 08:36:59 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 20 Aug 2006 00:36:59 +1200 Subject: Subprocess quote problem References: Message-ID: In message , Adriano Monteiro wrote: > "Failed to open input file "/home/adriano/umit/test/targets" for reading > QUITTING!" Which is not the same as saying: "Failed to open input file /home/adriano/umit/test/targets for reading QUITTING!" Spot the difference? > command = ['nmap', '-T', 'Aggressive', '-n', '-F', '-iL', > '"/home/adriano/umit/test/targets"'] Why exactly where you putting quotes within quotes in the path? That kind of thing is only necessary when typing things on the shell command line, to prevent the shell itself misinterpreting things, like putting word breaks in the wrong places or having wrong behaviours triggered by special characters. From richardjones at optushome.com.au Thu Aug 31 18:26:38 2006 From: richardjones at optushome.com.au (Richard Jones) Date: Fri, 01 Sep 2006 08:26:38 +1000 Subject: code for the graphics window? References: Message-ID: <44f7621f$0$5106$afc38c87@news.optusnet.com.au> squall_leonheart7 at netzero.net wrote: > Hi. I'm new to Python . . .very new. I was just wondering, once I've > written a program that opens the graphics window and I've got some > things going on in the grahics window, how do I display text in the > grahics window? I need to be able to display changeable text, so that > the words and numbers can be altered with what is going on inside the > graphics window. If that doesn't make much sense, maybe I could try > sending a bit of the code from my program. A bit of code would certainly help. How did you open this "graphics window"? Richard From luis at geodynamics.org Mon Aug 7 18:46:38 2006 From: luis at geodynamics.org (Luis Armendariz) Date: Mon, 07 Aug 2006 15:46:38 -0700 Subject: A problem from a Vim user In-Reply-To: <1154973541.450774.50090@75g2000cwc.googlegroups.com> References: <1154973541.450774.50090@75g2000cwc.googlegroups.com> Message-ID: <44D7C2CE.9030401@geodynamics.org> manuhack wrote: > When I use raw_input('Please type something.\n') in the python 2.4 > command line windows, it doesn't have any problem. However, when I run > the same command in vim 7 as :py raw_input('Please type something.\n'), > there is an EOFError: EOF when reading a line. Is there a way to use > that command within vim without raising errors? > > Thanks a lot. > You should read :help python-input On my version (Vim 7.0.17), it says that input() and raw_input() are not yet supported. So, submit a patch to the vim folks! -Luis From exarkun at divmod.com Sat Aug 12 12:55:37 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sat, 12 Aug 2006 12:55:37 -0400 Subject: self=pickle.load(file)? (Object loads itself) In-Reply-To: Message-ID: <20060812165537.1717.1893610882.divmod.quotient.20806@ohm> On Sat, 12 Aug 2006 18:36:32 +0200, Anton81 wrote: >Hi! > >it seems that > >class Obj: > def __init__(self): > f=file("obj.dat") > self=pickle.load(f) >... > >doesn't work. Can an object load itself with pickle from a file somehow? >What's an easy solution? You are trying to implement a constructor (__new__) for the Obj class, but you have actually implemented the initializer (__init__). In order to be able to control the actual creation of the instance object, you cannot use the initializer, since its purpose is to set up various state on an already created instance. Instead, you may want to use a class method: class Obj: def fromPickleFile(cls, fileName): return pickle.load(file(fileName)) fromPickleFile = classmethod(fromPickleFile) You can then use this like so: inst = Obj.fromPickleFile('obj.dat') Jean-Paul > >Anton >-- >http://mail.python.org/mailman/listinfo/python-list > From drodrig at magicbrain.com Thu Aug 3 18:56:06 2006 From: drodrig at magicbrain.com (drodrig) Date: 3 Aug 2006 15:56:06 -0700 Subject: Enhanced Listbox Message-ID: <1154645765.984577.122710@b28g2000cwb.googlegroups.com> My apologies if this question has been asked an answered. I am looking for a tkinter grid control or enhanced listbox that can act as a "receipt" for a cash register program. I would like the widget to contain a visible grid of columns and rows. I've tried binding multiple listboxes to a scrollbar. This works OK, but I am missing the vertical lines dividing each row and I can't seem to figure out how to set the height (or vertical margin) of each row in the listbox(es). If I could do these things my current implementation might be OK. Or, I could just use a pre-packaged solution, if I coud find one. Any help is appreciated. From johnjsal at NOSPAMgmail.com Tue Aug 1 16:11:59 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 01 Aug 2006 20:11:59 GMT Subject: Programming newbie coming from Ruby: a few Python questions In-Reply-To: <1154460978.604511.209260@75g2000cwc.googlegroups.com> References: <1154458926.738922.156910@h48g2000cwc.googlegroups.com> <1154460978.604511.209260@75g2000cwc.googlegroups.com> Message-ID: crystalattice wrote: > Of course there's the O'Reilly set: Learning Python, Programming > Python, Python in a Nutshell, etc. Yep, Learning Python is the best to start. I haven't tried Programming Python yet (new edition soon), and once you understand Python, Python in a Nutshell is an excellent reference and also teaches you how a lot of things work under the hood. For plenty of examples and "learn by doing," you can check out Dive Into Python. And while I don't really recommend Beginning Python to *learn* the language, there are 10 projects at the end of the book that you can work on once you have a grasp of the language. From venkatbo at yahoo.com Thu Aug 31 01:18:36 2006 From: venkatbo at yahoo.com (venkatbo at yahoo.com) Date: 30 Aug 2006 22:18:36 -0700 Subject: Possible problem in compiler/transformer.py of Python2.4... Message-ID: <1157001516.911682.207060@p79g2000cwp.googlegroups.com> Hi all, I have python2.4 running on ppc-linux 2.6.17. I'm attempting to get a TurboGears 0.9a9 (using CherryPy 2.2.1) based app running on it. During the TG-app startup sequence, it reaches the point where it imports cherrypy, which eventually causes py2.4's system file, compiler/transformer.py, to import a module by name, symbol. Unable to find it, python quits... Following are the error msgs: ... File "start-tg-app.py", line 24, in ? import cherrypy File "/usr/lib/python2.4/site-packages/CherryPy-2.2.1-py2.4.egg/cherrypy/__init__.py", line 10, in ? import config File "/usr/lib/python2.4/site-packages/CherryPy-2.2.1-py2.4.egg/cherrypy/config.py", line 8, in ? from cherrypy.lib import autoreload, cptools, httptools File "/usr/lib/python2.4/site-packages/CherryPy-2.2.1-py2.4.egg/cherrypy/lib/cptools.py", line 252, in ? import compiler File "/usr/lib/python2.4/compiler/__init__.py", line 24, in ? from transformer import parse, parseFile File "/usr/lib/python2.4/compiler/transformer.py", line 30, in ? import symbol ImportError: No module named symbol ... What is surprising is I checkd the entire py2.4 distribution and I can't see a symbol.py (or a module with symbol defined) where transformer.py could import the symbol module form. All I can see is: ...../lib/python2.4/compiler/symbols.py in the same directory as that of transformer.py (in compiler). Has anyone seen this error, or have any pointers to solve the problem. Thanks, /venkat From http Tue Aug 15 20:27:44 2006 From: http (Paul Rubin) Date: 15 Aug 2006 17:27:44 -0700 Subject: Printing n elements per line in a list References: <1155685889.626881.37040@m73g2000cwd.googlegroups.com> Message-ID: <7xmza5h6db.fsf@ruckus.brouhaha.com> "unexpected" writes: > If have a list from 1 to 100, what's the easiest, most elegant way to > print them out, so that there are only n elements per line. > > So if n=5, the printed list would look like: > > 1 2 3 4 5 > 6 7 8 9 10 > 11 12 13 14 15 > etc. > > My search through the previous posts yields methods to print all the > values of the list on a single line, but that's not what I want. I feel > like there is an easy, pretty way to do this. I think it's possible to > hack it up using while loops and some ugly slicing, but hopefully I'm > missing something The most direct way would be something like (untested): for i in xrange(0, 100, 5): print ' '.join(str(j) for j in a[i:i+5]) where a is the array. If you prefer a "coordinate-free" style, you could use something like: for x,y in itertools.groupby(a, lambda n: n//5): print ' '.join(str(k) for k in y) I hope I got that right. From mauriceling at acm.org Mon Aug 14 01:23:35 2006 From: mauriceling at acm.org (Maurice LING) Date: Mon, 14 Aug 2006 05:23:35 GMT Subject: Easy to use distributed system? In-Reply-To: References: Message-ID: <44e008d3$1@news.unimelb.edu.au> Jim Jones wrote: > I am looking for a system in Python that will easily allow me to distribute > processes across multiple systems? So, if I have a function 'foo', I'd > like to be able to call something along the lines of > > distribute(foo(x)) > > And have the system figure out which node is available for process, and then > have the results returned in some sort of callback fashion. > > Any insight is greatly appreciated. > Globus toolkit pyGlobus, python interface to Globus (http://dsd.lbl.gov/gtg/projects/pyGlobus/) pyLinda (http://www-users.cs.york.ac.uk/aw/pylinda/) Cheers maurice From rogue_pedro at yahoo.com Thu Aug 10 20:28:59 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 10 Aug 2006 17:28:59 -0700 Subject: easy string formating question References: <1155235180.871436.22480@75g2000cwc.googlegroups.com> Message-ID: <1155256139.632064.37390@b28g2000cwb.googlegroups.com> Slawomir Nowaczyk wrote: > On Thu, 10 Aug 2006 11:39:41 -0700 > f pemberton wrote: > > #> I have kind of an interesting string, it looks like a couple hundred > #> letters bunched together with no spaces. Anyway, i'm trying to put a > #> "?" and a (\n) newline after every 100th character of the string and > #> then write that string to a file. How would I go about doing that? Any > #> help would be much appreciated. > > In addition to all the other ideas, you can try using StringIO > > import StringIO > s = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' > size = 10 # 100 > input = StringIO.StringIO(s) > while input.tell() print input.read(size)+"?\n", > # instead of print just write to a file or accumulate the result > > > -- > Best wishes, > Slawomir Nowaczyk > ( Slawomir.Nowaczyk at cs.lth.se ) > > "Reality is that which, when you stop believing in it, > doesn't go away." -- Philip K. Dick There is a better way to check for exhausted StringIO (Note that "input" is a python built-in and should not be used for a variable name): import StringIO s = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' size = 10 # 100 S = StringIO.StringIO(s) data = S.read(size) while data: print data + "?\n", data = S.read(size) However, it's considered more "pythonic" to do it like so (also uses a StringIO as an output "file" to show how print can print to a file-like object): import StringIO s = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' size = 10 # 100 S = StringIO.StringIO(s) out = StringIO.StringIO()# stand-in for a real file. while True: data = S.read(size) if not data: break print >> out, data + "?\n", print out.getvalue() From dhable at gmail.com Wed Aug 9 15:24:40 2006 From: dhable at gmail.com (dhable at gmail.com) Date: 9 Aug 2006 12:24:40 -0700 Subject: Two Classes In Two Files Message-ID: <1155151480.848276.52650@75g2000cwc.googlegroups.com> I just started working with Python and ran into an annoyance. Is there a way to avoid having to use the "from xxx import yyy" syntax from files in the same directory? I'm sure it's been asked a million times, but I can't seem to find the answer. For example, I have two classes stored in separate files as such. File: one.py ======== class One: def methodA(self): print "class One" def methodB(self): print "class One" File two.py ======== from one import One class Two(One): def methodA(self): print "class Two" if __name__ == "__main__": x = Two() x.methodA() x.methodB() When I run the Two.py file, I get the expected output but I'd like to eliminate the from line in two.py. From john at castleamber.com Thu Aug 17 13:47:57 2006 From: john at castleamber.com (John Bokma) Date: 17 Aug 2006 17:47:57 GMT Subject: OT: p-gal website References: <7xk65buyf9.fsf@ruckus.brouhaha.com> <1155575797.856782.26370@p79g2000cwp.googlegroups.com> <1155588214.070179.224540@75g2000cwc.googlegroups.com> <1155821248.403265.149530@p79g2000cwp.googlegroups.com> Message-ID: "ajaksu" wrote: > And to answer your question, I recommend to follow standards because > that's how I call the mixed bag of Recommendations, some of which are > also Specifications, allowing for the inclusion of both significant > Standards and standards. I guess I must've been bitten by the buzzword > bug, sorry it that offends you. But I'm not the only one (TM). True, but if one follows a document, shouldn't one name it according to how it's named in the document itself? To me, the answer is yes. Especially if people start to claim that "ISO HTML" and HTML 4.01 are identical standards. A lot of people call Python, Perl, etc. *just* scripting languages, not real programming languages (whatever that may be). Should we join their ranks or educate? -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From sjmachin at lexicon.net Fri Aug 4 09:02:30 2006 From: sjmachin at lexicon.net (John Machin) Date: 4 Aug 2006 06:02:30 -0700 Subject: regex question In-Reply-To: References: <1983a3190608031410n71eaa4d1s2a3db7c10c519b88@mail.gmail.com> Message-ID: <1154696550.895672.17210@p79g2000cwp.googlegroups.com> taleinat wrote: > Gabriel Murray gmail.com> writes: > > > > > Hello, I'm looking for a regular expression which will match strings as > follows: if there are symbols a, b, c and d, then any pattern is valid if it > begins with a and ends with d and proceeds in order through the symbols. > However, at any point the pattern may reset to an earlier position in the > sequence and begin again from there. > > For example, these would be valid > patterns:aabbbaabbcccbbbcccdddaabcabcdabcdBut these would > not:aaaaabbbbbccccaaaaadddd (goes straight from a to d)aaaaaaaaaaabbbbbccc > (does not reach d)Can anyone think of a concise way of writing this regex? The > ones I can think of are very long and awkward.Gabriel > > > > Your cirteria could be defined more simply as the following: > * must start with an 'a' and end with a 'd' > * an 'a' must not be followed by 'c' or 'd' > * a 'b' must not be followed by 'd' In fact it is so regular that the rules for the same thing with N letters can be written with O(1) rules: E.g. for N == 26: * must start with a and end with z * can go to (1) same spot (2) ahead 1 spot (3) back to any previous spot. Does the OP really need a regex???? Give the spots numbers (say from 1 up) instead of letters and a checker becomes trivial: [untested] def check(size, path): if not path or path[0] != 1 or path[-1] != size: return False pos = 1 for newpos in path[1:]: if not(1 <= newpos <= min(size, pos + 1)): return False pos = newpos return True Cheers, John From crystalattice at gmail.com Tue Aug 1 12:59:59 2006 From: crystalattice at gmail.com (crystalattice) Date: 1 Aug 2006 09:59:59 -0700 Subject: Pickle vs XML for file I/O References: <1154391849.335723.94480@s13g2000cwa.googlegroups.com> <1154425425.794278.175050@75g2000cwc.googlegroups.com> Message-ID: <1154451599.729854.308390@m79g2000cwm.googlegroups.com> Simon Hibbs wrote: > I've recently gone through a similar evaluation of my options for > persisting data. Object serialization to pickles or XML is a very easy, > quick way of persisting data but it does have drawbacks. I'm not a > professional developer, so if there are errors in my analysis, I'd love > to be corrected. > > Suppose you make some changes to the object format - adding some new > attributes or properties. Suddenly your existing test data is useless. > At least with XML you can edit the files by hand to add dummy data, but > with pickles that's not an option and even with XML it's a painful and > error prone process. > > Idealy you need to be able to browse and edit your saved data outside > the main program, to scan for errors, fix them manualy and easily > update your data structure as the application data model grows and > changes. > > There are good reasons why relational databases are the default data > store for many professional applications because you can parse and edit > the data very easily using external tools. Personaly I'd go with > SQLite. It's soon to be a part of the Python standard library with 2.5 > and is very compact. It can be a lot more work than just serializing > automaticaly, but there are toolkits such as SQLObject and SQL Alchemy > that can automate this as well. > > Best regards, > > Simon Hibbs That's a good idea. I may implement that later. Right now though I'm mostly doing this as a hobby and an open-source project, so I don't want to add too much extra to the project. I want to see what the base Python language is capable of before I start using other toolkits and libraries. I just barely got comfortable with the OOP "mindset" so even working w/ classes and objects is still a struggle sometimes. From st at tobiah.org Wed Aug 30 18:37:30 2006 From: st at tobiah.org (tobiah) Date: Wed, 30 Aug 2006 15:37:30 -0700 Subject: csv module strangeness. In-Reply-To: <1156976916.699378.17330@p79g2000cwp.googlegroups.com> References: <44f5e870$0$8814$88260bb3@free.teranews.com> <44f5f347$0$8846$88260bb3@free.teranews.com> <1156976916.699378.17330@p79g2000cwp.googlegroups.com> Message-ID: <44f6060b$0$8914$88260bb3@free.teranews.com> > However, more generally, the docs also clearly state that "In addition > to, or instead of, the dialect parameter, the programmer can also > specify individual formatting parameters, which have the same names as > the attributes defined below for the Dialect class." I definitely missed that. Knowing that, I don't think I will ever need the Dialect class, but I still think that the docs for the Dialect class are broken. -- Posted via a free Usenet account from http://www.teranews.com From gene.tani at gmail.com Fri Aug 4 23:53:39 2006 From: gene.tani at gmail.com (gene tani) Date: 4 Aug 2006 20:53:39 -0700 Subject: Design Patterns in Python In-Reply-To: References: Message-ID: <1154750019.148655.65790@i42g2000cwa.googlegroups.com> Gabriel Genellina wrote: > Hello > > Most authors talk about Java/C++, and describe patterns used as a > workaround to their static class model; the dynamic nature of Python > allows for trivial implementations in some cases. Eckel's thinking in Python too http://www.mindview.net/Books/TIPython From coolazNOSPAM at web.de Mon Aug 21 05:44:01 2006 From: coolazNOSPAM at web.de (Martin Kulas) Date: Mon, 21 Aug 2006 11:44:01 +0200 Subject: Py_BuildValue("I", ...) does not work Message-ID: <0sbor3-0kv.ln1@thunderbird.tld> Hallo! I have a problem with Py_BuildValue: I want to convert an unsigned int to a PyObject *. http://docs.python.org/api/arg-parsing.html says that I can use "I" as a format string. But it does not work :-\ Here is my simplified code: $ cat -n mini.c 1 #include 2 3 static PyObject * 4 mini_foo(PyObject *self, PyObject *args) 5 { 6 /* should be 3735928495 not -559038801 */ 7 unsigned int v = 0xdeadbeafL; /* byte representation */ 8 9 return Py_BuildValue("I", v); 10 } 11 12 static PyMethodDef 13 mini_methods[] = { 14 { "foo", mini_foo, METH_NOARGS, 15 "bla." }, 16 { NULL, NULL, 0, NULL } 17 }; 18 19 PyMODINIT_FUNC 20 initmini(void) 21 { 22 Py_InitModule("mini", mini_methods); 23 } $ cat -n setup.py 1 from distutils.core import setup, Extension 2 3 module1 = Extension('mini', sources = ['mini.c']) 4 5 setup(name = 'mini', 6 ext_modules = [ module1] ) 7 $ python setup.py build running build running build_ext building 'mini' extension cc -pthread -fno-strict-aliasing -DNDEBUG -O2 -pipe -DTHREAD_STACK_SIZE=0x20000 -fPIC -fPIC -I/usr/local/include/python2.4 -c mini.c -o build/temp.openbsd-3.9-i386-2.4/mini.o cc -pthread -shared -fPIC -L/usr/obj/i386/python-2.4.2p0/Python-2.4.2 build/temp.openbsd-3.9-i386-2.4/mini.o -o build/lib.openbsd-3.9-i386-2.4/mini.so $ cd build/lib.openbsd-3.9-i386-2.4 $ ls mini.so $ python Python 2.4.2 (#1, Mar 2 2006, 14:17:22) [GCC 3.3.5 (propolice)] on openbsd3 Type "help", "copyright", "credits" or "license" for more information. >>> import mini >>> mini.foo() Traceback (most recent call last): File "", line 1, in ? SystemError: bad format char passed to Py_BuildValue >>> Is Python's documentation wrong (I hope not)? Or, have I missed anything? Tanks in advance, Martin From xah at xahlee.org Mon Aug 21 00:49:45 2006 From: xah at xahlee.org (Xah Lee) Date: 20 Aug 2006 21:49:45 -0700 Subject: A Editor Feature for Extending Selection based on Language Syntax In-Reply-To: <1155822175.534005.100490@75g2000cwc.googlegroups.com> References: <1155822175.534005.100490@75g2000cwc.googlegroups.com> Message-ID: <1156135784.964866.190530@i3g2000cwc.googlegroups.com> can anyone give me a guide about writing a short elisp function? (for non-emacs readers, this message will describe a editor feature i think will be very beneficial to spread this concept.) i want to write a function such that, when run, highlight a region between the nearest left and right delimiters. Delimiters are any of parenthesis, square brackets, or single and double quotes etc. When the function is run again, it extends the selection to the next enclosing delimiters. So, in this way, a user can repeatedly press a keyboard shortcut and extend the selection. This is feature of BBEdit/TextWrangler on the Mac, which extend selection to the nearest outer parenthesis. This is also a feature of the Mathematica editor, which actually extend selection to the nearest syntactical unit in the language, not just paired delimiters. What i wanted this for is mostly in editing HTML/XML, where one press can select the content, another press will include the enclosing tags, another press extends the selection to the next outer content, and another press include that tags too, and so on. I'm a elisp newbie. Here's a simple code i have so far: (defun d () "extend selection to nearest enclosing delimiters" (interactive) (skip-chars-backward "^<>()??{}[]") (push-mark) (skip-chars-forward "^<>()??{}[]") (exchange-point-and-mark 1) ) ... i think i have quite a lot to go... I think this would be a great feature for any mode, where the a keypress will highlight more syntactical units in any language's mode. For example, suppose in C-like language: function f (arg1, arg2) { line1; line2; } if the cursor is at arg1, then first press will highlight the content of the args, another press includes the parens, another press will include the whole function. If the cursor is at line1, then it selects that word in the line, then the line, then the whole function def body, then including {}, then the whole function... etc in many languages. For a xml language example, suppose we have this RSS/Atom example: Gulliver's Travels tag:xahlee.org,2006-08-21:030437 2006-08-20T20:04:41-07:00 Annotated a chapter of Gulliver's Travels If the cursor is inside a tag's enclosing content, say, on the T in Gulliver's Travels inside the tag, then the repeated extension is obvious. But however, suppose the cursor is at t in the ?alternate? inside the ?link? tag, then it would first select the whole ?alternate? word, then the whole ?rel="alternate"?, then the whole link tag, then the whole content of the entry tag, then including the ?<entry>? tags itself. (in short, the selection extends according to the language's syntax tree) Xah xah at xahlee.org ? http://xahlee.org/ From gagsl-py at yahoo.com.ar Wed Aug 23 15:36:07 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 23 Aug 2006 16:36:07 -0300 Subject: Class instantiation In-Reply-To: <eci9rs$2sg$1@sea.gmane.org> References: <eci9rs$2sg$1@sea.gmane.org> Message-ID: <7.0.1.0.0.20060823163407.0387beb0@yahoo.com.ar> At Wednesday 23/8/2006 16:21, Colin J. Williams wrote: >In the example below, with the disassembly following that, we run into >trouble with the line: >NameError: global name 'fileID' is not defined > >At line 26, location 31, why is LOAD_GLOBAL generated for fileId, when >LOAD_FAST has done the job at locations 0 and 20? Don't blame the code generator... fileId != fileID Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From me at privacy.net Thu Aug 3 22:32:26 2006 From: me at privacy.net (Dan Sommers) Date: Thu, 03 Aug 2006 22:32:26 -0400 Subject: md5 question References: <1154655374.571813.236870@75g2000cwc.googlegroups.com> Message-ID: <m28xm58c3p.fsf@unique.fqdn> On 3 Aug 2006 18:36:14 -0700, "Dan" <thermostat at gmail.com> wrote: > now pretend I wanted to save the string > '8b1a9953c4611296a827abf8c47804d7', and later create a new md5 object > such that when I did md5_w.update(" world") it would then have the hex > value '3e25960a79dbc69b674cd4ec67a72c62'. Is that possible? I've looked > for initialization options in the documentation and searched c.l.p., > but no luck. According to http://docs.python.org/lib/module-md5.html, you want the copy method of your existing md5 object. Regards, [Another] Dan -- Dan Sommers <http://www.tombstonezero.net/dan/> "I wish people would die in alphabetical order." -- My wife, the genealogist From bill.pursell at gmail.com Wed Aug 16 15:00:47 2006 From: bill.pursell at gmail.com (Bill Pursell) Date: 16 Aug 2006 12:00:47 -0700 Subject: PySequence_SetItem Message-ID: <1155754847.392950.266180@h48g2000cwc.googlegroups.com> The following code is pretty much straight out of section 1.2.1.1 of the Python/C reference manual: #include <Python.h> int main(void) { PyObject *l, *x; Py_Initialize(); l = PyList_New(3); x = PyInt_FromLong(1L); if (l == NULL || x == NULL) { PyErr_Print(); exit (EXIT_FAILURE); } PySequence_SetItem(l, 0, x); Py_DECREF(x); Py_Finalize(); return EXIT_SUCCESS; } Unforunately, it doesn't work. It segfaults, and the error occurs in list_ass_item() when the Py_DECREF macro is applied to old_value, which was set at line 699 of Objects/listobject.c with old_value = a->ob_item[i]; (old_value is being set to NULL, and Py_DECREF is being applied to NULL...boom!) I'm totally new to embedding/extending python, so I'm not sure if I'm doing something incredibly stupid, but it certainly looks like PySequence_SetItem() was expecting that there should already be an item at the desired index. Am I doing something stupid? -- Bill Pursell From gagsl-py at yahoo.com.ar Wed Aug 23 15:19:33 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 23 Aug 2006 16:19:33 -0300 Subject: swapping numeric items in a list In-Reply-To: <00d801c6c6e2$8a8924b0$900a14ac@corp.intusurg.com> References: <mailman.9675.1156291509.27775.python-list@python.org> <pan.2006.08.23.10.13.15.854509@gmx.net> <eci46s$ejs$1@sea.gmane.org> <7.0.1.0.0.20060823152758.03e17610@yahoo.com.ar> <00d801c6c6e2$8a8924b0$900a14ac@corp.intusurg.com> Message-ID: <7.0.1.0.0.20060823161501.03329c28@yahoo.com.ar> At Wednesday 23/8/2006 15:32, Jiang Nutao wrote: >This is what I got in the debugger: > >(Pdb) aa=array('b', [126, 55, 71, 112]) >(Pdb) aa >array('b', [126, 55, 71, 112]) >(Pdb) aa.byteswap() >(Pdb) aa >array('b', [126, 55, 71, 112]) Oh, sorry, to swap by two bytes "H" was the right typecode. But your input array should be: >>> aa = array('H', [0x1234, 0x5678]) which should give: array('H', [0x3412, 0x7856]) Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From tjreedy at udel.edu Wed Aug 23 18:36:33 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 23 Aug 2006 18:36:33 -0400 Subject: range of int() type. References: <1156368379.206968.288740@p79g2000cwp.googlegroups.com><1156368969.085690.92400@i42g2000cwa.googlegroups.com> <1156370039.116224.154430@75g2000cwc.googlegroups.com> Message-ID: <ecil9h$8pj$1@sea.gmane.org> "KraftDiner" <bobrien18 at yahoo.com> wrote in message news:1156370039.116224.154430 at 75g2000cwc.googlegroups.com... > > So what type / class should one use to represent a 16 bit integers > (signed or unsigned)? For most purposes, Python just has integers, with 'small' ones (depending on the machine) handled more efficiently. For special purposes, you may want to use the array or struct modules. tjr From geli at tasmail.com Sun Aug 20 19:39:03 2006 From: geli at tasmail.com (gel) Date: 20 Aug 2006 16:39:03 -0700 Subject: What would be the best way to run python client in the background References: <mailman.9418.1155735655.27775.python-list@python.org> Message-ID: <1156117143.314238.290970@i3g2000cwc.googlegroups.com> Tim Golden wrote: > | > [gel] > | > > | > | I have written a python client server app [...] > | > | I want to run the client end of the app more or less invisibly > | > | (no console) on the XP clients when ever a users logs on. > > While this isn't answering the question you first > asked, might I suggest an alternative approach? > Obviously, I'm working from no more than the sketch > you gave of your app and its requirements, but might > it be worth turning the problem on its head, and > using WMI? > > Advantages: > > 1) WMI will -- almost certainly -- already be running on your > target machines. No need to install your own service. > > 2) WMI has a fair range of mechanisms for determining > what processes are starting, stopping, etc. and for > manipulating them remotely. > > 3) You can, at least in theory, access any number of machines > from a central server, and with a bit of judicious threading > or looping, you should be able to generate a fair bit of resilience > to machine dropouts etc. > > Disadvantages: > > 1) What you're doing may be far more complex than you've > outlined, requiring a local service per target machine > for other reasons. > > 2) You may have already invested some amount of time and > effort in developing an app which does what you want. > > 3) I may have entirely misunderstood what you're trying > to do in any case. > > If you're interested and want a code sample, let me know. > If you're not, that's fine. > > TJG > Hi Tim Thanks for your suggestion, I have just got to read the post now and appolagise to you and the others who have replied to my post for the big gap. I will have a read today and get back to you. From luismgz at gmail.com Sun Aug 13 18:41:33 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 13 Aug 2006 15:41:33 -0700 Subject: looking for a simple way to load a program from another python program.. In-Reply-To: <1155507467.610127.247780@m79g2000cwm.googlegroups.com> References: <1155498660.285772.144140@m73g2000cwd.googlegroups.com> <1155502085.103104.295370@h48g2000cwc.googlegroups.com> <1155507467.610127.247780@m79g2000cwm.googlegroups.com> Message-ID: <1155508893.773715.62030@i42g2000cwa.googlegroups.com> Try this: import os os.startfile('cabel.py') This should work with any program or file, not only python ones. Hope this helps, Luis From wardm66 at gmail.com Sat Aug 12 18:54:46 2006 From: wardm66 at gmail.com (wardm) Date: Sun, 13 Aug 2006 08:54:46 +1000 Subject: Using a dictionary to pass data to/from embedded python functions References: <44dcf055@dnews.tpgi.com.au> <1hjy7rx.1sxrihq1jtyy68N%aleax@mac.com> Message-ID: <44de5c3b@dnews.tpgi.com.au> Thanks Alex for your help, (and advice on focusing the point of my question). I was able to compile and run your example OK, but when I try to use the "VarDictionary" in the MyScriptModule.py code, I get an exception. I added the following code to the C app just to add two entries to the Dictionary PyDict_SetItemString( m_pVarDictionary, "tk1", Py_BuildValue("s","test1Val")); PyDict_SetItemString( m_pVarDictionary, "tk2", Py_BuildValue("s","test2Val")); Then tried various things in the Python code to display the contents of the "VarDictionary", such as adding the "print VarDictionary" below. import InterfaceModule def functionName(): print "hello" print dir(InterfaceModule) print "that's all" print VarDictionary return Even though "VarDictionary " is in the Dir, every time I try to use the "VarDictionary" the program fails. Am I doing something wrong when I try and reference "VarDictionary" in Python ? I need to be able to get/set entries in VarDictionary from the Python function. "Alex Martelli" <aleax at mac.com> wrote in message news:1hjy7rx.1sxrihq1jtyy68N%aleax at mac.com... > wardm <wardm66 at gmail.com> wrote: > >> I have created a Dict object in a C++ App that calls (embedded) Python >> functions. > [[snip snip]] >> This python code throws an exception when it attempts to access the >> "VarDictionary". >> Does anyone know why this fails ? > > It fails due to some code of yours that you have not included: in other > words, the minimal application which embeds Python using _only_ the code > you show us does not exhibit the failure. > > I wrote the following file za.c: > > #include "Python.h" > #include "stdio.h" > #include "stdlib.h" > > int main() > { > printf("start\n"); > putenv("PYTHONPATH=."); > Py_Initialize(); > printf("inited\n"); > PyObject* m_pVarDictionary = PyDict_New(); > printf("dict is %p\n", m_pVarDictionary); > PyObject* m_pInterfaceModule = > PyImport_AddModule("InterfaceModule"); > printf("modu is %p\n", m_pInterfaceModule); > int status = PyModule_AddObject(m_pInterfaceModule, "VarDictionary" > , > m_pVarDictionary); > printf("stat is %d\n", status); > PyObject* m_pScriptModule = PyImport_ImportModule("MyScriptModule"); > printf("impo is %p\n", m_pScriptModule); > > PyObject* func = PyObject_GetAttrString(m_pScriptModule, > "functionName"); > printf("func is %p\n", func); > if (func && PyCallable_Check(func)) { > PyObject* ret = PyObject_CallObject(func, NULL); > printf("retu is %p\n", ret); > } > printf("done\n"); > return 0; > } > > and the following file MyScriptModule.py: > > import InterfaceModule > > def functionName(): > print "hello" > print dir(InterfaceModule) > print "that's all" > return > > and proceeded to compile and execute as follows: [[Note: it does not > matter that I'm using 2.5, the code is just as fine with previous > versions -- it just happens that 2.5 is what I'm using right now in > order to help out with 2.5's beta testing]]: > > brain:~/pyex alex$ gcc -c za.c -I/usr/local/include/python2.5 > brain:~/pyex alex$ gcc -o za za.o -L/usr/local/lib/python2.5/config/ > -lpython2.5 > brain:~/pyex alex$ ./za > > and observed exactly the kind of output I predicted [[Note: the exact > addresses printed of course do not matter]]: > > start > inited > dict is 0x51c780 > modu is 0x520230 > stat is 0 > impo is 0x5202d0 > func is 0x513770 > hello > ['VarDictionary', '__doc__', '__name__'] > that's all > retu is 0xe57c0 > done > brain:~/pyex alex$ > > As you see, in particular, VarDictionary is right up there in > InterfaceModule's dir. > > > There's a well-known essay by Eric Raymond, "How to ask questions the > smart way", at <http://catb.org/~esr/faqs/smart-questions.html> -- it > seems to me that you, quite commendably, follow most of Eric's advice, > but it's still worth reading -- the key point by which you could help us > to help you is what Eric mentions as "If you have a large, complicated > test case that is breaking a program, try to trim it and make it as > small as possible". > > In this case, you should try to trim your code down to the smallest > program using this approach, which you believe should work in a certain > way but actually doesn't. The exact code you posted plus the minimal > additions to make it a compilable program does work the way you appear > to desire, as I show above; therefore, there must be something else in > your code that is breaking things. Do tiny steps of addition and > restructuring to move this minimal skeleton towards the direction of > your bigger program (that does not behave this way) until you've found > exactly the "largest" version that still succeeds, and the minisculely > larger "smallest" version that fails -- the tiny difference between the > two must then be the root of the problem, and if the reason is not clear > at that point then posting here again is exactly the right thing to do. > > Perhaps you're falling afoul of the fact that (as documented e.g. at > <http://docs.python.org/api/moduleObjects.html>) PyModule_AddObject is a > "convenience function" that steals a reference to the value -- so you > end up with just one reference to the dictionary object, and if for some > reason you decref it, the object gets garbage collected. But, that's > just a wild guess on my part, since you have not shown us any code > performing (for example) any decrefs. > > > Alex From bgporter at acm.org Wed Aug 9 09:31:56 2006 From: bgporter at acm.org (Brett g Porter) Date: Wed, 09 Aug 2006 09:31:56 -0400 Subject: do people really complain about significant whitespace? In-Reply-To: <1155124820.123151.140580@p79g2000cwp.googlegroups.com> References: <1154991523.887791.9640@i42g2000cwa.googlegroups.com> <1154994477.450666.226550@b28g2000cwb.googlegroups.com> <mailman.9132.1155120873.27775.python-list@python.org> <1155124820.123151.140580@p79g2000cwp.googlegroups.com> Message-ID: <44D9E3CC.5070609@acm.org> brianmce at gmail.com wrote: > Its not the typing, its the fact that when you say the same thing > twice, there is the potential for them to get out of sync. If the > method the compiler uses (braces) and the method the human uses > (indentation) to determine what the code does don't agree, then a > reader will be likely to misunderstand what it will actually do. One > of the driving principles behind Python is that, because code will be > read more often than written, readability is more important. Not to mention the errors that creep in when code is maintained, like when C code starting out as if (i < SOME_CONSTANT) doSomething(); gets "maintained" to if (i < SOME_CONSTANT) doSomething(); doSomethingDangerous(); without the programmer adding the surrounding braces. The programmer's intent is clear to me as a human, but the C compiler will disagree with me, and in this case, the compiler will be right and I'm wrong. You can (and we do, at my company) have coding standards that mandate braces around single line if()s in C/C++, but that's really just patching around the problem (and it counts on humans being consistent). Pushing the scutwork down onto tools is not as good a solution as eliminating the scutwork, especially when it shouldn't be necessary at all... -- // Brett g Porter * bgp at bgporter.net // http://www.bgporter.net/blog From could.net at gmail.com Tue Aug 22 22:16:29 2006 From: could.net at gmail.com (could.net at gmail.com) Date: 22 Aug 2006 19:16:29 -0700 Subject: Python and STL efficiency In-Reply-To: <1156252193.524186.107520@b28g2000cwb.googlegroups.com> References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <eccb9u$kjs$1@gemini.csx.cam.ac.uk> <1hkh28d.xscw4v1y4v9a6N%riko@despammed.com> <mailman.9640.1156247569.27775.python-list@python.org> <1hkh6lb.6dsnh51lj8z96N%riko@despammed.com> <1156252193.524186.107520@b28g2000cwb.googlegroups.com> Message-ID: <1156299389.336939.211670@i42g2000cwa.googlegroups.com> That's to say, python is still much faster? I am a c++ newbie but I think c++ should be faster here. Maybe someone can post this to the c++ maillist and they will tell how to accelerate it. Tim N. van der Leeuw wrote: > Mc Osten wrote: > > Fredrik Lundh <fredrik at pythonware.com> wrote: > > > > > Python's memory allocator is also quite fast, compared to most generic > > > allocators... > > > > In fact also in the two "slow" versions Python outperforms C++. > > I didn't notice it in the first place. > > > > -- > > blog: http://www.akropolix.net/rik0/blogs | Uccidete i filosofi, > > site: http://www.akropolix.net/rik0/ | tenetevi riso e > > forum: http://www.akropolix.net/forum/ | bacchette per voi. > > Well, I guess I'm getting really obsessed with this. But anyways. I > installed MinGW on my Windows-XP (sp2) laptop. It is g++ version 3.4.5 > -- ancient, yes, but on windows it's the latest available. > > I compiled Mc Osten's C++ program (tweaked the output a little) and ran > it; ran his version of the python code too. > Oh boy; yes indeed the slow python is faster than the fast C++ > version... Must be something really awful happening in the STL > implementation that comes with GCC 3.4! > > Here's the output from my console: > > LeeuwT at nlshl-leeuwt ~/My Documents/Python > $ g++ -O3 -march=pentium-m -o SpeedTest SpeedTest.cpp > > LeeuwT at nlshl-leeuwt ~/My Documents/Python > $ ./SpeedTest.py > Begin Test > Number of unique string objects: 4 > so long... > What do you know > fool > chicken crosses road > Number of unique string objects: 40000 > so long... > What do you know > fool > chicken crosses road > Fast - Elapsed: 0.037574 seconds > Slow - Elapsed: 0.081520 seconds > > LeeuwT at nlshl-leeuwt ~/My Documents/Python > $ ./SpeedTest.exe > Begin Test > What do you know? > chicken crosses road > fool > so long... > What do you know? > chicken crosses road > fool > so long... > Fast - Elapsed: 2.089 seconds > Slow - Elapsed: 6.303 seconds > > LeeuwT at nlshl-leeuwt ~/My Documents/Python > > > Cheers, > > --Tim From Kiran.Karra at gmail.com Tue Aug 1 16:58:33 2006 From: Kiran.Karra at gmail.com (Kiran) Date: 1 Aug 2006 13:58:33 -0700 Subject: 2 timers, doesnt work? In-Reply-To: <1153891720.414935.270780@m73g2000cwd.googlegroups.com> References: <1153842726.327272.71850@p79g2000cwp.googlegroups.com> <1153891720.414935.270780@m73g2000cwd.googlegroups.com> Message-ID: <1154465913.371457.38190@p79g2000cwp.googlegroups.com> Makes sense Frank, and that seemed to work also, so thanks a lot! Frank Millman wrote: > Kiran wrote: > > I am creating 2 timers inside a GUI, but it seems that only the one > > declared last (the second timer), gets triggered, but the first one > > doesnt. > > > > You really should check the archives before posting. Exactly the same > question was asked less than a week ago. > > The original question was answered by Nikie. I have quoted the reply > verbatim - > > ---------------------------------------------------------------- > The problem is not that the first timer is stopped, the problem is > that both timers happen to call the same method in the end. > > Think of the "Bind" method as an assignment: it assigns a handler > function to an event source. If you call it twice for the same event > source, the second call will overwrite the first event handler. That's > what happens in your code. > > > The easiest way to change this is by using different ids for the > timers: > > > def startTimer1(self): > self.t1 = wx.Timer(self, id=1) > self.t1.Start(2000) > self.Bind(wx.EVT_TIMER, self.OnUpTime, id=1) > > > def startTimer2(self): > self.t2 = wx.Timer(self, id=2) > self.t2.Start(1000) > self.Bind(wx.EVT_TIMER, self.OnTime, id=2) > > > This way, the timers launch two different events, which are bound to > two different methods. > ---------------------------------------------------------------- > > I would suggest one minor change. Create a variable for the id using > wx.NewId(), and pass the variable as an argument in both places, > instead of hard-coding the id. That way you are guaranteed to get a > unique id. In a large project it can be difficult to keep track of > which id's have been used if they are all hard-coded. > > Frank Millman From mail at microcorp.co.za Sat Aug 19 10:11:57 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 19 Aug 2006 16:11:57 +0200 Subject: Small Troll on notation of variables over time References: <mailman.9535.1155985480.27775.python-list@python.org> <1155990895.294748.327300@m79g2000cwm.googlegroups.com> Message-ID: <009501c6c39a$0354b220$03000080@hendrik> "John Machin" <sjmachin at lexicon.net> wrote: | | Hendrik van Rooyen wrote: | [snip] | > What do you guys think? | | The subject said it all. You should find some other way of entertaining | yourself on the weekends :-) This is the right answer... *grin* - well - at least you *were* warned... - Hendrik From steve at holdenweb.com Thu Aug 17 00:51:36 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 17 Aug 2006 05:51:36 +0100 Subject: Newbie needs Help In-Reply-To: <ec0rl2$s3s$1@sea.gmane.org> References: <1155783551.689026.273260@m73g2000cwd.googlegroups.com> <ec0rl2$s3s$1@sea.gmane.org> Message-ID: <ec0sk1$tot$1@sea.gmane.org> Steve Holden wrote: [...] > > >>> def insertFromDict(table, d): vector ^^^^^^^^^^^^ Please ignore the Cygwin mousedroppings ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From khemkaamit at gmail.com Tue Aug 1 02:30:44 2006 From: khemkaamit at gmail.com (Amit Khemka) Date: Tue, 1 Aug 2006 12:00:44 +0530 Subject: PIL issues In-Reply-To: <3477267.Q72r8hj7zL@teancum> References: <3477267.Q72r8hj7zL@teancum> Message-ID: <1360b7230607312330y262ba267q7aefc8899cc2962b@mail.gmail.com> On 8/1/06, David Bear <david.bear at asu.edu> wrote: > I am trying to use PIL and when building it, PIL fails to find my jpeg > library. I am using a python 2.4.3 that I build myself on Suse linux 9.3. I > do have the following jpeg libraries: > > rpm -qa | grep jpeg > jpeg-6b-738 > libjpeg-32bit-9.3-7 > libjpeg-6.2.0-738 > > > yet, when building PIL I get: > > python setup.py build_ext -i > running build_ext > -------------------------------------------------------------------- > PIL 1.1.5 BUILD SUMMARY > -------------------------------------------------------------------- > version 1.1.5 > platform linux2 2.4.2 (#4, Jul 27 2006, 14:34:30) > [GCC 3.3.5 20050117 (prerelease) (SUSE Linux)] > -------------------------------------------------------------------- > *** TKINTER support not available > *** JPEG support not available > --- ZLIB (PNG/ZIP) support ok > *** FREETYPE2 support not available > -------------------------------------------------------------------- > To add a missing option, make sure you have the required > library, and set the corresponding ROOT variable in the > setup.py script. > > I don't know what ROOT variable the message is referring too. Any advice > would be appreciated. This is because PIL, is not able to find the jpeg/other libraries . 1. Install jpeg-libs from sources: (http://www.ijg.org/files/jpegsrc.v6b.tar.gz) 2.0: "clean" the PIL build 2.1 In setup.py that comes with PIL, set the JPEG_ROOT to the jpeg-lib path 3.0 run setup.py I hope that should help .. cheers, amit -- ---- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. From max at alcyone.com Wed Aug 9 15:30:21 2006 From: max at alcyone.com (Erik Max Francis) Date: Wed, 09 Aug 2006 12:30:21 -0700 Subject: #!/usr/bin/python or #!/usr/bin/env python? In-Reply-To: <ebc9oq$25hp$1@news.uit.no> References: <fj5Cg.2658$No6.51984@news.tufts.edu> <bL6dnTXbq9adbkXZnZ2dnUVZ_u2dnZ2d@speakeasy.net> <ebbtor$evr$1@kohl.informatik.uni-bremen.de> <mailman.9130.1155106885.27775.python-list@python.org> <ebc288$g8s$1@kohl.informatik.uni-bremen.de> <vsgCg.66818$zy5.1253926@twister1.libero.it> <ebc58g$h22$1@kohl.informatik.uni-bremen.de> <JfOdncqW_fzdAUTZnZ2dnUVZ_uWdnZ2d@speakeasy.net> <ebc7e4$243u$3@news.uit.no> <BumdnZCP_J3aP0TZnZ2dnUVZ_qednZ2d@speakeasy.net> <ebc9oq$25hp$1@news.uit.no> Message-ID: <OJudnRXmWMRQqkfZnZ2dnUVZ_sKdnZ2d@speakeasy.net> Tobias Brox wrote: > A shell script containing some inline tcl is a shell script, though > when the only shell-command is "start up tcl" and the rest of the file > is tcl-code, I really don't think it can be defined as a "shell > script" anymore. Particularly not if almost all tcl-scripts are > started that way. The problem is that there are endless ways to do that, and figuring out all the cases makes `file` an sh interpreter, not the magic number detector it's supposed to be. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Punctuality is the virtue of the bored. -- Evelyn Waugh From sjdevnull at yahoo.com Thu Aug 24 23:53:49 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 24 Aug 2006 20:53:49 -0700 Subject: Is this a good idea or a waste of time? In-Reply-To: <1156449402.022781.292840@p79g2000cwp.googlegroups.com> References: <1156449402.022781.292840@p79g2000cwp.googlegroups.com> Message-ID: <1156478029.202195.69550@p79g2000cwp.googlegroups.com> asincero wrote: > Would it be considered good form to begin every method or function with > a bunch of asserts checking to see if the parameters are of the correct > type (in addition to seeing if they meet other kinds of precondition > constraints)? Like: > > def foo(a, b, c, d): > assert type(a) == str > assert type(b) == str > assert type(c) == int > assert type(d) == bool > # rest of function follows That's bad form. If you insist on doing something like this, at least use "isinstance(a, str)" instead of typeof. But even that breaks duck typing; if a is a unicode string, that'll fail when the function may work fine for unicode strings. You could, of course, test explicitly for the interface you need (e.g. if you need a to have "lower" and "rjust" methods, do assertion tests for them). But in practice you're generally better off simply using the object and getting the exception a few lines lower. Much of the power of dynamic typing comes from the duck typing concept, so you should really try to familiarize yourself with it. > This is something I miss from working with more stricter languages like > C++, where the compiler will tell you if a parameter is the wrong type. Stricter is the wrong word. Python is strictly typed. The difference here is dynamic vs. static typing. > If anything, I think it goes a long way towards the code being more > self documenting. Or is this a waste of time and not really "the > Python way"? There are 3 main things that you can do to help here: 1. Choose better names for the arguments so that it's obvious what they are. I don't advocate Hungarian naming, normally something like "url" or "shoeSize" will be strongly indicative of what kinds of values are acceptable. 2. Write docstrings. That will not only document the types but also how they're used, what gets returned, and perhaps limits on exactly what ranges of values are acceptable. 3. Write unit tests. They'll catch far more errors than static typing ever will. From xi at gamma.dn.ua Sun Aug 20 14:40:37 2006 From: xi at gamma.dn.ua (Kirill Simonov) Date: Sun, 20 Aug 2006 21:40:37 +0300 Subject: [ANN] PyYAML-3.04: YAML parser and emitter for Python Message-ID: <20060820184037.GA5119@58sirius016.dc.ukrtel.net> ======================== Announcing PyYAML-3.04 ======================== A new release of PyYAML, featuring LibYAML bindings and support for recursive structures, is now available: http://pyyaml.org/wiki/PyYAML Changes ======= * Include experimental LibYAML bindings. * Fully support recursive structures. * Fix a number of bugs and annoyances (see http://pyyaml.org/wiki/PyYAML#History for more details). Resources ========= PyYAML homepage: http://pyyaml.org/wiki/PyYAML PyYAML documentation: http://pyyaml.org/wiki/PyYAMLDocumentation TAR.GZ package: http://pyyaml.org/download/pyyaml/PyYAML-3.04.tar.gz ZIP package: http://pyyaml.org/download/pyyaml/PyYAML-3.04.zip Windows installer: http://pyyaml.org/download/pyyaml/PyYAML-3.04.win32-py2.3.exe http://pyyaml.org/download/pyyaml/PyYAML-3.04.win32-py2.4.exe PyYAML SVN repository: http://svn.pyyaml.org/pyyaml Submit a bug report: http://pyyaml.org/newticket?component=pyyaml YAML homepage: http://yaml.org/ YAML-core mailing list: http://lists.sourceforge.net/lists/listinfo/yaml-core About PyYAML ============ YAML is a data serialization format designed for human readability and interaction with scripting languages. PyYAML is a YAML parser and emitter for Python. PyYAML features a complete YAML 1.1 parser, Unicode support, pickle support, capable extension API, and sensible error messages. PyYAML supports standard YAML tags and provides Python-specific tags that allow to represent an arbitrary Python object. PyYAML is applicable for a broad range of tasks from complex configuration files to object serialization and persistance. Example ======= >>> import yaml >>> print yaml.load(""" ... &A { ... direct self reference: *A, ... indirect self references: [*A, *A, *A] ... } ... """) {'direct self reference': {...}, 'indirect self references': [{...}, {...}, {...}]} Copyright ========= The PyYAML module is written by Kirill Simonov <xi at resolvent.net>. PyYAML is released under the MIT license. This release is developed with the support of the Google Summer of Code program under the mentorship of Clark Evans. From zxo102 at gmail.com Tue Aug 15 04:37:29 2006 From: zxo102 at gmail.com (zxo102) Date: 15 Aug 2006 01:37:29 -0700 Subject: start a multi-sockets server (a socket/per thread) with different ports but same host In-Reply-To: <1155630779.465968.299660@h48g2000cwc.googlegroups.com> References: <1155398402.738765.238610@m73g2000cwd.googlegroups.com> <c6zDg.5006$%j7.3352@newssvr29.news.prodigy.net> <1155630779.465968.299660@h48g2000cwc.googlegroups.com> Message-ID: <1155631049.258154.297080@b28g2000cwb.googlegroups.com> "That twisted example only accepts one client connection" if only one port is available. zxo102 ??? > Bryan, > Thanks for your note. Finally, I have made "one listener socket for > all the connections" work plus Queue-communication between the threads > in wxpython Gui and the threads for socket connections. > Trying to make that twisted example code in this topic for "one > listener socket-all the connections" but failed. That twisted example > only accepts one client connection. I have printed out the Twisted help > file (256 pages). Too much to read. > > Ouyang > > > Bryan Olson ??? > > > zxo102 wrote: > > > I am doing a small project using socket server and thread in python. > > > This is first time for me to use socket and thread things. > > > Here is my case. I have 20 socket clients. Each client send a set > > > of sensor data per second to a socket server. The socket server will > > > do two things: 1. write data into a file via bsddb; 2. forward the data > > > to a GUI written in wxpython. > > > I am thinking the code should work as follow (not sure it is > > > feasible) > > > 20 threads, each thread takes care of a socket server with a > > > different port. > > > I want all socket servers start up and wait for client connection. > > > In the attached demo code, It stops at the startup of first socket > > > server somewhere in the following two lines and waits for client call: > > > > > > lstn.listen(5) > > > (clnt,ap) = lstn.accept() > > > > It will block there, waiting for connection. > > > > > Any ideas how to handle these 20 clients? Really appreciate your > > > suggestions. > > > > One reserved port for each client strikes me as whacked, > > as does coding a server to handle exactly 20 of them. Since > > you say this is your first socket server, maybe you just > > haven't seen the usual techniques. > > > > Normally, one listener socket accepts all the connections. > > Each call to accept() returns a new, independent socket for the > > connection. You can then start a thread to handle the new > > socket. Untested: > > > > > > listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > listener.bind(('', 2000)) > > listener.listen(5) > > while True: # or some should_continue() thing > > sock, _ = listener.accept() > > thread.start_new_thread(service_function, (sock,)) > > # Or start threads via class Threading > > > > > > To update the GUI, you could use the Queue from the Python > > library, and call wxPostEvent to tell the GUI go wake up and > > check the queue. > > > > > > -- > > --Bryan From zxo102 at gmail.com Tue Aug 15 04:32:59 2006 From: zxo102 at gmail.com (zxo102) Date: 15 Aug 2006 01:32:59 -0700 Subject: start a multi-sockets server (a socket/per thread) with different ports but same host In-Reply-To: <c6zDg.5006$%j7.3352@newssvr29.news.prodigy.net> References: <1155398402.738765.238610@m73g2000cwd.googlegroups.com> <c6zDg.5006$%j7.3352@newssvr29.news.prodigy.net> Message-ID: <1155630779.465968.299660@h48g2000cwc.googlegroups.com> Bryan, Thanks for your note. Finally, I have made "one listener socket for all the connections" work plus Queue-communication between the threads in wxpython Gui and the threads for socket connections. Trying to make that twisted example code in this topic for "one listener socket-all the connections" but failed. That twisted example only accepts one client connection. I have printed out the Twisted help file (256 pages). Too much to read. Ouyang Bryan Olson ??? > zxo102 wrote: > > I am doing a small project using socket server and thread in python. > > This is first time for me to use socket and thread things. > > Here is my case. I have 20 socket clients. Each client send a set > > of sensor data per second to a socket server. The socket server will > > do two things: 1. write data into a file via bsddb; 2. forward the data > > to a GUI written in wxpython. > > I am thinking the code should work as follow (not sure it is > > feasible) > > 20 threads, each thread takes care of a socket server with a > > different port. > > I want all socket servers start up and wait for client connection. > > In the attached demo code, It stops at the startup of first socket > > server somewhere in the following two lines and waits for client call: > > > > lstn.listen(5) > > (clnt,ap) = lstn.accept() > > It will block there, waiting for connection. > > > Any ideas how to handle these 20 clients? Really appreciate your > > suggestions. > > One reserved port for each client strikes me as whacked, > as does coding a server to handle exactly 20 of them. Since > you say this is your first socket server, maybe you just > haven't seen the usual techniques. > > Normally, one listener socket accepts all the connections. > Each call to accept() returns a new, independent socket for the > connection. You can then start a thread to handle the new > socket. Untested: > > > listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > listener.bind(('', 2000)) > listener.listen(5) > while True: # or some should_continue() thing > sock, _ = listener.accept() > thread.start_new_thread(service_function, (sock,)) > # Or start threads via class Threading > > > To update the GUI, you could use the Queue from the Python > library, and call wxPostEvent to tell the GUI go wake up and > check the queue. > > > -- > --Bryan From gelists at gmail.com Wed Aug 9 22:50:34 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Wed, 9 Aug 2006 23:50:34 -0300 Subject: do people really complain about significant whitespace? References: <1154986984.740638.241130@m79g2000cwm.googlegroups.com> <ebabqf$c3$1@panix2.panix.com> <mailman.9107.1155060736.27775.python-list@python.org> <2AY13sCznQ2EFw8+@objmedia.demon.co.uk> <mailman.9117.1155081436.27775.python-list@python.org> <w$3EInHMze2EFwem@objmedia.demon.co.uk> Message-ID: <ljohv0839xut.dlg@gelists.gmail.com> On 2006-08-09 11:10:20, Stephen Kellett wrote: > If you mean, should code be well written, thought about, well formatted, > sensible class/variable names, redesigned if you find a better way, sure > no problem with that. I mean the code should be written so that as few as possible comments are necessary to understand it. I don't mean that additional comments are a bad thing. Gerhard From rupole at hotmail.com Wed Aug 16 04:39:59 2006 From: rupole at hotmail.com (Roger Upole) Date: Wed, 16 Aug 2006 04:39:59 -0400 Subject: What would be the best way to run python client in the background References: <1155625271.858914.175780@m73g2000cwd.googlegroups.com> Message-ID: <1155717093_49711@sp6iad.superfeed.net> You can use the Task Scheduler to run a script at login. It's not as robust as creating a service, but it's much less work. Roger "gel" <geli at tasmail.com> wrote in message news:1155625271.858914.175780 at m73g2000cwd.googlegroups.com... > Hi > I have written a python client server app that keeps an eye on > processes starting and ending on a client and makes decision on what to > do based on information from the server end. I want to run the client > end of the app more or less invisibly (no console) on the XP clients > when ever a users logs on. What would be the best way to get this > done? A bit more info on the purpose of the app... it is to act as a > licence server, where we have a limited number of licences for software > and the software installed on all PCs. The app will only allow a pre > defined number of clients to run the software at any one time. > From fredrik at pythonware.com Sat Aug 19 01:49:41 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 19 Aug 2006 07:49:41 +0200 Subject: efficient memoize decorator? In-Reply-To: <7.0.1.0.0.20060819000545.05ae6a98@yahoo.com.ar> References: <1155931932.349283.27700@h48g2000cwc.googlegroups.com> <1155932056.313643.81420@i3g2000cwc.googlegroups.com> <7.0.1.0.0.20060819000545.05ae6a98@yahoo.com.ar> Message-ID: <ec68pl$q2r$1@sea.gmane.org> Gabriel Genellina wrote: > This implementation uses cPickle to generate a key from the supplied > function arguments, which is very slow and defeats the purpose of > memoizing. depends on the cost of recreating an object, of course. it's a bit surprising that so many programmers seem to think that there are "one size fits all" solutions to caching and memoization... </F> From rogue_pedro at yahoo.com Fri Aug 25 18:54:27 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 25 Aug 2006 15:54:27 -0700 Subject: Avoiding if..elsif statements In-Reply-To: <1156545375.962486.49540@h48g2000cwc.googlegroups.com> References: <1156545375.962486.49540@h48g2000cwc.googlegroups.com> Message-ID: <1156546466.953467.64170@p79g2000cwp.googlegroups.com> unexpected wrote: > I have a program where based on a specific value from a dictionary, I > call a different function. Currently, I've implemented a bunch of > if..elsif statements to do this, but it's gotten to be over 30 right > now and has gotten rather tedious. Is there a more efficient way to do > this? > > Code: > > value = self.dictionary.get(keyword)[0] > > if value == "something": > somethingClass.func() > elsif value == "somethingElse": > somethingElseClass.func() > elsif value == "anotherthing": > anotherthingClass.func() > elsif value == "yetanotherthing": > yetanotherthingClass.func() > > Is it possible to store these function calls in a dictionary so that I > could just call the dictionary value? Yup. dispatch = dict( something = somethingClass.func, somethingElse = somethingElseClass.func, anotherthing = anotherthingClass.func, yetanotherthing = yetanotherthingClass.func ) def default(): pass # call it like this dispatch.get(switch_value, default)() From Roberto.Bonvallet at cern.ch Thu Aug 31 07:37:48 2006 From: Roberto.Bonvallet at cern.ch (Roberto Bonvallet) Date: 31 Aug 2006 11:37:48 GMT Subject: Syntax suggestion. References: <1156954306.471779.117520@p79g2000cwp.googlegroups.com> Message-ID: <ed6hmc$ld1$1@sunnews.cern.ch> samir wrote: > Being a fond of Python, I had this idea: Why not making Python a Unix > shell? [...] > So, why not making the use of parentheses when a function is one lined > optional to have commands like this: [...] > Then, why not making the comma optional too when executing such > instructions: [...] > And finally, why not making the string parameter "-less when it is the > only parameter: ...so finally you get something that is exactly like any Unix shell, and completely different to Python. If you want Python to look like bash, work like bash and have bash-like syntax, you should really consider using bash :) -- Roberto Bonvallet From http Fri Aug 25 10:47:10 2006 From: http (Paul Rubin) Date: 25 Aug 2006 07:47:10 -0700 Subject: sum and strings References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <slrneeatf3.nbt.sybrenUSE@schuimige.stuvel.eu> <1155922208.930580.135080@m79g2000cwm.googlegroups.com> <mailman.9516.1155930431.27775.python-list@python.org> <1156365271.487489.62640@m73g2000cwd.googlegroups.com> <44ECC789.1010202@tim.thechases.com> <ecjga9$558$1@sea.gmane.org> <44EDCFDE.9060604@tim.thechases.com> <mailman.9795.1156436731.27775.python-list@python.org> <ufzHg.2868$yO7.1580@newssvr14.news.prodigy.com> Message-ID: <7xodu8j2j5.fsf@ruckus.brouhaha.com> Bryan Olson <fakeaddress at nowhere.org> writes: > And herein is the problem: A class may implement "__add__" any > way the programmer chooses. Python should require, or at least > document requirements, on further properties of addition. Python > should insist that addition be symmetric an transitive, and > classes implementing addition provide an additive identity. Are you saying "abc"+"def" should not be concatenation? I guess that's reasonable. As long as + is string concatenation though, the principle of least astonishment suggests that "sum" should conconcatenate several strings. I'm not sure what you mean by addition being symmetric or transitive; it is not an equivalence relation. Do you mean commutative and associative? I'm not sure if floating-point arithmetic has those properties, strictly speaking. From blue99 at interia.pl Thu Aug 10 07:01:51 2006 From: blue99 at interia.pl (Rob Wolfe) Date: 10 Aug 2006 04:01:51 -0700 Subject: do people really complain about significant whitespace? In-Reply-To: <mailman.9190.1155206644.27775.python-list@python.org> References: <mailman.9132.1155120873.27775.python-list@python.org> <1155134021.169710.24540@75g2000cwc.googlegroups.com> <mailman.9190.1155206644.27775.python-list@python.org> Message-ID: <1155207711.454940.89370@m73g2000cwd.googlegroups.com> Slawomir Nowaczyk wrote: > On Wed, 09 Aug 2006 07:33:41 -0700 > Rob Wolfe <blue99 at interia.pl> wrote: > > #> Slawomir Nowaczyk wrote: > #> > #> > Really, typing brace after function/if/etc should add newlines and > #> > indent code as required -- automatically. Actually, for me, it is even > #> > *less* typing in C and similar languages... I probably should teach my > #> > Emacs to automatically add newline after colon in Python, just as it > #> > does after a brace in C... As soon as I figure out how to deal with > #> > dictionary literals. Hmmm. > #> > #> Are you sure? My Emacs already know how to do it with the help > #> of python-mode and magic function py-newline-and-indent. > #> > #> emacs-version "21.3.1" > #> py-version "$Revision: 4.63 $" > > OK, my python-mode.el was older, so I upgraded to 4.75, but it still > doesn't work. Did you mean that after you write > > if x==1: > > the newline is inserted automatically when you type ":"? That's a Exactly. > functionality I would like to see, but it doesn't seem to work this > way. Here is fragment of my python-mode.el: """ The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on the indentation of preceding statements. E.g., assuming py-indent-offset is 4, after you enter \tif a > 0: \\[py-newline-and-indent] the cursor will be moved to the position of the `_' (_ is not a character in the file, it's just used here to indicate the location of the cursor): \tif a > 0: \t _ If you then enter `c = d' \\[py-newline-and-indent], the cursor will move to \tif a > 0: \t c = d \t _ Python-mode cannot know whether that's what you intended, or whether \tif a > 0: \t c = d \t_ was your intent. In general, Python-mode either reproduces the indentation of the (closest code or indenting-comment) preceding statement, or adds an extra py-indent-offset blanks if the preceding statement has `:' as its last significant (non-whitespace and non- comment) character. If the suggested indentation is too much, use \\[py-electric-backspace] to reduce it. """ Regards, Rob From mariano.difelice at gmail.com Mon Aug 21 11:47:29 2006 From: mariano.difelice at gmail.com (mardif) Date: 21 Aug 2006 08:47:29 -0700 Subject: wxPython getPosition() limit Message-ID: <1156175248.948844.131930@p79g2000cwp.googlegroups.com> Hi, I've this big problem: I've an wx.ScrolledWindow object, which contains <n> element. These elements have the event OnPaint that draw itself same objects. For drawing, each element call the method GetPosition(), which returns a tuple int. But, if I have the element 5000 that it must be designed at position x = 30 y = 40000, this object cannot be designed in this location, but on x=30, x= 32767, because GetPosition() return a INT tuple. I note that this problem doesn't exists on Unix Platform ( wxPython installed on Fedora ), but on Windows this is a disaster! Someone have any idea? thx very much From jweida at gmail.com Thu Aug 24 11:54:27 2006 From: jweida at gmail.com (Jerry) Date: 24 Aug 2006 08:54:27 -0700 Subject: telnetlib thread-safe? Message-ID: <1156434867.163326.42160@i42g2000cwa.googlegroups.com> Can anyone tell me if the telnetlib module is thread-safe? I've done some looking, but don't know, and I don't know how to tell from reading the module code. From g.brandl-nospam at gmx.net Wed Aug 30 03:57:11 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Wed, 30 Aug 2006 09:57:11 +0200 Subject: What do you want in a new web framework? In-Reply-To: <1156923758.526608.251530@b28g2000cwb.googlegroups.com> References: <1156100330.768482.326760@h48g2000cwc.googlegroups.com> <ecbrm1$l0h$1@upsn250.cri.u-psud.fr> <1156923758.526608.251530@b28g2000cwb.googlegroups.com> Message-ID: <ed3gco$er8$1@news.albasani.net> Maxim Sloyko wrote: > Laurent Pointal wrote: >> >> Look at http://wiki.python.org/moin/WebFrameworks >> >> Do you *really* need to develop a *new* framework (maybe a scholl >> exercise - it that case, KISS)? > > Isn't the main reason why there are so many of them is that all of them > suck badly? The reason is that writing one is fun in Python. Georg From simon.hibbs at gmail.com Tue Aug 1 05:50:07 2006 From: simon.hibbs at gmail.com (Simon Hibbs) Date: 1 Aug 2006 02:50:07 -0700 Subject: Borg vs. Module In-Reply-To: <mailman.8756.1154381019.27775.python-list@python.org> References: <44ce522c$0$9895$88260bb3@free.teranews.com> <mailman.8756.1154381019.27775.python-list@python.org> Message-ID: <1154425807.207468.181160@p79g2000cwp.googlegroups.com> Jordan R McCoy wrote: > For example, the Twisted framework uses this technique to allow global > access to the installed reactor via import syntax, which works well > within the framework. It did, however, throw me a bit when I first > encountered it, and drove me to pour over the source to find out what > was happening. It sounds to me like this was a case of poor code commenting in Twisted (Iv'e not looked at it myself). It seems to me this is a useful trick, but like any unusual or clever bit of coding it's use should be carefully commented to make sure it's clear to anyone coming across it. Simon Hibbs From tdelaney at avaya.com Wed Aug 9 17:33:51 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Thu, 10 Aug 2006 07:33:51 +1000 Subject: Question about using python as a scripting language Message-ID: <2773CAC687FD5F4689F526998C7E4E5F0743BC@au3010avexu1.global.avaya.com> Carl Banks wrote: > Delaney, Timothy (Tim) wrote: >> Steve Lianoglou wrote: >> >>> So, for instance, you can write: >>> my_list = eval('[1,2,3,4]') >> >> This is just asking for trouble. >> >> my_list = eval('import shutil; shutil.rmtree('/')') > > Fortunately, that won't work because eval expects an expression. > Unfortunately, this will: > > my_list = eval('__import__("shutil").rmtree("/")') Yeah - forgot the specifics in getting the point across ;) To answer the other question - when should you use eval? When the risk/reward warrants it. What is the risk of using eval (or exec) on untrusted code? Note that you *have* to decide where the line is drawn, because effectively all .py files run through the same process (not quite, but I hope you can see where I'm going). For me, the line in nearly every case is to not use eval/exec - use something else that validates - like int(). Tim Delaney From jgodoy at gmail.com Thu Aug 31 10:42:47 2006 From: jgodoy at gmail.com (Jorge Godoy) Date: Thu, 31 Aug 2006 11:42:47 -0300 Subject: Pros/Cons of Turbogears/Rails? References: <WXmIg.20772$gY6.18513@newssvr11.news.prodigy.com> <1157034321.926854.123520@m79g2000cwm.googlegroups.com> Message-ID: <87ac5l6k60.fsf@gmail.com> "Jaroslaw Zabiello" <hipertracker at gmail.com> writes: > kenneth.m.mcdonald at sbcglobal.net wrote: > >> + SqlObject allows working with the DB tables without >> using SQL itself. > > Rails has ActiveRecord ORM, which IMO has nicer and simpler > syntax than SQLObject. Rails has migrations, TB - not (Migrations is > versioning system for evolving database schema) TG supports SQL Alchemy as well. With SQL Alchemy I believe you'll have a better experience than with Rails' ORM. With regards to Migrations, SQL Object does support something like that, but you have to explicitly code it and then you can run sqlobject-admin upgrade (or the equivalente tg-admin sql upgrade, since it is a wrapper...). > But rhtml is much more flexible because it can generate *any content*, > not only xml. But Rails has THREE template systems: rhtml (main), rxml > (for rss and xml generation) and rjs (for javascript and AJAX). Well, TG has a few templating systems... MarkUp, Kid, Cheetah, ZPT, and others. You can choose the one that best fits your needs / brain. You can even have multiple template systems used depending on what was requested for the same controller... Which one is better isn't of my concern. I've already tested then and decided what I want to use. The best thing is try them and see what works. You don't have to choose only one -- but you have to use one per project to make it less messy ;-) -- Jorge Godoy <jgodoy at gmail.com> From bdesth.quelquechose at free.quelquepart.fr Wed Aug 2 13:36:30 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 02 Aug 2006 19:36:30 +0200 Subject: Using Python for my web site In-Reply-To: <pan.2006.08.01.23.30.45.679440@nothanks.org> References: <1154361480.915174.262720@b28g2000cwb.googlegroups.com> <44ce3a5c$0$18952$626a54ce@news.free.fr> <pan.2006.08.01.23.30.45.679440@nothanks.org> Message-ID: <44d0e0a3$0$32434$626a54ce@news.free.fr> Conrad a ?crit : > On Mon, 31 Jul 2006 19:14:03 +0200, Bruno Desthuilliers wrote: > > >>northband wrote: >> >>>Hi, I am interested in re-writing my website in Python vs PHP but have a >>>few questions. Here are my specs, please advise as to which >>>configuration would be best: >>> >>>1.Dell Poweredge Server, w/IIS, currently Windows but considering >>>FreeBSD >> >>I may be a bit biased, but I would not run a web server under Windows... >> > > > That's not biased Well, actually, yes it is. Definitively. <troll> To make a long story short, my opinion is that the only sensible thing to do with Windows is to wipe it out and install an OS instead. OTHO, there are surely strong objective reasons for *not* using Windows - I just don't feel like wasting my time finding them !-) </troll> From jcollett at oshtruck.com Tue Aug 15 08:42:31 2006 From: jcollett at oshtruck.com (Hoop) Date: 15 Aug 2006 05:42:31 -0700 Subject: Basic Boost.Python Question In-Reply-To: <9J6Eg.12022$rP1.2992@news-server.bigpond.net.au> References: <1155586541.415711.14950@i42g2000cwa.googlegroups.com> <9J6Eg.12022$rP1.2992@news-server.bigpond.net.au> Message-ID: <1155645751.116107.41320@i42g2000cwa.googlegroups.com> Hi Neil, I have never heard of IronPython. Do you know if you can embedd the Python interpreter ? Thanks Jeff Neil Hodgson wrote: > Hoop: > > > I am starting on an application that will developed in VS2005, probably > > using C++/CLI. > > I haven't heard any reports of Boost.Python code being compatible > with C++/CLI so you may need to add an adaptation layer. To run inside > .NET, I'd choose IronPython. > > Neil From python.list at tim.thechases.com Tue Aug 29 14:27:34 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 29 Aug 2006 13:27:34 -0500 Subject: Split with python In-Reply-To: <44F47F9E.9050404@khine.net> References: <44F47F9E.9050404@khine.net> Message-ID: <44F48716.8040301@tim.thechases.com> Norman Khine wrote: > Hello, > I have a csv file which is has a field that has something like: > > text.csv > "text (xxx)" > "text (text) (yyy)" > "text (text) (text) (zzz)" > > I would like to split the last '(text)' out and put it in a new column, > so that I get: > > new_test.csv > "text","(xxx)" > "text (text)","(yyy)" > "text (text) (text)","(zzz)" > > how can this be done? line.rsplit(None, 1) seems to do the trick for me: >>> tests=[ ... ("text (xxx)", ("text","(xxx)")), ... ("text (text) (yyy)", ("text (text)","(yyy)")), ... ("text (text) (text) (zzz)", ("text (text) (text)","(zzz)")) ... ] >>> for test, result in tests: ... r = test.rsplit(None,1) ... if r[0] <> result[0] or r[1] <> result[1]: ... print test, result ... shows that the results of rsplit() match the expected results. -tkc From PPNTWIMBXFFC at spammotel.com Wed Aug 9 06:29:01 2006 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: Wed, 09 Aug 2006 12:29:01 +0200 Subject: Looking for an intellisense with good help IDE for Python References: <1155022590.845074.256900@i42g2000cwa.googlegroups.com> Message-ID: <op.td0h2nj9c87q46@famasm> The best code completion you can get for Python is delivered by WingIDE: http://wingware.com/ I have seen, PyDev, Kommodo, Spe and when it comes to code completion for Python than nothing beats WingIDE. Maybe anyone can proof the contrary. WingIDE is not for free though (Personal: 35 USD upto Profession: 180 USD) - you can download a fully fuctional version and prolong it a few times... try it out, if you are willing to pay a few bucks. Cheers, Marco From gherron at islandtraining.com Mon Aug 21 11:38:43 2006 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 21 Aug 2006 08:38:43 -0700 Subject: Loading module via full path In-Reply-To: <nk4or3-hr4.ln1@svn2.wasy.de> References: <nk4or3-hr4.ln1@svn2.wasy.de> Message-ID: <44E9D383.7040801@islandtraining.com> Andre Poenitz wrote: > Hi all. > > Is there a way to load a module given a full path to the module > without extending sys.path first? > > Andre' > > The standard module named "imp" can help you with this. Gary Herron From sjmachin at lexicon.net Wed Aug 30 18:47:54 2006 From: sjmachin at lexicon.net (John Machin) Date: 30 Aug 2006 15:47:54 -0700 Subject: csv module strangeness. In-Reply-To: <44f6060b$0$8914$88260bb3@free.teranews.com> References: <44f5e870$0$8814$88260bb3@free.teranews.com> <mailman.10135.1156971429.27775.python-list@python.org> <44f5f347$0$8846$88260bb3@free.teranews.com> <1156976916.699378.17330@p79g2000cwp.googlegroups.com> <44f6060b$0$8914$88260bb3@free.teranews.com> Message-ID: <1156978074.034127.250510@e3g2000cwe.googlegroups.com> tobiah wrote: > > However, more generally, the docs also clearly state that "In addition > > to, or instead of, the dialect parameter, the programmer can also > > specify individual formatting parameters, which have the same names as > > the attributes defined below for the Dialect class." > > I definitely missed that. Knowing that, I don't think I will ever need the Dialect > class, but I still think that the docs for the Dialect class are broken. FWIW, I think the whole Dialect class idea is a baroque byzantine over-elaborated unnecessity that also happens to suffer from poor docs. [Exit, pursued by a bear] From kirk at strauser.com Tue Aug 1 11:22:34 2006 From: kirk at strauser.com (Kirk Strauser) Date: Tue, 01 Aug 2006 10:22:34 -0500 Subject: Finding the name of a class Message-ID: <q684q3xmd11.ln2@news.conpoint.com> Given a class: >>> class foo(object): >>> pass how can I find its name, such as: >>> b = foo >>> print something(b) 'foo' I'm writing a trace() decorator for the sake of practice, and am trying to print the name of the class that a traced method belongs to. This seems like it should be easy, but I think I've been staring at the problem too long. -- Kirk Strauser From grig.gheorghiu at gmail.com Mon Aug 7 17:57:04 2006 From: grig.gheorghiu at gmail.com (Grig Gheorghiu) Date: 7 Aug 2006 14:57:04 -0700 Subject: Python Projects Continuous Integration References: <1154087739.722910.110310@b28g2000cwb.googlegroups.com> <1154937320.090143.204600@n13g2000cwa.googlegroups.com> Message-ID: <1154987824.477543.272850@i3g2000cwc.googlegroups.com> Ziga Seilnacht wrote: > Dave Potts wrote: > > Hi, > > > > I'm just starting a development project in Python having spent time in > > the Java world. I was wondering what tool advice you could give me > > about setting up a continuous integration environment for the python > > code: get the latest source, run all the tests, package up, produce the > > docs, tag the code repository. I'm used to things like Maven and > > CruiseControl in the Java world. > > > > Cheers, > > > > Dave. > > Buildbot might be what you are looking for: > http://buildbot.sourceforge.net/ > > Hope this helps, > Ziga +1 for buildbot. It is amazingly flexible and powerful, once you get past staring at the configuration file and trying to make sense of it. Here's a blog post I wrote that can help you get started: <http://agiletesting.blogspot.com/2006/02/continuous-integration-with-buildbot.html>. Hope this helps, Grig From sjmachin at lexicon.net Wed Aug 2 09:03:01 2006 From: sjmachin at lexicon.net (John Machin) Date: 2 Aug 2006 06:03:01 -0700 Subject: Datetime objects In-Reply-To: <1154520968.852075.66140@m79g2000cwm.googlegroups.com> References: <1154519280.363058.224110@m73g2000cwd.googlegroups.com> <slrned14es.g49.sybrenUSE@schuimige.stuvel.eu> <1154520968.852075.66140@m79g2000cwm.googlegroups.com> Message-ID: <1154523780.974204.26740@m73g2000cwd.googlegroups.com> Lad wrote: > Sybren Stuvel wrote: > > Lad enlightened us with: > > > How can I find days and minutes difference between two datetime > > > objects? > > > For example If I have > > > b=datetime.datetime(2006, 8, 2, 8, 57, 28, 687000) > > > a=datetime.datetime(2006, 8, 1, 18, 19, 45, 765000) > > > > diff = b - a > > Ok, I tried > > >>> diff=b-a > >>> diff > datetime.timedelta(0, 52662, 922000) > >>> diff.min > datetime.timedelta(-999999999) Reread the manual: 1. "min" is minIMUM, not minUTES 2. You need: >>> diff.days 0 >>> diff.seconds 52662 >>> diff.microseconds 922000 >>> minutes = (diff.seconds + diff.microseconds / 1000000.0) / 60.0 >>> minutes 877.71536666666668 >>> > > > which is not good for me. > > So I tried to use toordinal like this > diff=b.toordinal()-a.toordinal() > > but I get > diff=1 > > Why? because toordinal() works only on the date part, ignoring the time part. HTH, John From sjmachin at lexicon.net Wed Aug 16 17:39:24 2006 From: sjmachin at lexicon.net (John Machin) Date: 16 Aug 2006 14:39:24 -0700 Subject: PySequence_SetItem In-Reply-To: <mailman.9442.1155763376.27775.python-list@python.org> References: <1155754847.392950.266180@h48g2000cwc.googlegroups.com> <1155755905.233229.93440@74g2000cwt.googlegroups.com> <1155761144.583994.260150@m73g2000cwd.googlegroups.com> <mailman.9442.1155763376.27775.python-list@python.org> Message-ID: <1155764364.775366.76070@i3g2000cwc.googlegroups.com> Jack Diederich wrote: > Changing the PySequence_SetItem to PyList_SetItem and dropping the > DECREF works for me too (PyList functions steal a reference). I also > tried setting the list to length 1, still no dice. The PySequence > version segs under 2.4 and 2.5. It segs even when the Int is changed > to a String. > > Yikes, I'll poke around some more. Yikes indeed. Not the OP's problem, but a bug in the manual: example in the chapter that the OP was reading acts as though the 2nd arg to PyObject_SetItem is a C int (as it is for the List and Sequence varieties) -- it is in fact a (PyObject *), which explains the SystemError that I got. Cheers, John From nicogrubert at gmail.com Thu Aug 10 05:41:43 2006 From: nicogrubert at gmail.com (Nico Grubert) Date: Thu, 10 Aug 2006 11:41:43 +0200 Subject: How to change the path for python binary? Message-ID: <44DAFF57.3080104@gmail.com> Hi there, I have installed Python 2.3.5 on Suse Linux 10. If I enter "python" in the shell, the Python 2.3.5 interpreter is called. After I installed Python 2.4.3. the Python 2.4.3 interpreter is called which is the default behaviour I guess. "which python" brings me "/usr/local/bin/python" which calls the Python 2.4.3 interpreter. My question now is: What do I have to do in order to get the Python 2.3.5 interpreter each time I enter "python" in the shell? Regards, Nico From paddy3118 at netscape.net Fri Aug 18 02:47:55 2006 From: paddy3118 at netscape.net (Paddy) Date: 17 Aug 2006 23:47:55 -0700 Subject: sum and strings Message-ID: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> I was browsing the Voidspace blog item on "Flattening Lists", and followed up on the use of sum to do the flattening. A solution was: >>> nestedList = [[1, 2], [3, 4], [5, 6]] >>> sum(nestedList,[]) [1, 2, 3, 4, 5, 6] I would not have thought of using sum in this way. When I did help(sum) the docstring was very number-centric: It went further, and precluded its use on strings: >>> help(sum) Help on built-in function sum in module __builtin__: sum(...) sum(sequence, start=0) -> value Returns the sum of a sequence of numbers (NOT strings) plus the value of parameter 'start'. When the sequence is empty, returns start. The string preclusion would not help with duck-typing (in general), so I decided to consult the ref doc on sum: sum( sequence[, start]) Sums start and the items of a sequence, from left to right, and returns the total. start defaults to 0. The sequence's items are normally numbers, and are not allowed to be strings. The fast, correct way to concatenate sequence of strings is by calling ''.join(sequence). Note that sum(range(n), m) is equivalent to reduce(operator.add, range(n), m) New in version 2.3. The above was a lot better description of sum for me, and with an inquisitive mind, I like to think that I might have come up with using sum to flatten nestedList :-) But there was still that warning about using strings. I therefore tried sum versus their reduce "equivalent" for strings: >>> import operator >>> reduce(operator.add, "ABCD".split(), '') 'ABCD' >>> sum("ABCD".split(), '') Traceback (most recent call last): File "<interactive input>", line 1, in ? TypeError: sum() can't sum strings [use ''.join(seq) instead] >>> Well, after all the above, there is a question: Why not make sum work for strings too? It would remove what seems like an arbitrary restriction and aid duck-typing. If the answer is that the sum optimisations don't work for the string datatype, then wouldn't it be better to put a trap in the sum code diverting strings to the reduce equivalent? Just a thought, - Paddy. From python.list at tim.thechases.com Tue Aug 8 11:55:41 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 08 Aug 2006 10:55:41 -0500 Subject: Tkinter module not found In-Reply-To: <t62Cg.2648$No6.52006@news.tufts.edu> References: <1155049496.292471.37020@h48g2000cwc.googlegroups.com> <t62Cg.2648$No6.52006@news.tufts.edu> Message-ID: <44D8B3FD.4070107@tim.thechases.com> > The cause of this is usually that you are using a different > version of Python than the one you installed Tkinter into, but > being a Linux newbie I have yet to discover how to redirect > the 'python' command to invoke the newer version of Python. The OS looks for the first 'python' it finds in its path. In Linux (or other *nix OSes), you can use bash> which python and it will reply with which python it's pointing to. You can then change into that directory (usually "/usr/bin") and get back a listing of various pythons. On my Debian linux distro at home, I get something back that looks like bash> which python /usr/bin/python bash> cd /usr/bin bash> ls -lsF python* | grep -o "python.*" python -> python2.3* python2.3* python2.4* You *should* be able to just relink the "python" link to the new version of python: bash> ln -sf /usr/bin/python2.4 /usr/bin/python I don't know if this will cause other problems down the line for packages that expect the system default. Alternatively, at least on my system, you can force your choice by explicity running "python2.3" or "python2.4" instead of just "python". You can determine your path via bash> echo $PATH along which your shell will search for an executable. Win32 has a similar executable search path c:\> echo %PATH% but doesn't have something as handy as the "which" command to do the hunting for you. HTH, -tkc From rosedb0 at gmail.com Tue Aug 8 16:24:35 2006 From: rosedb0 at gmail.com (hiaips) Date: 8 Aug 2006 13:24:35 -0700 Subject: newb question: file searching In-Reply-To: <1155067720.211789.208560@i42g2000cwa.googlegroups.com> References: <1155067111.892386.130610@n13g2000cwa.googlegroups.com> <1155067720.211789.208560@i42g2000cwa.googlegroups.com> Message-ID: <1155068675.101390.299110@i3g2000cwc.googlegroups.com> > jaysherby at gmail.com wrote: > > I'm new at Python and I need a little advice. Part of the script I'm > > trying to write needs to be aware of all the files of a certain > > extension in the script's path and all sub-directories. Can someone > > set me on the right path to what modules and calls to use to do that? > > You'd think that it would be a fairly simple proposition, but I can't > > find examples anywhere. Thanks. dir_name = 'mydirectory' extension = 'my extension' import os files = os.listdir(dir_name) files_with_ext = [file for file in files if file.endswith(extension)] That will only do the top level (not subdirectories), but you can use the os.walk procedure (or some of the other procedures in the os and os.path modules) to do that. --Dave From pedro.werneck at terra.com.br Mon Aug 7 20:26:16 2006 From: pedro.werneck at terra.com.br (Pedro Werneck) Date: Mon, 7 Aug 2006 21:26:16 -0300 Subject: singleton decorator In-Reply-To: <7008329d0608071633odfbf134n749c223293e3cb90@mail.gmail.com> References: <7008329d0608071633odfbf134n749c223293e3cb90@mail.gmail.com> Message-ID: <20060807212616.46fd3571.pedro.werneck@terra.com.br> On Tue, 8 Aug 2006 01:33:31 +0200 "Andre Meyer" <meyer at acm.org> wrote: > > Am I missing something here? What is the preferred pythonic way of > implementing singleton elegantly? I think the most "elegant" is with a metaclass, since I feel like a singleton is not just an ordinary type (and __init__ must be called only once)... but, as "practicality beats purity", the most pythonic way is probably using the __new__ method and inheritance. Something like this: >>> class Singleton(object): ... def __new__(cls, *args, **kwds): ... try: ... return cls._it ... except AttributeError: ... cls._it = object.__new__(cls, *args, **kwds) ... return cls._it ... >>> class A(Singleton): ... pass ... >>> x = A() >>> y = A() >>> x is y True But __init__ will be called once for each time you call A, even if it's always the same instance returned. If this is a problem, you'll need another method to use for initialization and call it only once. -- Pedro Werneck From blue99 at interia.pl Thu Aug 10 06:17:09 2006 From: blue99 at interia.pl (Rob Wolfe) Date: 10 Aug 2006 03:17:09 -0700 Subject: Advice on a TCP passthru daemon for HTTP proxy rotation In-Reply-To: <pan.2006.08.10.09.59.05.903686@digital-crocus.com> References: <pan.2006.08.10.09.59.05.903686@digital-crocus.com> Message-ID: <1155205029.386404.161840@b28g2000cwb.googlegroups.com> Robin Haswell wrote: > Hey there > > Soon we will have many squid proxies on many seperate connections for use > by our services. I want to make them available to users via a single HTTP > proxy - however, I want fine-grained control over how the squid proxies > are selected for each connection. This is so I can collect statistics, > control usage on each proxy, monitor what's going on - etc. However I > don't want to implement the HTTP proxy protocol in Python, and would > much rather let my daemon run as a man-in-the-middle for TCP, similar to > this netcat command: > > rob at aranea:~$ mknod backpipe p > rob at aranea:~$ nc -l -p 8080 < backpipe | nc ganesh 8080 > backpipe > > Basically when my daemon received a connection (call it "c1"), it makes a > connection to one of my squid proxies ("c2"), then all data which gets > read from c1 is written to c2 - all data read from c2 is written to c1. > I'm pretty sure there's an elegant way to do this but I was wondering if > anyone had any input? I've tried GIYF'ing this but it's difficult to > search for :P Maybe this is what you're looking for: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/483732 Regards, Rob From yogamatt1970 at gmail.com Tue Aug 15 10:33:42 2006 From: yogamatt1970 at gmail.com (yogamatt1970 at gmail.com) Date: 15 Aug 2006 07:33:42 -0700 Subject: Best IDE for Python In-Reply-To: <1155541849.350392.31190@h48g2000cwc.googlegroups.com> References: <1155541849.350392.31190@h48g2000cwc.googlegroups.com> Message-ID: <1155652422.017843.182790@m79g2000cwm.googlegroups.com> stylecomputers at gmail.com wrote: > Hi All, What do you find the best IDE for creating web applications in > Python is? Preferably FOS IDE. > > Cheers I like ActiveState's Komodo. It's heavyweight and not free ($30 for the personal edition) but it also supports Perl, Ruby, PHP and TCL. I started using it mostly on Windows but I've used it on Linux more recently (and it runs on Solaris and OSX now too). It has all the bells and whistles and probably won't appeal too much to hardcore emacs/vim people because it is so GUI oriented and nowhere near as fast. Also, it's text editor is similar to the ones you get with other popular IDE's like MS DevStudio and Eclipse i.e. not very powerful. I've used it extensively with Python and it handles whitespace indentation beautifully. I like that it also supports Perl because I use Perl quite a bit too. That being said, I'm going to give Wing IDE a try at some point soon. From pmartin at snakecard.com Sat Aug 19 07:35:15 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Sat, 19 Aug 2006 06:35:15 -0500 Subject: How to get the ascii code of Chinese characters? References: <1155986298.643983.157460@i3g2000cwc.googlegroups.com> Message-ID: <oTCFg.85160$LF4.74017@dukeread05> many_years_after wrote: > Hi,everyone: > > Have you any ideas? > > Say whatever you know about this. > > > thanks. Hi, You mean unicode I assume: http://www.rikai.com/library/kanjitables/kanji_codes.unicode.shtml Regards, Philippe From gagsl-py at yahoo.com.ar Wed Aug 23 10:34:16 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 23 Aug 2006 11:34:16 -0300 Subject: find, replace and save string in ascii file In-Reply-To: <1156337317.644501.120480@m73g2000cwd.googlegroups.com> References: <1156337317.644501.120480@m73g2000cwd.googlegroups.com> Message-ID: <7.0.1.0.0.20060823113249.03e89610@yahoo.com.ar> At Wednesday 23/8/2006 09:48, peter wrote: >What I did is that I can find all strings which I need, next I change >these strings based on CODE, but what I can't is to replace old string >with new one, on the same position in the file. It always writes new >string at the end of the file. Here is my code.... Better create a new file with the new contents, and then rename it. Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From john106henry at hotmail.com Wed Aug 9 17:55:22 2006 From: john106henry at hotmail.com (John Henry) Date: 9 Aug 2006 14:55:22 -0700 Subject: What's the cleanest way to compare 2 dictionary? In-Reply-To: <1155149273.270320.176030@75g2000cwc.googlegroups.com> References: <1155147450.628625.20270@m79g2000cwm.googlegroups.com> <1155149273.270320.176030@75g2000cwc.googlegroups.com> Message-ID: <1155160522.308295.254510@75g2000cwc.googlegroups.com> Paddy wrote: > John Henry wrote: > > Hi list, > > > > I am sure there are many ways of doing comparision but I like to see > > what you would do if you have 2 dictionary sets (containing lots of > > data - like 20000 keys and each key contains a dozen or so of records) > > and you want to build a list of differences about these two sets. > > > > I like to end up with 3 lists: what's in A and not in B, what's in B > > and not in A, and of course, what's in both A and B. > > > > What do you think is the cleanest way to do it? (I am sure you will > > come up with ways that astonishes me :=) ) > > > > Thanks, > I make it 4 bins: > a_exclusive_keys > b_exclusive_keys > common_keys_equal_values > common_keys_diff_values > > Something like: > > a={1:1, 2:2,3:3,4:4} > b = {2:2, 3:-3, 5:5} > keya=set(a.keys()) > keyb=set(b.keys()) > a_xclusive = keya - keyb > b_xclusive = keyb - keya > _common = keya & keyb > common_eq = set(k for k in _common if a[k] == b[k]) > common_neq = _common - common_eq > > > If you now simple set arithmatic, it should read OK. > > - Paddy. Thanks, that's very clean. Give me good reason to move up to Python 2.4. From cginboston at hotmail.com Tue Aug 29 10:58:12 2006 From: cginboston at hotmail.com (Chaz Ginger) Date: Tue, 29 Aug 2006 14:58:12 GMT Subject: refering to base classes In-Reply-To: <44F454D6.5040606@hotmail.com> References: <1156862012.068397.284040@m73g2000cwd.googlegroups.com> <44F454D6.5040606@hotmail.com> Message-ID: <44F45603.6050504@hotmail.com> Chaz Ginger wrote: > glenn wrote: >> hi - Im quite new to python, wondering if anyone can help me understand >> something about inheritance here. In this trivial example, how could I >> modify the voice method of 'dog' to call the base class 'creatures' >> voice method from with in it? >> >> class creature: >> def __init__(self): >> self.noise="" >> def voice(self): >> return "voice:" + self.noise >> >> class dog(creature): >> def __init__(self): >> self.noise="bark" >> >> def voice(self): >> print "brace your self:" >> >> thanks >> glenn >> > Try this: > > class dog(creature): > ..... > def voice(self): > print "brace your self:" > creature.voice(self) > > This should do it. I did forget to mention that in 'dog"s' __init__ you had better call creature's __init__. You might make it look like this: def __init__(self): self.noise = 'bark' creature.__init__(self) There is another approach - using Superclass - but I will leave that exercise to the reader. From dwelch91 at gmail.com Tue Aug 29 13:38:03 2006 From: dwelch91 at gmail.com (dwelch91 at gmail.com) Date: 29 Aug 2006 10:38:03 -0700 Subject: Issues with Installer written in Python for Linux Message-ID: <1156873083.035005.325410@i3g2000cwc.googlegroups.com> c.l.p- I am undertaking writing an installer for a software package using Python. It is exclusively for Linux. Because this is an installer and has to run on numerous Linux distros, it is presenting some unique challenges. First off, I have begun this project by writing a text mode only interface. I would like to provide a GUI as an alternative, but I ran into problems in my early tests. Thinking that Tkinter would be the most universal GUI framework on Linux in Python, I wrote some test screens. Well, after trying the code on several distros (Mandriva, Ubuntu, Fedora, SUSE, etc), I discovered that Tkinter is not as universal as I had thought. On about 50% of the distros, it is not installed with the system copy of Python. So much for the "standard" library! :-) So, this leaves me with the problem that I don't know what else might work. I am assuming that PyQt and PyGTK are both not preinstalled on all Linux distros. I could ship and install a package of my own if it were very small and an "easy" installation. I can't use package managers because I need to work on systems that use apt, rpm, portage, etc. Does anyone have any suggestions? My next issue is a usability issue, that really isn't strictly a Python issue, but since the members of c.l.p are some of the most intelligent and knowledgable people around, I thought I'd give it a try. My installer is part of a tarball that is subsequently wrapped up into a self extracting archive (SFX) using 'makeself'. This all works great. The user can download the SFX (which is in the form of a .run file) in a _terminal_ and the package will self extract and then run my installer. The problem is that I would like the user to be able to download the file to their desktop or whereever, and then simply doubleclick on it to make the installer execute. When I do this now, the installer refuses to run, I guess because it has no terminal to output to. So, the question is, from a Python program, can I detect that I am not running in a terminal/console and somehow get one going? (I tried playing with things like 'xterm' to force the install into a console, but, of course, xterm is missing on some distros too). Thanks, Don From sjmachin at lexicon.net Mon Aug 28 03:14:20 2006 From: sjmachin at lexicon.net (John Machin) Date: 28 Aug 2006 00:14:20 -0700 Subject: Segmentation Fault References: <1156737764.729811.297280@m79g2000cwm.googlegroups.com> Message-ID: <1156749260.014584.101590@p79g2000cwp.googlegroups.com> pycraze wrote: > I would like to ask a question. How do one handle the exception due to > Segmentation fault due to Python ? This is confusing. A seg fault kills the process immediately. No exception (in the Python sense of that word) is raised. > Our bit operations and arithmetic > manipulations are written in C Do you have a Python extension that is written in C, or are you embedding Python in a C program -- in other words, is a Python script calling a C function, or is a C program calling a Python function? > and to some of our testcases we > experiance Segmentation fault from the python libraries. What is it that you are calling "the python libraries"? Tell us the filenames of these libraries. *Show us what is output on your stderr when you experience "Segmentation fault from the python libraries".* Was this Python/C combination recently created by current personnel, or do we have a case of vanished author(s)? > > If i know how to handle the exception for Segmentation fault , it will > help me complete the run on any testcase , even if i experiance Seg > Fault due to any one or many functions in my testcase. It would also help if you told us what platform (hardware and software) that you are running on, what version of Python, and what versions of any 3rd-party Python modules/packages that may be involved. Cheers, John From fredrik at pythonware.com Fri Aug 25 18:55:19 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 26 Aug 2006 00:55:19 +0200 Subject: Don't use __slots__ (was Re: performance of dictionary lookup vs.object attributes) References: <mailman.9853.1156495094.27775.python-list@python.org><1156508104.583914.323700@b28g2000cwb.googlegroups.com><ecn1qa$ksp$1@panix2.panix.com> <1156527535.973500.247680@p79g2000cwp.googlegroups.com> Message-ID: <ecnv4p$c57$1@sea.gmane.org> bearophileHUGS at lycos.com wrote: > I think that the official python documentation has to become more like > wikipedia, where people can fix it more easely, so I can add such > warning into the text. comment away: http://pyref.infogami.com/ </F> From mail at ozzmosis.com Fri Aug 4 11:39:01 2006 From: mail at ozzmosis.com (andrew clarke) Date: Sat, 5 Aug 2006 01:39:01 +1000 Subject: Windows vs. Linux In-Reply-To: <slrned6dpm.rei.sybrenUSE@schuimige.stuvel.eu> References: <1154301694.445639.99580@m79g2000cwm.googlegroups.com> <44cddfb3$0$7761$7a628cd7@news.club-internet.fr> <e%szg.3$gY6.1@newssvr11.news.prodigy.com> <slrnecustl.dsk.sybrenUSE@schuimige.stuvel.eu> <mailman.8961.1154685680.27775.python-list@python.org> <slrned6dpm.rei.sybrenUSE@schuimige.stuvel.eu> Message-ID: <20060804153901.GA42653@ozzmosis.com> On Fri, Aug 04, 2006 at 02:01:58PM +0200, Sybren Stuvel wrote: > > OS/2 (and eComStation) also uses the backslash as the path > > separator. > > You mean OS/2 is still in actual use? 'fraid so. :-) From rubbishemail at web.de Fri Aug 25 04:43:30 2006 From: rubbishemail at web.de (rubbishemail at web.de) Date: 25 Aug 2006 01:43:30 -0700 Subject: IVI-COM (Interchangeable Virtual Instrument) Message-ID: <1156495410.833293.190090@m73g2000cwd.googlegroups.com> Hello, has anyone experience using IVI-COM drivers from python? http://adn.tm.agilent.com/index.cgi?CONTENT_ID=1919 http://ivifoundation.org/ Many thanks Daniel From hitesh287 at gmail.com Wed Aug 16 12:00:57 2006 From: hitesh287 at gmail.com (Hitesh) Date: 16 Aug 2006 09:00:57 -0700 Subject: Adding a char inside path string In-Reply-To: <mailman.9419.1155738127.27775.python-list@python.org> References: <1155737700.290268.248250@i42g2000cwa.googlegroups.com> <mailman.9419.1155738127.27775.python-list@python.org> Message-ID: <1155744057.573884.111850@m73g2000cwd.googlegroups.com> Thank you Fredrik. That works for a string. But I am getting list of tuples from DB. rows = [('\\serverName\C:\FolderName1\FolderName2\example.exe',), ('\\serverName\C:\FolderName1\FolderName2\example2.exe',), ('\\serverName\C:\FolderName1\FolderName2\example3.exe',), ('\\serverName\C:\FolderName1\FolderName2\example4.exe',)] I tried this: for i in rows: row = str(i) path = row.replace("C:" , "c$") print path I am getting path something like ('\\serverName\c$:\FolderName1\FolderName2\example.exe',) How on the earth I can remove those paranthesis? ty hj Fredrik Lundh wrote: > "Hitesh" wrote: > > > I get path strings from a DB like: > > > > \\serverName\C:\FolderName1\FolderName2\example.exe > > > > I am writing a script that can give me access to that exe file. > > But problem is that string is not universal path, I need to add C$. > > Any idea how I can add $ char in that string. > > ServerName is not fixed length. It could be any chars length. > > upath = path.replace("C:", "C$") > > </F> From grante at visi.com Tue Aug 15 15:59:10 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 15 Aug 2006 19:59:10 -0000 Subject: X windows and Python? References: <7xy7tpyhbf.fsf_-_@ruckus.brouhaha.com> <12e48tl6q5vs8fc@corp.supernews.com> Message-ID: <12e49senp0pg42d@corp.supernews.com> On 2006-08-15, Grant Edwards <grante at visi.com> wrote: >> I'd like to program my Python script to put a string into the >> X windows cut buffer. Can anyone suggest the simplest way to >> do that? > > There isn't a simple way to do that. I forgot to mention, there are actually three different selections (plus the cut buffers). Here's a nice explanation of just the selection part of the mess: http://www.msu.edu/~huntharo/xwin/docs/xwindows/selection.pdf If you want something quick and dirty, you can just use os.popen() to call xsel: http://www.niksula.hut.fi/~vherva/xsel/ xsel doesn't do the "cut buffer" thing. It obtains ownership of the selection, and then forks off a copy of itself to service requests for the selection contents. I would probably have just copied the selection to cut buffer 0 and exited, but this way works fine. -- Grant Edwards grante Yow! I will SHAVE and at buy JELL-O and bring my visi.com MARRIAGE MANUAL!! From jerome.decasteau at ksz-bcss.fgov.be Fri Aug 4 05:49:17 2006 From: jerome.decasteau at ksz-bcss.fgov.be (jdec) Date: 4 Aug 2006 02:49:17 -0700 Subject: karrigell and multi-threading In-Reply-To: <1154596119.164830.129970@i3g2000cwc.googlegroups.com> References: <1154596119.164830.129970@i3g2000cwc.googlegroups.com> Message-ID: <1154684957.548123.184690@m79g2000cwm.googlegroups.com> You have a specific discussion group for all Karrigell topics: http://groups.google.com/group/karrigell?lnk=li It's active and followed by the author of Karrigell. Shalyd wrote: > Hello, > Here is my problem :-) : > i am actually using karrigell, and i use Karrigell.py server, i have a > page running a > script (which takes around 5 min to execute), when i launch this script > (by the page) then, > i cant acces to any other page of the site until the script ends. > so i tried the karrigell-ThreadingSocketServer.py and i have the same > problem, exept that i can access the pages but they are "blank" until > the script ends. > i just want to allow different users to launch the script even if the > script isnt multi-threaded. for example, 1 launch the script, then > another launches i,t goes take a cofee and then when the first script > ends, the second is proceeded. > Any idea to solve that? > Thanks by advance :-) . From robert.kern at gmail.com Sat Aug 19 01:12:26 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 18 Aug 2006 22:12:26 -0700 Subject: couple more questions about sqlite In-Reply-To: <1155950477.783716.177870@74g2000cwt.googlegroups.com> References: <MqnFg.2703$No6.52653@news.tufts.edu> <1155930772.591854.53910@m79g2000cwm.googlegroups.com> <1rpFg.2705$No6.52662@news.tufts.edu> <1155943434.653053.232100@74g2000cwt.googlegroups.com> <44e666f9$0$12542$c3e8da3@news.astraweb.com> <1155950477.783716.177870@74g2000cwt.googlegroups.com> Message-ID: <ec66jn$mfq$1@sea.gmane.org> John Machin wrote: > John Salerno wrote: >> John Machin wrote: >> >>> Your confusion is quite understandable. I started looking at sqlite >>> when the announcement that it would be included in Python 2.5 came out. >>> Puzzlement reigned. I ended up with the following up the front of my >>> experimental module: >> So does this mean that when 2.5 is released, all I need is the built-in >> module sqlite3? > > Plus the command-line utility, which AFAICT is not included with Python > 2.5. Why? The sqlite3 module links to the library; it doesn't need a separate executable. Or is that what you meant (since one generally never installs the library without also installing the executable, too)? -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From claudio.grondi at freenet.de Mon Aug 28 14:03:07 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Mon, 28 Aug 2006 20:03:07 +0200 Subject: How to let a loop run for a while before checking for break condition? In-Reply-To: <mailman.9986.1156786167.27775.python-list@python.org> References: <mailman.9986.1156786167.27775.python-list@python.org> Message-ID: <ecvb4s$8im$1@newsreader2.netcologne.de> Sorin Schwimmer wrote: > to Fredrik Lundh > I'm afraid Claudio Grondi can't use your solution, as > he needs it hosted on Windows, which lacks > signal.alarm. > > to Claudio Grondi > How about splitting your loop in two? The first loop > would check for your boolean, which is changed by your > timer, the second loop will check for your "normal" > exit condition? I don't understand your proposal. Do you mean using another thread? I suppose, that wxPython provides something like what I am looking for, but using it only to speed up a Python loop is sure not an option. Concluding from lack of responses related to a Windows version of Fredriks solution I suppose, that there is no way to achieve it with standard Python on Windows. Claudio Grondi From Kiran.Karra at gmail.com Fri Aug 4 10:28:58 2006 From: Kiran.Karra at gmail.com (Kiran) Date: 4 Aug 2006 07:28:58 -0700 Subject: wxPython font color Message-ID: <1154701738.123713.137210@s13g2000cwa.googlegroups.com> hey everybody, i cant seem to find a way to create a font with a non-default color using the wx.Font constructor. anybody know how to change hte color? thanks From david_wahler at bic.ky Tue Aug 15 02:15:54 2006 From: david_wahler at bic.ky (david_wahler at bic.ky) Date: 15 Aug 2006 01:15:54 -0500 Subject: =?utf-8?Q?Re:_LDTP_0.5.0_released_=21=21=21?= Message-ID: <20060815061554.6496.qmail@BICSRV1011.bic.ky> I'll be out of the office until approximately August 20th. If you have any questions, please email support at bic.ky. -- David Wahler From david.bear at asu.edu Thu Aug 3 22:02:12 2006 From: david.bear at asu.edu (David Bear) Date: Thu, 03 Aug 2006 19:02:12 -0700 Subject: current recursion level Message-ID: <1226217.mpGFtGyZVl@teancum> Is there an easy way to get the current level of recursion? I don't mean sys.getrecursionlimit. I want to know during a live run of a script how many times the functions has recursed -- curses, I don't know how to say it better. -- David Bear -- let me buy your intellectual property, I want to own your thoughts -- From zxo102 at gmail.com Sun Aug 13 00:59:20 2006 From: zxo102 at gmail.com (zxo102) Date: 12 Aug 2006 21:59:20 -0700 Subject: start a multi-sockets server (a socket/per thread) with different ports but same host In-Reply-To: <mailman.9281.1155423457.27775.python-list@python.org> References: <1155404669.209725.45840@i3g2000cwc.googlegroups.com> <mailman.9281.1155423457.27775.python-list@python.org> Message-ID: <1155445160.805336.136010@i3g2000cwc.googlegroups.com> Jean-Paul, I just start to learn Twisted. Here is my simple case: I can find the data sent by clients in dataReceived but I don't know which client/which port the data is from. After I know where the data comes from, I can do different things there, for example, write them into different files via bsddb. I am not sure if it is the correct way to do it. def dataReceived(self, data): # Accumulate the new data in our list self.received.append(data) # And then echo the entire list so far back to the client self.transport.write(''.join(data)) print "============> data: ", data print " which Port? : ", self.factory.port # unforunately it is an object here. # if Port == 2001: # write the data into a file via bsddb # if Port == 2002: # write the data into another file via bsddb # etc ..... Ouyang Jean-Paul Calderone ??? > On 12 Aug 2006 10:44:29 -0700, zxo102 <zxo102 at gmail.com> wrote: > >Jean-Paul, > >Thanks a lot. The code is working. The python twisted is new to me too. > >Here are my three more questions: > >1. Since the code need to be started in a wxpyhon GUI (either by > >clicking a button or up with the GUI), do I have to run the code in a > >thread (sorry, I have not tried it yet)? > > You can try to use Twisted's wxPython integration support: > > http://twistedmatrix.com/projects/core/documentation/howto/choosing-reactor.html#auto15 > > But note the warnings about how well it is likely to work. Using a separate > thread might be the best solution. > > >2. How can I grab the client data in the code? Can you write two lines > >for that? I really appreciate that. > > I'm not sure what you mean. The data is available in the `received' attribute > of the protocol instance. Any code which needs to manipulate the data can get > that list and do whatever it likes with it. > > >3. After I change > >self.transport.write(''.join(self.data)) > > to > >self.transport.write(''.join(data)) > > and scan all the ports with the following code twice (run twice). > >First round scanning says "succefully connected". But second round > >scanning says "failed". I have to restart your demo code to make it > >work. > > I intentionally added code which shuts the server off after the first round > of connections is completed, since that seemed to be what your example > program was doing. If you don't want this, just remove the shutdown code. > > Jean-Paul From nick at craig-wood.com Thu Aug 24 05:30:03 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 24 Aug 2006 04:30:03 -0500 Subject: Can Python do Perl's print <<EOF; notation? - popen, subprocess works? References: <1156385752.859545.158280@p79g2000cwp.googlegroups.com> Message-ID: <slrneeqp4g.i90.nick@irishsea.home.craig-wood.com> yichun.wei at gmail.com <yichun.wei at gmail.com> wrote: > However, when the code in the string was actually > qsubcmds = """ > echo > cd %(cwd)s > %(cmds) %(args) > rm -f %(files)s > """ % vars() > > in which %(cmd)s folks a subprocess, when this string was write to some > pipe, e.g.: > > QSUB = Popen(qsubcmds, shell=True, stdin=PIPE) > print >> QSUB.stdin, qsubcmds > (or Popen.communicate(qsubcmds)) > > the "rm -f " was not executed in my case. Not sure why you are sending the mini shell script to itself on stdin? That doesn't seem to make sense. Come up with a simple example everyone can try and post it running in an interactive python session. Here are my attempts to replicate your problem. This runs fine... >>> from subprocess import * >>> cmds="""echo one ... echo two ... echo three ... echo four ... """ >>> >>> out = Popen(cmds, shell=True, stdin=PIPE) >>> one two three four >>> As does this using stdin >>> cmds="""read A ... read B ... read C ... echo $C $B $A""" >>> out = Popen(cmds, shell=True, stdin=PIPE) >>> out.communicate("""one ... two ... three""") three two one (None, None) >>> -- Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick From deets at nospam.web.de Wed Aug 9 07:12:46 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 09 Aug 2006 13:12:46 +0200 Subject: setup.py when you can't write to site-packages? References: <1155121231.384846.86090@i3g2000cwc.googlegroups.com> Message-ID: <4jtu9eF9mcl3U1@uni-berlin.de> andybak wrote: > There are several gaps in my Python knowledge, one of which is the what > exactly setuptools does and how it works. > > I'm on a shared host so can't write to site-packages therefore most > setup.py's fail. > > My strategy for pure python packages is to run setup.py locally and > copy anything that gets put in site-packages across to the shared host > somewhere in my Python path. I'm sure there is a better solution! > > What's the best approach for situations when you can't tamper with the > Python install? If you've got setuptools installed, you can use the development mode + a staging dir that you put in your PYTHONPATH. Then the copying is done for you. Diez From giles_brown at hotmail.com Thu Aug 31 06:51:08 2006 From: giles_brown at hotmail.com (Giles Brown) Date: 31 Aug 2006 03:51:08 -0700 Subject: How to avoid a warning message box when sending email via Outlook In-Reply-To: <mailman.10161.1157011283.27775.python-list@python.org> References: <mailman.10161.1157011283.27775.python-list@python.org> Message-ID: <1157021468.496429.165460@i3g2000cwc.googlegroups.com> Tim Golden wrote: > [Dermot Doran] > > | I'm very new to using win32com! I just want to send an email > | message via Outlook. However, I keep getting an annoying > | message box (generated by Outlook) indicating that my program > | could be a virus. Does anybody know how to get around this? > > As far as I've ever been able to tell, you're stuck with it. > Obviously, in a sense, since otherwise any would-be virus / > zombie program would simply turn the option off before using > Outlook to send out its emails! Can't remember the details, but last time I looked (a year ago) you could avoid this if you changed a setting for the user at the exchange server. I found this out by doing a bit of googling and can't remember what I did, but managed to solve the same problem. Giles From duncan.booth at invalid.invalid Wed Aug 16 15:26:24 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 Aug 2006 19:26:24 GMT Subject: It is __del__ calling twice for some instances? References: <ebvnod$mp7$1@pandora.alkar.net> Message-ID: <Xns9821CFF0D1C70duncanbooth@127.0.0.1> Max Yuzhakov wrote: > It is correct behaviour for python to call __del__ on some > identity of a class object more than once? Not with the code which you gave as an example, but in the general case yes, the only guarantee that Python gives about the __del__ method on an instance is that it will be called zero, one or more than one times during the run of the program. In practice there are various situations where __del__ will not be called, but it is only called multiple times if you resurrect the object during a call to __del__. The output from your stat function could, of course, also be generated by creating and destroying lots of foo objects in another thread. If a foo was both created and destroyed between the first two print statements, and another one was created and destroyed in the middle of the evaluation of the last print statement then you could see the output you described without any multiple __del__ calls in the same object. You should post a working code sample which generates your output if you want a more useful answer. From mensanator at aol.com Sat Aug 5 00:46:40 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 4 Aug 2006 21:46:40 -0700 Subject: Pywin32 Excel question In-Reply-To: <1154746648.811259.111460@h48g2000cwc.googlegroups.com> References: <1154746648.811259.111460@h48g2000cwc.googlegroups.com> Message-ID: <1154753200.591305.316770@i42g2000cwa.googlegroups.com> John Henry wrote: > I posted the following message to the Pywin32 list but if anybody here > can help, it would be appreciated very much. > > ============================ > Hi list, > > I have a need to copy 3 rows of data from the top of my Excel > spreadsheet to another location. I would have throught that this > should be very straightforward since I've done a fair amount of > Excel/Python programming. Unforturnately, I am stuck on this one. > > The VB Macro says I need to: > > Range("1:1,2:2,3:3").Select > Range("A3").Activate > Selection.Copy > Rows("20:20").Select > ActiveSheet.Paste > > So, I figure the Python code would be something like: > > <xlApp determined already> > 1) xlSheet=xlApp.ActiveWorkbook.ActiveSheet > 2) xlSel=xlSheet.Range("1:1,2:2,3:3").Select() > 3) #xlSel=xlSheet.Range("A3").Activate() > 4) xlSel.Copy() > 5) xlSheet.Rows("20:20").Select() > 6) xlSheet.Paste() > > Unfortunately, this doesn't work. After line 2, xlSel becomes "True" - > not a "Selection" and so the code fails at line 4). I am not sure why > I have to do the "Activate" on line 3 but it didn't matter, the code > still fails at line 4. My first guess is that the True returned in step 2 merely tells you the requested selection succeeded (the cells on the worksheet became highlighted). What would happen if you requested 500 columns? Would you get False? My second guess is that step 4 should be xlSheet.Copy() based on your using xlSheet.Paste(). For that matter, step 5 doesn't assign the result of the select to a variable. Perhaps that indicates that the assignment isn't necessary? Or maybe you should test that the selection succeeded before attempting to paste? > > > What am I doing wrong? > > Any help is greatly appreciated. > > Regards, From herrekberg at users.sf.net Mon Aug 14 11:00:29 2006 From: herrekberg at users.sf.net (Pontus Ekberg) Date: Mon, 14 Aug 2006 17:00:29 +0200 Subject: A little assistance with os.walk please. References: <1155566679.139086.279430@h48g2000cwc.googlegroups.com> Message-ID: <pan.2006.08.14.15.00.29.770993@users.sf.net> On Mon, 14 Aug 2006 07:44:39 -0700, KraftDiner wrote: > The os.walk function walks the operating systems directory tree. > > This seems to work, but I don't quite understand the tupple that is > returned... > Can someone explain please? > > for root, dirs, files in os.walk('/directory/'): > print root > # print dirs > # print files >>> print os.walk.__doc__ Directory tree generator. For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), yields a 3-tuple dirpath, dirnames, filenames dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..'). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists are just names, with no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name). If optional arg 'topdown' is true or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top down). If topdown is false, the triple for a directory is generated after the triples for all of its subdirectories (directories are generated bottom up). When topdown is true, the caller can modify the dirnames list in-place (e.g., via del or slice assignment), and walk will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, or to impose a specific order of visiting. Modifying dirnames when topdown is false is ineffective, since the directories in dirnames have already been generated by the time dirnames itself is generated. By default errors from the os.listdir() call are ignored. If optional arg 'onerror' is specified, it should be a function; it will be called with one argument, an os.error instance. It can report the error to continue with the walk, or raise the exception to abort the walk. Note that the filename is available as the filename attribute of the exception object. Caution: if you pass a relative pathname for top, don't change the current working directory between resumptions of walk. walk never changes the current directory, and assumes that the client doesn't either. Example: from os.path import join, getsize for root, dirs, files in walk('python/Lib/email'): print root, "consumes", print sum([getsize(join(root, name)) for name in files]), print "bytes in", len(files), "non-directory files" if 'CVS' in dirs: dirs.remove('CVS') # don't visit CVS directories From pavlovevidence at gmail.com Tue Aug 1 07:11:10 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 1 Aug 2006 04:11:10 -0700 Subject: Borg vs. Module References: <44ce522c$0$9895$88260bb3@free.teranews.com> Message-ID: <1154430670.389237.306540@s13g2000cwa.googlegroups.com> tobiah wrote: > I am making a web app, made up of many modules > that all need access to some important data, like > the current session data, cookies, navigation history, > post/get variables, etc. > > I decided to go with the 'Borg' idea, by assigning the > __dict__ of an object to a class variable so that each > instantiation of the Borg() would share the same data. > That way I can either pass the Borg around, or just > Borg() it if I need it in some obscure place. > > Then I read an argument that it usually makes more sense > to just have a module with the data and functions that > I need, which all the other modules can simply import. > Since I only need one instance, I could just stuff data > and call 'methods' on this module, probably without even > changing existing syntax. > > Are there any arguments as to which method is better? I would recommend a module over a Borg class simply because it's less of a hack. One thing that I never liked about using modules as classes was the constant need to use the global statement when rebinding any module level variables. For that reason, if there was a lot of rebinding, I would rewrite the module as a singleton class. That had its own problems; most significantly, it was a thorn in my side for initializing things in the right order. (My current project used lots of circular imports which made things a lot worse.) I finally lost my patience and decided to pull that thorn out by converting the singletons back to modules. That's when I came up with this little decorator that obviates the need to use global statements, plus it lets the module look and mostly act like a class. def modmethod(func): class modproxy(object): __getattribute__ = func.func_globals.__getitem__ __setattr__ = func.func_globals.__setitem__ self = modproxy() def call_with_method(*args,**kwargs): return func(self,*args,**kwargs) call_with_method.func_name = func.func_name return call_with_method This decorator means the function will get called with the module (actually a proxy) as the first argument. That way, you can access module-level variable exactly like you would access instance variables in a class, i.e., via self. I was able to convert all my singletons to modules simply by dedenting one level, and prefixing all the methods with @modmethod. This worked so sweetly it this is now my slam dunk recommendation for implementing a "global singleton" class. Carl Banks From dingbat at codesmiths.com Tue Aug 8 05:53:07 2006 From: dingbat at codesmiths.com (Andy Dingley) Date: 8 Aug 2006 02:53:07 -0700 Subject: Newbie - How to iterate list or scalar ? Message-ID: <1155030787.666942.277610@m79g2000cwm.googlegroups.com> I seem to be writing the following fragment an awful lot, and I'm sure it's not the best and Pythonic way to do things. Any advice on better coding style? pluginVersionNeeded is a parameter passed into a method and it can either be a simple scalar variable, or it can be a list of the same variables. My problem is how to iterate it, whether it's a a list or not. I can't simply throw it into the for...in loop -- if the scalar variable were to be a string (which is considered to be atomic in my application) then Python sees this string as iterable and iterates over the characters in it! versionsNeeded = pluginVersionNeeded if isinstance( versionsNeeded, list): versionsToTest = versionsNeeded else: versionsToTest = [ versionsNeeded ] for versionNeeded in versionsToTest: pass Thanks for any advice From chosechu at gmail.com Tue Aug 29 08:35:58 2006 From: chosechu at gmail.com (chosechu) Date: 29 Aug 2006 05:35:58 -0700 Subject: Extending the dict class In-Reply-To: <44f4313e$0$26985$626a54ce@news.free.fr> References: <1156852916.254032.172390@b28g2000cwb.googlegroups.com> <44f4313e$0$26985$626a54ce@news.free.fr> Message-ID: <1156854958.228815.107090@m73g2000cwd.googlegroups.com> > I'm not sure to understand why you want to do so - perhaps you could > tell more about your real use case ? Without diving into too many details: I am calling SOAPpy to build SOAP requests. When calling a proxy, named arguments are used to build up the corresponding XML like: proxy.call(alpha=1, beta=2, gamma=3) would end up like: <alpha>1</alpha> <beta>2</beta> <gamma>3</gamma> Unfortunately, since the arguments as retrieved with **k their order is lost in the call. The corresponding XML file re-arranges the parameter order randomly and the final XML request is unordered, which is not supported by a number of braindead SOAP servers (including one produced by a well-known software company I will not name here). SOAPpy cannot know in advance the argument names since they are server-dependent and SOAPpy is generic, so retrieving named arguments with **k seems like the sensible thing to do. Unfortunately this gets converted to a dict so looses all ordering when being received. Extending the base dict class to support ordering was one possible idea. > Anyway, and since it's not directly possible, a possible workaround > could be to pass a sequence of (key, value) tuples instead (possibly as > *args). This of course requires that you can modify the implementation > of myfunc(). Yes, if I could simply modify myfunc() I would have workarounds. This would mean me modifying SOAPpy and specializing it for my needs. There are other ways to implement SOAP clients anyway so no real need. Just wanted to try out some metaclass stuff. From webraviteja at gmail.com Tue Aug 8 17:36:35 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 8 Aug 2006 14:36:35 -0700 Subject: New to Python-- Help In-Reply-To: <Ql7Cg.35239$W93.15393@dukeread05> References: <3%6Cg.57$1W7.17@fe04.lga><Ql7Cg.35239$W93.15393@dukeread05> Message-ID: <1155072995.131777.85850@p79g2000cwp.googlegroups.com> Philippe Martin wrote: > John & Mary Cook wrote: > > > I just installed Python on Windows XP Pro. When I enter 'python' at the > > >>> prompt in Pythonwin IDE I get the following: > > > > Traceback (most recent call last): > > File "<interactive input>", line 1, in ? > > Name Error: name 'python' is not defined > > > > Can anyone help? > > > > Thank you, > > > > J. T. Cook > > Did you install Python, or Pythonwin ? > > Cannot use #2 without #1. He probably used ActivePython. It includes both. Besides PythonWin IDE won't start without Python :-) John: Try this tutorial. It does not assume a programming background. http://honors.montana.edu/~jjc/easytut/easytut/ You already started Python when you started PythonWin IDE. You won't need to type python in it again :-) In the tutorial I linked, PythonWin is analogous to IDLE (another IDE) mentioned in it. You should also have IDLE installed in your menus. From johnjsal at NOSPAMgmail.com Wed Aug 30 12:08:16 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 30 Aug 2006 16:08:16 GMT Subject: How ahead are you guys in the (Python) real world? In-Reply-To: <1156952585.686270.265300@m73g2000cwd.googlegroups.com> References: <1156821234.820929.299740@p79g2000cwp.googlegroups.com> <XGgJg.2715$No6.53253@news.tufts.edu> <1156952585.686270.265300@m73g2000cwd.googlegroups.com> Message-ID: <QJiJg.2716$No6.53004@news.tufts.edu> sjdevnull at yahoo.com wrote: > The real question in most production environments isn't "why not > upgrade?", it's "why upgrade?". Good way to put it. Now I'm starting to see how much of a pain it can be. :) From sjmachin at lexicon.net Thu Aug 31 05:34:56 2006 From: sjmachin at lexicon.net (John Machin) Date: 31 Aug 2006 02:34:56 -0700 Subject: how can i change the text delimiter References: <1156929540.715287.123060@h48g2000cwc.googlegroups.com> <1156938927.933389.101170@m73g2000cwd.googlegroups.com> <mailman.10106.1156939657.27775.python-list@python.org> <1157009138.684850.302570@m79g2000cwm.googlegroups.com> Message-ID: <1157016896.519900.249960@i42g2000cwa.googlegroups.com> sonald wrote: > Hi, > I am using > Python version python-2.4.1 and along with this there are other > installables > like: > 1. fastcsv-1.0.1.win32-py2.4.exe Well, you certainly didn't get that from the object-craft website -- just go and look at their download page http://www.object-craft.com.au/projects/csv/download.html -- stops dead in 2002 and the latest windows kit is a .pyd for Python 2.2. As you have already been told and as the object-craft csv home-page says, their csv was the precursor of the Python csv module. > 2. psyco-1.4.win32-py2.4.exe > 3. scite-1.63-setup.exe > > We are freshers here, joined new... and are now into handling this > module which validates the data files, which are provided in some > predefined format from the third party. > The data files are provided in the comma separated format. > > The fastcsv package is imported in the code... > import fastcsv > and > csv = fastcsv.parser(strict = 1,field_sep = ',') Aha!! Looks like some misguided person has got a copy of the object-craft code, renamed it fastcsv, and compiled it to run with Python 2.4 ... so you want some docs. The simplest thing to do is to ask it, e.g. like this, but with Python 2.4 (not 2.2) and call it fastcsv (not csv): ... command-prompt...>\python22\python Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import csv >>> help(csv.parser) Help on built-in function parser: parser(...) parser(ms_double_quote = 1, field_sep = ',', auto_clear = 1, strict = 0, quote_char = '"', escape_char = None) -> Parser Constructs a CSV parser object. ms_double_quote When True, quotes in a fields must be doubled up. field_sep Defines the character that will be used to separate fields in the CSV record. auto_clear When True, calling parse() will automatically call the clear() method if the previous call to parse() raised an exception during parsing. strict When True, the parser will raise an exception on malformed fields rather than attempting to guess the right behavior. quote_char Defines the character used to quote fields that contain the field separator or newlines. If set to None special characters will be escaped using the escape_char. ##### That's what you are looking for ##### escape_char Defines the character used to escape special characters. Only used if quote_char is None. >>> help(csv) Help on module csv: NAME csv - This module provides class for performing CSV parsing and writing. FILE SOMEWHERE\csv.pyd DESCRIPTION The CSV parser object (returned by the parser() function) supports the following methods: clear() Discards all fields parsed so far. If auto_clear is set to zero. You should call this after a parser exception. parse(string) -> list of strings Extracts fields from the (partial) CSV record in string. Trailing end of line characters are ignored, so you do not need to strip the string before passing it to the parser. If you pass more than a single line of text, a csv.Error exception will be raised. join(sequence) -> string Construct a CSV record from a sequence of fields. Non-string elements will be converted to string. Typical usage: import csv p = csv.parser() file = open('afile.csv') while 1: line = file.readline() if not line: break fields = p.parse(line) if not fields: # multi-line record continue # process the fields [snip remainder of docs] > > can u plz tell me where to find the parser function definition, (used > above) > so that if possible i can provide a parameter for > text qualifier or text separator or text delimiter.. > just as {field_sep = ','} (as given above) > > I want to handle string containing double quotes (") > but the problem is that the default text qualifier is double quote > > Now if I can change the default text qualifier... to say pipe (|) > the double quote inside the string may be ignored... > plz refer to the example given in my previous query... > It *appears* from this message that you have data already in a file, and that data is *NOT* (as some one has already told you) in standard CSV format. Let me explain: The magic spell for quoting a field in standard CSV format is: quote = '"' sep = ',' twoquotes = quote + quote if quote in fld: fld = quote + fld.replace(quote, twoquotes) + quote elif sep in fld: fld = quote + fld + quote Note carefully that if the quote character appears in the raw input data, it must be *doubled* in the output. If it is not, the standard reader can't decode the input unambiguously. If is possible that the using ms_double_quote=0 with the [fast]csv module will do the job for you. If not, it is possible, if the original data contains *pairs* of quotes e.g. -- He said "Hello" to his friend -- to decode that using a different state machine. If that's what you've got, e-mail me; I may be able to help. However the example you gave had just one quote :-( *But* are you reading or writing this data? On one hand you say that you are getting the data from a 3rd party and can't change it [which implies that you are reading] but on the other hand you want to know how to tell the [fast]csv module use a "|" as the quote character; that would be appropriate under two circumstances (1) you are reading a file that already has "pipe" as the quote character (2) you want to create a file that quotes using "pipe" ... IOW, it's not guaranteed to work for reading an existing file that uses " as the quote character. If there is a pipe character in the original data, it will fail. If (more likely) there are commas in the original data, then you will get one extra field per comma. A quick simple question: after the above csv = fastcsv.parser(.......), does it do csv.parse(.....) or csv.join(...)???? Can you see any fread() or fwrite() calls in the code??? If so, which??? HTH -- but you will have to describe what's going on a lot more precisely. Cheers, John From python.list at tim.thechases.com Mon Aug 14 15:58:19 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 14 Aug 2006 14:58:19 -0500 Subject: Memory problem In-Reply-To: <c10caf8f25daf5bd94f484eb1842f72f@stanford.edu> References: <c10caf8f25daf5bd94f484eb1842f72f@stanford.edu> Message-ID: <44E0D5DB.6000408@tim.thechases.com> > I need to read a large amount of data into a list. So I am trying to > see if I'll have any memory problem. When I do > x=range(2700*2700*3) I got the following message: > > Traceback (most recent call last): > File "<stdin>", line 1, in ? > MemoryError > > Any way to get around this problem? I have a machine of 4G memory. The > total number of data points (float) that I need to read is in the order > of 200-300 millions. While others on the list have given you options for how to accommodate this monstrosity, you've not mentioned what you intend to do with the data once you've shoveled it all into ram. Often, the easiest way to solve the problem is to prevent it from happening in the first place. Is there any way to operate on your data in a stream-oriented fashion? Or use a database filestore underneath? This would allow you to operate on a much smaller scale, and perhaps simply gather some aggregate statistics while skimming along the data stream. -tkc From apardon at forel.vub.ac.be Mon Aug 7 06:30:40 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 7 Aug 2006 10:30:40 GMT Subject: Python open a named pipe == hanging? References: <op.tdp5i6tsh12lye@cadet.mshome.net> <1hjic95.ojxkeuodeqbtN%aleax@mac.com> <op.tdrmzdd1h12lye@cadet.mshome.net> <1hjk5ng.1e8swk9u9cxwzN%aleax@mac.com> <op.tdv8dv05h12lye@cadet.mshome.net> Message-ID: <slrnede5if.a6n.apardon@rcpc42.vub.ac.be> On 2006-08-07, Rochester <rochester1976 at gmail.com> wrote: > Thanks Alex, now I think I understand much better the fifo/pipe mechanism > and how Python treats them. > > For those who are interested, I would like to restate the problem I was > tring to solve and a working solution (inspired by Alex Martelli's code), > feel free to criticize it: > > The problem: > > I have an external program which takes two matrices (two text files) as > input, and produces an output to stdout, you can take diff as an example. > I want to call this program from within Python, without writing any > temporary file (for the performance reason). > > In Bash, this task would be best written as: > > #!/bin/bash > > diff <(step1) <(step2) | step3 > > Where step1, step2 and step3 have to be independent external programs. > > Now in Python, since there is no exact equivalence of <() magic a.k.a. > process substitution, I figured taht the best solution should be to create > a pair of fifos and do something like this: > > #!/bin/bash > > mkfifo fifo1 fifo2 > step1 > fifo1 & > step2 > fifo2 & > diff step1 step2 | step3 > > And a working Python equivalent code is: I think your code only works because of an artefacts that may not work in general. > #!/usr/bin/python > > import os > > # do step1 and step2 in Python, say we end up with something like these: > > s1 = "some string\n second line." # results from step1 > s2 = "some string\n a different line." # results from step2 > > os.mkfifo('fifo1') > os.mkfifo('fifo2') > > op = os.popen(' '.join(['diff', 'fifo1', 'fifo2'])) # this step is crucial! > print >> open('fifo1', 'w'), s1 > print >> open('fifo2', 'w'), s2 This will not work in general. Suppose diff would open the two files simultaneously and read the files in parralel. Since you first feed the whole first file before you start the second, a deadlock could occur if s1 was sufficiently large. Something like the following instead of the two print statements would be better IMO (not tested): def cat(fn, st): fl = file(fn, 'w') fl.write(st) fl.close() Threading.Thread(target = cat, args = ('fifo1', s1)).start() Threading.Thread(target = cat, args = ('fifo2', s2)).start() -- Antoon Pardon From fredrik at pythonware.com Thu Aug 24 15:04:43 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Aug 2006 21:04:43 +0200 Subject: telnetlib thread-safe? In-Reply-To: <1156441749.350442.101520@i42g2000cwa.googlegroups.com> References: <1156434867.163326.42160@i42g2000cwa.googlegroups.com> <mailman.9794.1156436433.27775.python-list@python.org> <1156441749.350442.101520@i42g2000cwa.googlegroups.com> Message-ID: <eckt8a$2br$3@sea.gmane.org> Jerry wrote: >> define thread-safe. how do you plan to use it? > > I would like to write a program that spawns ~10 threads. Each thread > would get a host to connect to from a Queue object and run then do it's > thing (i.e. connecting to the host, running some commands, returning > back a success or fail based on the results). > > I just want to make sure that telnetlib is safe for this. as long as each thread uses it's own Telnet instance, that should be no problem at all (as far as I can tell). </F> From bignose+hates-spam at benfinney.id.au Mon Aug 14 05:18:56 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 14 Aug 2006 19:18:56 +1000 Subject: Best IDE for Python References: <1155541849.350392.31190@h48g2000cwc.googlegroups.com> Message-ID: <87ac67wu7z.fsf@benfinney.id.au> stylecomputers at gmail.com writes: > Hi All, What do you find the best IDE for creating web applications > in Python is? Preferably FOS IDE. I don't know what a "FOS IDE" is, but my preferred free software development environment for making web applications is: - GNU screen <URL:http://www.gnu.org/software/screen/> - Powerful editor; lately I prefer Emacs with python-mode <URL:http://www.gnu.org/software/emacs/> <URL:http://www.emacswiki.org/cgi-bin/wiki/PythonMode> - Standards-compliant browser, such as Firefox; the web developer toolbar extension is a must. <URL:http://www.mozilla.com/firefox/> <URL:http://chrispederick.com/work/webdeveloper/> Separate 'screen' windows for: - VCS interaction - Continuous unit test running - Emacs session - Python interactive session Many of the above could be in Emacs windows instead, but I already know how to work 'screen'. The wonderful part about using 'screen' as my IDE is that any of the tools can be interchanged as I like. -- \ "The WWW is exciting because Microsoft doesn't own it, and | `\ therefore, there's a tremendous amount of innovation | _o__) happening." -- Steve Jobs | Ben Finney From gelists at gmail.com Fri Aug 4 08:46:38 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Fri, 4 Aug 2006 09:46:38 -0300 Subject: How to force a thread to stop References: <mailman.8475.1153762034.27775.python-list@python.org>mailman.8528.1153845034.27775.python-list@python.org>mailman.8572.1153932090.27775.python-list@python.org><1153942270.301732.99880@h48g2000cwc.googlegroups.com><mailman.8585.1153946003.27775.python-list@python.org><7xslkoum88.fsf@ruckus.brouhaha.com><44C7E7EC.4020301@mvista.com><1lwn8bs8qhg4c.dlg@gelists.gmail.com><mailman.8597.1153960691.27775.python-list@python.org><fangc2hg3d6rmcusjqqpk8ct8v3m8eqbd8@4ax.com><mailman.8615.1154004533.27775.python-list@python.org><3sphc25or7ir5keeithpvb1k3vog39botu@4ax.com><mailman.8644.1154070822.27775.python-list@python.org><7xwt9y8916.fsf@ruckus.brouhaha.com><mailman.8655.1154092222.27775.python-list@python.org><7xvephg7yq.fsf@ruckus.brouhaha.com><mailman.8693.1154164578.27775.python-list@python.org><1hjgrs7.w01xtjt192o1N%aleax@mac .com><00ae01c6b6e5$9996ca00$03000080@hendrik> <zmj78svvh7nl.dlg@gelists.gmail.com> <00d301c6b79d$f91fd800$03000080@hendrik> Message-ID: <1s2zfko9eippw.dlg@gelists.gmail.com> On 2006-08-04 02:33:07, H J van Rooyen wrote: > The next step above the 555 is a PIC... then you can steal power from the > RS-232 line - and its a small step from "PIC" to "PIG"... I see... you obviously know what to do, if you want to :) But I'm not sure such a device alone is of much help in a typical server. I think it's probably just as common that only one service hangs. To make it useful, the trigger process has to be carefully designed, so that it actually has a chance of failing when you need it to fail. This probably requires either code changes to the various services (so that they each trigger their own watchdog) or some supervisor program that only triggers the watchdog if it receives responses from all relevant services. Gerhard From fredrik at pythonware.com Tue Aug 22 17:15:27 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Aug 2006 23:15:27 +0200 Subject: Python and STL efficiency In-Reply-To: <200608222249.35315.maric@aristote.info> References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <eccb9u$kjs$1@gemini.csx.cam.ac.uk> <1hkh28d.xscw4v1y4v9a6N%riko@despammed.com> <200608222249.35315.maric@aristote.info> Message-ID: <ecfs5g$jos$1@sea.gmane.org> Maric Michaud wrote: > The problem here, is that the strings in the set are compared by value, which > is not optimal, and I guess python compare them by adress ("s*n is s*n" has > the same complexity than "s*n == s*n" in CPython, right ?). wrong. > timeit -s"s='x'; n=1000" "s*n is n*s" 1000000 loops, best of 3: 1.9 usec per loop > timeit -s"s='x'; n=1000" "s*n == n*s" 100000 loops, best of 3: 4.5 usec per loop </F> From no at spam.com Tue Aug 29 15:41:37 2006 From: no at spam.com (John Doe) Date: Tue, 29 Aug 2006 22:41:37 +0300 Subject: Generator chaining? Message-ID: <ed259i$mvn$1@news2.netvision.net.il> This is sort of a feature request/idea: Chaining generators. If you have two lists (or tuples) and you add them, the result is a concatenation of the two. I think it would be nice if it was possible to do something similar with generators. The best way to explain is by code example: def add_generators(gen1, gen2): for x in gen1: yield x for y in gen2: yield y Just a thought... From binnyva at gmail.com Mon Aug 14 01:40:34 2006 From: binnyva at gmail.com (BinnyVA) Date: 13 Aug 2006 22:40:34 -0700 Subject: Python/Tk not working in Linux In-Reply-To: <pan.2006.08.12.07.25.34.513867@gmx.net> References: <1155354248.783487.217200@m79g2000cwm.googlegroups.com> <pan.2006.08.12.07.25.34.513867@gmx.net> Message-ID: <1155534034.779323.184130@m79g2000cwm.googlegroups.com> > Some distributions move the > `Tkinter` stuff into an own package. Search for a package called > `python-tk` or `python-tkinter` or similar. I could use a 'python-tk' package - but the problem is the latest version of python may not be available. I am going to download Tcl/Tk and install it. Then I would try to install Python once again. If that works, great. If not I will install a full 'python-tk' package. Maybe 'ActivePython'(http://www.activestate.com/Products/Download/Download.plex?id=ActivePython) like Cameron Laird have suggested. -- Binny V A http://www.bin-co.com/ - Bin-Co From lbolognini at gmail.com Mon Aug 28 05:02:12 2006 From: lbolognini at gmail.com (lbolognini at gmail.com) Date: 28 Aug 2006 02:02:12 -0700 Subject: Truly platform-independent DB access in Python? In-Reply-To: <1156748466.739709.117850@h48g2000cwc.googlegroups.com> References: <1156748466.739709.117850@h48g2000cwc.googlegroups.com> Message-ID: <1156755732.005451.170070@h48g2000cwc.googlegroups.com> bobrik wrote: > I am using the Python DB API for access to MySQL. But it is not > platform-independent - I need a module not included in Python by > default - python-mysql, and it uses a compiled binary _mysql.so. So it > is not platform-independent because for each web-server on different > platform, I would have to download it and extra compile it specifically > for that platform. Do you know of any Python solution for MySQL access > that is 100% platform-independent? Probably SqlAlchemy http://www.sqlalchemy.org/ Lorenzo From boris.dusek at gmail.com Wed Aug 23 17:56:22 2006 From: boris.dusek at gmail.com (bobrik) Date: 23 Aug 2006 14:56:22 -0700 Subject: in-memory-only file object from string Message-ID: <1156370182.719946.223220@i3g2000cwc.googlegroups.com> Hello, how to create a file object whose contents I initialize from a string and which is purely in memory? I can make a workaround like this: filecontents = "Very interesting stuff ... " file = os.tmpfile () file.write (filecontents) file.seek (0) procedure (fileobject = file) but this creates a file on harddisk. Instead I would like to use something like: filecontents = "Very interesting stuff ... " file = stringfile (filecontents) procedure (fileobject = file) Is this possible somehow? I appreciate any help. From david_wahler at bic.ky Sat Aug 12 09:42:53 2006 From: david_wahler at bic.ky (david_wahler at bic.ky) Date: 12 Aug 2006 08:42:53 -0500 Subject: =?utf-8?Q?Re:_Program_=2D_Leipzig_Python_Workshop?= Message-ID: <20060812134253.7316.qmail@BICSRV1011.bic.ky> I'll be out of the office until approximately August 20th. If you have any questions, please email support at bic.ky. -- David Wahler From nospam at domain.tld Wed Aug 30 00:17:09 2006 From: nospam at domain.tld (Stephan Kuhagen) Date: Wed, 30 Aug 2006 06:17:09 +0200 Subject: Issues with Installer written in Python for Linux References: <1156873083.035005.325410@i3g2000cwc.googlegroups.com> Message-ID: <ed33g5$dca$1@kohl.informatik.uni-bremen.de> dwelch91 at gmail.com wrote: > I am undertaking writing an installer for a software package using > Python. It is exclusively for Linux. Because this is an installer and > has to run on numerous Linux distros, it is presenting some unique > challenges. I had the same problem to solve as you, and I hope, my answer is not too offtopic to you, since I wrote the solution in Tcl/Tk. I needed the installer to work in text-mode, if no X is available and with a GUI, if X can be used. The Installer works in both modes. It is not very fancy, but allows to run additional scripts after installation, shows some info and License-Agreement, Logo and so on. The "trick" was to pack all in a single script, that first runs as a shell script, checks if Tcl is available at all (for you python), the starting up Tcl, feeding it the same file as a Tcl-Script, then checking inside of Tcl, if Tk can be loaded (for you TkInter, which is the same thing) and if so, run the GUI, otherwise run in a text-mode, which I implemented using only basic shell-commands (cat, md5sum for validity-check, bzip2, but gzip would also work, and sed, the other commands are bash-builtins) so they should be on every distro. But that part possibly can better also be implemented in python or Tcl. - If you are interested, how it works and think, it would help you, tell me. You can look at the installer at www.mevislab.de -> Downloads, take one of the Linux-Installers. If you want, I can also give you the scripts, that create such a installer. They are a little bit confused written, since they had to be finished yesterday, as ever (and laying around since, annoying me, when I look at the code). But may be they help or at least inspire you, doing the same thing but better. Regards Stephan From felipe.lessa at gmail.com Wed Aug 23 22:02:57 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Wed, 23 Aug 2006 23:02:57 -0300 Subject: range of int() type. In-Reply-To: <1156379328.244950.293210@p79g2000cwp.googlegroups.com> References: <1156368379.206968.288740@p79g2000cwp.googlegroups.com> <1156370039.116224.154430@75g2000cwc.googlegroups.com> <mailman.9747.1156372628.27775.python-list@python.org> <1156379328.244950.293210@p79g2000cwp.googlegroups.com> Message-ID: <c2701f5c0608231902w58a34ebcmc3729c52cba1bc29@mail.gmail.com> 23 Aug 2006 17:28:48 -0700, KraftDiner <bobrien18 at yahoo.com>: > This is obvious... but how do I crop off the high order bits if > necessary? > a[0]&0xFFFF ? min(a[0], 0xFFFF) ? -- Felipe. From gagsl-py at yahoo.com.ar Fri Aug 4 22:42:54 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 04 Aug 2006 23:42:54 -0300 Subject: Design Patterns in Python Message-ID: <7.0.1.0.0.20060804221618.0490dc20@softlab.com.ar> Hello Most authors talk about Java/C++, and describe patterns used as a workaround to their static class model; the dynamic nature of Python allows for trivial implementations in some cases. I've seen some design patterns examples on the ActiveState site, and some discussions some time ago on this list. But does anyone know of a complete discussion/analysis of patterns in Python? Books, articles, web pages... Unfortunately the pattern-SIG is now defunct... Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From shekhar.kaushik at gmail.com Fri Aug 4 14:47:28 2006 From: shekhar.kaushik at gmail.com (Chandrashekhar kaushik) Date: Sat, 5 Aug 2006 00:17:28 +0530 Subject: SWIG Python Extension winth C++ Problematic In-Reply-To: <17619.20741.271987.946155@montanaro.dyndns.org> References: <c56a14170608032129vde5306elbaf72cda998d70ee@mail.gmail.com> <17619.20741.271987.946155@montanaro.dyndns.org> Message-ID: <c56a14170608041147q70b3408fy87759b2dfc4bfc13@mail.gmail.com> Hi skip thanks for replying I made a small test case that fails with a similar problem This is how it looks 1. Two simple classes A and B , each holds an integer. 2. A has a function getB() that returns pointer to B. /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\\ #ifndef __AB_H__ #define __AB_H__ class B{ public: int b; B( int num = 0 ){ b = num; } ~B(){} }; class A{ public: int a; A( int a = 0 ){ this->a = a; } ~A(){} B* getB(){ B* temp = new B(a); return temp; } }; #endif __AB_H__ /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\\ The swig file is as follows %module testcase %{ #include "AB.h" %} %include "AB.h" /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\\ Compilation commands swig-1.3 -c++ -python -o swig.cc swig.i g++ -c -fPIC swig.cc -o swig.o -I /usr/local/include/python2.1/ g++ -shared swig.o -o _testcase.so /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\\ Python File from testcase import * a = A() # works fine b = B() # works fine c = a.getB() # crashes ( Segmentation Fault ) /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\\ See if you can makeout something out of that -- shekhar On 8/4/06, skip at pobox.com <skip at pobox.com> wrote: > > > >> I have been working getting my C++ code to be used in Python ( > >> Basically Extending ) This is the problem i am facing rite now. > >> > >> I have a function that returns a Pointer to a class in my C++ Code > >> > >> It looks like this > ... > >> I have used SWIG to get the Glue code. > >> > >> When i call this function ( in python ) and it eventually returns ( > >> when it gets a connection in this case ) it crashes ! I get a SEG > >> FAULT ! > >> > >> Is it some thing that cannot be done ? > > I'm certainly no SWIG expert, however: > > 1. Is your SLSocket class wrapped with SWIG? Do you maybe need a > typemap? Can you explicitly create one from Python? If so, does > that work? > > 2. What does your SWIG .i file look like? > > 3. Finally, have you tried asking on the SWIG mailing list > (swig-user at lists.sourceforge.net)? There are probably many more > SWIG > experts there than here. > > Skip > -- -- shekhar -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060805/bb7f19e8/attachment.html> From claird at lairds.us Wed Aug 9 14:30:19 2006 From: claird at lairds.us (Cameron Laird) Date: Wed, 9 Aug 2006 18:30:19 +0000 Subject: Are there any AOP project in python community? References: <1154562487.677431.274440@i3g2000cwc.googlegroups.com> <1154567742.168880.150920@h48g2000cwc.googlegroups.com> <47ufq3-37m.ln1@lairds.us> Message-ID: <r6mpq3-9ov.ln1@lairds.us> In article <47ufq3-37m.ln1 at lairds.us>, I teased: . . . >with Python. I'd emphasize that Python *needs* AOP less >than do Java and C++. I've been asked in private e-mail if I "mean that Python is aspect-oriented from its beginning." Yes. Well, yes and no. And also, I'm not sure. My personal sum- mary is that aspect orientation is largely a palliative to correct misfeatures in such object-oriented languages as Java. Python supports object orientation but doesn't require it, and practices "duck typing", so the benefits of aspect orientation are doubly marginal for Python. It's not difficult for a Python function to, say, sort a variety of different things, while Java must contrive weird containers and casts to get the right results. Java needs aspects, and Python doesn't. On the other hand, Jim Hugunin says <URL: http://www.ccs.neu.edu/research/demeter/seminar/2003/april7/Jim%20Hugunin%20(The%20Next%20Steps%20For%20Aspect-).doc > AOP is a good and even powerful thing, and I know that Jim's right about many subjects where I'm in error, so maybe I've got this one wrong, too. From robert.kern at gmail.com Mon Aug 28 03:32:50 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 28 Aug 2006 02:32:50 -0500 Subject: Pros/Cons of Turbogears/Rails? In-Reply-To: <1156748398.870837.13690@p79g2000cwp.googlegroups.com> References: <WXmIg.20772$gY6.18513@newssvr11.news.prodigy.com> <1156726071.579429.44650@b28g2000cwb.googlegroups.com> <1156740469.645955.52080__9194.07857950336$1156740696$gmane$org@i3g2000cwc.googlegroups.com> <mailman.9953.1156743738.27775.python-list@python.org> <1156748398.870837.13690@p79g2000cwp.googlegroups.com> Message-ID: <ecu672$ciu$1@sea.gmane.org> Ray wrote: > Robert Kern wrote: >> You might be. No one else in the thread is. > > What are you saying? That my perception that RoR is mature is wrong? No, that the part of your message that I quoted was wrong. Specifically, "we're talking of perception here." No one else here is talking about the perception of maturity but claims about the actual maturity. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From smeenehan at hmc.edu Thu Aug 3 23:17:40 2006 From: smeenehan at hmc.edu (smeenehan at hmc.edu) Date: 3 Aug 2006 20:17:40 -0700 Subject: Problem reading/writing files Message-ID: <1154661460.803694.241220@s13g2000cwa.googlegroups.com> This is a bit of a peculiar problem. First off, this relates to Python Challenge #12, so if you are attempting those and have yet to finish #12, as there are potential spoilers here. I have five different image files shuffled up in one big binary file. In order to view them I have to "unshuffle" the data, which means moving bytes around. Currently my approach is to read the data from the original, unshuffle as necessary, and then write to 5 different files (2 .jpgs, 2 .pngs and 1 .gif). The problem is with the read() method. If I read a byte valued as 0x00 (in hexadecimal), the read method returns a character with the value 0x20. When printed as strings, these two values look the same (null and space, respectively), but obviously this screws with the data and makes the resulting image file unreadable. I can add a simple if statement to correct this, which seems to make the .jpgs readable, but the .pngs still have errors and the .gif is corrupted, which makes me wonder if the read method is not doing this to other bytes as well. Now, the *really* peculiar thing is that I made a simple little file and used my hex editor to manually change the first byte to 0x00. When I read that byte with the read() method, it returned the correct value, which boggles me. Anyone have any idea what could be going on? Alternatively, is there a better way to shift about bytes in a non-text file without using the read() method (since returning the byte as a string seems to be what's causing the issue)? Thanks in advance! From jason at adapt.com Sun Aug 13 20:44:23 2006 From: jason at adapt.com (Jason Nordwick) Date: Sun, 13 Aug 2006 17:44:23 -0700 Subject: yet another noob question In-Reply-To: <1155492110.659011.196280@75g2000cwc.googlegroups.com> References: <1155492110.659011.196280@75g2000cwc.googlegroups.com> Message-ID: <44DFC767.1030106@adapt.com> Or without filter: from operator import add def pr(x): print x def cross(x,y): return reduce(add, [[a+b for b in y] for a in x]) x=map(pr, reduce(cross, [map(str,range(1,6))]*5)) mike_wilson1333 wrote: > I would like to generate every unique combination of numbers 1-5 in a 5 > digit number and follow each combo with a newline. So i'm looking at > generating combinations such as: (12345) , (12235), (55554) and so on. > What would be the best way to do this? So, basically i'm looking for a > list of all combinations of 1-5 in a 5 digit unique number. Also, when > I send the list to print there can't be any duplicates of the combos. > > > Thanks, > > Mike > From bj_666 at gmx.net Mon Aug 14 14:35:18 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 14 Aug 2006 20:35:18 +0200 Subject: TypeError: 'module' object is not callable (newby question) References: <yp2Eg.1858$VQ.825@trndny05> Message-ID: <pan.2006.08.14.18.35.17.483297@gmx.net> In <yp2Eg.1858$VQ.825 at trndny05>, Charles Russell wrote: > Why does this work from the python prompt, but fail from a script? > How does one make it work from a script? > > #! /usr/bin/python > import glob > # following line works from python prompt; why not in script? > files=glob.glob('*.py') > print files > > Traceback (most recent call last): > File "./glob.py", line 2, in ? > import glob > File "/home/cdr/python/glob.py", line 5, in ? > files=glob.glob('*.py') > TypeError: 'module' object is not callable Don't call your file `glob.py` because then you import this module and not the `glob` module from the standard library. Ciao, Marc 'BlackJack' Rintsch From DavidMLewis at mac.com Sat Aug 12 20:47:32 2006 From: DavidMLewis at mac.com (David Lewis) Date: Sat, 12 Aug 2006 17:47:32 -0700 Subject: Recurse Directories and process files in directory References: <1155401214.163465.235830@m79g2000cwm.googlegroups.com> Message-ID: <2006081217473216807-DavidMLewis@maccom> On 2006-08-12 09:46:54 -0700, "KraftDiner" <bobrien18 at yahoo.com> said: > Hi I need help writing a python script that traverses (recursivly) a > directory and its sub directories and processes all files in the > directory. In addition to os.walk, I find Jason Orendorff's 'path' module very helpful and much easier to use. You can get at <http://www.jorendorff.com/articles/python/path/>. With it, for instance, processing all the C source files in a directory, recursively, would look like: theDir = path('pathToDir') for theFile in theDir.walkFiles('*.c'): # Do something Best, David From gelists at gmail.com Sun Aug 20 08:43:23 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Sun, 20 Aug 2006 09:43:23 -0300 Subject: How to get the ascii code of Chinese characters? References: <1155986298.643983.157460@i3g2000cwc.googlegroups.com> <1155990488.395220.178810@74g2000cwt.googlegroups.com> <1155999554.486951.303480@i42g2000cwa.googlegroups.com> <pan.2006.08.19.15.42.29.167353@gmx.net> <mailman.9552.1156006565.27775.python-list@python.org> <ec7qac$3ra$1@online.de> <yj9yy3dk3293$.dlg@gelists.gmail.com> <ec9834$356$1@sea.gmane.org> Message-ID: <1qmwgpkqdo3wg.dlg@gelists.gmail.com> On 2006-08-20 05:56:05, Fredrik Lundh wrote: >>> No. ASCII characters range is 0..127 while Unicode characters range is >>> at least 0..65535. >> >> Actually, Unicode goes beyond 65535. > > you may want to look up "at least" in a dictionary. As a homework, try to parse "at least until" and "goes beyond" and compare the two (a dictionary is not necessarily of help with this :) "range is least 0..65535" : upper_bound >= 65535 "goes beyond 65535" : upper_bound > 65535 For some discussions (like how to represent code points etc) this distinction is crucial. Gerhard From gerard.blais at gmail.com Wed Aug 2 13:17:28 2006 From: gerard.blais at gmail.com (Gerry Blais) Date: Wed, 02 Aug 2006 13:17:28 -0400 Subject: Newbie Cygwin Q References: <bvl1d21ndlfsk9ce4lst3lqo47lkq2j4j1@4ax.com> Message-ID: <ifn1d2l54hq9tcinv1i1ft54spcqaueju8@4ax.com> Sorry - problem solved. My #!/usr/Pyrthon2.4.exe was inadvertently on line 2... Gerry On Wed, 02 Aug 2006 13:04:10 -0400, Gerry Blais <gerard.blais at gmail.com> wrote: >I'm trying to install and run, on XP, a queueing analysis package, >PDQ, which has a{ Python, swig, C library version}. > >I'm new to Cygwin (but not to Unix). > >After installing Cygwin and Python, there is a Python2.4.exe in /lib. > >If I have a file with > >#!/lib/Python2.4.exe > >Print "hello" > >and I do the chmod, and submit ./hello.py > >I get a message "hello.py is currently being printed" and nothing >happens, until I give up and ^C out. > >or, now, with no changes I can see, > >Can't find file hello > >What am I missing? > >Thanks, > >Gerry From wirecom at wirelessmeasurement.com Thu Aug 10 06:26:17 2006 From: wirecom at wirelessmeasurement.com (wirecom at wirelessmeasurement.com) Date: Thu, 10 Aug 2006 11:26:17 +0100 (BST) Subject: (newbie) Float() and high precision Message-ID: <51301.149.254.200.215.1155205577.squirrel@www.wirelessmeasurement.com> What's the best way to do higher precision maths than the standard Float()? From anthra.norell at tiscalinet.ch Sat Aug 26 04:38:35 2006 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Sat, 26 Aug 2006 10:38:35 +0200 Subject: Taking data from a text file to parse html page References: <1156378275.662140.214650@h48g2000cwc.googlegroups.com><1156473610.654066.323410@p79g2000cwp.googlegroups.com><mailman.9887.1156535934.27775.python-list@python.org> <1156564037.135087.48890@i42g2000cwa.googlegroups.com> Message-ID: <014f01c6c8eb$06a6c3e0$0201a8c0@mcuf7> No, I am not running Linux to any extent. But I am very strict about case. There is not a single instance of "se.py" or "sel.py" anywhere on my system. You' ll have to find out where lower case sneaks in on yours. The zip file preserves case and in the zip file the names are upper case. I am baffled. But I believe that an import tripping up on the wrong case can't be a hard nut to crack. Frederic ----- Original Message ----- From: "DH" <dylanhughes at gmail.com> Newsgroups: comp.lang.python To: <python-list at python.org> Sent: Saturday, August 26, 2006 5:47 AM Subject: Re: Taking data from a text file to parse html page > Yes I know how to import modules... I think I found the problem, Linux > handles upper and lower case differently, so for some reason you can't > import SE but if you rename it to se it gives you the error that it > can't find SEL which if you rename it will complain that that SEL isn't > defined... Are you running Linux? Have you tested it with Linux? > From diffuser78 at gmail.com Fri Aug 11 15:21:57 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 11 Aug 2006 12:21:57 -0700 Subject: How to write a Installer for a Python App in Linux In-Reply-To: <12dpgp2o5gjh07d@corp.supernews.com> References: <1155240625.157696.143230@i42g2000cwa.googlegroups.com> <slrnedn60g.n0d.sybrenUSE@schuimige.stuvel.eu> <1155316580.905203.245070@b28g2000cwb.googlegroups.com> <12dpgp2o5gjh07d@corp.supernews.com> Message-ID: <1155324117.748289.53080@h48g2000cwc.googlegroups.com> Has anybody written a file for cx_freeze. I am running Ubuntu Linux and downloaded version for Python2.4. When I run it I get an error saying that I dont have GLIBC_2.4. I couldnt find this in Synaptic too. Any clues ? From paddy3118 at netscape.net Mon Aug 21 08:04:37 2006 From: paddy3118 at netscape.net (Paddy) Date: 21 Aug 2006 05:04:37 -0700 Subject: Regular Expression question In-Reply-To: <1156153916.849933.178790@75g2000cwc.googlegroups.com> References: <1156153916.849933.178790@75g2000cwc.googlegroups.com> Message-ID: <1156161877.614943.97890@m79g2000cwm.googlegroups.com> stevebread at yahoo.com wrote: > Hi, I am having some difficulty trying to create a regular expression. Steve, I find this tool is great for debugging regular expressions. http://kodos.sourceforge.net/ Just put some sample text in one window, your trial RE in another, and Kodos displays a wealth of information on what matches. Try it. - Paddy. From carsten at uniqsys.com Tue Aug 22 14:13:29 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 22 Aug 2006 14:13:29 -0400 Subject: how do you get the name of a dictionary? In-Reply-To: <1156264475.968894.221710@p79g2000cwp.googlegroups.com> References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <pan.2006.08.21.03.33.27.84160@REMOVEME.cybersource.com.au> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> <mailman.9631.1156227418.27775.python-list@python.org> <1156264475.968894.221710@p79g2000cwp.googlegroups.com> Message-ID: <1156270409.8427.44.camel@dot.uniqsys.com> On Tue, 2006-08-22 at 12:34, jojoba wrote: > Hello again, > > Fredrick said: > > > Python's object model. an object has a value, a type, and an identity, > > but no name. > > I say: > > Thank you Fredrick for the reply! > However, although python's object model does not currently support what > i am asking for, how difficult would it be to assign a string name(s) > to an object upon creation (and upon referencing)? > > please note: > i don't want to do anything sophisticated with this, i am really only > looking for a TITLE for my dictionary when i throw it in a tree editor > that i have built. And i do realize that its not possible now. I am > just pressing a point here. At the risk of stating the obvious, why don't you simply add a parameter for the title in the invocation of the tree editor? I.e. instead of invoke_tree_editor(somedict) do invoke_tree_editor(somedict, "somedict") HTH, Carsten. From faulkner612 at comcast.net Wed Aug 23 14:22:04 2006 From: faulkner612 at comcast.net (faulkner) Date: 23 Aug 2006 11:22:04 -0700 Subject: callable to disappear? In-Reply-To: <slrneeopqs.a7l.apardon@rcpc42.vub.ac.be> References: <slrneeopqs.a7l.apardon@rcpc42.vub.ac.be> Message-ID: <1156357324.838315.234500@i42g2000cwa.googlegroups.com> what's wrong with hasattr(obj, '__call__')? Antoon Pardon wrote: > I have been reading http://www.python.org/dev/peps/pep-3100/ > en there is written: > > To be removed: > ... > > callable(): just call the object and catch the exception > > ... > > But that doesn't seem to be a generally available option. > The place where you want to check if something is callable > doens't need to be the place where you actually want to call > it. Removing callable will mean that you can't check whether > or not something is callable without incurring the side-effects > of calling it. > > I also think code will become more ugly > > How do you suggest I would code the following: > > if callable(func): > for i, el in lst: > lst[i] = func(el) > othercode() > > > I can code as follows: > > try: > for i, el in lst: > lst[i] = func(el) > othercode() > except TypeError: > pass > > > But this has the problem that othercode could throw a TypeError: > > So it seems I would need at least two try statements > > try: > for i, el in lst: > try: > lst[i] = func(el) > except TypeError > raise LoopBreak > othercode() > except LoopBreak: > pass > > And this still has problems because the TypeError could be > raised because lst is an unsubscriptable object. > > > Is there a chance this will be reconsidered? > > -- > Antoon Pardon From ray_usenet at yahoo.com Mon Aug 28 02:59:58 2006 From: ray_usenet at yahoo.com (Ray) Date: 27 Aug 2006 23:59:58 -0700 Subject: Pros/Cons of Turbogears/Rails? In-Reply-To: <mailman.9953.1156743738.27775.python-list@python.org> References: <WXmIg.20772$gY6.18513@newssvr11.news.prodigy.com> <1156726071.579429.44650@b28g2000cwb.googlegroups.com> <1156740469.645955.52080__9194.07857950336$1156740696$gmane$org@i3g2000cwc.googlegroups.com> <mailman.9953.1156743738.27775.python-list@python.org> Message-ID: <1156748398.870837.13690@p79g2000cwp.googlegroups.com> Robert Kern wrote: > You might be. No one else in the thread is. What are you saying? That my perception that RoR is mature is wrong? I never even said that was mine. That was what I got from talking to a lot of developers whose main language is neither Python nor Ruby, while I was trying to introduce Python to them. I've always been enthusiastic about Python and think it'd be nice for a change to be able to work with it in a project at work instead of at home. And yes, no one else in this thread, which consists of 6 posts so far, says so, so how is it even relevant to how other developers perceive RoR in comparison with Django or Turbogears? You're not making any sense here. > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it had > an underlying truth." > -- Umberto Eco From python.list at tim.thechases.com Fri Aug 11 11:24:06 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 11 Aug 2006 10:24:06 -0500 Subject: Tab delimited file In-Reply-To: <000f01c6bd54$4b514e40$6501a8c0@mshome> References: <000f01c6bd54$4b514e40$6501a8c0@mshome> Message-ID: <44DCA116.8080605@tim.thechases.com> > However as far as I know Python does not allow you to easily change a > specific line in a text file. You have to place the whole file to memory, > change what you need to and then write the file back after deleting the > previous information. > > Assuming this is true, how do i find where the tabs are in the file so that > I can distinguish between the different criteria? Well, I usually just use something like NAME = 0 RATING = 1 SIZE = 2 OCCURS = 3 name = 'foo' out = file('output.txt', 'w') for line in file('input.txt'): line = line.rstrip('\n') items = line.split('\t') # do something with items: if name in items[NAME].lower(): items[RATING] = str(int(items[RATING]) + 1) out.write('\t'.join(items)) out.write('\n') which will loop through each line, incrementing the RATING field (assuming it's numeric?) where the NAME field contains 'foo'; then writing the resulting stuff back out to the output file. -tkc From mail at microcorp.co.za Thu Aug 3 03:18:41 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Thu, 3 Aug 2006 09:18:41 +0200 Subject: Is there an obvious way to do this in python? References: <mailman.8853.1154537129.27775.python-list@python.org> <44d128e5$0$13484$636a55ce@news.free.fr> Message-ID: <017001c6b6cd$308f81e0$03000080@hendrik> "Bruno Desthuilliers" <bdesth.quelquechose at free.quelquepart.fr> wrote: |H J van Rooyen a ?crit : |> Hi, |> |> I want to write a small system that is transaction based. |> |> I want to split the GUI front end data entry away from the file handling and |> record keeping. |> |> Now it seems almost trivially easy using the sockets module to communicate |> between machines on the same LAN, so that I want to do the record keeping on one |> machine. |> |> I want to keep the "server" machine as simple as possible - just doing record |> keeping on a stimulus response basis - I would prefer it to do one thing at a |> time to completion because this style of operation, though limited in |> performance, keeps a lot of hassles out of life - a transaction has either |> completed, or it has not - recovery scenarios are relatively easy... | |IOW, you want a SQL DBMS. May I recommand PostgreSQL ? | Looks like the way to go - after the argy bargy here in another thread seems mySQL has no supporters left... |> Up to this point, I don't have a problem - my toy system can create a dummy |> transaction, and I can echo it from the "server" machine, with more than one |> "user" machine running - so I think it is feasible to have several tens of "data |> entry terminal" systems running, served by one not very strong machine. |> |> Now what I would really like to do is to differentiate between the 'User" |> machines, so that some can do a full range of transactions, and others a limited |> range. | |Any decent SQL DBMS is able to handle this. It's kind of builtin... Yes - if you do the whole job on the server - the architecture I have mind is more like a banking terminal scenario - please see my reply to Simon | |> And I would like to make this flexible, so that it becomes easy to introduce new |> transactions, without having to run around updating the code in all the user |> machines, with the concomitant version number hassles. | |Then you want a web front end. This seems to me to assume that the server does all the work | |> And I would like to do the whole thing in python | |You'll at least need bits of SQL (but SQLAlchemy may hide away most of |it) and HTML (but there are some python packages that knows how to build |HTML from declarative Python code). | that is good news - which packages? |> - so my question is this - is |> it possible to do the equivalent of dynamic linking? - i.e. if I keep a list of |> what a user is allowed to do | |In SQL : GRANT/REVOKE again - centric thinking - I really would like to change the bits on the client, as I explained to Simon | |> - can I somehow send him just the bits he needs to |> do the job, without having to change the static code on his machine? | |HTTP/HTML. | everybody says this - I am being dragged, kicking and screaming... |> - it seems |> to me that the eval() thingy could possibly do this for me, | |Err... I thought you wanted a reasonnably secure system, but I may have |misunderstood. | this is the guts of what I want - if eval is NFG then how do I implement such a kind of "dynamic linking" of modules on the client? |> by sending it data |> that makes it do import statements followed by calls to whatever... - will this |> work, or is there a better way? |> |> Or has all this been done already? | |Yes, it's called a web frontend for a SQL DBMS. There's no shortage of |Python frameworks to do this kind of things. | I kind of wanted to avoid the web based stuff - the application data is so small and trivial, in a sense. |> - and no I don't want a web server | |If you don't want Apache, there are Python-based application servers. |CherryPy comes to mind. | |> and php | |Why PHP ? | seems popular |> and browsers and Java | |Why Java ? | it addresses what I want - to dynamically and securely download bits of code and execute them on the remote machine... |> and html or xml... - I want to write something that works |> simply and reliably | |We do write SQL-based web apps all day long, and I can tell you they are |certainly more simple and reliable than whatever eval()-based home-made |solution we could imagine !-) Aah! but I would like you to stretch that imagination - to tell me how to do some of what Java was designed to do, but better and easier, because this is python we are talking about... I saw something in another thread here - they were talking about weave - can I use that if eval is nfg? If my original post was unclear I am sorry - the point I want answered, if possible, is how to make the client code effectively updateable on the fly - because the answer to this will influence the whole design of the rest of the system... - Hendrik From hongqn at gmail.com Fri Aug 25 01:37:01 2006 From: hongqn at gmail.com (Qiangning Hong) Date: Fri, 25 Aug 2006 13:37:01 +0800 Subject: Is this a good idea or a waste of time? In-Reply-To: <1156478029.202195.69550@p79g2000cwp.googlegroups.com> References: <1156449402.022781.292840@p79g2000cwp.googlegroups.com> <1156478029.202195.69550@p79g2000cwp.googlegroups.com> Message-ID: <b64ef0ce0608242237l5703d492t6d4c4983026b68aa@mail.gmail.com> On 24 Aug 2006 20:53:49 -0700, sjdevnull at yahoo.com <sjdevnull at yahoo.com> wrote: > That's bad form. If you insist on doing something like this, at least > use "isinstance(a, str)" instead of typeof. But even that breaks duck > typing; if a is a unicode string, that'll fail when the function may > work fine for unicode strings. To check both str and unicode, you could use "isinstance(a, basestring)". From aleax at mac.com Wed Aug 2 21:58:17 2006 From: aleax at mac.com (Alex Martelli) Date: Wed, 2 Aug 2006 18:58:17 -0700 Subject: function v. method References: <1153199618.435747.162950@i42g2000cwa.googlegroups.com> <44bc9de9$0$24602$626a54ce@news.free.fr> <1153359804.284999.252840@s13g2000cwa.googlegroups.com> <1153448634.727066.82620@m79g2000cwm.googlegroups.com> <slrnec1c6g.9ek.apardon@rcpc42.vub.ac.be> <1153510567.102175.210420@s13g2000cwa.googlegroups.com> <slrnec6d1f.h6r.apardon@rcpc42.vub.ac.be> <1153758523.757935.320080@b28g2000cwb.googlegroups.com> <eec9f8ee0607250116g7859c6fdm4483a9040335247@mail.gmail.com> <mailman.8524.1153834518.27775.python-list@python.org> Message-ID: <1hjghjt.fct7tddfohj4N%aleax@mac.com> Gerhard Fiedler <gelists at gmail.com> wrote: > On 2006-07-25 05:16:04, Wesley Brooks wrote: > > >> prefix your names with _ or __. Both are ommited from autogenerated > >> docuementation and both are OFFICALLY not supposed to be used. > >> > > > > Could you elaborate on that a little or point me in the right direction to > > read up on it? I'm currently re-writing a large lump of my coding and trying > > to use best practice. I thought it was considered good practice to make > > stuff private (in this case using __ ) that wasn't intened to be accessed > > from outside the function/class? > > I think fuzzylollipop meant that such members should not be used from the > outside of the class; that is, they should be considered implementation, > not API. (Which is why apparently autogenerated docs leave them out.) Unfortunately, there is a slight ambiguity here. Consider for example the wonderful Queue class. Its methods _put, _get are not documented in help(Queue.Queue) nor on <http://docs.python.org/lib/QueueObjects.html>, respecting the "private" convention. But if you read Queue.py, you'll see...: # Override these methods to implement other queue organizations # (e.g. stack or priority queue). # These will only be called with appropriate locks held ... # Put a new item in the queue def _put(self, item): ... etc -- i.e., Queue.py itself strongly appears to consider these methods *protected* (in C++ parlance), NOT *private*. Indeed, the only reason these methods are factored out is exactly as "hook methods" (meant to be overridden by subclasses), in a beautiful example of the "Template Method" design pattern (in the specific variant in which the methods MAY but DON'T HAVE TO be overridden, because the base class, Queue.Queue, already provides them with useful functionality -- a LIFO queue). Unfortunately Python does not have any specific naming convention to indicate "methods that should never be CALLED by client code, but may be usefully OVERRIDDEN in subclasses", so the leading-underscore one does double duty -- and since the simpler interpretation "this is a private implementation detail, ignore it completely" is so much more common than the one about "this is a hook method which you should override in a subclass if you want to tweak some detail of functionality", it's all too easy to forget about the latter case (fortunately Queue.Queue is there to remind us of it:-). Alex From kirk at strauser.com Tue Aug 1 11:56:52 2006 From: kirk at strauser.com (Kirk Strauser) Date: Tue, 01 Aug 2006 10:56:52 -0500 Subject: Finding the name of a class References: <q684q3xmd11.ln2@news.conpoint.com> <44CF7569.9020509@websafe.com> Message-ID: <57a4q3xgf21.ln2@news.conpoint.com> Larry Bates wrote: > print print b.__class__.__name__ gives what you want That doesn't seem to do it, though. Here's the result of importing a module from my company's internally-developed library: >>> from Daycos.TableCopier.copyfro import StateProcessor >>> print StateProcessor.__class__.__name__ type I'm looking for something that would print 'StateProcessor' but am not having much luck. -- Kirk Strauser From rzantow at gmail.com Mon Aug 7 07:18:11 2006 From: rzantow at gmail.com (Rick Zantow) Date: Mon, 07 Aug 2006 07:18:11 -0400 Subject: Proposal: [... for ... while cond(x)] References: <1154879331.903490.106020@m73g2000cwd.googlegroups.com> <Xns9817B24E36816duncanbooth@127.0.0.1> <1154886383.696899.171490@i3g2000cwc.googlegroups.com> <Xns9817CB6E2A9DEduncanbooth@127.0.0.1> <4jnfq5F8qvauU1@uni-berlin.de> <Xns981854A828521duncanbooth@127.0.0.1> Message-ID: <Xns98184A4AC62ABrzed@208.49.80.253> Duncan Booth <duncan.booth at invalid.invalid> wrote in news:Xns981854A828521duncanbooth at 127.0.0.1: > Diez B. Roggisch wrote: > >>> No, the list comprehension lets you write an expression directly >>> avoiding a function call, and it also allows you to add in a >>> condition which can be used to filer the sequence. Your proposal adds >>> nothing. >> >> It does. Consider this: >> >> whatever = [x for x in xrange(1000000000) while x < 10] >> >> >> That would run only in a splitsecond of what the whole listcomp would. > > Except that the comparable listcomp today is: > > whatever = [x for x in takewhile(lambda x: x < 10, xrange (1000000000))] > > which also runs in a split second. > > Actually, the OP was correct, it does add something: it removes the need > for a function or lambda in the takewhile just as the original listcomp > removes a function or lambda compared with the map version. > Consider how it would be if the situation were reversed, and whatever = [x for x in xrange(1000000000) while x < 10] was the convention today. What advantage would there be to replacing it with whatever = [x for x in takewhile(lambda x: x < 10, xrange(1000000000))]? As a newcomer to Python, I'd find the first syntax far more readily graspable, and I'd have to wonder why I'd ever need takewhile and lambda just to do what appears to be straightforward conditioning of a loop. I'm not a newcomer to Python, and I wonder about that anyway. I also note this, using Python 2.4.2 on win32: >>> whatever = [x for x in takewhile(lambda x: x < 10, xrange (1000000000))] Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name 'takewhile' is not defined So in addition to the two functions, I need an import statement. It looks like the argument can certainly be made that simplifying the syntax and lightening the call load bring some advantage to the table. There are other arguments to be made against the proposed syntax, I'm sure. -- rzed From michiel at thingmajig.org Thu Aug 10 10:46:28 2006 From: michiel at thingmajig.org (Michiel Sikma) Date: Thu, 10 Aug 2006 16:46:28 +0200 Subject: (newbie) Float() and high precision In-Reply-To: <51301.149.254.200.215.1155205577.squirrel@www.wirelessmeasurement.com> References: <51301.149.254.200.215.1155205577.squirrel@www.wirelessmeasurement.com> Message-ID: <B6081CC9-1E6D-4C3E-9660-B7CE3F9DBFB9@thingmajig.org> Op 10-aug-2006, om 12:26 heeft wirecom at wirelessmeasurement.com het volgende geschreven: > What's the best way to do higher precision maths than the standard > Float()? > > > -- > http://mail.python.org/mailman/listinfo/python-list You know, I don't usually answer questions like the gurus of this mailing list/newsgroup do, but I think that most would agree that it would be kind of nice if you could take the time to say hi and thanks... Michiel From hipertracker at gmail.com Thu Aug 31 12:43:47 2006 From: hipertracker at gmail.com (Jaroslaw Zabiello) Date: Thu, 31 Aug 2006 17:43:47 +0100 Subject: Pros/Cons of Turbogears/Rails? References: <WXmIg.20772$gY6.18513@newssvr11.news.prodigy.com> <1157034321.926854.123520@m79g2000cwm.googlegroups.com> <87ac5l6k60.fsf@gmail.com> Message-ID: <1kewrlxsm0s0z.1wwd5xt4meia.dlg@40tude.net> On Thu, 31 Aug 2006 11:42:47 -0300, Jorge Godoy wrote: > TG supports SQL Alchemy as well. With SQL Alchemy I believe you'll have a > better experience than with Rails' ORM. I would not be so sure. I have tried to work with SQL Alchemy (using Pylons) and I have been disappointed. :( It's syntax for selects is ugly and not intuitive. Django ORM looks much better. SQLAlchemy has to be added to Django as alternative ORM but *without breaking* current, clean API: http://groups.google.com/group/django-developers/browse_thread/thread/5149e1c60dc65bff/a177bb34cfde1ec7 >> But rhtml is much more flexible because it can generate *any content*, >> not only xml. But Rails has THREE template systems: rhtml (main), rxml >> (for rss and xml generation) and rjs (for javascript and AJAX). > > Well, TG has a few templating systems... MarkUp, Kid, Cheetah, ZPT, and > others. You can choose the one that best fits your needs / brain. This is another topic. Rails can also use another third-party template system (like Liquid which was inspired by Django). For me using many, different template systems *for the same task* make no sense. Rails uses three templates, but for *different tasks*. Its RJS is perfect for AJAX. Really cool, simple, and almost no javascript is required. Just clean Ruby for everything. -- Jaros?aw Zabie??o http://blog.zabiello.com From jspeis at gmail.com Tue Aug 8 17:56:30 2006 From: jspeis at gmail.com (Jon) Date: 8 Aug 2006 14:56:30 -0700 Subject: Open file handles? In-Reply-To: <PvmdnW7gW8hCn0TZnZ2dnUVZ_oSdnZ2d@telcove.net> References: <PvmdnW7gW8hCn0TZnZ2dnUVZ_oSdnZ2d@telcove.net> Message-ID: <1155074190.804203.173840@b28g2000cwb.googlegroups.com> Perhaps using os you could work with lsof [http://www.linuxcommand.org/man_pages/lsof8.html] Jon Thomas Bartkus wrote: > This may be more of a Linux question, but I'm doing this from Python. ..... > > How can I know if anything (I don't care who or what!) is in the middle of > using a particular file? > > This comes in context of needing to copy a file BUT only if I can verify > that something else doesn't have an open write handle to that file. IOW - I > need to decline the operation if something else hasn't finished writing to > the file. > > How can I know? > Thomas Bartkus From http Sat Aug 26 15:35:16 2006 From: http (Paul Rubin) Date: 26 Aug 2006 12:35:16 -0700 Subject: random writing access to a file in Python References: <ecn00i$t2o$1@newsreader2.netcologne.de> <mailman.9872.1156515341.27775.python-list@python.org> <ecn22h$3o5$1@newsreader2.netcologne.de> <5a9ue2lrjh214ecmme09fsodhm3ico1ntm@4ax.com> <ecno4v$h11$1@newsreader2.netcologne.de> Message-ID: <7xhczzqoi3.fsf@ruckus.brouhaha.com> Claudio Grondi <claudio.grondi at freenet.de> writes: > Is there a ready to use (free, best Open Source) tool able to sort > lines (each line appr. 20 bytes long) of a XXX GByte large text file > (i.e. in place) taking full advantage of available memory to speed up > the process as much as possible? Try the standard Unix/Linux sort utility. Use the --buffer-size=SIZE to tell it how much memory to use. From pedro.werneck at terra.com.br Wed Aug 9 18:13:55 2006 From: pedro.werneck at terra.com.br (Pedro Werneck) Date: Wed, 9 Aug 2006 19:13:55 -0300 Subject: Two Classes In Two Files In-Reply-To: <1155152148.014855.166690@p79g2000cwp.googlegroups.com> References: <1155151480.848276.52650@75g2000cwc.googlegroups.com> <44DA3937.5040901@mxm.dk> <1155152148.014855.166690@p79g2000cwp.googlegroups.com> Message-ID: <20060809191355.64c266c7.pedro.werneck@terra.com.br> On 9 Aug 2006 12:35:48 -0700 "dhable at gmail.com" <dhable at gmail.com> wrote: > > > It's just the way it is. Why worry about it? > > Wasn't so much a worry, just trying to figure out how to think the > python way. Seems like you're thinking the Java way... if you don't want to do it, put both classes in the same file. -- Pedro Werneck From fredrik at pythonware.com Tue Aug 22 09:53:46 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Aug 2006 15:53:46 +0200 Subject: How to decode a string References: <1156170296.076521.174180@i3g2000cwc.googlegroups.com><mailman.9610.1156171864.27775.python-list@python.org><1156175385.580508.302330@m73g2000cwd.googlegroups.com><pan.2006.08.21.17.10.16.104915@gmx.net><1156229239.418473.248090@i3g2000cwc.googlegroups.com><mailman.9632.1156233052.27775.python-list@python.org> <1156244818.061709.115190@m73g2000cwd.googlegroups.com> Message-ID: <ecf29b$j5q$1@sea.gmane.org> "Lad" wrote: > The result of print "*", repr(RealName), type(RealName), "*" is > > * 'Fritschov\xe1 Laura' <type 'str'> * looks like the MySQL interface is returning 8-bit strings using ISO-8859-1 encoding (or some variation of that; \xE1 is "LATIN SMALL LETTER A WITH ACUTE" in 8859-1). have you tried passing "use_unicode=True" to the connect() call ? </F> From pmaupin at gmail.com Mon Aug 28 20:30:16 2006 From: pmaupin at gmail.com (Patrick Maupin) Date: 28 Aug 2006 17:30:16 -0700 Subject: Don't use __slots__ (was Re: performance of dictionary lookup vs. object attributes) In-Reply-To: <x7u03w7jce.fsf@handshake.de> References: <mailman.9853.1156495094.27775.python-list@python.org> <1156508104.583914.323700@b28g2000cwb.googlegroups.com> <ecn1qa$ksp$1@panix2.panix.com> <7.0.1.0.0.20060825122244.03790010@yahoo.com.ar> <mailman.9880.1156520034.27775.python-list@python.org> <1156621904.481215.243080@m73g2000cwd.googlegroups.com> <x7u03w7jce.fsf@handshake.de> Message-ID: <1156811416.701420.296610@m73g2000cwd.googlegroups.com> Dieter Maurer wrote: > "Patrick Maupin" <pmaupin at gmail.com> writes on 26 Aug 2006 12:51:44 -0700: > > ... > > The only > > problem I personally know of is that the __slots__ aren't inherited, > > "__slots__" *ARE* inherited, although the rules may be a bit > complex. Yes, I didn't write that correctly. What's not inherited is the lack of a dictionary :) >>> class foo(object): ... __slots__ = 'a b c'.split() ... >>> class bar(foo): ... pass ... >>> set(dir(foo())) - set(dir(bar())) set([]) >>> set(dir(bar())) - set(dir(foo())) set(['__dict__', '__weakref__']) And you are correct that the rules are a bit complicated, but for my purposes (memory usage reduction on non-subclassed classes) __slots__ seem to work fine. Thanks, Pat From jaywgraves at gmail.com Thu Aug 3 11:40:45 2006 From: jaywgraves at gmail.com (jay graves) Date: 3 Aug 2006 08:40:45 -0700 Subject: Running queries on large data structure In-Reply-To: <mailman.8915.1154615978.27775.python-list@python.org> References: <200608022224.00925.email@christoph-haas.de> <mailman.8915.1154615978.27775.python-list@python.org> Message-ID: <1154619645.356336.189640@p79g2000cwp.googlegroups.com> Christoph Haas wrote: > On Wednesday 02 August 2006 22:24, Christoph Haas wrote: > I suppose my former posting was too long and concrete. So allow me to try > it in a different way. :) OK. I'll bite. > The situation is that I have input data that take ~1 minute to parse while > the users need to run queries on that within seconds. I can think of two > ways: What is the raw data size? Are there any effciencies to be gained in the parsing code? > (1) Database > (very quick, but the input data is deeply nested and it would be > ugly to convert it into some relational shape for the database) Depending on your tolerance for this ugliness. You could use a SQLite 'memory' database. _Might_ be faster than the PostgreSQL but you can't tell until you profile it. > (2) cPickle > (Read the data every now and then, parse it, write the nested Python > data structure into a pickled file. The let the other application > that does the queries unpickle the variable and use it time and > again.) How hard would it be to create this nested structure? I've found pickling really large data structures doesn't really save a huge amount of time when reloading them from disk but YMMV and you would have to profile it to know for sure. > So the question is: would you rather force the data into a relational > database and write object-relational wrappers around it? Or would you > pickle it and load it later and work on the data? The latter application > is currently a CGI. I'm open to whatever. :) Convert your CGI to a persistant python webserver (I use CherryPy but you can pick whatever works for you.) and store the nested data structure globally. Reload/Reparse as necessary. It saves the pickle/unpickle step. In an application I'm working on, I create multiple 'views' off of a single expensive database query. I tuck all of these views (read as 'deeply nested python structures') into a cache with a expiration time (currently 5 min in the future). My data layer checks the cache before doing any queries and uses the appropriate view according to the request. If the cache hit misses or is expired, I call the expensive query and reload the cache. This way there is a 'fat' web page every 5 minutes (load time of about 4 seconds on my dev box) and almost every other page is sub second. > Thanks for any enlightenment. Just my 2 cents. ... jay graves From fredrik at pythonware.com Fri Aug 18 07:04:55 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 18 Aug 2006 13:04:55 +0200 Subject: sum and strings References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <slrneeatf3.nbt.sybrenUSE@schuimige.stuvel.eu> Message-ID: <ec46sn$nr3$1@sea.gmane.org> Sybren Stuvel wrote: >> Why not make sum work for strings too? > > Because of "there should only be one way to do it, and that way should > be obvious". I would have thought that "performance" and "proper use of English" was more relevant, though. </F> From pedro.werneck at terra.com.br Tue Aug 8 12:35:29 2006 From: pedro.werneck at terra.com.br (Pedro Werneck) Date: Tue, 8 Aug 2006 13:35:29 -0300 Subject: Class attributes, instances and metaclass __getattribute__ In-Reply-To: <1155047094.195627.103820@p79g2000cwp.googlegroups.com> References: <mailman.9062.1154989741.27775.python-list@python.org> <1155021039.756914.148530@75g2000cwc.googlegroups.com> <mailman.9090.1155041279.27775.python-list@python.org> <1155047094.195627.103820@p79g2000cwp.googlegroups.com> Message-ID: <20060808133529.3ce9eed0.pedro.werneck@terra.com.br> On 8 Aug 2006 07:24:54 -0700 "Ziga Seilnacht" <ziga.seilnacht at gmail.com> wrote: > [snip] > > Well... I'm not talking about metaclass attributes... that's > > perfectly consistent, agreed. > > > > I'm saying that when the class implements a custom __getattribute__, > > when you try to access the instance attributes from itself, it uses > > it. But if the class is a metaclass, instances of its instances have > > acess to the attribute anyway, but don't use the custom > > __getattribute__ you implemented. > > Attribute lookup for instances of a class never calls metaclass' > __getattribute__() method. This method is called only when you > access attributes directly on the class. Well... thanks for the answer. As I said on the first mail, I noticed this when I was explaining descriptors and methods to someone else... I implemented a pure-python Method class to show him exactly how it works. But, since their __get__ call is available at the class too, my first thought was that it was implemented at the metaclass __getattribute__, and when an instance tries to get a class attribute it would fail on its own __getattribute__, use the bound method at its class and make the call. After implementing a test metaclass I noticed it doesn't work this way, and even if it's a bit inconsistent (especially in the case of 'virtual' attributes), it seemed to me the reasonable thing to do, exactly for what you mentioned on your code... someone could easily break a lot of stuff doing it the wrong way, instead if not using __dict__. I mailed the list because someone else thought it might be a bug and I was in doubt... now it's clear it was the right thing to do. Regards, -- Pedro Werneck From neokosmos at gmail.com Wed Aug 16 03:22:12 2006 From: neokosmos at gmail.com (neokosmos at gmail.com) Date: 16 Aug 2006 00:22:12 -0700 Subject: Python form Unix to Windows In-Reply-To: <1155712427.551814.247010@74g2000cwt.googlegroups.com> References: <1155712427.551814.247010@74g2000cwt.googlegroups.com> Message-ID: <1155712932.056173.139760@75g2000cwc.googlegroups.com> Pradeep wrote: > We are changing the python application from Unix to Windows. The source > code of Python application should work well in windows. How to make > changed to windows environment. > In Python code we have login module, ftp, socket programming. > > Please help in changing the code from Unix envirnment to Windows > Environment. You ask a good question. However, the question is too large to be answered in a newsgroup post. The appropriate thing for you to do is to go through the Python documentation and see which modules your application depends on that are not available on Windows. Then, you need to decide how you'll either provide the missing functionality or recode your app to better fit with the Windows environment. Also, I'd like to note that if this is an app of any size, the work involved might be fairly sizeable. In that case, your best bet is to either slog through the process i outlined above (returning to the newsgroup when you're stuck on how to proceed), or pay someone to do it. I don't think you'll find anyone here willing to do that amount and that kind of work for free. O:-) From fabio.pliger at gmail.com Thu Aug 10 17:46:51 2006 From: fabio.pliger at gmail.com (Mr BigSmoke) Date: 10 Aug 2006 14:46:51 -0700 Subject: "running" code on client side with cherrypy? In-Reply-To: <1155240909.620857.233020@b28g2000cwb.googlegroups.com> References: <1155239338.574898.193520@m79g2000cwm.googlegroups.com> <1155240909.620857.233020@b28g2000cwb.googlegroups.com> Message-ID: <1155246411.130360.74270@i42g2000cwa.googlegroups.com> Tnx Jay... as i supposed there's no easy solution... I just thought that, maybe, being on an intranet there was a possible solution... About pysvn a tortoise... i do use tortoiseSVN and t works really really fine.. we (developers) use it, but i'm writting server for "normal" users that can checkout our applications releases... I'll try some other solution... thanks very much! cheers Fabio jay graves wrote: > Mr BigSmoke wrote: > > Hi All, > > I'm developing a website to handle some code/application version > > control on a intranet. I'm using cherrypy and pysvn. Everything runs > > quite good but i want the user to be able to checkout some projects > > from the server. The user(on the client side) selects a folder in his > > machine (i.e.: C:\Project1) and the server should checkout > > (download/copy) all the project selected to the client machine. But > > what happens is that the webserver shckout the project on the same > > folder selected by the user but at server side. Everything works if > > the user gives a network path (like \\pcname\sharedFolder). Any hint? > > The folder is created on the server because that is where the CherryPy > code is running. It's not running on the client. Security concerns > dictate that this will never work the way you want. It's a fundamental > restriction of the web. > How would the user feel if they accidentally selected 'C:\windows\' as > the download path and their computer got messed up? ;-) Or more > likely, a spyware website could download a trojan to your computer when > you thought your were downloading a movie. When this kind of thing > happens today it's considered an exploit. > > The reason that the UNC path works is that you are on an intranet and > the target PC has a shared folder. If you are actually signed on the > the web server and you open a CMD prompt you could key an equivalent > copy command and it would work. CherryPy is just doing the same thing. > But if your CheryPy app was exposed to the internet and I was running > it and asked to save the code to \\jgraves\share it would not work > because your intranet does not have a machine named 'jgraves' > (presumably). > > I think the best that you could do would be to give a link to a zip > file and let the user choose the path they want to unzip to once they > have downloaded the file. > > As for working with SVN, I really like TortoiseSVN but you would have > to install it on all machines which is what you are trying to avoid (I > think.) > > Sorry to be the bearer of bad news. > > ... > jay graves From ask at me Fri Aug 25 03:28:13 2006 From: ask at me (alf) Date: Fri, 25 Aug 2006 03:28:13 -0400 Subject: smtpd and custom MAIL_FROM/RCPT_TO validation Message-ID: <O-KdnQKRW7byL3PZnZ2dnUVZ_rGdnZ2d@comcast.com> Hi, I use smtpd for the SMTP server in my app, but I need a little bit more as far as immediate MAIL_FROM/RCPT_TO validation. Returning from process_message is too late SMTP protocol-wise. The ad hoc solution is to create own SMTPServer2 by deriving from and own SMTPChannel2 by deriving SMTPChannel. What bothers me that some code duplication from SMTPServer.__init__ and SMTPChannel.smtp_MAIL/RCPT will have to take place. Is there any way to avoid it. Probably not :-( ... -- alf From taleinat at gmail.com Wed Aug 9 07:37:53 2006 From: taleinat at gmail.com (taleinat) Date: Wed, 9 Aug 2006 11:37:53 +0000 (UTC) Subject: Looking for an intellisense with good help IDE for Python References: <1155022590.845074.256900@i42g2000cwa.googlegroups.com> <1155062200.732123.37500@m79g2000cwm.googlegroups.com> Message-ID: <loom.20060809T095047-908@post.gmane.org> Miki <miki.tebeka <at> gmail.com> writes: > The IDLE that will come (soon) with Python 2.5 with have some > intellisense. Not all that you requested but some of it. > On the same note, IDLE's completion module has received some serious upgrades recently (such as dictionary key completion and case-insensitive completion), but these haven't made it into the main Python trunk yet. I maintain a stable version of IDLE with many new features, including the much-improved completion, which can be found at: http://www.mashebali.com/?Tal_Einat%27s_IDLE Feel free to download, comment, and report bugs :) - Tal reduce(lambda m,x:[m[i]+s[-1] for i,s in enumerate(sorted(m))], [[chr(154-ord(c)) for c in '.&-&,l.Z95193+179-']]*18)[3] From effigies at gmail.com Mon Aug 7 09:55:08 2006 From: effigies at gmail.com (Chris Johnson) Date: 7 Aug 2006 06:55:08 -0700 Subject: is it possible to dividing up a class in multiple files? In-Reply-To: <eb7ftn$t15$1@news.lrz-muenchen.de> References: <eb7ftn$t15$1@news.lrz-muenchen.de> Message-ID: <1154958908.314550.156220@n13g2000cwa.googlegroups.com> Martin H?fling wrote: > Hi there, > > is it possible to put the methods of a class in different files? I just > want to order them and try to keep the files small. > > Regards > Martin I ran across pyp the other day. It may be what you're wanting. http://www.freenet.org.nz/python/pyp/ From sjmachin at lexicon.net Tue Aug 8 17:39:20 2006 From: sjmachin at lexicon.net (John Machin) Date: 8 Aug 2006 14:39:20 -0700 Subject: Getting previous file name In-Reply-To: <1155063398.455157.43750@m73g2000cwd.googlegroups.com> References: <1154983936.588478.298380@m79g2000cwm.googlegroups.com> <1155063398.455157.43750@m73g2000cwd.googlegroups.com> Message-ID: <1155073160.424852.68840@i3g2000cwc.googlegroups.com> Miki wrote: > Hello hj, > > > I have a small script here that goes to inside dir and sorts the file > > by create date. I can return the create date but I don't know how to > > find the name of that file... > > I need file that is not latest but was created before the last file. > > Any hints... I am newbiw python dude and still trying to figure out lot > > of 'stuff'.. > > > > ... > Remember that Python comes with "battaries included": > #!/usr/bin/env python > > from os import walk > from os.path import getctime, join > > def cmp_file_by_ctime(file1, file2): > return cmp(getctime(file1), getctime(file2)) If there are F files to be sorted, the OP's method requires F calls to os.stat(), and C comparisons of a create time, where C is presumably O(F*ln(F)) and is certainly >= (F-1). Your method requires 2*C calls to os.path.getctime(). This might be considered a little over the top -- you could be charged with "assault and battery" :-) > > def walktree(path): > file_list = [] > for root, dirs, files in walk(path): > file_list += [join(root, file) for file in files] > > file_list.sort(cmp_file_by_ctime) > return file_list[-2] > The OP gives every indication of wanting to examine all the files in one directory, *NOT* walk over a directory tree. Cheers, John From sjdevnull at yahoo.com Tue Aug 29 11:15:35 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 29 Aug 2006 08:15:35 -0700 Subject: Python editor In-Reply-To: <ifYIg.2712$No6.53186@news.tufts.edu> References: <mailman.9834.1156459647.27775.python-list@python.org> <44EE3312.8040707@websafe.com> <ed02ij$591$1@news.cn99.com> <ifYIg.2712$No6.53186@news.tufts.edu> Message-ID: <1156864535.593418.168340@h48g2000cwc.googlegroups.com> John Salerno wrote: > Is it possible to get vim-python for Windows, or is that just a Linux build? It builds for windows. From sile_brennan at hotmail.com Mon Aug 28 07:47:02 2006 From: sile_brennan at hotmail.com (Sile) Date: 28 Aug 2006 04:47:02 -0700 Subject: f2py on windows XP - "Unknown Switch"?? References: <1156177095.867153.327380@h48g2000cwc.googlegroups.com> <1156629368.463878.138620@h48g2000cwc.googlegroups.com> <1156754647.169794.272430@m79g2000cwm.googlegroups.com> <44F2B70A.3080209@lexicon.net> Message-ID: <1156765622.807252.235140@i3g2000cwc.googlegroups.com> Thanks for your reply, Sorry about the last post - pasting from another post didn't work so well... The --version output from my f95 compiler is as follows: C:\>g95 --version G95 (GCC 4.0.3 (g95 0.90!) Aug 22 2006) Copyright (C) 2002-2005 Free Software Foundation, Inc. G95 comes with NO WARRANTY, to the extent permitted by law. You may redistribute copies of G95 under the terms of the GNU General Public License. For more information about these matters, see the file named COPYING The f95.py file is located under Numpy as follows....... C:\Program Files\ESI_Software\UTILS_2006\Python2.3_CFD\Lib\site-packages\numpy\distutils\fcompiler\f95.py import os import sys from numpy.distutils.cpuinfo import cpu from numpy.distutils.fcompiler import FCompiler class G95FCompiler(FCompiler): compiler_type = 'g95' version_pattern = r'G95.*\(GCC 4.0.3 \(g95!\) (?P<version>.*)\).*' THE LINE ABOVE WAS ORIGINALLY: version_pattern = r'G95.*\(experimental \(g95!\) (?P<version.*)\).*' executables = { 'version_cmd' : ["g95", "--version"], 'compiler_f77' : ["g95", "-ffixed-form"], 'compiler_fix' : ["g95", "-ffixed-form"], 'compiler_f90' : ["g95"], 'linker_so' : ["g95","-shared"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } pic_flags = ['-fpic'] module_dir_switch = '-fmod=' module_include_switch = '-I' def get_flags(self): return ['-fno-second-underscore'] def get_flags_opt(self): return ['-O'] def get_flags_debug(self): return ['-g'] if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils.fcompiler import new_fcompiler #compiler = new_fcompiler(compiler='g95') compiler = G95FCompiler() compiler.customize() print compiler.get_version() The output from f2py when I check the fortran compilers is......... C:\>f2py -c --help-fcompiler ................... Could not locate executable f95 Executable f95 does not exist customize VastFCompiler Could not locate executable vf90 Executable vf90 does not exist customize GnuFCompiler customize IbmFCompiler Could not locate executable xlf Executable xlf does not exist customize Gnu95FCompiler Could not locate executable f95 Executable f95 does not exist Could not locate executable f95 Executable f95 does not exist Could not locate executable f95 Executable f95 does not exist customize IntelVisualFCompiler Could not locate executable ifl Executable ifl does not exist customize G95FCompiler Couldn't match compiler version for 'G95 (GCC 4.0.3 (g95 0.90!) Aug 22 2006)\nCo pyright (C) 2002-2005 Free Software Foundation, Inc.\n\nG95 comes with NO WARRAN TY, to the extent permitted by law.\nYou may redistribute copies of G95\nunder the terms of the GNU General Public License.\nFor more information about these matters, see the file named COPYING' customize IntelItaniumFCompiler Could not locate executable efc Executable efc does not exist customize PGroupFCompiler Could not locate executable pgf77 Executable pgf77 does not exist customize LaheyFCompiler Could not locate executable lf95 Executable lf95 does not exist customize CompaqVisualFCompiler customize MipsFCompiler customize HPUXFCompiler customize IntelItaniumVisualFCompiler Could not locate executable efl Executable efl does not exist customize IntelEM64TFCompiler Could not locate executable efc Executable efc does not exist List of available Fortran compilers: --fcompiler=compaqv DIGITAL|Compaq Visual Fortran Compiler (6.5) --fcompiler=gnu GNU Fortran Compiler (3.4.5) I hope that makes it a bit clearer, Thanks, Sile From deets at nospam.web.de Wed Aug 9 03:53:19 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 09 Aug 2006 09:53:19 +0200 Subject: import logging fails on MacPython 2.4.3 In-Reply-To: <QpdCg.224$25.5066@news.uchicago.edu> References: <QpdCg.224$25.5066@news.uchicago.edu> Message-ID: <4jtijgF9g8m2U1@uni-berlin.de> Tod Olson schrieb: > Anyone have advice for importing the logging module using MacPython 2.4.3? > > MacPython installs the logging module in: > > /Library/Frameworks/Python.framework/Versions/2.4/lib/logging/ On my machine, that is /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/logging > There's an __init__.py there and everything, but this directory is not > in sys.path. I add it to sys.path as follows: > > >>> sys.path.append(os.path.join(sys.prefix, 'lib', 'logging')) > >>> print sys.path[-1] > /Library/Frameworks/Python.framework/Versions/2.4/lib/logging Which is wrong - you'd have to add the path without the logging part! Diez From python.list at tim.thechases.com Sat Aug 5 17:31:19 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 05 Aug 2006 16:31:19 -0500 Subject: Why do I require an "elif" statement here? In-Reply-To: <1154812783.619385.293820@n13g2000cwa.googlegroups.com> References: <1154712731.375032.203570@m79g2000cwm.googlegroups.com> <mailman.8999.1154714505.27775.python-list@python.org> <1154812783.619385.293820@n13g2000cwa.googlegroups.com> Message-ID: <44D50E27.4040208@tim.thechases.com> > Hard to believe that lstrip() produces an empty string on lines with > just spaces and doesn't remove the '\n' with lines that have > characters. It's easy to understand that lstrip() is doing exactly what it's supposed to. It evaluates from the left of your string, discarding whitespace (spaces, tabs, and cr/lf characters) until it hits a non-whitespace character or the end of the string. When there's no non-whitespace, it returns an empty string. If you wanted to remove the \n from the right of lines, there was an earlier discussion on the list where someone (Bruno?) and I went back and forth and I think we finally decided that the "best" solution was s.rstrip('\n') which had the fewest side-effects. However, when you use the output.write() method, you'd then have to add the \n back in to make sure it ended up in the output stream. If you wanted to continue to use lstrip(), you could also just ensure that you're only stripping spaces (chr(0x20)) by using s.lstrip(' ') This would leave \t and \n characters unmolested. More info can be found at >>> help("".lstrip) >>> help("".rstrip) >>> help("".strip) Hope this helps, -tkc From rogue_pedro at yahoo.com Tue Aug 15 20:33:11 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 15 Aug 2006 17:33:11 -0700 Subject: programming with Python 3000 in mind References: <1155672987.522793.47080@74g2000cwt.googlegroups.com> Message-ID: <1155688391.861879.53660@m79g2000cwm.googlegroups.com> beliavsky at aol.com wrote: > Some basic syntax such as > > print "hello world" > > is going away to make print look like a function. IMO, fixing what is > not broken because of the aesthetic tastes of the BDFL is a bad idea. > His reasoning is at > http://mail.python.org/pipermail/python-dev/2005-September/056154.html > . When it comes to programming language design, I *trust* Guido. I think he makes good non-aesthetic-taste-based points in that posting. Just the other day, someone was wanting to know how to capture the output from ftplib printing to stdout. IIRC, the least inconvenient way (without replacing stdout) was rewriting it not to use print statements... http://groups.google.ca/group/comp.lang.python/browse_frm/thread/70aca5068c18384f/d19e9119b7ca1af2 Peace, ~Simon From rogue_pedro at yahoo.com Sat Aug 12 13:41:11 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 12 Aug 2006 10:41:11 -0700 Subject: reading from sockets References: <1155227695.625250.17920@m73g2000cwd.googlegroups.com> <TFQCg.103113$hp.69833@read2.cgocable.net> <1155387684.513673.130770@75g2000cwc.googlegroups.com> Message-ID: <1155404471.418202.252850@75g2000cwc.googlegroups.com> AndrewTK wrote: > > I'm assuming that your server waits to receive the word 'hello' before > > replying with the three strings (first, second, and third)? So once your > > Nope - actually it's a threaded "server", with the main thread simply > dumping network input to the console and command line input being > directly dumped to the network output stream. > > I confess to having typed the three lines manually...! > > It's at: > http://www.dcs.st-and.ac.uk/~atk1/perso/java/servers/RespondingServer.java > > It launches on the command line with > java RespondingServer _port_ > > _port_ being the port number it should listen for data on. Hooooy. I tried reading your Java code.. What can I say? There's a reason why I like Python... :-) I couldn't see anything obviously broken in your server, but there's definitely nothing wrong with your python code, except that you call flush() on the socket (fixed in your posted code but not in the linked code.) Here are the results of testing, with netcat substituted for your java server: # on the server side: sforman at garbage:~ $ netcat -p 54321 -l hellohi there how are you I'm fine thanks sforman at garbage:~ $ # on the client side: sforman at garbage:~ $ python delme.py 'hi there\n' 'how are you\n' "I'm fine thanks\n" sforman at garbage:~ $ So I'm guessing it's something wrong in your java server. HTH, ~Simon From ewill at sirius.tg00suus7038.net Fri Aug 25 18:00:04 2006 From: ewill at sirius.tg00suus7038.net (The Ghost In The Machine) Date: Fri, 25 Aug 2006 22:00:04 GMT Subject: Duck typing alows true polymorfisim References: <1156532721.879808.40990@i3g2000cwc.googlegroups.com> Message-ID: <va64s3-gsr.ln1@sirius.tg00suus7038.net> In comp.lang.java.advocacy, atbusbook at aol.com <atbusbook at aol.com> wrote on 25 Aug 2006 12:05:21 -0700 <1156532721.879808.40990 at i3g2000cwc.googlegroups.com>: > lets say you want a generic numerical algorithom like sum > > Ruby > > def sum lst > lst.inject(0){|total,current| total*current} > end > > Java // i dont know if there is a numeric super class for numbers > > class Sum{ > public static int sum(int[] lst){ > int total = 0; > for(int current : lst){ > total+=current; > } > return total; > } > // repeat for all other number types > } > There isn't; Java makes the distinction between an int and an Integer, a double and a Double. Java 5 did introduce autoboxing, which makes things like Number[] numbers = new Number[]{1, 2.3, 4, 5.6}; possible, and Number is a baseclass for both Integer and Double (but not int and double). Therefore, one could write: public class Sum { public static double sum(int[] lst) { Number[] nlst = new Number[lst.length]; for(int i = 0; i < nlst.length; i++) nlst[i] = new Integer(lst[i]); return sum(Arrays.asList(nlst)); } public static double sum(double[] lst) { Number[] nlst = new Number[lst.length]; for(int i = 0; i < nlst.length; i++) nlst[i] = new Double(lst[i]); return sum(Arrays.asList(nlst)); } public static double sum(float[] lst) { Number[] nlst = new Number[lst.length]; for(int i = 0; i < nlst.length; i++) nlst[i] = new Double(lst[i]); return sum(Arrays.asList(nlst)); } public static double sum(Number[] lst) { return sum(Arrays.asList(lst)); } public static double sum(Collection<Number> lst) { double sum = 0; for(Iterator<Number> i = lst.iterator(); i.hasNext()) sum += i.next().doubleValue(); return sum; } } A rather ugly but possibly useful duckling. -- #191, ewill3 at earthlink.net Windows Vista. Because it's time to refresh your hardware. Trust us. From mariano.difelice at gmail.com Mon Aug 21 11:47:35 2006 From: mariano.difelice at gmail.com (mardif) Date: 21 Aug 2006 08:47:35 -0700 Subject: wxPython getPosition() limit Message-ID: <1156175255.237057.39650@75g2000cwc.googlegroups.com> Hi, I've this big problem: I've an wx.ScrolledWindow object, which contains <n> element. These elements have the event OnPaint that draw itself same objects. For drawing, each element call the method GetPosition(), which returns a tuple int. But, if I have the element 5000 that it must be designed at position x = 30 y = 40000, this object cannot be designed in this location, but on x=30, x= 32767, because GetPosition() return a INT tuple. I note that this problem doesn't exists on Unix Platform ( wxPython installed on Fedora ), but on Windows this is a disaster! Someone have any idea? thx very much From matt.newville at gmail.com Thu Aug 31 21:36:59 2006 From: matt.newville at gmail.com (matt.newville at gmail.com) Date: 31 Aug 2006 18:36:59 -0700 Subject: Coding style and else statements References: <44f355d6$0$8812$88260bb3@free.teranews.com> <1156898310.795476.187030@i3g2000cwc.googlegroups.com> <mailman.10091.1156921386.27775.python-list@python.org> Message-ID: <1157074619.876691.290470@b28g2000cwb.googlegroups.com> > To my eyes, that's less readable than, and has no benefit over, the > following: > > def foo(thing): > if thing: > result = thing+1 > else: > result = -1 > return result I wouldn't discount: def foo(thing): result = -1 if thing: result = thing+1 return result especially if "thing" is the less expected case. This puts the "more likely" result first, followed by checks that might modify that result. But, I also try to avoid adding 1 to things that I test for Truth: >>> x = 8 >>> foo(x) 9 >>> foo(x>1) 2 >>> foo(x and 1) 2 >>> foo(x or 1) 9 --Matt From vyzasatya at gmail.com Wed Aug 23 18:15:24 2006 From: vyzasatya at gmail.com (Vyz) Date: 23 Aug 2006 15:15:24 -0700 Subject: Translating Javascript programs to python. In-Reply-To: <1156318571.722528.127110@h48g2000cwc.googlegroups.com> References: <1156264202.542785.172270@74g2000cwt.googlegroups.com> <1156318571.722528.127110@h48g2000cwc.googlegroups.com> Message-ID: <1156371324.186510.273930@75g2000cwc.googlegroups.com> Its a module to transliterate from telugu language written in roman script into native unicode. right now its running in a browser window at www.lekhini.org I Intend to translate it into python so that I can integrate into other tools I have. I am able to pass arguments and get output from the script also would be OK. or how about ways to wrap these javascript functions with python. Thanks Vyz supercoder wrote: > Vyz wrote: > > Hi, > > I have a script with hundreds of lines of javascript spread accross 7 > > files. Is there any tool out there to automatically or > > semi-automatically translate the code into python. > > > > Thanks > > Vyz > > Not a tool, but assuming the javascript is not too complex you could > interpret some of it using python and the CGI module. > > But really, what would be the use? From ask at me Mon Aug 28 23:11:44 2006 From: ask at me (alf) Date: Mon, 28 Aug 2006 23:11:44 -0400 Subject: M$ windows python libs installed in arbitrary directories forcustomized python distributions In-Reply-To: <44f31d35$0$17268$9b622d9e@news.freenet.de> References: <mKydnXWdR_33KXPZnZ2dnUVZ_o-dnZ2d@comcast.com> <mailman.9861.1156503058.27775.python-list@python.org> <44f31d35$0$17268$9b622d9e@news.freenet.de> Message-ID: <YvOdnaKfZ8KlIW7ZnZ2dnUVZ_vWdnZ2d@comcast.com> Martin v. L?wis wrote: >>it's spelled "Windows installers" > I want to second this. It was me who created the installer, and I don't > like to see my name abbreviated as M$ (if you think you should write > out the name of the MSI creator, please say "Martin's installer" :-). ok, let me clarify, by M$ I meant Micro$oft. -- alf From stevebread at yahoo.com Mon Aug 21 05:51:56 2006 From: stevebread at yahoo.com (stevebread at yahoo.com) Date: 21 Aug 2006 02:51:56 -0700 Subject: Regular Expression question Message-ID: <1156153916.849933.178790@75g2000cwc.googlegroups.com> Hi, I am having some difficulty trying to create a regular expression. Consider: <tag1 name="john"/> <br/> <tag2 value="adj__tall__"/> <tag1 name="joe"/> <tag1 name="jack"/> <tag2 value="adj__short__"/> Whenever a tag1 is followed by a tag 2, I want to retrieve the values of the tag1:name and tag2:value attributes. So my end result here should be john, tall jack, short My low quality regexp re.compile('tag1.+?name="(.+?)".*?(?!tag1).*?="adj__(.*?)__', re.DOTALL) cannot handle the case where there is a tag1 that is not followed by a tag2. findall returns john, tall joe, short Ideas? Thanks. From pranav.choudhary at gmail.com Thu Aug 3 07:50:35 2006 From: pranav.choudhary at gmail.com (pranav.choudhary at gmail.com) Date: 3 Aug 2006 04:50:35 -0700 Subject: opposite of import Message-ID: <1154605835.465468.97550@m79g2000cwm.googlegroups.com> Hi I am new to python. I wanted to know if there is an opposite of "import" From john106henry at hotmail.com Thu Aug 10 16:12:06 2006 From: john106henry at hotmail.com (John Henry) Date: 10 Aug 2006 13:12:06 -0700 Subject: What's the cleanest way to compare 2 dictionary? In-Reply-To: <1155165349.766502.314760@n13g2000cwa.googlegroups.com> References: <1155147450.628625.20270@m79g2000cwm.googlegroups.com> <1155165349.766502.314760@n13g2000cwa.googlegroups.com> Message-ID: <1155240726.922672.279230@i3g2000cwc.googlegroups.com> John, Yes, there are several scenerios. a) Comparing keys only. That's been answered (although I haven't gotten it to work under 2.3 yet) b) Comparing records. Now it gets more fun - as you pointed out. I was assuming that there is no short cut here. If the key exists on both set, and if I wish to know if the records are the same, I would have to do record by record comparsion. However, since there are only a handful of records per key, this wouldn't be so bad. Maybe I just overload the compare operator or something. John Machin wrote: > John Henry wrote: > > Hi list, > > > > I am sure there are many ways of doing comparision but I like to see > > what you would do if you have 2 dictionary sets (containing lots of > > data - like 20000 keys and each key contains a dozen or so of records) > > and you want to build a list of differences about these two sets. > > > > I like to end up with 3 lists: what's in A and not in B, what's in B > > and not in A, and of course, what's in both A and B. > > > > What do you think is the cleanest way to do it? (I am sure you will > > come up with ways that astonishes me :=) ) > > > > Paddy has already pointed out a necessary addition to your requirement > definition: common keys with different values. > > Here's another possible addition: you say that "each key contains a > dozen or so of records". I presume that you mean like this: > > a = {1: ['rec1a', 'rec1b'], 42: ['rec42a', 'rec42b']} # "dozen" -> 2 to > save typing :-) > > Now that happens if the other dictionary contains: > > b = {1: ['rec1a', 'rec1b'], 42: ['rec42b', 'rec42a']} > > Key 42 would be marked as different by Paddy's classification, but the > values are the same, just not in the same order. How do you want to > treat that? avalue == bvalue? sorted(avalue) == sorted(bvalue)? Oh, and > are you sure the buckets don't contain duplicates? Maybe you need > set(avalue) == set(bvalue). What about 'rec1a' vs 'Rec1a' vs 'REC1A'? > > All comparisons are equal, but some comparisons are more equal than > others :-) > > Cheers, > John From gagsl-py at yahoo.com.ar Thu Aug 10 01:37:08 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 10 Aug 2006 02:37:08 -0300 Subject: loop until keypress (Windows XP) In-Reply-To: <1155187164.696015.252920@b28g2000cwb.googlegroups.com> References: <1155187164.696015.252920@b28g2000cwb.googlegroups.com> Message-ID: <7.0.1.0.0.20060810023048.03fd3828@yahoo.com.ar> At Thursday 10/8/2006 02:19, placid wrote: >chr = sys.stdin.read(1) >while chr != "q": > """ keep printing text """ > chr = sys.stdin.read(1) > >but again this blocks too. > >is there a way to do this, wait for user input but dont block? I could >use a thread that just does the previous code block but i already have >three Thread classes, its just getting too complex with threads! If your script only needs to be run on Windows -as the subject suggests- you can use the msvcrt module: from msvcrt import kbhit,getch stop = False while not stop: print "Hello world!" if kbhit(): stop = getch()=='q' kbhit() is used to detect when a keypress is waiting, so the next getch() will not block. Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From jzgoda at o2.usun.pl Mon Aug 14 14:38:17 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Mon, 14 Aug 2006 20:38:17 +0200 Subject: Which KDE IDE for Python? In-Reply-To: <4kb1c6FbdmfhU1@uni-berlin.de> References: <1154682596.419636.70320@p79g2000cwp.googlegroups.com> <ebpidb$s0s$1@nemesis.news.tpi.pl> <4kb1c6FbdmfhU1@uni-berlin.de> Message-ID: <ebqg3k$3kf$1@nemesis.news.tpi.pl> Diez B. Roggisch napisa?(a): >>As a side note, Eric3 has no KDE integration because it's pure PyQt >>application. > > Not fully true. While it certainly doesn't aim to be a fully integrated ide, > it has some kde-support. Which you can disable using the --nokde argument, > btw. > > It will then use kde color-dialogs, file-dialogs and the like. I wouldn't call this "integration" (like using kio, dcop, kparts, etc.), but you are right, it may use some elements of KDE desktop. Anyway, I think OP's wish for integration was closer to my understanding of integration with desktop environment. ;) Which doesn't change situation, that currently there's no KDE-based (nor even fully integrated with KDE) IDE for Python. -- Jarek Zgoda http://jpa.berlios.de/ From onurb at xiludom.gro Tue Aug 1 11:37:26 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 01 Aug 2006 17:37:26 +0200 Subject: Finding the name of a class In-Reply-To: <q684q3xmd11.ln2@news.conpoint.com> References: <q684q3xmd11.ln2@news.conpoint.com> Message-ID: <44cf7538$0$29435$626a54ce@news.free.fr> Kirk Strauser wrote: > Given a class: > >>>> class foo(object): >>>> pass > > how can I find its name, such as: > >>>> b = foo I suppose you mean b = foo() ? >>>> print something(b) > 'foo' The name of a class is in the attribute '__name__' of the class. The class of an object is in the attribute '__class__' of the object. >>> class Foo(object): ... pass ... >>> b = Foo >>> b.__name__ 'Foo' >>> b = Foo() >>> b.__class__.__name__ 'Foo' >>> > I'm writing a trace() decorator for the sake of practice, and am trying to > print the name of the class that a traced method belongs to. This seems > like it should be easy, but I think I've been staring at the problem too > long. >>> help(dir) Help on built-in function dir in module __builtin__: dir(...) dir([object]) -> list of strings Return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it: No argument: the names in the current scope. Module object: the module attributes. Type or class object: its attributes, and recursively the attributes of its bases. Otherwise: its attributes, its class's attributes, and recursively the attributes of its class's base classes. >>> -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From andre at wasy.de Mon Aug 21 04:59:23 2006 From: andre at wasy.de (Andre Poenitz) Date: Mon, 21 Aug 2006 08:59:23 +0000 (UTC) Subject: Stack trace in C References: <mailman.8519.1153831141.27775.python-list@python.org> Message-ID: <49smp3-hiq.ln1X@svn2.wasy.de> Jean-Paul Calderone <exarkun at divmod.com> wrote: > On Tue, 25 Jul 2006 14:20:41 +0200, Andre Poenitz <andre at wasy.de> wrote: >> >> >>Bear with me - I am new to Python. (And redirect me to a more suitable >>newsgroup in case this one is not appropriate.) >> >>I am trying to embed Python into a C++ application and want to get back >>a backtrace in case of errors in the python code. > > I think you'd have more luck with the traceback module, which has such > methods as format_exception and print_tb. That's where I got my 'inspiration' from. Unfortunately my attempt to translate this into C failed, and I can't see the reason. Thanks for the hint nevertheless Andre' From rcs at bgoark.no Sun Aug 6 18:16:56 2006 From: rcs at bgoark.no (baalbek) Date: Mon, 07 Aug 2006 00:16:56 +0200 Subject: Windows vs. Linux In-Reply-To: <1154428264.934787.112500@s13g2000cwa.googlegroups.com> References: <1154301694.445639.99580@m79g2000cwm.googlegroups.com> <1154385878.713809.113060@i42g2000cwa.googlegroups.com> <1154428264.934787.112500@s13g2000cwa.googlegroups.com> Message-ID: <44d66a54$0$8000$c83e3ef6@nn1-read.tele2.net> Andy Dingley wrote: >> Python and Ubuntu rock...go fot it. > > That's nice. I've just burned myself a new Ubuntu f*ck-a-duck release CD Now, just out of curiosity, what's f*ck-a-duck? Baalbek From rup at invalid.com Sat Aug 26 10:00:42 2006 From: rup at invalid.com (JAG CHAN) Date: 26 Aug 2006 14:00:42 GMT Subject: Learning Python References: <44f03c80$0$75042$14726298@news.sunsite.dk> <1156597310.493911.241160@i42g2000cwa.googlegroups.com> Message-ID: <44f0540a$0$75041$14726298@news.sunsite.dk> bearophileHUGS at lycos.com wrote in news:1156597310.493911.241160 at i42g2000cwa.googlegroups.com: > JAG CHAN: >> As I had written earlier, I am trying to learn Python. >> I chose IDLE as an editor to learn Python. >> Now I find that it is an online editor. >> It is not possible for me to be always on online while learning. >> Kindly suggest me a suitable editor (for Windows XP) which does not >> require me to be on online. > > Maybe your firewall tells you that IDLE asks for access to the net, > but it's not an online sofware. You can use a different editor, like > SPE, or if you want to start with something simpler you can try > ActivePython, or probably it's even better a normal and very fast txt > editor with a python grammar for colorization, with a macro added to > run the script being edited. > > Bye, > bearophile > Thanks for your response. You are right. Whenever I try to open IDLE, my zone firewall tells me pythonw.exe is trying to access the trusted zone. Whenever I try to open new IDLE window I get the following message: "IDLE's subprocess didn't make connection.Either IDLE can't start a subprocess or personal firewall software is blocking the connection." I will be grateful if you kindly suggest a way out, then, I won't have to install another editor. Regards. From haraldarminmassa at gmail.com Thu Aug 10 13:31:59 2006 From: haraldarminmassa at gmail.com (GHUM) Date: 10 Aug 2006 10:31:59 -0700 Subject: win32 load icon not from file, but from <something> Message-ID: <1155231118.940407.311040@m79g2000cwm.googlegroups.com> I have found a "make a icon in traybar" skript, and it loads its Icon from a file hinst = win32gui.GetModuleHandle(None) iconPathName= "c:/myapp/myapp.ico" icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE hicon = win32gui.LoadImage(hinst, str(iconPathName), win32con.IMAGE_ICON, 0, 0, icon_flags) that works great. But now I have to distribute that icon together with the application - that is one file more to take track. I would like to load this image from <something> with something being a string / a cStringIO / something pickled The obvious cPickle.dumps(hicon) leads to nothing, cause it only gets the ID of the hicon :( Any ideas / recommendations / tipps? Harald From hg at nospam.com Wed Aug 30 11:02:43 2006 From: hg at nospam.com (hg) Date: Wed, 30 Aug 2006 10:02:43 -0500 Subject: Python for Windows In-Reply-To: <12fb95ba4q18i53@corp.supernews.com> References: <1156889674.296093.5390@74g2000cwt.googlegroups.com> <12fb95ba4q18i53@corp.supernews.com> Message-ID: <FNhJg.121908$LF4.61023@dukeread05> Grant Edwards wrote: > >> Will the msi installer modify registry or other system files? >> Does it possible install Python not touching registry and >> system files? > You can make your own installer to install Python, and make sure the registry is not touched - I think the current installer modifies at least the .py .pyw file association. hg From kairo.matthias at web.de Tue Aug 15 15:18:40 2006 From: kairo.matthias at web.de (Kairo Matthias) Date: Tue, 15 Aug 2006 21:18:40 +0200 Subject: yEnc Message-ID: <597dc$44e21e10$5497e66d$9926@nf4.news-service.com> How can i encode with yEnc? From jaysherby at gmail.com Wed Aug 30 21:14:39 2006 From: jaysherby at gmail.com (Putty) Date: 30 Aug 2006 18:14:39 -0700 Subject: python equivalent for fputc Message-ID: <1156986879.533017.241450@b28g2000cwb.googlegroups.com> I'm porting a program a friend wrote in C over to Python and I've run into a little hang-up. The C program writes characters out to a file. I'm 99% sure that a conversion is going on here as well. I know for a fact that it's taking a number and turning it into a character. So what kind of call can I make to do it in Python? From enigmadude at rock.com Thu Aug 10 20:35:27 2006 From: enigmadude at rock.com (enigmadude) Date: 10 Aug 2006 17:35:27 -0700 Subject: hide python code ! In-Reply-To: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> Message-ID: <1155256527.061808.135200@74g2000cwt.googlegroups.com> I don't think you're the first person that has wondered about this. But you might have some options: 1. If you are running it on Windows only, use py2exe to wrap it up as an executable. 2. I've never done this, but you might be able to encrypt or otherwise turn you modules into binary form, and then use a clever import hook. I know zipimport in the standard lib gives you more control over importing zip files, but I don't think it can handle encrypted ones. 3. Write a custom module importer in C using Python's API so you can encrypt your modules any way you want as long as you know how to use C to decrypt them again. There's probably a thousand other ways if you're clever enough (e.g. write it in Jython and package it as .jar files). As long as your program sticks closer to pure Python, the easier it will be. If you're using a lot of open source modules to help you out, you might want to double-check their licensing to see if what you're doing is allowed anyway. Bayazee wrote: > hi > can we hide a python code ? > if i want to write a commercial software can i hide my source code from > users access ? > we can conver it to pyc but this file can decompiled ... so ...!! > do you have any idea about this ...? > > --------------------------------------- > First Iranian Open Source Community : www.python.ir From dieter at handshake.de Mon Aug 21 13:37:48 2006 From: dieter at handshake.de (Dieter Maurer) Date: 21 Aug 2006 19:37:48 +0200 Subject: a bug in list.remove? References: <mailman.9512.1155926076.27775.python-list@python.org> Message-ID: <x7k652xa4z.fsf@handshake.de> Astan Chee <stanc at al.com.au> writes on Sat, 19 Aug 2006 03:34:26 +1000: > >>> for p in ps: > if p in qs: > ps.remove(p) You are modifying an object ("ps") while you iterate over it. This is a receipe for surprises... The standard idiom is to iterate over a copy rather than the object itself: for p in ps[:]: .... Dieter From danielobrien at gmail.com Wed Aug 30 20:08:14 2006 From: danielobrien at gmail.com (Daniel O'Brien) Date: 30 Aug 2006 17:08:14 -0700 Subject: question about SOAPpy In-Reply-To: <44f4bfd9$0$25943$ba4acef3@news.orange.fr> References: <44f4bfd9$0$25943$ba4acef3@news.orange.fr> Message-ID: <1156982894.420014.323650@i3g2000cwc.googlegroups.com> For my purposes I'm not particularly satisfied. Though there's always a possibility that it's operator error on my part. To name off a few issues: - I've yet to find a good way to force data to be consistently untyped. Setting the "typed" configuration option doesn't seem to untype data consistently, meaning I end up wrapping essentially every variable in SOAPpy.untypedType(). - Why do I want everything untyped? Because SOAPpy's ints and longs (which, as far as I know, just depend on type()) don't play nice with, for example, Java/Axis's restrictions on ints and longs. Besides, often with doc-lit services the type information is redundant. - SOAPpy attempts to reference redundant values, possibly for efficiency purposes. It does a poor job of this, often referencing the wrong IDs, or attempting to link values recursively (i.e. dies with an error). There's a configuration option to turn this off, but this feature doesn't seem to be implemented. My workaround? Wrapping raw XML in untypedType(). - It uses str() to marshal data. I'd considered ZSI, but at the time it wasn't possible to set header values, so it wasn't viable. It looks like they've updated since then, so it may be worth re-evaluating. At present I use a heavily modified copy of SOAPpy. If anyone happens to have feedback regarding the above issues, I'd appreciate the input. Daniel O'Brien m.banaouas wrote: > Hello Pythoneers: > > I would like to ask you a simple question: > Are you satisfied by SOAPpy module? > > Actually, I use this module since a year and i immediately found it very > well-implemented, corresponding to dynamic "meta-data" discovering > nature of SOAP/WSDL. > > BUT i read sometimes threads saying that SOAPpy is "dead" and we should > all migrationg to Zolera SOAP Infrastructure (ZSI) module. > > Can you tell me what do you think about it ? > > thanks. From santafefrank at cybermesa.com Thu Aug 24 09:58:30 2006 From: santafefrank at cybermesa.com (Frank LaFond) Date: Thu, 24 Aug 2006 07:58:30 -0600 Subject: Record Audio Analysis In-Reply-To: <hWcHg.69909$zg.46493@tornado.rdc-kc.rr.com> References: <hWcHg.69909$zg.46493@tornado.rdc-kc.rr.com> Message-ID: <eckbaa$kl1$1@reader2.nmix.net> Jo Chase wrote: > I would like to record audio from a mic and perform some basic analysis on > the audio wave patterns produced. What would be the easiest way to > accomplish this in Python? Take a look at http://pymedia.org I think it allows the features you want. Frank. From grover.uk at gmail.com Sat Aug 26 11:50:03 2006 From: grover.uk at gmail.com (groves) Date: 26 Aug 2006 08:50:03 -0700 Subject: rollover effect Message-ID: <1156607403.741240.25000@74g2000cwt.googlegroups.com> hi I am trying to get a roll over effect on my canvas.(this is a virtual program which will eventually fit into my final program) Exactly i have a text on my screen and I want to have a brief discription across it whenever the user takes the mouse on it n hence giving information about the type of text(event). Another thign i am looking for is to have a right click on that very text as well If somebody can put some light on it, then it would be really great for my project. Thank you in advance. From st at tobiah.org Thu Aug 31 17:44:45 2006 From: st at tobiah.org (tobiah) Date: Thu, 31 Aug 2006 14:44:45 -0700 Subject: csv module strangeness. In-Reply-To: <1157055377.000676.243270@b28g2000cwb.googlegroups.com> References: <44f5e870$0$8814$88260bb3@free.teranews.com> <mailman.10135.1156971429.27775.python-list@python.org> <44f5f347$0$8846$88260bb3@free.teranews.com> <mailman.10167.1157014794.27775.python-list@python.org> <mailman.10212.1157054053.27775.python-list@python.org> <1157055377.000676.243270@b28g2000cwb.googlegroups.com> Message-ID: <44f74b2e$0$8935$88260bb3@free.teranews.com> John Machin wrote: > tobiah wrote: >>> </F> >>> >> I agree with Henryk's evaluation > > Henryk?? Have I missed a message in the thread, or has the effbot > metamorphosed into the aitchbot? > How strange. Either my client was whacked, or I was. I was actually referring to your "baroque byzantine over-elaborated unnecessity" comment. Henryk was from a later thread, I guess. -- Posted via a free Usenet account from http://www.teranews.com From kbk at shore.net Sat Aug 26 23:27:23 2006 From: kbk at shore.net (Kurt B. Kaiser) Date: Sat, 26 Aug 2006 23:27:23 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200608270327.k7R3RNcT027925@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 407 open ( +3) / 3393 closed (+17) / 3800 total (+20) Bugs : 888 open (+28) / 6145 closed (+14) / 7033 total (+42) RFE : 232 open ( +3) / 236 closed ( +1) / 468 total ( +4) New / Reopened Patches ______________________ most missing from Windows distribution (2006-08-16) CLOSED http://python.org/sf/1541412 opened by Jim Jewett buffer overrun in repr() for unicode strings (2006-08-16) CLOSED http://python.org/sf/1541585 opened by Simon Law work around clocks with low resolution (uuid.py) (2006-08-17) http://python.org/sf/1541863 opened by Hirokazu Yamamoto patch in bug 1542016 (2006-08-17) CLOSED http://python.org/sf/1542019 opened by Santiago Gala fix crash with continue in nested try/finally (2006-08-18) http://python.org/sf/1542451 opened by Neal Norwitz Improve dynamic linking support on AIX (2006-08-18) http://python.org/sf/1542544 opened by G?ran Uddeborg Tweak pydoc to speak about with and CONTEXTMANAGERS (2006-08-18) http://python.org/sf/1542681 opened by Santiago Gala Fix the vc8 solution files (2006-08-18) http://python.org/sf/1542946 opened by baus urllib2 regression (2006-08-19) CLOSED http://python.org/sf/1542948 opened by John J Lee tarfile.py: fix for bug 1543303 (2006-08-21) CLOSED http://python.org/sf/1543897 opened by Lars Gust?bel Socket module is not thread-safe (2006-08-21) http://python.org/sf/1544279 opened by Maxim Sobolev Implementation of PEP 362 (2006-08-22) http://python.org/sf/1544909 opened by Brett Cannon Fixes SocketServer Bug 1531963 (2006-08-23) http://python.org/sf/1545011 opened by Damon Kohler new splicetee module (2006-08-23) http://python.org/sf/1545262 opened by Omar AitMous new directio module (2006-08-23) http://python.org/sf/1545275 opened by Omar AitMous xrange that supports longs, etc (2006-08-24) http://python.org/sf/1546078 opened by Neal Norwitz crash in dict_equal (2006-08-24) http://python.org/sf/1546288 opened by Guido van Rossum Create a real zip iterator object; not using itertools.izip (2006-08-24) CLOSED http://python.org/sf/1546297 opened by Brian Holmes broken error reporting when filename specified by -s missing (2006-08-25) http://python.org/sf/1546372 opened by lplatypus Patches Closed ______________ most missing from Windows distribution (2006-08-16) http://python.org/sf/1541412 closed by jimjjewett buffer overrun in repr() for unicode strings (2006-08-16) http://python.org/sf/1541585 closed by gbrandl broken shortcut keys (2006-08-15) http://python.org/sf/1540874 closed by kbk patch in bug 1542016 (2006-08-17) http://python.org/sf/1542019 closed by gbrandl urllib2 regression (2006-08-19) http://python.org/sf/1542948 closed by gbrandl Backports from trunk to release24-maint (2006-08-15) http://python.org/sf/1540329 closed by gbrandl tarfile.py: fix for bug 1543303 (2006-08-21) http://python.org/sf/1543897 closed by nnorwitz Add some explication to PEP 3100 (2006-07-13) http://python.org/sf/1522038 closed by bcannon Create a real zip iterator object; not using itertools.izip (2006-08-24) http://python.org/sf/1546297 closed by gvanrossum Add readinto method to StringIO and cStringIO (2006-08-12) http://python.org/sf/1539381 closed by bcannon Remove the repr()-backticks (2006-06-04) http://python.org/sf/1500623 closed by bcannon Move reduce() to functools (2006-06-28) http://python.org/sf/1513870 closed by gvanrossum New / Reopened Bugs ___________________ infinite __str__ recursion in thread causes seg fault (2003-07-31) http://python.org/sf/780714 reopened by gbrandl tools and demo missing from windows (2006-08-16) http://python.org/sf/1541420 opened by Jim Jewett bug in python 2.4.3 for windows? (2006-08-16) CLOSED http://python.org/sf/1541566 opened by tinkiwinky Compiler command percent-sign causes format string error (2006-08-16) CLOSED http://python.org/sf/1541642 opened by Matthew Cowles bsddb can't use unicode filenames (2006-08-17) http://python.org/sf/1541671 opened by Zooko O'Whielacronx Incorrect example calls to PyObject_SetItem (2006-08-17) CLOSED http://python.org/sf/1541682 opened by John Machin Recently introduced sgmllib regexp bug hangs Python (2006-08-17) http://python.org/sf/1541697 opened by John J Lee Exceptions don't call _PyObject_GC_UNTRACK(self) (2006-08-17) http://python.org/sf/1542051 opened by ?iga Seilnacht global variable: multiple id()-addresses (2006-08-17) CLOSED http://python.org/sf/1542166 opened by Frank R. Schaefer Nested finally in generators don't follow PEP 342 (2006-08-17) http://python.org/sf/1542308 opened by Bob Ippolito httplib reads one byte per system call (2006-08-18) http://python.org/sf/1542407 opened by Zoyd Wheeler python-2.5c1.msi contains ICE validation errors and warnings (2006-08-18) http://python.org/sf/1542432 opened by Bob Arnson Bug in definition of PyImport_ImportModuleEx macro (2006-08-18) CLOSED http://python.org/sf/1542693 opened by Chris Stawarz idle in python 2.5c1 freezes on macos 10.3.9 (2006-08-18) http://python.org/sf/1542949 opened by David Strozzi tarfile in mode w|gz adds padding that annoys gunzip (2006-08-19) CLOSED http://python.org/sf/1543303 opened by alexis "from __future__ import foobar;" causes wrong SyntaxError (2006-08-20) http://python.org/sf/1543306 opened by daniel hahler Operator precedence inconsistent for complex literal (2006-08-20) CLOSED http://python.org/sf/1543347 opened by [N/A] test_tempfile fails on cygwin (2006-08-20) http://python.org/sf/1543467 opened by Miki Tebeka test_subprocess fails on cygwin (2006-08-20) http://python.org/sf/1543469 opened by Miki Tebeka md5 sums are different between Solaris and Windows XP SP1 (2006-08-21) http://python.org/sf/1543801 reopened by sunmountain md5 sums are different between Solaris and Windows XP SP1 (2006-08-21) http://python.org/sf/1543801 opened by Stefan Sonnenberg ctypes unit test fails (test_macholib.py) under MacOS 10.4.7 (2006-08-21) http://python.org/sf/1544102 opened by M. J. Fromberger test_anydbm segmentation fault (2006-08-21) http://python.org/sf/1544106 opened by Clay Spence python compiler support for with stmt (2006-08-21) http://python.org/sf/1544277 opened by Neal Norwitz Fix Lib/test/test___all__.py (2006-08-21) http://python.org/sf/1544295 opened by Hasan Diwan checking size of int... configure: error: cannot compute siz (2006-08-21) http://python.org/sf/1544306 opened by arrecostao _ctypes fails to build on Solaris x86 32-bit (Sun compiler) (2006-08-21) http://python.org/sf/1544339 opened by Case Van Horsen Bad result of calculation (2006-08-22) CLOSED http://python.org/sf/1544381 opened by Jean-Christophe BERTOLINI x!=y and [x]=[y] (!) (2006-08-22) http://python.org/sf/1544762 opened by Alex Martelli setup() keyword have to be list (doesn't work with tuple) (2006-08-23) http://python.org/sf/1545341 opened by STINNER Victor New-style classes fail to cleanup attributes (2006-08-23) http://python.org/sf/1545463 opened by Alexander Belopolsky inconsistent treatment of NULs in int() (2006-08-23) http://python.org/sf/1545497 opened by Neal Norwitz distutils home scheme lacks python versioning (2006-08-24) http://python.org/sf/1545658 opened by John Levon distutils needs vendor-packages support (2006-08-24) http://python.org/sf/1545659 opened by John Levon gcc trunk (4.2) exposes a signed integer overflows (2006-08-24) http://python.org/sf/1545668 opened by Jack Howarth structmember T_LONG won't accept a python long (2006-08-24) http://python.org/sf/1545696 opened by Roger Upole Incomplete info in 7.18.1 ZipFile Objects (2006-08-24) http://python.org/sf/1545836 opened by Taco array.array borks on deepcopy (2006-08-24) http://python.org/sf/1545837 opened by V?clav Haisman PyString_FromString() clarification (2006-08-24) http://python.org/sf/1546052 opened by Christian Walther bcannon secure branch issues (2006-08-24) CLOSED http://python.org/sf/1546203 opened by Jim Jewett subprocess.Popen can't read file object as stdin after seek (2006-08-25) http://python.org/sf/1546442 opened by GaryD String methods don't support explicit None arguments (2006-08-25) http://python.org/sf/1546585 opened by Nick Coghlan urlparse.urljoin odd behaviour (2006-08-25) http://python.org/sf/1546628 opened by Andres Riancho Bugs Closed ___________ Python 2.5 svn crash in _elementtree.c (2006-08-04) http://python.org/sf/1534630 closed by effbot bug in python 2.4.3 for windows? (2006-08-16) http://python.org/sf/1541566 closed by gbrandl Compiler command percent-sign causes format string error (2006-08-16) http://python.org/sf/1541642 deleted by mdcowles Incorrect example calls to PyObject_SetItem (2006-08-17) http://python.org/sf/1541682 closed by gbrandl global variable: multiple id()-addresses (2006-08-17) http://python.org/sf/1542166 closed by gbrandl Bug in definition of PyImport_ImportModuleEx macro (2006-08-18) http://python.org/sf/1542693 closed by nnorwitz tarfile in mode w|gz adds padding that annoys gunzip (2006-08-19) http://python.org/sf/1543303 closed by nnorwitz Operator precedence inconsistent for complex literal (2006-08-20) http://python.org/sf/1543347 closed by gbrandl md5 sums are different between Solaris and Windows XP SP1 (2006-08-21) http://python.org/sf/1543801 closed by sunmountain Bad result of calculation (2006-08-22) http://python.org/sf/1544381 closed by gbrandl bcannon secure branch issues (2006-08-24) http://python.org/sf/1546203 closed by bcannon New / Reopened RFE __________________ Optimizations for cgi.FieldStorage methods (2006-08-16) http://python.org/sf/1541463 opened by Bob Kline wsgi.org link in wsgiref (2006-08-18) http://python.org/sf/1542920 opened by Ian Bicking RFE Closed __________ extend strptime to understand logging timestamps (2004-08-10) http://python.org/sf/1006786 closed by bcannon From jason at adapt.com Sun Aug 13 20:47:24 2006 From: jason at adapt.com (Jason Nordwick) Date: Sun, 13 Aug 2006 17:47:24 -0700 Subject: yet another noob question In-Reply-To: <44DFC767.1030106@adapt.com> References: <1155492110.659011.196280@75g2000cwc.googlegroups.com> <44DFC767.1030106@adapt.com> Message-ID: <44DFC81C.2080408@adapt.com> better (sorry, still learning Python): def cross(x,y): return [a+b for a in x for y in b] Jason Nordwick wrote: > Or without filter: > > from operator import add > def pr(x): print x > def cross(x,y): return reduce(add, [[a+b for b in y] for a in x]) > x=map(pr, reduce(cross, [map(str,range(1,6))]*5)) > > > > mike_wilson1333 wrote: >> I would like to generate every unique combination of numbers 1-5 in a 5 >> digit number and follow each combo with a newline. So i'm looking at >> generating combinations such as: (12345) , (12235), (55554) and so on. >> What would be the best way to do this? So, basically i'm looking for a >> list of all combinations of 1-5 in a 5 digit unique number. Also, when >> I send the list to print there can't be any duplicates of the combos. >> >> >> Thanks, >> >> Mike >> > From http Thu Aug 10 10:12:43 2006 From: http (Paul Rubin) Date: 10 Aug 2006 07:12:43 -0700 Subject: Password authentication systems References: <1155218165.193546.136090@h48g2000cwc.googlegroups.com> Message-ID: <7xk65g3cis.fsf@ruckus.brouhaha.com> neokosmos at gmail.com writes: > Presumably, this is done using the crypt() system call (and, > fortunuately, Python has a builtin crypt module!). Presumably, as > well, this is at least somewhat secure, assuming a source of > cryptographic randomness to use to choose the salt. Are SHA1 and MD5 > suitable for this sort of thing as well, or would I need to move to > something more "industrial strength" from, say, the pyCrypto module if > I wanted to avoid a dependency on the crypt module? The salt doesn't really have to be cryptographically random. There are two main issues: 1) Unix password hashing uses several different algorithms depending on version and configuration. Do you need to interoperate, or are you just trying to do something similar? 2) Even with salting, computers are fast enough thse days to run dictionary searches against unkeyed hashed passwords, so Unix now uses a non-publicly-readable shadow password file. You're best off hashing with an actual secret key, if you have a way to maintain one. I'd suggest using the hmac module: hash = hmac.new(secret_key, password).hexdigest() will give you a hex digit string; or if you prefer, you could use .digest() instead of .hexdigest() and base64 encode it if you want printable output. Keep in mind, though, that if the secret key leaks, you effectively have an unsalted hash. You could add a salt if you want (untested): import os salt = os.urandom(8) # 8 random bytes hash = (salt, hmac.new(secret_key, salt + password).digest()) note that the salt and hash are both binary. You may want to encode them (e.g. base64) if you need printable chars. From you at cogeco.ca Fri Aug 11 01:40:46 2006 From: you at cogeco.ca (AlbaClause) Date: Fri, 11 Aug 2006 01:40:46 -0400 Subject: Password authentication systems References: <1155218165.193546.136090@h48g2000cwc.googlegroups.com> Message-ID: <aIUCg.67141$Uy1.12506@read1.cgocable.net> neokosmos at gmail.com wrote: > This may only be tangentially related to Python, but since I am coding > a password authentication system in Python, I thought I would ask here. > > In Linux (and presumably other *NIX systems that support it), when > shadow passwords are enabled, the actual password is not stored. > Instead an encrypted version is stored. Then, to authenticate the > password, the system re-encrypts the user's input to see if it matches > the stored, encrypted version. > Correct me if I'm wrong, but I believe that all Linux passwords are encrypted whether you enable shadow passwords or not. I believe that when you enable shadow passwords, the encrypted passwords are stored in a file other than 'passwd'. Is this not correct? From bdesth.quelquechose at free.quelquepart.fr Wed Aug 9 16:28:08 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 09 Aug 2006 22:28:08 +0200 Subject: converting a nested try/except statement into try/except/else In-Reply-To: <s8qCg.2663$No6.52066@news.tufts.edu> References: <s8qCg.2663$No6.52066@news.tufts.edu> Message-ID: <44da4329$0$702$626a54ce@news.free.fr> John Salerno a ?crit : > I'm starting out with this: > > try: > if int(text) > 0: > return True > else: > self.error_message() > return False > except ValueError: > self.error_message() > return False > > I rewrote it as this: > > try: > int(text) > except ValueError: > self.error_message() > return False > else: > return True > > I think it's much cleaner, but obviously I lost the test in the original > if statement. > > So my question is, can I still retain this second structure and still > test for > 0, but not have any extra nesting? solution 1: def wrong(): raise ValueError try: int(text) > 0 or wrong() except ValueError: self.error_message() return False else: return True But that's being-too-clever imho... solution 2: def error_message(): self.error_message() return False try: return int(text) > 0 or error_message() except ValueError: return error_message() From dhable at gmail.com Wed Aug 9 15:35:48 2006 From: dhable at gmail.com (dhable at gmail.com) Date: 9 Aug 2006 12:35:48 -0700 Subject: Two Classes In Two Files In-Reply-To: <44DA3937.5040901@mxm.dk> References: <1155151480.848276.52650@75g2000cwc.googlegroups.com> <44DA3937.5040901@mxm.dk> Message-ID: <1155152148.014855.166690@p79g2000cwp.googlegroups.com> > It's just the way it is. Why worry about it? Wasn't so much a worry, just trying to figure out how to think the python way. Max M wrote: > dhable at gmail.com wrote: > > I just started working with Python and ran into an annoyance. Is there > > a way to avoid having to use the "from xxx import yyy" syntax from > > files in the same directory? I'm sure it's been asked a million times, > > but I can't seem to find the answer. > > Probably none that are better. > > 1: > import one > class Two(one.One) > > 2: > put both classes in the same file. > > > It's just the way it is. Why worry about it? > > > > For example, I have two classes stored in separate files as such. > > > > File: one.py > > ======== > > class One: > > def methodA(self): > > print "class One" > > def methodB(self): > > print "class One" > > > > > > File two.py > > ======== > > from one import One > > > > class Two(One): > > def methodA(self): > > print "class Two" > > > > if __name__ == "__main__": > > x = Two() > > x.methodA() > > x.methodB() > > > > When I run the Two.py file, I get the expected output but I'd like to > > eliminate the from line in two.py. > > > > > -- > > hilsen/regards Max M, Denmark > > http://www.mxm.dk/ > IT's Mad Science > > Phone: +45 66 11 84 94 > Mobile: +45 29 93 42 96 From guotie.9 at gmail.com Tue Aug 29 03:41:00 2006 From: guotie.9 at gmail.com (=?utf-8?B?5Y+u5Y+u5b2T5b2T?=) Date: 29 Aug 2006 00:41:00 -0700 Subject: The lib email parse problem... Message-ID: <1156837260.222395.305960@b28g2000cwb.googlegroups.com> hi, all when a email body consist with multipart/alternative, i must know when the boundary ends to parse it, but the email lib have not provide some function to indicate the boundary end, how to solve it ? thanks. From lsumnler at gmail.com Thu Aug 10 13:11:37 2006 From: lsumnler at gmail.com (len) Date: 10 Aug 2006 10:11:37 -0700 Subject: semi-Newbie question Message-ID: <1155229897.356144.183750@m79g2000cwm.googlegroups.com> Hi all I have a file that I receive from another party which is basicly a csv file containing the following type of information; Tagname Scope Value "first_name","POL01","John" "last_name","POL01","Doe" "birthday","POL01","04/03/61" etc I need to convert this file info into my file format used in my application. I have been given a file from the other company that gives me all of the tagname that could be used and their scope. I want to build a table which would have all of the various tagnames, scope, and put a fieldname equivalent in the fieldname in my file structure in my application. Then read through the vendors csv file index into my table file and get the field name of where to move the data into my data structure. Here is my question? basicly I need to get the data referenced by fieldname variable in my table and then use that data as a variable name in a python assignment statement. Thus changing the actual python code at each iteration through the lines in the csv file. for i in tagfile find tagname in tagtable *** the following line of code would change through each iteration *** myfirst = value *** next iteration mylast = value *** next iteration mybirth = value etc I hope this make sense. I remember seeing something like this somewhere. Any help appreciated. Len Sumnler Unique Insurance From pydecker at gmail.com Wed Aug 16 19:29:42 2006 From: pydecker at gmail.com (Peter Decker) Date: Wed, 16 Aug 2006 19:29:42 -0400 Subject: Mega Newbie Questions: Probably FAQs In-Reply-To: <qNcEg.61$dB.36@read2.cgocable.net> References: <E64Eg.103891$hp.90053@read2.cgocable.net> <ebrg55$13r$1@news-int2.gatech.edu> <qNcEg.61$dB.36@read2.cgocable.net> Message-ID: <ca55a9900608161629w3f33d7a5ufa835d78c7bf043d@mail.gmail.com> On 8/15/06, Zeph <zeph_zhang at yahoo.co.uk> wrote: > > Framework for what kind of apps? Web, native GUI, client-server, etc? > > MVC is an abstract architecture rather than a specific implementation. > > Even so, many implementations rarely employ a purely MVC design. > > Native GUI with some client-server abilities. Basically, it's a > database-inventory sort of thing with some pretty intense reporting. > Call it a productivity app--no need for intense graphics or massive > computation. Fundamentally, what I want is to be able to distribute a > "regular app", mainly for the Windows market, but I also want to offer > it to the Mac and Linux crowd--on one code base if possible. You should really check out Dabo. It is an application framework designed to create database apps in a really Pythonic way. Probably the best way to start is to check out the screencasts - they really show just how cool Dabo is. I'd start with the one on quickly creating a database app: http://leafe.com/screencasts/appwizard.html The rest of them are listed at http://dabodev.com/documentation. I've been using the UI module from Dabo for over a year, and it's rock-solid. -- # p.d. From johan2sson at gmail.com Mon Aug 28 18:39:02 2006 From: johan2sson at gmail.com (johan2sson at gmail.com) Date: 28 Aug 2006 15:39:02 -0700 Subject: naive misuse? (of PyThreadState_SetAsyncExc) In-Reply-To: <1156720585.068907.244240@i3g2000cwc.googlegroups.com> References: <1156720585.068907.244240@i3g2000cwc.googlegroups.com> Message-ID: <1156804741.964769.98030@i42g2000cwa.googlegroups.com> johan2sson at gmail.com wrote: > The documentation for PyThreadState_SetAsyncExc says "To prevent naive > misuse, you must write your own C extension to call this". Anyone care > to list a few examples of such naive misuse? No? I'll take that then as proof that it's impossible to misuse the function. Thanks, Johan From grante at visi.com Fri Aug 11 13:49:22 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 11 Aug 2006 17:49:22 -0000 Subject: How to write a Installer for a Python App in Linux References: <1155240625.157696.143230@i42g2000cwa.googlegroups.com> <slrnedn60g.n0d.sybrenUSE@schuimige.stuvel.eu> <1155316580.905203.245070@b28g2000cwb.googlegroups.com> Message-ID: <12dpgp2o5gjh07d@corp.supernews.com> On 2006-08-11, diffuser78 at gmail.com <diffuser78 at gmail.com> wrote: > > Every help is appreciated. Thanks. > >> You could freeze the Python program. That'll ensure all the required >> files are packaged with your program, including Python itself. If you >> build a RPM from that, your users will be quite happy. > How can we freeze the python program and how will it ensure that all > the python files are packages with the programs (including python and > wxPython). Can anybody give me some pointers on this. http://www.google.com/search?hl=en&lr=&q=freeze+python+program+linux -- Grant Edwards grante Yow! Imagine--a WORLD at without POODLES... visi.com From kylotan at gmail.com Mon Aug 14 10:16:41 2006 From: kylotan at gmail.com (Ben Sizer) Date: 14 Aug 2006 07:16:41 -0700 Subject: hide python code ! In-Reply-To: <pan.2006.08.14.08.55.18.243936@REMOVEME.cybersource.com.au> References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155300852.497741.73230@74g2000cwt.googlegroups.com> <1155301468.870340.82920@b28g2000cwb.googlegroups.com> <1155307415.855555.124760@i3g2000cwc.googlegroups.com> <1155309563.898182.195950@p79g2000cwp.googlegroups.com> <1155313092.743230.33950@m73g2000cwd.googlegroups.com> <pan.2006.08.14.08.55.18.243936@REMOVEME.cybersource.com.au> Message-ID: <1155565001.913956.37300@m73g2000cwd.googlegroups.com> Steven D'Aprano wrote: > On Fri, 11 Aug 2006 09:18:12 -0700, Ben Sizer wrote: > > > Imagine if you were the single-person developer of a small application > > that did something quite innovative, > > And imagine that you found a money-tree in your back yard... > > How about a more likely scenario? Imagine you're using a boring, > run-of-the-mill algorithm, the same as 99.9% of all software out there, > and that it's neither non-obvious nor innovative in any way at all. > Statistically, I'd say it is ten thousand times more likely that this is > the case than that the algorithm is at all valuable. Everybody thinks > their algorithm is "special". They almost never are. I work in game development, where new algorithms and processes are being discovered all the time. Sure, they're not going to cure cancer or end poverty but there are most definitely some algorithms devised by many developers which other companies have no idea how to emulate until years down the line; long enough for the first company to enjoy a little commercial benefit based on their individual implementation. > Valuable algorithms are rare. Most software is not valuable for the > algorithm, which is hidden in the source code, but for the functionality, > which is obvious. Algorithms are a dime a dozen. True, however, most is not all, and I think it's unfair to categorise all software as being so trivial. > Yes, and for every algorithm "worth stealing", there are ten thousand that > aren't. Play the odds, and you too will poo-poo the idea that some random > developer on Usenet has discovered a valuable innovative algorithm. More > likely he's just ashamed of his code, or wants to hide backdoors in it. Play the odds, and pretty much everything is unlikely. Of all the names in the world, what was the chance of this language being called Python? Yet these things occasionally happen. I have no opinion on why the original poster wants to hide code, only an opinion on there definitely being a few applications where it is very useful. -- Ben Sizer From michiel at thingmajig.org Thu Aug 10 08:00:16 2006 From: michiel at thingmajig.org (Michiel Sikma) Date: Thu, 10 Aug 2006 14:00:16 +0200 Subject: sys.platform documentation? In-Reply-To: <1155207649.983067.55840@h48g2000cwc.googlegroups.com> References: <mailman.9183.1155198457.27775.python-list@python.org> <1155207649.983067.55840@h48g2000cwc.googlegroups.com> Message-ID: <6B6F02F4-2881-4145-B008-E6CD232AAF3C@thingmajig.org> Op 10-aug-2006, om 13:00 heeft Tim Golden het volgende geschreven: > Michiel Sikma wrote: >> Hello everybody, >> >> I was thinking about making a really insignificant addition to an >> online system that I'm making using Python: namely, I would like it >> to print the platform that it is running on in a human-readable >> manner. I was thinking of doing it like this: > > [... snip ...] > >> However, in order to populate the list of platforms, I need to know >> which strings sys.platform can return. I haven't found any >> documentation on this > > Not that this answers your question directly, but is the > platform module of any more use to you? > > http://docs.python.org/lib/module-platform.html > > TJG > > -- > http://mail.python.org/mailman/listinfo/python-list I didn't even know there was a platform module. Too bad that one also does not have documentation on possible values for common systems. It seems that uname() is the most resourceful function. So if I do this: >>> import platform >>> platform.uname() ('Darwin', 'imac-g5-van-michiel-sikma.local', '8.6.0', 'Darwin Kernel Version 8.6.0: Tue Mar 7 16:58:48 PST 2006; root:xnu-792.6.70.obj~1/ RELEASE_PPC', 'Power Macintosh', 'powerpc') That's on Mac OS X 10.4.6. Indeed more useful. Michiel From bytter at gmail.com Thu Aug 10 20:47:49 2006 From: bytter at gmail.com (Hugo Ferreira) Date: Fri, 11 Aug 2006 01:47:49 +0100 Subject: Rendering Vector Graphics Message-ID: <4e8efcf50608101747o69f573d7ueabc5f81bf449b55@mail.gmail.com> Hi ppl, I need to render high-quality vector graphics with Python. I was thinking of something like 'cairo', though I need to run under win32 and can't find a pycairo package for it. Suggestions? Thanks, Hugo Ferreira -- GPG Fingerprint: B0D7 1249 447D F5BB 22C5 5B9B 078C 2615 504B 7B85 -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060811/60cefbf0/attachment.html> From jdjmson at yahoo.com Thu Aug 31 21:15:01 2006 From: jdjmson at yahoo.com (JDJMSon) Date: 31 Aug 2006 18:15:01 -0700 Subject: Boost Python Issue In-Reply-To: <mailman.10221.1157072704.27775.python-list@python.org> References: <1157063033.800940.181130@e3g2000cwe.googlegroups.com> <mailman.10221.1157072704.27775.python-list@python.org> Message-ID: <1157073301.401994.166920@h48g2000cwc.googlegroups.com> Neal Becker wrote: > Shouldn't that be: > .def("TestFunction",&TestClass::TestFunction) > > ; Yes, you're right, but I'm still getting the error. I'm using a prebuilt python library, so later I'm going to rebuild python myself and see if that helps, as has been suggested. Thanks. From steve at REMOVEME.cybersource.com.au Mon Aug 14 04:55:15 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Mon, 14 Aug 2006 18:55:15 +1000 Subject: hide python code ! References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155300852.497741.73230@74g2000cwt.googlegroups.com> <mailman.9245.1155301627.27775.python-list@python.org> <1155302186.352955.111180@p79g2000cwp.googlegroups.com> Message-ID: <pan.2006.08.14.08.55.13.899443@REMOVEME.cybersource.com.au> On Fri, 11 Aug 2006 06:16:26 -0700, Fuzzyman wrote: > What you can do with Python is almost certainly *good enough* for most > people who ask this question - and that fact never seems to be included > in the 'reality' propogated by the knee jerk reactionists... :-p The Original Poster *explicitly* stated that he was aware of the .pyc files, and rejected that strategy because .pyc files can be decompiled. He was asking for something which can't be decompiled, which is not possible since machine code can also be decompiled -- in fact, there are probably lots more disassemblers and decompilers for C than there are for Python. I'd rather educate him so he stops wasting his time rather than reinforce his ignorance by pretending that there are ways of distributing code without it also being decompilable. You suggested that it does harm to Python to give developers a realistic understanding of what Python is capable of, and that it's better to give them a misleading answer. I reject that idea utterly. -- Steven D'Aprano From http Wed Aug 16 13:03:06 2006 From: http (Paul Rubin) Date: 16 Aug 2006 10:03:06 -0700 Subject: X windows and Python? References: <7xy7tpyhbf.fsf_-_@ruckus.brouhaha.com> <12e48tl6q5vs8fc@corp.supernews.com> Message-ID: <7xu04c7gvp.fsf@ruckus.brouhaha.com> Grant Edwards <grante at visi.com> writes: > The way (well, _one_ way) it's supposed to work is you make an > Xlib call to claim ownership of "the selection". ... Thanks, this explanation was very interesting. It would be great if tkinter had some calls to do this stuff, which I guess means the underlying Tk needs them (I dunno if it has them). Anyway, for what I was doing, it wasn't that urgent, and I'm using an awful workaround. From steve at REMOVEME.cybersource.com.au Tue Aug 22 20:37:13 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 23 Aug 2006 10:37:13 +1000 Subject: how do you get the name of a dictionary? References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <pan.2006.08.21.03.33.27.84160@REMOVEME.cybersource.com.au> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> <mailman.9631.1156227418.27775.python-list@python.org> <1156264475.968894.221710@p79g2000cwp.googlegroups.com> Message-ID: <pan.2006.08.23.00.37.13.778241@REMOVEME.cybersource.com.au> On Tue, 22 Aug 2006 09:34:36 -0700, jojoba wrote: > i don't want to do anything sophisticated with this, i am really only > looking for a TITLE for my dictionary when i throw it in a tree editor > that i have built. And i do realize that its not possible now. I am just > pressing a point here. Something like this might help. def get_object_title(object, namespace=None): """Returns a possible title/name for object, in the given namespace.""" if namespace is None: namespace = globals() try: return object.__name__ # works for functions, classes, modules except AttributeError: # search the namespace for key,value in namespace.items(): if object is value: # do NOT use == return key # not found in the namespace either # maybe an unnamed object? return "Object ID %d" % id(object) Hope this helps. -- Steven D'Aprano From bill.mill at gmail.com Thu Aug 17 10:10:44 2006 From: bill.mill at gmail.com (Bill Mill) Date: 17 Aug 2006 07:10:44 -0700 Subject: iTunes Search Algorithm/Data Structure? Message-ID: <1155823844.679026.276610@i3g2000cwc.googlegroups.com> Hello all, What data structure would you use to implement something analogous to the iTunes search? I imagine that it must be a tree of some sort, but I can't figure out an easy structure for it. Requirements (in case you haven't used it): You are given 4 rows in a list view: [["alpha, "beta"], ["delta", "gamma"], ["foo", "bar"], ["etc", "etc"]] and a search text box. Typing "a" in the list box leaves rows 0, 1 and 2 in the list box, because some element in each of those rows has an "a" in it. Typing "am" leaves only row 1, since "gamma" has the substring "am" in it. The key here is that this works instantaneously as you type, even with very large lists with many elements per row. I'd like the employee list in my current application to be similarly filtered, but I don't quite see how. Thoughts? -Bill Mill bill.mill at gmail.com billmill.org From sjmachin at lexicon.net Wed Aug 9 20:28:09 2006 From: sjmachin at lexicon.net (John Machin) Date: 9 Aug 2006 17:28:09 -0700 Subject: Class data being zapped by method In-Reply-To: <1155144925.636419.80510@75g2000cwc.googlegroups.com> References: <1155065906.910642.77320@75g2000cwc.googlegroups.com> <mailman.9111.1155066643.27775.python-list@python.org> <1155076971.519157.92540@i42g2000cwa.googlegroups.com> <1155081910.390971.249200@p79g2000cwp.googlegroups.com> <1155094292.614160.49320@75g2000cwc.googlegroups.com> <1155099427.204715.113250@n13g2000cwa.googlegroups.com> <1155144925.636419.80510@75g2000cwc.googlegroups.com> Message-ID: <1155169689.446373.139250@p79g2000cwp.googlegroups.com> Kevin M wrote: > Good news. I've fixed it up and all seems to be well. > > Thanks, all. I've learned a lot from this -:) Kindly share the learning by feeding back: (1) What the original problem ("class data being zapped by method") really was. (2) What was the cause of the drama with pyc files. (3) Answers to the questions posed after you asked about speed bottlenecks? [See below] > > > Does anybody see any major bottlenecks in the code? I'd like to be able > > > to speed up the program considerably. Psyco was really no help. > > 1. Get it refactored and working correctly first. "except IndexError: > > pass" certainly won't help you win the Grand Prix; how many of those > > were you doing per 20MB of data? > > 2. How long does it take to run ? How long would you prefer it to take? > > How many lines x how many tests == 20 MB? Cheers, John From rosedb0 at gmail.com Wed Aug 16 19:04:03 2006 From: rosedb0 at gmail.com (hiaips) Date: 16 Aug 2006 16:04:03 -0700 Subject: How to delete a directory tree in FTP In-Reply-To: <1155742012.987806.236060@75g2000cwc.googlegroups.com> References: <1155742012.987806.236060@75g2000cwc.googlegroups.com> Message-ID: <1155769443.011810.194340@i3g2000cwc.googlegroups.com> T wrote: > I connect to a FTP server which can be either unix or windows server. > Once in the FTP session, I would like to delete a directory tree on the > server. Is there a command that will do this? If not, can someone > point me to a right direction? > > Thanks! Try using an "FTP" object from the ftplib module. There's a "delete" method there (along with several other useful things.) --dave From onurb at xiludom.gro Tue Aug 29 04:51:06 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 29 Aug 2006 10:51:06 +0200 Subject: Truly platform-independent DB access in Python? In-Reply-To: <1156781824.501010.257890@p79g2000cwp.googlegroups.com> References: <1156748466.739709.117850@h48g2000cwc.googlegroups.com> <44f2bade$0$13039$626a54ce@news.free.fr> <1156778705.807852.140510@75g2000cwc.googlegroups.com> <44f310e3$0$26022$636a55ce@news.free.fr> <1156781824.501010.257890@p79g2000cwp.googlegroups.com> Message-ID: <44f3fffb$0$31016$626a54ce@news.free.fr> Boris Du?ek wrote: > Bruno Desthuilliers wrote: > >>> but what if the OS with server accessing the site that is on >>> shared area changes? >> And what if Python is not installed on it ?-) >> >> Seriously, do you think that hosting companies swap OS very often ? > > No, I don't. But I was trying to find the best solution. :-) Is there any reason to find a solution for a non-yet-existing problem ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From thomasbartkus at comcast.net Tue Aug 8 13:09:50 2006 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Tue, 8 Aug 2006 12:09:50 -0500 Subject: Newbie question: what's with "self"? References: <1155054411.511813.203270@i42g2000cwa.googlegroups.com> Message-ID: <kOSdnaMqEaqOWEXZnZ2dnUVZ_uWdnZ2d@telcove.net> "donkeyboy" <fivenastydisco at hotmail.com> wrote in message news:1155054411.511813.203270 at i42g2000cwa.googlegroups.com... > This is probably a really basic question, but anyway ... > > I'm new to both Python and OO programming. From looking at a number of > code examples, the word "self" is used a lot when referring to classes. > As such, what does "self" mean and/or do? I've read things that say > it's a naming convention, but no-one has really spelt it out (in idiot > form!) in a way I can understand. > > Any help you can provide would be great: at the moment, when code > doesn't work as expected, I'm randomly sprinkling "self"s in all over > the place to see if that helps, but without much of an idea of what it > really achieves. > > Thanks in advance!! > To put it simply, a class needs a way to know which instance (of itself!) to operate on. If you have a class "str" (and Python has that built in!), then there will be many instances of class "str" in a typical program. The parameter "self" refers to the particular string the class method is being called to operate upon. If you have a method upper() that convert everything to uppercase, your class definition would need the "self" parameter in order to know which particular string to convert. Thomas Bartkus From robert.kern at gmail.com Thu Aug 24 12:15:38 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 24 Aug 2006 11:15:38 -0500 Subject: Newbie question about numpy In-Reply-To: <e4hre29hpv4ef1spfbqsu2hq0ee4apgdpv@4ax.com> References: <e4hre29hpv4ef1spfbqsu2hq0ee4apgdpv@4ax.com> Message-ID: <eckjb5$u62$1@sea.gmane.org> Paul Johnston wrote: > Hi I'm new to python and have just been taking a look at what it has > to offer. > I noted the lack of matrices so installed numpy You will want to ask numpy questions on the numpy list. http://www.scipy.org/Mailing_Lists numpy arrays are not matrices; they are arrays. All of the arithmetic operations on them are done element-wise. The dot() function will do matrix multiplication. There is a matrix class (with the constructor numpy.mat(some_array)) that derives from arrays and overrides the * operator to do matrix multiplication if that is what you want. I prefer using dot() on regular arrays, myself. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From python at hope.cz Tue Aug 22 10:39:36 2006 From: python at hope.cz (Lad) Date: 22 Aug 2006 07:39:36 -0700 Subject: How to decode a string In-Reply-To: <mailman.9645.1156254872.27775.python-list@python.org> References: <1156170296.076521.174180@i3g2000cwc.googlegroups.com> <1156244818.061709.115190@m73g2000cwd.googlegroups.com> <mailman.9645.1156254872.27775.python-list@python.org> Message-ID: <1156257576.760734.155560@p79g2000cwp.googlegroups.com> Fredrik Lundh wrote: > "Lad" wrote: > > > The result of print "*", repr(RealName), type(RealName), "*" is > > > > * 'Fritschov\xe1 Laura' <type 'str'> * > > looks like the MySQL interface is returning 8-bit strings using ISO-8859-1 > encoding (or some variation of that; \xE1 is "LATIN SMALL LETTER A > WITH ACUTE" in 8859-1). > > have you tried passing "use_unicode=True" to the connect() call ? > > </F> Frederik, Thank you for your reply. I found out that if I do not decode the string at all, it looks correct. But I do not know why it is ok without decoding. I use Django and I do not use use_unicode=True" to the connect() call. From skip at pobox.com Wed Aug 30 17:59:17 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 30 Aug 2006 16:59:17 -0500 Subject: csv module strangeness. In-Reply-To: <44f5e947$0$8814$88260bb3@free.teranews.com> References: <44f5e870$0$8814$88260bb3@free.teranews.com> <44f5e947$0$8814$88260bb3@free.teranews.com> Message-ID: <17654.2613.698898.556858@montanaro.dyndns.org> tobiah> So now it works, but it is still strange about the absent tobiah> defaults. The csv.Dialect class is essentially pure abstract. Most of the time I subclass csv.excel and just change the one or two things I need. Skip From rogue_pedro at yahoo.com Sun Aug 20 14:34:48 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 20 Aug 2006 11:34:48 -0700 Subject: Access to sys.argv when python interpreter is invoked in some modes like 'python -c "command"' In-Reply-To: <1156097760.557614.195120@74g2000cwt.googlegroups.com> References: <1156097760.557614.195120@74g2000cwt.googlegroups.com> Message-ID: <1156098888.255139.177840@b28g2000cwb.googlegroups.com> poggle.themammal at gmail.com wrote: > The python tutorial says > "When the script name is given as '-' (meaning standard input), > sys.argv[0] is set to '-'. When -c command is used, sys.argv[0] is > set to '-c'. " but when we use a command say 'python -c "command"' > where can we access "sys.argv" (are there some commands where > "sys.argv" is accessed. I can run 'python -c "import sys sys.argv", I > get an error message > > -Tiro When you get an error message, and you ask a question concerning the error message, *post* the error message. But first, read it yourself. It will probably tell you what's wrong. That's why it exists. Meantime, what's your question? BTW, "import sys sys.argv" is invalid python. When putting code statements together on one line like this you must separate them with ";". I.e. "import sys; sys.argv". Note that this will still not do what (I'm guessing) you want because this code is not being executed interactively. It will simply "get" the value of sys.argv and then throw it away. Try "import sys; print sys.argv", if you want to print the value of sys.argv. Happy coding, ~Simon From andre.roberge at gmail.com Tue Aug 15 17:59:56 2006 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 15 Aug 2006 14:59:56 -0700 Subject: programming with Python 3000 in mind In-Reply-To: <mailman.9386.1155678036.27775.python-list@python.org> References: <1155672987.522793.47080@74g2000cwt.googlegroups.com> <1155677243.626081.188200@i42g2000cwa.googlegroups.com> <mailman.9386.1155678036.27775.python-list@python.org> Message-ID: <1155679196.033251.223150@p79g2000cwp.googlegroups.com> Fredrik Lundh wrote: > Andr? wrote: > > > When it comes to *teaching/learning* Python, it makes much more sense > > to have print() as a function (same with exec) given what it does > > -compared with the purpose of the other keywords. > > that's rubbish, of course, and seems to assume that python students, in > general, are obsessed with hyper-generalization. they're not. > > </F> On a scale of 0-10, for Python technical knowledge, you (F.L.) are probably at 9.5 whereas I might hover around 2 - and I will most likely always defer to your expertise in this area. However, I have some experience as a Python student (having learned about programming in Python on my own over the past two years) and as a teacher (*mostly* in a very different field) and I respectfully disagree over this hyper-generalised characterisation of my stated opinion on this subject as "rubbish". Andr? From fredrik at pythonware.com Mon Aug 28 14:16:34 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 28 Aug 2006 20:16:34 +0200 Subject: class problem In-Reply-To: <Xns982DBFD76BA73duncanbooth@127.0.0.1> References: <1156786617.162744.128870@h48g2000cwc.googlegroups.com> <Xns982DBFD76BA73duncanbooth@127.0.0.1> Message-ID: <ecvbu2$j8h$2@sea.gmane.org> Duncan Booth wrote: > Yes, the first one is a syntax error because you aren't allowed empty > parentheses in a class statement however, $ python Python 2.5c1 /.../ >>> class foo(): ... pass ... >>> foo <class __main__.foo at 0x00A3D840> >>> </F> From drodrig at magicbrain.com Sat Aug 12 00:28:38 2006 From: drodrig at magicbrain.com (drodrig) Date: 11 Aug 2006 21:28:38 -0700 Subject: Kill process based on window name (win32) Message-ID: <1155356918.399290.266470@p79g2000cwp.googlegroups.com> Hi. I am trying to close/kill all processes that show visible windows on Windows XP. So far I've created a script that uses win32gui.EnumWindows to iterate through all windows, check for which windows are visible, then send a WM_CLOSE message to the window to request that it closes. Of course, not all apps want to close nicely. At this point I need to use something like TerminateProcess to kill the app, but how do I find the process id (hopefully based on the window id). Thanks for any help. From diffuser78 at gmail.com Fri Aug 11 13:16:20 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 11 Aug 2006 10:16:20 -0700 Subject: How to write a Installer for a Python App in Linux In-Reply-To: <slrnedn60g.n0d.sybrenUSE@schuimige.stuvel.eu> References: <1155240625.157696.143230@i42g2000cwa.googlegroups.com> <slrnedn60g.n0d.sybrenUSE@schuimige.stuvel.eu> Message-ID: <1155316580.905203.245070@b28g2000cwb.googlegroups.com> Hi, How can we freeze the python program and how will it ensure that all the python files are packages with the programs (including python and wxPython). Can anybody give me some pointers on this. Every help is appreciated. Thanks. > You could freeze the Python program. That'll ensure all the required > files are packaged with your program, including Python itself. If you > build a RPM from that, your users will be quite happy. > Sybren From gherron at islandtraining.com Thu Aug 31 11:04:58 2006 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 31 Aug 2006 08:04:58 -0700 Subject: genetic algorithms package for python ? In-Reply-To: <44F6F464.8080103@gmail.com> References: <44F6F464.8080103@gmail.com> Message-ID: <44F6FA9A.2090103@islandtraining.com> Xiao Jianfeng wrote: > Hi all, > > I am looking for a genetic algorithms package for Python. > > I have googled the web before posting and found some links. The link of > pygene(http://www.freenet.org.nz/python/pygene) cannot be opened. > > I also tried the recipe on ASPN, but it is too simple for my > application, and the ga model in SciPy, which is in testing in the > "sandbox". > > Are there any more genetic algorithms packages for Python ? > > Thanks a lot! > > xiaojf > > Here's pointers to one in Lisp and another in Python. I know *nothing* about either one. http://packages.debian.org/unstable/devel/cl-rsm-genetic-alg.html http://home.gna.org/oomadness/en/genetic/ Enjoy, Gary Herron From andrew.arobert at gmail.com Tue Aug 29 12:02:11 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Tue, 29 Aug 2006 12:02:11 -0400 Subject: Python editor In-Reply-To: <1156864535.593418.168340@h48g2000cwc.googlegroups.com> References: <mailman.9834.1156459647.27775.python-list@python.org> <44EE3312.8040707@websafe.com> <ed02ij$591$1@news.cn99.com> <ifYIg.2712$No6.53186@news.tufts.edu> <1156864535.593418.168340@h48g2000cwc.googlegroups.com> Message-ID: <12f8p85fqtoftcf@corp.supernews.com> sjdevnull at yahoo.com wrote: > John Salerno wrote: >> Is it possible to get vim-python for Windows, or is that just a Linux build? > > > It builds for windows. > When installed, you may also want to consider the python add-on located at http://www.vim.org/scripts/script.php?script_id=790 Enhanced version of the original (from vim6.1) python.vim for Python programming language. The changes since the original python.vim are: - changed strings highlighting; - enhanced special symbols highlighting inside strings; - enhanced numbers highlighting; - added optional highlighting for %-formatting inside strings; - added highlighting for some error conditions (wrong symbols in source file, mixing spaces and tabs, wrong number values, wrong %-formatting inside strings); - added highlighting for magic comments: source code encoding and #! (executable) strings; - added highlighting for new exceptions and builtins introduced in python 2.3, 2.4 and 2.5; - added highlighting for doctests; - added highlighting for new @decorator syntax introduced in Python 2.4a2; - added highlighting for trailing-space errors (triggered by new option: python_highlight_space_errors); - added highlighting for variable name errors; - added highlighting for hex number errors; From fredrik at pythonware.com Wed Aug 16 10:21:51 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Aug 2006 16:21:51 +0200 Subject: Adding a char inside path string References: <1155737700.290268.248250@i42g2000cwa.googlegroups.com> Message-ID: <ebv9lu$4ov$1@sea.gmane.org> "Hitesh" wrote: > I get path strings from a DB like: > > \\serverName\C:\FolderName1\FolderName2\example.exe > > I am writing a script that can give me access to that exe file. > But problem is that string is not universal path, I need to add C$. > Any idea how I can add $ char in that string. > ServerName is not fixed length. It could be any chars length. upath = path.replace("C:", "C$") </F> From rrs at researchut.com Sat Aug 5 14:56:05 2006 From: rrs at researchut.com (Ritesh Raj Sarraf) Date: Sun, 06 Aug 2006 00:26:05 +0530 Subject: Thread Question References: <1153998422.670828.148360@m79g2000cwm.googlegroups.com> <1154019801.999805.150000@m73g2000cwd.googlegroups.com> <mailman.8857.1154541684.27775.python-list@python.org> <1154544553.990241.280030@i3g2000cwc.googlegroups.com> <1154590917.731457.106230@s13g2000cwa.googlegroups.com> <1154613366.350191.81880@m73g2000cwd.googlegroups.com> <1154676387.063576.100570@i42g2000cwa.googlegroups.com> <1154690942.385855.41130@m79g2000cwm.googlegroups.com> <lfYAg.3102$kO3.2277@newssvr12.news.prodigy.com> <mailman.9014.1154801071.27775.python-list@python.org> <tp5Bg.3519$9T3.1625@newssvr25.news.prodigy.net> Message-ID: <eb2pk8$bbr$1@sea.gmane.org> Bryan Olson on Saturday 05 Aug 2006 23:56 wrote: > You don't want "ziplock = threading.Lock()" in the body of > the function. It creates a new and different lock on every > execution. Your threads are all acquiring different locks. > To coordinate your threads, they need to be using the same > lock. > > Try moving "ziplock = threading.Lock()" out of the function, so > your code might read, in part: > > > ziplock = threading.Lock() > > def run(request, response, func=copy_first_match): > # And so on... Thanks. That did it. :-) Ritesh -- Ritesh Raj Sarraf RESEARCHUT - http://www.researchut.com "Necessity is the mother of invention." "Stealing logic from one person is plagiarism, stealing from many is research." "The great are those who achieve the impossible, the petty are those who cannot - rrs" From michiel at thingmajig.org Fri Aug 11 04:05:36 2006 From: michiel at thingmajig.org (Michiel Sikma) Date: Fri, 11 Aug 2006 10:05:36 +0200 Subject: sys.platform documentation? In-Reply-To: <1155230321.846569.115260@b28g2000cwb.googlegroups.com> References: <mailman.9183.1155198457.27775.python-list@python.org> <1155207649.983067.55840@h48g2000cwc.googlegroups.com> <mailman.9194.1155211222.27775.python-list@python.org> <1155230321.846569.115260@b28g2000cwb.googlegroups.com> Message-ID: <A6649522-040B-4565-B1BB-00FF23EA5EEB@thingmajig.org> Op 10-aug-2006, om 19:18 heeft Simon Forman het volgende geschreven: > It might be a good idea to write a brief script to print out > sys.platform, platform.platform(), platform.uname(), etc.. and > post it > here for people to run and post their results. > > Peace, > ~Simon > > -- > http://mail.python.org/mailman/listinfo/python-list sys.platform is actually not needed anymore once you use platform, it seems. So if you run this script: -- import platform platform.platform() platform.uname() -- You will get all the information that is necessary. And then you just need to provide it with a human-determined name of the operating system you're using. My output: >>> import platform >>> platform.platform() 'Darwin-8.6.0-Power_Macintosh-powerpc-32bit' >>> platform.uname() ('Darwin', 'imac-g5-van-michiel-sikma.local', '8.6.0', 'Darwin Kernel Version 8.6.0: Tue Mar 7 16:58:48 PST 2006; root:xnu-792.6.70.obj~1/RELEASE_PPC', 'Power Macintosh', 'powerpc') And I'm on Mac OS X 10.4.6 on a G5 iMac. Michiel From pythonnews at nospam.jmbc.fr Fri Aug 4 02:50:27 2006 From: pythonnews at nospam.jmbc.fr (jean-michel bain-cornu) Date: Fri, 04 Aug 2006 08:50:27 +0200 Subject: [Linux] What toolkit for a good grid/spreadsheet widget? In-Reply-To: <ma85d2lg1l260fmgg6k14kcqu6al2ift3c@4ax.com> References: <6fo4d2h0lnq2qcgi8jknh0ddmphhdgaulj@4ax.com> <mailman.8938.1154639225.27775.python-list@python.org> <ma85d2lg1l260fmgg6k14kcqu6al2ift3c@4ax.com> Message-ID: <44d2eebb$0$7764$7a628cd7@news.club-internet.fr> Hi, > Thx for the two pointers. Are those widgets more than just tables, ie. > can I edit the contents, including displaying a combo box, can items > be grouped or hierarchized, or are they just basic, read-only tables > to display results? > > I need this kind of widget to build a 2+ column interface to let users > type entries into the application as an alternative to MS Access-style > complicated entry masks. Wx have got an excellent one. I was succesful to use it with editable cells and to include a choice in a cell. However, it was pretty hard to reach that, ie to extract a working sample from the demo. Once done that, no more problems with it. What I suggest you is to have a look on the demo, in the chapter "Core Windows/Controls -> Grid -> wx.Grid showing Editors and Renderers". Rgds, jm From originalbrownster at gmail.com Tue Aug 1 21:58:03 2006 From: originalbrownster at gmail.com (OriginalBrownster) Date: 1 Aug 2006 18:58:03 -0700 Subject: Zipping files/zipfile module Message-ID: <1154483883.796081.35140@p79g2000cwp.googlegroups.com> This will probably sound like a very dumb question. I am trying to zip some files within a directory. I want to zip all the files within a directory called "temp" and have the zip archive saved in a directory with temp called ziptemp I was trying to read up on how to use the zipfile module python provides, but I cannot seem to find adequate documentation on function itself. Perhaps someone could help me in this task? I am guessing it must be something like the shutile module something like copy(src,dst) THank you Stephen From st at tobiah.org Tue Aug 15 19:04:12 2006 From: st at tobiah.org (tobiah) Date: Tue, 15 Aug 2006 16:04:12 -0700 Subject: Clean way to not get object back from instantiation attempt gone bad Message-ID: <44e245c0$0$20991$88260bb3@free.teranews.com> Suppose I do: myfoo = Foo('grapes', 'oranges') And in the __init__() of Foo, there is a real problem with the consumption of fruit. Is there a clean way to ensure that myfoo will be None after the call? Would the __init__() just do del(self), or is there a better way to think about this? Thanks, Toby -- Posted via a free Usenet account from http://www.teranews.com From skip at pobox.com Thu Aug 10 09:41:45 2006 From: skip at pobox.com (skip at pobox.com) Date: Thu, 10 Aug 2006 08:41:45 -0500 Subject: Python-list Digest, Vol 35, Issue 160 In-Reply-To: <CC0D63AF-2F0C-4B84-A8BA-BFE5BBE1036B@carnegielearning.com> References: <mailman.33888.1155215103.27774.python-list@python.org> <CC0D63AF-2F0C-4B84-A8BA-BFE5BBE1036B@carnegielearning.com> Message-ID: <17627.14233.684281.17915@montanaro.dyndns.org> Brendon> Seems that parsing negative numbers is outside of the scope of Brendon> this routine. Here's the source (which is Frederik's source Brendon> with one minor renaming; I take no credit here); anyone have Brendon> any ideas? Negative numbers are actually tokenized as a MINUS followed by a NUMBER: % python Python 2.5b2 (trunk:50921, Jul 28 2006, 20:21:50) [GCC 4.0.0 (Apple Computer, Inc. build 5026)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> - 47 -47 Try changing your atom function to detect a minus sign, remember that fact, then require the next token to be a number. Skip From jemminger at gmail.com Thu Aug 17 17:26:09 2006 From: jemminger at gmail.com (jemminger at gmail.com) Date: 17 Aug 2006 14:26:09 -0700 Subject: re.sub() backreference bug? Message-ID: <1155849969.628999.287180@b28g2000cwb.googlegroups.com> using this code: import re s = 'HelloWorld19-FooBar' s = re.sub(r'([A-Z]+)([A-Z][a-z])', "\1_\2", s) s = re.sub(r'([a-z\d])([A-Z])', "\1_\2", s) s = re.sub('-', '_', s) s = s.lower() print "s: %s" % s i expect to get: hello_world19_foo_bar but instead i get: hell?_?orld19_fo?_?ar (in case the above doesn't come across the same, it's: hellX_Yorld19_foX_Yar, where X is a white smiley face and Y is a black smiley face !!) is this a bug, or am i doing something wrong? tested on Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32 and Python 2.4.4c0 (#2, Jul 30 2006, 15:43:58) [GCC 4.1.2 20060715 (prerelease) (Debian 4.1.1-9)] on linux2 From acachinero at gmail.com Sun Aug 20 02:40:58 2006 From: acachinero at gmail.com (eltower) Date: 19 Aug 2006 23:40:58 -0700 Subject: [NEWB]: List with random numbers In-Reply-To: <pan.2006.08.20.06.32.08.543241@gmx.net> References: <1156054456.520655.49040@b28g2000cwb.googlegroups.com> <pan.2006.08.20.06.32.08.543241@gmx.net> Message-ID: <1156056058.107929.30300@p79g2000cwp.googlegroups.com> Marc 'BlackJack' Rintsch wrote: > In <1156054456.520655.49040 at b28g2000cwb.googlegroups.com>, eltower wrote: > > > Generate a random number from 0 to 6 > > Insert this random number to the end of a list unless the number is > > already there > > finish with a len(list) = 7 > > > > so far, I have this: > > > > import random > > > > random_list = [] > > > > while len(random_list) < 8: > > Well, you said yourself that you finish with a list of length 7. And you > are doing this as long as your list is shorter than 8. 7 < 8 is always > true ? infinite loop. > > > j = random.randrange(6) > > if (j in random_list): > > continue > > else: > > random_list.append(j) > > continue > > > > print random_list > > > > > > however, I get stuck in an infinite loop. > > > > Any suggestions? > > Do you know `random.shuffle()`? > > In [4]: random_list = range(7) > > In [5]: random.shuffle(random_list) > > In [6]: random_list > Out[6]: [1, 4, 6, 2, 5, 0, 3] > > Same effect but more efficient than your approach. > > Ciao, > Marc 'BlackJack' Holey moley. random.shuffle() seems to be just the answer that I needed, thank you very much :) Adri From sjmachin at lexicon.net Wed Aug 9 20:55:18 2006 From: sjmachin at lexicon.net (John Machin) Date: 9 Aug 2006 17:55:18 -0700 Subject: using python with tar files and compressed files In-Reply-To: <1155142962.511995.265280@p79g2000cwp.googlegroups.com> References: <1HmCg.2661$No6.51985@news.tufts.edu> <1155142962.511995.265280@p79g2000cwp.googlegroups.com> Message-ID: <1155171318.638957.188390@n13g2000cwa.googlegroups.com> enigmadude at rock.com wrote: > This syntax works on other bzipped tar files. But it's not unheard of > that large tarballs will get corrupted from a download mirror. Use a > download manager and try redownloading the file. Usually a mirror will > include an md5sum text file so that you can compare the checksum to > your downloaded file to verify its integrity. For some reason, the > wxPython site doesn't have them. > > John Salerno wrote: > > Here's the name of a file I have: wxPython-newdocs-2.6.3.3.tar.bz2 > > > > Now, I tried this: > > > > import tarfile > > tar = tarfile.open('wxPython-newdocs-2.6.3.3.tar.bz2', 'r:bz2') > > > > but got this: > > > > Traceback (most recent call last): > > File "<pyshell#5>", line 1, in -toplevel- > > tar = tarfile.open('wxPython-newdocs-2.6.3.3.tar.bz2', 'r:bz2') > > File "C:\Python24\lib\tarfile.py", line 901, in open > > return func(name, filemode, fileobj) > > File "C:\Python24\lib\tarfile.py", line 1006, in bz2open > > raise ReadError, "not a bzip2 file" > > ReadError: not a bzip2 file > > > > So I'm a little confused. When dealing with a tar.gz or tar.bz2 file, do > > you need to uncompress it first with the proper module (gzip or bz2)? Or > > does tarfile take care of this? If so, why doesn't it recognize the > > above file? Or am I just doing it the wrong way? (I'm following an > > example in the docs) Another check on download corruption would be to use the "test integrity" option on the stand-alone bzip2 executable [which may already be on your machine, or can be obtained (directly or in source which you'd compile) from www.bzip2.org]: bzip2 -t yourfile HTH, John From jojoba12 at hotmail.com Fri Aug 18 14:34:40 2006 From: jojoba12 at hotmail.com (jojoba) Date: 18 Aug 2006 11:34:40 -0700 Subject: how do you get the name of a dictionary? Message-ID: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> Hello! Does anyone know how to find the name of a python data type. Conside a dictionary: Banana = {} Then, how do i ask python for a string representing the name of the above dictionary (i.e. 'Banana')? thanks to anyone who has time to answer this nube question! jojoba From deets at nospam.web.de Fri Aug 4 08:41:21 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 04 Aug 2006 14:41:21 +0200 Subject: Which KDE IDE for Python? In-Reply-To: <1154688723.966070.27590@b28g2000cwb.googlegroups.com> References: <1154682596.419636.70320@p79g2000cwp.googlegroups.com> <4jgj6qF7n43lU1@uni-berlin.de> <1154688723.966070.27590@b28g2000cwb.googlegroups.com> Message-ID: <4jgtjhF81iidU1@uni-berlin.de> > Actually I doubt it. For example on question why doesn't Eric use > katepart as editor, he responded: > "Because it is actually written using PyQt and is meant to work on > Win... and Mac OS X as well. Therefore it must not depend on KDE (or > any other non-portable or non-ported toolkit)." That is a totally different beast. The editor component is very tangled into the whole application, whereas the loading/saving can easily wrapped away. Matter of factly eric already uses _some_ KDE widgets, if not whole components. Diez From fredrik at pythonware.com Sun Aug 20 04:56:05 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Aug 2006 10:56:05 +0200 Subject: How to get the ascii code of Chinese characters? In-Reply-To: <yj9yy3dk3293$.dlg@gelists.gmail.com> References: <1155986298.643983.157460@i3g2000cwc.googlegroups.com> <1155990488.395220.178810@74g2000cwt.googlegroups.com> <1155999554.486951.303480@i42g2000cwa.googlegroups.com> <pan.2006.08.19.15.42.29.167353@gmx.net> <mailman.9552.1156006565.27775.python-list@python.org> <ec7qac$3ra$1@online.de> <yj9yy3dk3293$.dlg@gelists.gmail.com> Message-ID: <ec9834$356$1@sea.gmane.org> Gerhard Fiedler wrote: >> No. ASCII characters range is 0..127 while Unicode characters range is >> at least 0..65535. > > Actually, Unicode goes beyond 65535. you may want to look up "at least" in a dictionary. </F> From hitesh287 at gmail.com Tue Aug 8 14:54:56 2006 From: hitesh287 at gmail.com (Hitesh) Date: 8 Aug 2006 11:54:56 -0700 Subject: Getting previous file name References: <1154983936.588478.298380@m79g2000cwm.googlegroups.com> Message-ID: <1155063296.221470.88220@n13g2000cwa.googlegroups.com> Thank you all. Here is my BETA ver. import os, time, sys from stat import * def findfile(path): file_list = [] for f in os.listdir(path): filename = os.path.join(path, f) if not os.path.isfile(filename): print "*** Not a file:", repr(filename) continue create_date_secs = os.stat(filename)[ST_CTIME] create_date = time.strftime("%Y%m%d%H%M%S", time.localtime(create_date_secs)) #print create_date, " ....." , f file_list.append((create_date, filename)) file_list.sort() print file_list[-2] return file_list[-2] if __name__ == '__main__': path = r'srv12\\c$\\backup\\my_folder' create_date, prev_file = findfile(path) Thank you hj Hitesh wrote: > Hi, > > I have a small script here that goes to inside dir and sorts the file > by create date. I can return the create date but I don't know how to > find the name of that file... > I need file that is not latest but was created before the last file. > Any hints... I am newbiw python dude and still trying to figure out lot > of 'stuff'.. > > > import os, time, sys > from stat import * > > def walktree(path): > test1 = [] > for f in os.listdir(path): > filename = os.path.join(path, f) > create_date_sces = os.stat(filename)[ST_CTIME] > create_date = time.strftime("%Y%m%d%H%M%S", > time.localtime(create_date_sces)) > print create_date, " ....." , f > test1.append(create_date) > test1.sort() > print test1 > return test1[-2] > > > if __name__ == '__main__': > path = '\\\\srv12\\c$\\backup\\my_folder\\' > prev_file = walktree(path) > print "Previous back file is ", prev_file > > > Thank you, > hj From peter.maas at somewhere.com Tue Aug 29 16:27:00 2006 From: peter.maas at somewhere.com (Peter Maas) Date: Tue, 29 Aug 2006 22:27:00 +0200 Subject: What do you want in a new web framework? In-Reply-To: <mailman.9742.1156369727.27775.python-list@python.org> References: <1156100331.329889.216340@p79g2000cwp.googlegroups.com> <pan.2006.08.20.19.48.34.996227@gmx.net> <1156156636.515678.118210@75g2000cwc.googlegroups.com> <4jele2pe011di99c5dnq4olclglrkieggc@4ax.com> <1hkgnbt.ebn4o1111ftp0N%aleax@mac.com> <ecicsj$91v$1@online.de> <mailman.9742.1156369727.27775.python-list@python.org> Message-ID: <ed27uk$ihd$2@online.de> Cliff Wells wrote: > On Wed, 2006-08-23 at 22:13 +0200, Peter Maas wrote: >> Alex Martelli wrote: [...] >>> I have already suggested to the BDFL that he can remedy this situation >>> in Py3k: all he has to do, of course, is to add a LOT more keywords. >> Here is another remedy: he adds one of the frameworks to the standard >> library :) > > That didn't help Tk maintain a monopoly on Python GUI toolkits. I must not be a monopoly. A center of gravity would be nice, too. Peter Maas, Aachen From sjmachin at lexicon.net Tue Aug 1 19:15:42 2006 From: sjmachin at lexicon.net (John Machin) Date: 1 Aug 2006 16:15:42 -0700 Subject: Reinstalling Python Problem (Newbie) In-Reply-To: <eanuit$mbk$1@news.u-bordeaux1.fr> References: <mailman.8802.1154445784.27775.python-list@python.org> <eanuit$mbk$1@news.u-bordeaux1.fr> Message-ID: <1154474142.727345.222890@m73g2000cwd.googlegroups.com> Avell Diroll wrote: > beno wrote: > > I have to rebuild > > python. [snip] Platform is FreeBSD 5.? I have > > the following questions: > > > > What is meant by pointing to this folder thus: > > ./configure --prefix=/usr/python > > > > When I run make test I get these errors: > > > *** errors *** > > I've googled this with no luck. Please advise what to do or at least how > > to start > > TIA, > > beno > > > I believe this is not the best place to ask your question, ... > you should try : > * the mod_python mailing list : http://www.modpython.org/ > * some freebsd resources (e.g. http://www.freebsd.org/community.html ) > * some zope resources ( http://www.zope.org/Resources/MailingLists ) > The OP said he is re-building Python, and showed output where tests of Python failed. "mod_python" and "Zope" appear to be irrelevant to his problem. "Python" would appear to me to be the most significant keyword, with "freebsd" second. This list is inhabited by heaps of people with experience of building Python on *x platforms ... sorry, I'm not one such and can't help further. Cheers, John From s99999999s2003 at yahoo.com Fri Aug 4 04:09:18 2006 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 4 Aug 2006 01:09:18 -0700 Subject: platform independent process check Message-ID: <1154678958.255444.20310@s13g2000cwa.googlegroups.com> hi is there any Python modules that can list the processes that are running on a machine? I don't wish to shell out using the "ps" command because the "ps" command is not available in Windows.. thanks? From jscrerar at compuserve.com Sat Aug 5 17:19:43 2006 From: jscrerar at compuserve.com (Jim) Date: 5 Aug 2006 14:19:43 -0700 Subject: Why do I require an "elif" statement here? In-Reply-To: <mailman.8999.1154714505.27775.python-list@python.org> References: <1154712731.375032.203570@m79g2000cwm.googlegroups.com> <mailman.8999.1154714505.27775.python-list@python.org> Message-ID: <1154812783.619385.293820@n13g2000cwa.googlegroups.com> Tim Chase wrote: > > Could somebody tell me why I need the "elif char == '\n'" in > > the following code? > > > > This is required in order the pick up lines with just spaces > > in them. > > Why doesn't the "else:" statement pick this up? > > Following through with the below code: > > if the line consists of only a newline, it gets ignored due to > the "if line[0] == whitespace" line. However, if the line > consists of only whitespace followed by a newline you *do* > successfully get to the "else" in question. There's no other > place for you to go. > > However, what happens then? If you fall into you the top half of > your "if x > 0 ..." statement: > > you strip **all** *true* whitespace from the line with your > lstrip() call. Since there's nothing between your "whitespace" > (simple spaces) and the \n, the \n gets swallowed by the lstrip() > call. Thus, you output.write() an empty string. > > I recommend a few judiciously placed "print repr(thing)" lines as > you try to debug to see where things aren't what you expect them > to be. > > As another sidelight, rather than using the "i=0, i+= 1" aspect, > you can use the more pythonic idiom of > > for i, char in enumerate(line): > > (taking into consideration that i becomes zero-based). This will > automatically update "i" on each pass. > > -tkc > > > > > OLD_INDENT = 5 # spaces > > NEW_INDENT = 4 # spaces > > > > print 'Reindent.py:' > > print '\nFrom file %s' % infile > > print 'Change %i space indentation to %i space indentation.' % ( > > OLD_INDENT, NEW_INDENT) > > print 'And place revised file into %s' % outfile > > > > whitespace = ' ' > > n = 0 > > nline = 0 > > > > for line in input.readlines(): > > nline += 1 > > # Only look at lines that start with a space. > > if line[0] == whitespace: > > i = 0 > > for char in line: > > i += 1 > > if char == whitespace: > > pass > > elif char == '\n': # Why do I need this for a > > blank line with only spaces? > > output.write(line) > > break > > else: # Why doesn't the blank line > > get picked up here? > > x = line.count(whitespace*OLD_INDENT,0,i) > > # Reindent lines that have exactly a multiple of > > OLD_INDENT. > > if x > 0 and (i-1)%OLD_INDENT == 0: > > output.write(whitespace*NEW_INDENT*x+line.lstrip()) > > n += 1 > > break > > else: > > output.write(line) > > break > > else: > > output.write(line) > > > > input.close() > > output.close() > > print 'Total number of %i lines reindented out of %i lines.' % (n, > > nline) > > Thank you Tim. Hard to believe that lstrip() produces an empty string on lines with just spaces and doesn't remove the '\n' with lines that have characters. I'm now using all your suggestions, even "print repr(thing)" which I wasn't aware of. Thanks, Jim From larry.bates at websafe.com Thu Aug 17 17:06:14 2006 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 17 Aug 2006 16:06:14 -0500 Subject: Py2Exe and sys.argv : The Lost Arguments In-Reply-To: <1155843766.143216.325400@m73g2000cwd.googlegroups.com> References: <1155843766.143216.325400@m73g2000cwd.googlegroups.com> Message-ID: <44E4DA46.8050109@websafe.com> I entered the following simple program, compiled with py2exe (2.4) and ran it the way you describe with two files selected and it did what you said (e.g. only shows ays.argv[0] and sys.argv[1]): import sys print sys.argv x=raw_input('Press return to continue') Under 2.5 it didn't work at all (not sure why). Funny thing is that if I select two .txt files and do a Open With Notepad, Explorer only opens one of them. So I think it is Explorer that is throwing away the extra arguments. Otherwise I would expect it to open multiple notepad instances. -Larry Bates Thomas W wrote: > I've created a simple script like so : > > import sys > import wx > > app = wx.PySimpleApp() > dlg = wx.MessageDialog(None, "%s" % sys.argv, 'A Message Box', > wx.YES_NO | wx.ICON_QUESTION) > retCode = dlg.ShowModal() > app.MainLoop() > > If I run this on the command line like > python testcmd.py <path-to>/somefile.ext <path-to>/anotherfile.ext > > it displays a messagebox with a stringformatted list containing > testcmd.py, somefile.ext and anotherfile.ext. > > Then I "compile" the script using py2exe, generate a file called > testcmd.exe and select the same two files in Explorer, right click, > "Open with ...", browse to testcmd.exe and proceed. Now the dialogbox > only shows two items in the list; testcmd.exe and one of the files I > selected. Why? > > Is it impossible to compile a script using py2exe and pass selected > items in Explorer to my script? It works fine when called on the > command line so it might be something related to Explorer but I'm > completly lost. > From johnjsal at NOSPAMgmail.com Fri Aug 18 16:29:49 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 18 Aug 2006 20:29:49 GMT Subject: couple more questions about sqlite In-Reply-To: <1155930772.591854.53910@m79g2000cwm.googlegroups.com> References: <MqnFg.2703$No6.52653@news.tufts.edu> <1155930772.591854.53910@m79g2000cwm.googlegroups.com> Message-ID: <1rpFg.2705$No6.52662@news.tufts.edu> andychambers2002 at yahoo.co.uk wrote: >> 2. What's the difference between sqlite and pysqlite? Do you need both, >> just one, or is one an older version of the same thing? > > To access your database from python you need both (or some alternative > to pysqlite) I can understand this in terms of MySQL being one thing, and mysqldb being the necessary module for Python to use MySQL. But in 2.5, for example, which comes with sqlite3, is this all you need, or do you still need pysqlite? Or are these two different things that can access the sqlite system? (I guess I kind of thought there would be just one standard module used for each type of database, such as mysqldb being the one used for MySQL.) From rogue_pedro at yahoo.com Mon Aug 28 13:47:29 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 28 Aug 2006 10:47:29 -0700 Subject: Segmentation Fault References: <1156737764.729811.297280@m79g2000cwm.googlegroups.com> <1156741148.580820.309840@74g2000cwt.googlegroups.com> <6hssljhrpx5.fsf@koollbox.kooll.org> Message-ID: <1156787249.482933.194580@m73g2000cwd.googlegroups.com> thomas.samson at gmail.com wrote: > "Simon Forman" <rogue_pedro at yahoo.com> writes: > > > pycraze wrote: > >> I would like to ask a question. How do one handle the exception due to > >> Segmentation fault due to Python ? Our bit operations and arithmetic > >> manipulations are written in C and to some of our testcases we > >> experiance Segmentation fault from the python libraries. > >> > >> If i know how to handle the exception for Segmentation fault , it will > >> help me complete the run on any testcase , even if i experiance Seg > >> Fault due to any one or many functions in my testcase. > > > > AFAIK, seg fault kills your program dead. There's no exception to > > handle. If you're getting seg faults from the python standard library, > > that's a pretty serious thing, way more serious than just not-passed > > testcases. > > Segfault handling is platform-dependant... So, at least on unix-like > platform, you can use the signal module to detect segfault: > > import signal > > def handler(signum, frame): > print 'Segfault detected' > # you may use the stack frame here to help debugging > > signal.signal(signal.SIGSEGV, handler) > > -- > Thomas SAMSON > "You're very sure of your facts, " he said at last, "I > couldn't trust the thinking of a man who takes the Universe > - if there is one - for granted. " It's good to know that this is possible. However, it's almost certainly a bad idea to "catch" seg faults and then just proceed with further testcases. Printing out debugging information would be pretty good though. Peace, ~Simon From steve at REMOVEME.cybersource.com.au Thu Aug 17 05:46:41 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 17 Aug 2006 19:46:41 +1000 Subject: trouble understanding inheritance... References: <1155753183.207393.116940@m79g2000cwm.googlegroups.com> <mailman.9435.1155753894.27775.python-list@python.org> <1155754767.694480.256200@h48g2000cwc.googlegroups.com> <1155756282.851876.46470@b28g2000cwb.googlegroups.com> <1155757992.706040.288890@74g2000cwt.googlegroups.com> Message-ID: <pan.2006.08.17.09.46.40.346457@REMOVEME.cybersource.com.au> On Wed, 16 Aug 2006 12:53:12 -0700, KraftDiner wrote: >> > Well how does one select which class baseClass really is when you >> > contruct the object? >> > What am I missing? >> > >> > a = typeA() >> > b = typeB() >> > c = baseClass(a) >> >> a = typeA() >> b = typeB() >> >> You're done. Stop there. >> > I can see that this might work... > c = [a, b] > for c in [a,b]: > c.getName() > > but when does baseClass ever get used? > Why did i even have to define it? So that you don't duplicate code. That's it. Here is a basic example. I have a class Foo with a method foo() that returns "foo", and a second class Foos which is *almost* the same except method foo() takes an argument and returns that number of foos. class BaseClass(): def foo(self): return "foo" class Foo(BaseClass): def foo(self): return self.__class__.foo() # call the parent class method class Foos(BaseClass): def foo(self, n): return self.__class__.foo() * n Obviously in this case, there is no real need for BaseClass -- Foos could inherit from Foo. But in more complex cases, you might need something like this. Hope this helps. -- Steven D'Aprano From brochu121 at gmail.com Fri Aug 11 12:36:02 2006 From: brochu121 at gmail.com (david brochu jr) Date: Fri, 11 Aug 2006 12:36:02 -0400 Subject: Automate logging into page Message-ID: <9583ed900608110936p57cdee4ek9d8c5ae0d0c3ac02@mail.gmail.com> I am trying to automate logging a website and have been unsuccessful. The code below is supposed to log me into the site, but changing the username/password to an incorrect combination does not cause an error or crash to be seen. My goal is to log into this page and save the cookie from the page so that when I spawn IE and navigate to this site I will be logged in. I am using the urllib2 module. Any suggestions? import urllib import urllib2 url = ' http://my.compete.com/login?origin=http%3A%2F%2Fmy.compete.com%2Flogin%2F%3Forigin%3D%2F ' values = {'id_l_email': 'XXXXX', 'id_l_password':'XXXXX'} data = urllib.urlencode(values) req = urllib2.Request(url,data) response = urllib2.urlopen(req) the_page = response.read() -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060811/894f0421/attachment.html> From onurb at xiludom.gro Wed Aug 2 03:28:53 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 02 Aug 2006 09:28:53 +0200 Subject: Finding the name of a class In-Reply-To: <mva4q3xb731.ln2@news.conpoint.com> References: <q684q3xmd11.ln2@news.conpoint.com> <44cf7538$0$29435$626a54ce@news.free.fr> <mva4q3xb731.ln2@news.conpoint.com> Message-ID: <44d05436$0$13472$636a55ce@news.free.fr> Kirk Strauser wrote: > Bruno Desthuilliers wrote: > >> Kirk Strauser wrote: > >>>>>> class foo(object): >>>>>> pass >>> how can I find its name, such as: >>> >>>>>> b = foo > >> I suppose you mean b = foo() ? > > Actually, I meant 'b = foo' in this case - I want to find the name of the > class that b references, Ok. Could have been a typo, just wanted to make sure. >> The name of a class is in the attribute '__name__' of the class. The >> class of an object is in the attribute '__class__' of the object. > > I swear that didn't work earlier. Honest. :-) Not sure if it works for old-style classes... > OK, now for the good stuff. In the code below, how can I find the name of > the class that 'bar' belongs to: > >>>> class Foo(object): > ... def bar(self): > ... pass > ... >>>> b = Foo.bar >>>> dir(b) > ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'im_class', 'im_func', 'im_self'] >>> b.im_class <class '__main__.Foo'> >>> b.im_class.__name__ 'Foo' >>> >>>> b.__class__ This will give you the class of b itself. Remember that in Python, everything and it's sister is an object - including functions, methods, classes and modules. In this case, b is a method object - IOW a descriptor that wraps a function object. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From max at alcyone.com Tue Aug 8 16:25:28 2006 From: max at alcyone.com (Erik Max Francis) Date: Tue, 08 Aug 2006 13:25:28 -0700 Subject: #!/usr/bin/python or #!/usr/bin/env python? In-Reply-To: <44d8e5a5$0$5567$9b622d9e@news.freenet.de> References: <fj5Cg.2658$No6.51984@news.tufts.edu> <44d8e5a5$0$5567$9b622d9e@news.freenet.de> Message-ID: <bL6dnTTbq9albkXZnZ2dnUVZ_u2dnZ2d@speakeasy.net> Martin v. L?wis wrote: > I use /usr/bin/env if I don't know what the operating system is; > some systems don't have Python in /usr/bin. I use /usr/bin/pythonX.Y > if I want a specific version on a specific operating system (typically > Linux). Even there, /usr/bin/env pythonX.Y would be a better choice. (Maybe that's what you meant.) -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Never contend with a man who has nothing to lose. -- Baltasar Gracian, 1647 From rogue_pedro at yahoo.com Tue Aug 15 21:21:55 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 15 Aug 2006 18:21:55 -0700 Subject: Printing n elements per line in a list References: <1155685889.626881.37040@m73g2000cwd.googlegroups.com> Message-ID: <1155691315.863294.295960@b28g2000cwb.googlegroups.com> unexpected wrote: > If have a list from 1 to 100, what's the easiest, most elegant way to > print them out, so that there are only n elements per line. > > So if n=5, the printed list would look like: > > 1 2 3 4 5 > 6 7 8 9 10 > 11 12 13 14 15 > etc. > > My search through the previous posts yields methods to print all the > values of the list on a single line, but that's not what I want. I feel > like there is an easy, pretty way to do this. I think it's possible to > hack it up using while loops and some ugly slicing, but hopefully I'm > missing something >From http://docs.python.org/lib/itertools-recipes.html there's the grouper() function: from itertools import izip, chain, repeat def grouper(n, iterable, padvalue=None): """ Return n-tuples from iterable, padding with padvalue. Example: grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x') """ return izip(*[chain(iterable, repeat(padvalue, n-1))]*n) R = range(1, 101) for N in grouper(5, R, ''): print ' '.join(str(n) for n in N) If your iterable is not a multiple of n (of course not the case for 100 and 5), and you don't want the extra spaces at the end of your last line, you could join the lines with '\n' and stick a call to rstrip() in there: G = grouper(5, R, '') print '\n'.join(' '.join(str(n) for n in N) for N in G).rstrip() but then you're back to ugly. lol. Peace, ~Simon From vinjvinj at gmail.com Tue Aug 15 13:07:28 2006 From: vinjvinj at gmail.com (vj) Date: 15 Aug 2006 10:07:28 -0700 Subject: recommended general-purpose string template packages? In-Reply-To: <1155523735.614470.199840@h48g2000cwc.googlegroups.com> References: <1155523735.614470.199840@h48g2000cwc.googlegroups.com> Message-ID: <1155661648.531446.46670@i3g2000cwc.googlegroups.com> I use preppy from reportlab: http://www.reportlab.org/preppy.html It's one file, is fast and can be easily embedded in any application. Vineet From riko at despammed.com Tue Aug 22 19:31:02 2006 From: riko at despammed.com (Mc Osten) Date: Wed, 23 Aug 2006 01:31:02 +0200 Subject: Python and STL efficiency References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <eccb9u$kjs$1@gemini.csx.cam.ac.uk> <1hkh28d.xscw4v1y4v9a6N%riko@despammed.com> <mailman.9640.1156247569.27775.python-list@python.org> <1hkh6lb.6dsnh51lj8z96N%riko@despammed.com> <1156252193.524186.107520@b28g2000cwb.googlegroups.com> <1hkhexv.18m65rl61swqyN%riko@despammed.com> <1156265848.875774.251640@i42g2000cwa.googlegroups.com> <1156278230.590485.35610@75g2000cwc.googlegroups.com> Message-ID: <1hki0qf.18959131ony9pjN%riko@despammed.com> Tim N. van der Leeuw <tim.leeuwvander at nl.unisys.com> wrote: > And the results of IronPython (1.0rc2) are just in as well: I can't test this one. > > And for Python 2.5: > LeeuwT at nlshl-leeuwt ~/My Documents/Python > $ /cygdrive/c/Python25/python.exe SpeedTest.py > Begin Test > Number of unique string objects: 4 > so long... > What do you know > fool > chicken crosses road > Number of unique string objects: 400000 > so long... > What do you know > fool > chicken crosses road > Fast - Elapsed: 0.440619 seconds > Slow - Elapsed: 1.095341 seconds What the heck... you have a Cray, haven't you? $ /opt/misc/bin/python2.5 -O set_impl.py so long... What do you know fool chicken crosses road so long... What do you know fool chicken crosses road Elapsed: 1.300000 seconds Elapsed: 1.290000 seconds Yes... good optimizer work. The 'slow' code here is faster than the fast one. $ python -O set_impl.py so long... What do you know fool chicken crosses road so long... What do you know fool chicken crosses road Elapsed: 1.360000 seconds Elapsed: 3.800000 seconds > (Next step would be to create a VB version and a Java version of the > same program, oh and perhaps to try a version that would work with > Jython... perhaps somehow w/o the 'set') Ok. I can do the Java version. If I find a RealBasic Set class I can do it. However, I don't remember anything about VB6, and have done nothing with .Net. But I don't think it is that interesting. Java strings are immutable too: I expect it to outperform Python (unless Java Set class sucks). And I don't see the point of taking in VB. A good BASIC implentation is comparable with Pascal or C++ speedwise. (At least this results from Great Language Shootout and Free Basic). -- blog: http://www.akropolix.net/rik0/blogs | Uccidete i filosofi, site: http://www.akropolix.net/rik0/ | tenetevi riso e forum: http://www.akropolix.net/forum/ | bacchette per voi. From nephish at gmail.com Sat Aug 26 14:09:13 2006 From: nephish at gmail.com (nephish) Date: 26 Aug 2006 11:09:13 -0700 Subject: question about class, functions and scope In-Reply-To: <1156613573.374812.165660@m79g2000cwm.googlegroups.com> References: <1156583602.302530.206630@74g2000cwt.googlegroups.com> <1156589657.706430.69650@74g2000cwt.googlegroups.com> <1156604233.729177.66440@i3g2000cwc.googlegroups.com> <1156609028.269804.189220@74g2000cwt.googlegroups.com> <1156613573.374812.165660@m79g2000cwm.googlegroups.com> Message-ID: <1156615753.359782.11250@75g2000cwc.googlegroups.com> bearophileHUGS at lycos.com wrote: > nephish: > > one more question. > > the functions defined above the classes that the could be called from > > within the classes, they do not need a 'self' declaration because they > > are not part of a class, right? > > Class methods generally require the self as first parameter, functions > don't need the self. So your original code was wrong (sorry, I haven't > seen that before). > > You can also inject functions as methods inside a class, and in such > case your function usually needs a self parameter too. > > Bye, > bearophile ok, thanks much, thats all i needed to know. shawn From haha at asifIdgiveoutmyemail.com Sat Aug 5 04:38:22 2006 From: haha at asifIdgiveoutmyemail.com (sleem) Date: Sat, 05 Aug 2006 17:38:22 +0900 Subject: python scripting for eggdrop? Message-ID: <eb1lds$eco$1@news-02.connect.com.au> Can it be done? I hate tcl. Is there someway I could parse all irc events so they can be handled by python's irclib? From bdesth.quelquechose at free.quelquepart.fr Mon Aug 28 16:13:04 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 28 Aug 2006 22:13:04 +0200 Subject: inheritance? In-Reply-To: <1155751628.114929.194250@75g2000cwc.googlegroups.com> References: <1155695711.057312.8020@p79g2000cwp.googlegroups.com> <pan.2006.08.16.04.16.16.41660@REMOVEME.cybersource.com.au> <1155751628.114929.194250@75g2000cwc.googlegroups.com> Message-ID: <44f34b95$0$18354$626a54ce@news.free.fr> KraftDiner a ?crit : (snip) > > Here I tried this example and maybe this will explain the difficulties > I'm having. > 1) at the time the baseClass is constructed shouldn't the constructor > of the appropriate type be called. It is. But neither the constructor nor 'the appropriate type' are what you think they are. > 2) getName is doing nothing... Of course. It's body is a 'pass' statement, which in Python means 'do nothing'. > class baseClass: > def __init__(self): > pass This initializer is useless. > def fromfile(self, str): > if (str == 'A'): > a = typeA() > else: > a = typeB() And then the method returns and the object bound to the local name 'a' is garbage-collected. > def getName(self): > pass > > class typeA(baseClass): > def __init__(self): > self.name='A' > print 'typeA init' > def fromfile(self, str=None): > print 'typeA fromfile' This method is not called by your code > def getName(self): > print self.name This method is not called by your code > class typeB(baseClass): > def __init__(self): > self.name='B' > print 'typeB init' > def fromfile(self, str=None): > print 'typeB fromfile' This method is not called by your code > def getName(self): > print self.name This method is not called by your code > bc = baseClass() creates an instance of baseClass and bind it to the name bc > bc.fromfile('A') calls the fromfile method of class baseClass with (object bound to) bc as first param and 'A' as second param. This methods creates an instance of typeA, bind it to the local name 'a', and then returns. > bc.getName() calls the getName method of class baseClass, which body is a 'pass' statement. > bc.fromfile('B') calls the fromfile method of class baseClass with (object bound to) bc as first param and 'B' as second param. This methods creates an instance of typeB, bind it to the local name 'a', and then returns. > bc.getName() calls the getName method of class baseClass, which body is a 'pass' statement. > bc.getName() calls the getName method of class baseClass, which body is a 'pass' statement. See John Henry's answer for a correct implementation. From bwm at acm.org Sat Aug 19 19:53:53 2006 From: bwm at acm.org (Bernhard Mulder) Date: Sat, 19 Aug 2006 23:53:53 GMT Subject: cloning generator iterators In-Reply-To: <cXMFg.14720$gY6.373@newssvr11.news.prodigy.com> References: <cXMFg.14720$gY6.373@newssvr11.news.prodigy.com> Message-ID: <lwNFg.14723$gY6.3737@newssvr11.news.prodigy.com> Oops. Got the indentation wrong. Here is the corrected version: def generator(self): while True: while True: if (yield 1): if (yield 1): break self.n = 2 while (yield self.n): self.n += 1 From bearophileHUGS at lycos.com Tue Aug 15 18:48:58 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 15 Aug 2006 15:48:58 -0700 Subject: idea on how to get/set nested python dictionary values In-Reply-To: <1155678816.942660.296140@74g2000cwt.googlegroups.com> References: <1155663671.716249.18780@m79g2000cwm.googlegroups.com> <1155678816.942660.296140@74g2000cwt.googlegroups.com> Message-ID: <1155682138.572677.231460@h48g2000cwc.googlegroups.com> wittempj at hotmail.com wrote: > py> def SetNewDataParam2(Data, NewData): > ... if type(Data[Data.keys()[0]]) == type(dict()): > ... SetNewDataParam2(Data[Data.keys()[0]], NewData) > ... else: > ... Data[Data.keys()[0]] = NewData > ... > ... return Data > py> Data = {'a':{'b':{'c':1}}} > py> NewData = 666 > py> ret = SetNewDataParam2(Data, NewData) > py> print ret > {'a': {'b': {'c': 666}}} This looks better: def setNested(nest, val): el = nest.iterkeys().next() if isinstance(nest[el], dict): setNested(nest[el], val) else: nest[el] = val return nest But maybe something like this is closer to the OP needs: def setNested(nest, path, val): nest2 = nest for key in path[:-1]: nest2 = nest2[key] nest2[path[-1]] = val return nest ndict = {'a1':{'b1':{'c1':1}, "b2":{"c2":2}}} print ndict print setNested(ndict, ("a1", "b1", "c1"), 3) print setNested(ndict, ("a1", "b2", "c2"), 4) Output: {'a1': {'b1': {'c1': 1}, 'b2': {'c2': 2}}} {'a1': {'b1': {'c1': 3}, 'b2': {'c2': 2}}} {'a1': {'b1': {'c1': 3}, 'b2': {'c2': 4}}} (But I don't like too much that kind of in place modify.) Bye, bearophile From nevillednz at gmail.com Tue Aug 15 23:28:34 2006 From: nevillednz at gmail.com (NevilleDNZ) Date: 15 Aug 2006 20:28:34 -0700 Subject: proc A def/calls proc B: variable scoping rules. In-Reply-To: <mailman.9398.1155696126.27775.python-list@python.org> References: <1155685233.002415.184150@74g2000cwt.googlegroups.com> <mailman.9395.1155689411.27775.python-list@python.org> <1155692329.075173.49060@p79g2000cwp.googlegroups.com> <mailman.9397.1155693082.27775.python-list@python.org> <1155695497.999739.295650@m73g2000cwd.googlegroups.com> <mailman.9398.1155696126.27775.python-list@python.org> Message-ID: <1155698914.087129.67680@i42g2000cwa.googlegroups.com> Steve Holden wrote: > No. It's too horrible to contemplate without getting mild feelings of > nausea. What exactly is it you are tring to achieve here (since I assume > your goal wasn't to make me feel sick :-)? It is part of an algorithum: #!/usr/bin/env python def A(k, x1, x2, x3, x4, x5): def B(): k = k - 1; B.out=A.out=A(k, B, x1, x2, x3, x4) return B.out if k <= 0: A.out = x4 + x5 else: B() return A.out print A(10, 1, -1, -1, 1, 0); # correct output is -67 The scope of k remains one problem, as it is passed as an argument to A. I think x1,x2,x3,x4 are meant to be lambdas as well... :-) N From rogue_pedro at yahoo.com Tue Aug 15 05:11:27 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 15 Aug 2006 02:11:27 -0700 Subject: how to deepcopy a slice object? In-Reply-To: <1155629155.207232.50400@m79g2000cwm.googlegroups.com> References: <1155629155.207232.50400@m79g2000cwm.googlegroups.com> Message-ID: <1155633086.985976.59960@m79g2000cwm.googlegroups.com> Alexandre Guimond wrote: > Hi all, > > i'm trying to deepcopy a slice object but i get the following error. > Does anyone know a workaround? > > ActivePython 2.4.3 Build 12 (ActiveState Software Inc.) based on > Python 2.4.3 (#69, Apr 11 2006, 15:32:42) [MSC v.1310 32 bit (Intel)] > on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import copy > >>> copy.deepcopy( slice( 1, 10, 2 ) ) > Traceback (most recent call last): > File "<stdin>", line 1, in ? > File "C:\Program Files\Python\lib\copy.py", line 204, in deepcopy > y = _reconstruct(x, rv, 1, memo) > File "C:\Program Files\Python\lib\copy.py", line 336, in _reconstruct > y = callable(*args) > File "C:\Program Files\Python\lib\copy_reg.py", line 92, in > __newobj__ > return cls.__new__(cls, *args) > TypeError: slice expected at least 1 arguments, got 0 > > thx for any help. Why would you want to [deep]copy a slice object? Anyway, I don't know much about them, other than that they are slightly unusual objects that play a very restricted role in python, rather like the Ellipsis. Workarounds are possible, I think, but really you almost certainly don't need to do this. Peace, ~Simon From fredrik at pythonware.com Thu Aug 17 03:02:26 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 17 Aug 2006 09:02:26 +0200 Subject: PySequence_SetItem In-Reply-To: <20060817004911.GF5772@performancedrivers.com> References: <1155754847.392950.266180@h48g2000cwc.googlegroups.com> <1155755905.233229.93440@74g2000cwt.googlegroups.com> <1155761144.583994.260150@m73g2000cwd.googlegroups.com> <mailman.9442.1155763376.27775.python-list@python.org> <1155764364.775366.76070@i3g2000cwc.googlegroups.com> <mailman.9443.1155765750.27775.python-list@python.org> <1155767139.084992.133200@i42g2000cwa.googlegroups.com> <mailman.9448.1155772454.27775.python-list@python.org> <1155773602.991452.12450@74g2000cwt.googlegroups.com> <20060817004911.GF5772@performancedrivers.com> Message-ID: <ec149n$ffa$2@sea.gmane.org> Jack Diederich wrote: > It is handy for functions that take a mutable list as an argument. an *existing*, and properly *initialized*, mutable sequence. PyList_New doesn't give you such an object. </F> From ask at me Sat Aug 12 12:26:12 2006 From: ask at me (alf) Date: Sat, 12 Aug 2006 12:26:12 -0400 Subject: [OT] why cd ripping on Linux is so slow In-Reply-To: <44ddf564@news.vo.lu> References: <Y9SdnYe4GtMrdEDZnZ2dnUVZ_oadnZ2d@comcast.com> <44ddf564@news.vo.lu> Message-ID: <x9ednd8nvpjKkEPZnZ2dnUVZ_radnZ2d@comcast.com> Patrick Useldinger wrote: > > This is really OT: yes it is > and you might be better off looking in Linux forums > like http://www.linuxquestions.org/. That said, it's likely that your > DMA is not switched on. thx for the hint and the reference - see hopefully I got to know where to find the answer. -- alf From sjmachin at lexicon.net Fri Aug 11 05:28:46 2006 From: sjmachin at lexicon.net (John Machin) Date: 11 Aug 2006 02:28:46 -0700 Subject: Python script setup In-Reply-To: <1155284108.102938.294860@m79g2000cwm.googlegroups.com> References: <1155284108.102938.294860@m79g2000cwm.googlegroups.com> Message-ID: <1155288526.912397.42960@m79g2000cwm.googlegroups.com> 2Good4You-Veki(Cro) wrote: > Hi all, > > When I want setup my script: > > I write: > > from distutils.core import setup > setup(name="myscript", > version='1.0', > scripts=["myscripts.py"]) > > or some else example,error is > > > Traceback (most recent call last): > File "<pyshell#5>", line 1, in -toplevel- Do you get the same result if you put those Python statements in a file (typically named setup.py) and run it in the Windows "Command Prompt" window as shown in the manual: http://docs.python.org/inst/standard-install.html instead of using pyshell? Where/how are you supplying the "install" argument when using pyshell? > setup(name="myscript", > version='1.0', > scripts=["myscripts.py"]) > File "C:\Python24\distutils\core.py", line 101, in setup My distutils is where I'd expect it to be (C:\Python24\Lib\distutils) because that's where the standard Python installation puts it relative to my choice of the Python installation directory (C:\Python24). How did yours end up like that? Did you download distutils and install it as a separate package? If so, how did you install it? What version of Python are you using? > _setup_distribution = dist = klass(attrs) > File "C:\Python24\distutils\dist.py", line 130, in __init__ > setattr(self, method_name, getattr(self.metadata, method_name)) > AttributeError: DistributionMetadata instance has no attribute > 'get___doc__' HTH, John From zxo102 at gmail.com Tue Aug 1 04:10:18 2006 From: zxo102 at gmail.com (zxo102) Date: 1 Aug 2006 01:10:18 -0700 Subject: how to make python socket server work with the app.MainLoop() in wxpython? In-Reply-To: <NM3zg.1529$W93.507@dukeread05> References: <1154269116.890584.215040@i3g2000cwc.googlegroups.com> <kK3zg.1528$W93.382@dukeread05> <NM3zg.1529$W93.507@dukeread05> Message-ID: <1154419818.825540.327500@i3g2000cwc.googlegroups.com> Philippe, I just wrote the code following the example you provided. The image location can be controlled with the data from socket client. But only one thing confuse me. When the image keeps moving to a new location, the image at a "old" location is not deleted and is left behind in the frame. Do you know what is going on with it? The location of image is processed in "def OnResult(self,event):" and is initialized in "def __init__(self, parent, id):" of "class MainFrame" ( See the code attached). Thanks a lot. ouyang ################################################## import time from threading import * import wx, string from socket import * from Main import opj host = "192.168.0.2" port = 21567 buf = 1024 addr = (host,port) UDPSock = socket(AF_INET,SOCK_DGRAM) UDPSock.bind(addr) # Button definitions ID_START = wx.NewId() ID_STOP = wx.NewId() # Define notification event for thread completion EVT_RESULT_ID = wx.NewId() def EVT_RESULT(win, func): """Define Result Event.""" win.Connect(-1, -1, EVT_RESULT_ID, func) class ResultEvent(wx.PyEvent): """Simple event to carry arbitrary result data.""" def __init__(self, data): """Init Result Event.""" wx.PyEvent.__init__(self) self.SetEventType(EVT_RESULT_ID) d = string.split(data,'-') self.data = [string.atoi(d[0]),string.atoi(d[1]),string.atof(d[2])] # Thread class that executes processing class WorkerThread(Thread): """Worker Thread Class.""" def __init__(self, notify_window): """Init Worker Thread Class.""" Thread.__init__(self) self._notify_window = notify_window self._want_abort = 0 # This starts the thread running on creation, but you could # also make the GUI thread responsible for calling this self.start() def run(self): """Run Worker Thread.""" # This is the code executing in the new thread. Simulation of # a long process (well, 10s here) as a simple loop - you will # need to structure your processing so that you periodically # peek at the abort variable while 1: if self._want_abort: wx.PostEvent(self._notify_window, ResultEvent(None)) #return break else: data,addr = UDPSock.recvfrom(buf) if not data: print "Client has exited!" break else: print "\nReceived message '", data,"'" wx.PostEvent(self._notify_window, ResultEvent(data)) # Close socket UDPSock.close() def abort(self): """abort worker thread.""" # Method for use by main thread to signal an abort self._want_abort = 1 # GUI Frame class that spins off the worker thread class MainFrame(wx.Frame): """Class MainFrame.""" def __init__(self, parent, id): """Create the MainFrame.""" wx.Frame.__init__(self, parent,id, title='monitoring system', size=(500,600)) self.panel = wx.Panel(self,-1,(0,0),(500,600)) self.bmp = wx.Image(opj('bitmaps/image.bmp'), wx.BITMAP_TYPE_BMP) self.bmp.SetMask(True) # Dumb sample frame with two buttons wx.Button(self.panel, ID_START, 'Start', pos=(0,0)) wx.Button(self.panel, ID_STOP, 'Stop', pos=(0,50)) self.status = wx.StaticText(self.panel, -1, '', pos=(0,100)) x = 50 y = 150 angle = 1.23 bmp = self.bmp.Rotate(angle, (x,y), True,None) bmp = bmp.ConvertToBitmap() wx.StaticBitmap(self.panel, -1, bmp, (x, y), (bmp.GetWidth(), bmp.GetHeight())) self.Bind(wx.EVT_BUTTON, self.OnStart, id=ID_START) self.Bind(wx.EVT_BUTTON, self.OnStop, id=ID_STOP) # Set up event handler for any worker thread results EVT_RESULT(self,self.OnResult) # And indicate we don't have a worker thread yet self.worker = None def OnStart(self, event): """Start Computation.""" # Trigger the worker thread unless it's already busy if not self.worker: self.status.SetLabel('Starting computation') self.worker = WorkerThread(self) def OnStop(self, event): """Stop Computation.""" # Flag the worker thread to stop if running if self.worker: self.status.SetLabel('Trying to abort computation') self.worker.abort() def OnResult(self, event): """Show Result status.""" if event.data is None: # Thread aborted (using our convention of None return) self.status.SetLabel('Computation aborted') else: # Process results here self.status.SetLabel('Computation Result: %s-%s-%s' % (event.data[0], event.data[1],event.data[2])) angle = event.data[2] x = event.data[0] y = event.data[1] bmp = self.bmp.Rotate(angle, (x,y), True,None) bmp = bmp.ConvertToBitmap() wx.StaticBitmap(self.panel, -1, bmp, (x, y), (bmp.GetWidth(), bmp.GetHeight())) # In either event, the worker is done self.worker = None class MainApp(wx.App): """Class Main App.""" def OnInit(self): """Init Main App.""" self.frame = MainFrame(None, -1) self.frame.Show(True) self.SetTopWindow(self.frame) return True if __name__ == '__main__': app = MainApp(0) app.MainLoop() ########################################################## Philippe Martin ??? > Philippe Martin wrote: > > > zxo102 wrote: > > > >> Hi everyone, > >> I am using a python socket server to collect data from a socket > >> client and then control a image location ( wxpython) with the data, > >> i.e. moving the image around in the wxpython frame. > >> But the "app.MainLoop()" in wxpython looks like conflicting with > >> the "while 1:" in socket server. After I commented the > >> "app.MainLoop()", everything is working except two things: > >> 1. if I click anywhere on the screen with the mouse, the image is > >> gong and only the empty frame( or panel) is left. > >> 2. if I don't touch anything, the image is being moved around but > >> the previous images are left behind in the panel. > >> I guess that may be caused by "app.MainLoop()" commented. > >> Anybody knows how to make the two things work together? I really > >> appreciate your help. > >> My sample code is modified based on the wxpython demo: image.py. > >> socket client is also attached for your reference. > >> > >> Ouyang > >> > >> ################ socket server with wxpython ############## > >> > >> from Main import opj > >> import wx,string > >> class MMCS(wx.Frame): > >> def __init__(self): > >> self.bmp = wx.Image(opj('bitmaps/image.bmp'), > >> wx.BITMAP_TYPE_BMP) > >> self.bmp.SetMask(True) > >> wx.Frame.__init__(self, parent=None, title='monitoring system', > >> size=(500,600)) > >> self.panel = wx.Panel(self,-1) > >> > >> def monitor(self,x,y,angle): > >> bmp = self.bmp.Rotate(angle, (x,y), True,None) > >> bmp = bmp.ConvertToBitmap() > >> > >> wx.StaticBitmap(self.panel, -1, bmp, (x, y), (bmp.GetWidth(), > >> bmp.GetHeight())) > >> del bmp > >> > >> app = wx.PySimpleApp() > >> frame = MMCS() > >> frame.Show() > >> frame.monitor(50,10,0.0) > >> #app.MainLoop() > >> > >> # Server program > >> from socket import * > >> # Set the socket parameters > >> host = "192.168.0.2" > >> port = 21567 > >> buf = 1024 > >> addr = (host,port) > >> > >> # Create socket and bind to address > >> UDPSock = socket(AF_INET,SOCK_DGRAM) > >> UDPSock.bind(addr) > >> > >> # Receive messages > >> while 1: > >> data,addr = UDPSock.recvfrom(buf) > >> if not data: > >> print "Client has exited!" > >> break > >> else: > >> print "\nReceived message '", data,"'" > >> d = string.split(data, '-') > >> > >> frame.monitor(string.atoi(d[0]),string.atoi(d[1]),string.atof(d[2])) > >> if data == 'END': > >> print "end of moving the ship" > >> > >> # Close socket > >> UDPSock.close() > >> > >> ############# socket client ######################> > >> rom socket import * > >> import time > >> > >> # Set the socket parameters > >> host = "192.168.0.2" > >> port = 21567 > >> buf = 1024 > >> addr = (host,port) > >> > >> # Create socket > >> UDPSock = socket(AF_INET,SOCK_DGRAM) > >> def_msg = "===Enter message to send to server==="; > >> print "\n",def_msg > >> > >> # Send messages > >> while (1): > >> for i in range(100): > >> time.sleep(1) > >> data = "50-100-%s"%(0.1*i) > >> if(UDPSock.sendto(data,addr)): > >> print "Sending message '",data,"'....." > >> # Close socket > >> UDPSock.close() > > > > > > If you get rid of app.MaiLoop(), you basically get rid of all GUI events. > > You need to have you server in a separate thread. > > > > Philippe > PS: > > http://wiki.wxpython.org/index.cgi/LongRunningTasks From jack at psynchronous.com Sat Aug 19 10:50:56 2006 From: jack at psynchronous.com (Jack Diederich) Date: Sat, 19 Aug 2006 10:50:56 -0400 Subject: PyThreadState_Swap(NULL) In-Reply-To: <ec5b3m$puo$1@sea.gmane.org> References: <ec5b3m$puo$1@sea.gmane.org> Message-ID: <20060819145056.GL5772@performancedrivers.com> On Fri, Aug 18, 2006 at 02:21:40PM -0700, Bryan wrote: > > i've written a program that uses python c api code that lives in a > shared library that is loaded by a custom apache module (mod_xxx). this > python c api code all works correctly under our test server and under > apache but only if mod_python isn't loaded. when apache loads > mod_python as shown in the http.conf snippet below, > PyThreadState_Swap(NULL) in mod_xxx returns NULL. when the snippet of > code in http.conf is commented out, it works again. what do i have to > do to have mod_xxx code work correctly when apache loads mod_python? > > > failure case when apache loads mod_python: > Py_Initialize() succeeded > PyThreadState_Swap(NULL) failed > > > sucess case when apache doesn't load mod_python: > Py_Initialize() succeeded > PyThreadState_Swap(NULL) succeeded > Running multiple python interpreters in the same process isn't supported. It works OK for most things but some low-level guts are shared between interpreters so it is possible to run into trouble. You aren't running multiple interpreters in the same process. You and mod_python both think you are in charge and end up nuking each other's states. Py_Initialize() resets the global state and shouldn't be called more than once. You can create more than one sub-interpreter (check out the mod_python source for how, the source is small and readable). The best thing to do would be to load your module last and conitionally call Py_Initialize() if someone else hasn't already. -Jack From p.barbierdereuille at free.fr Mon Aug 14 04:42:47 2006 From: p.barbierdereuille at free.fr (Pierre Barbier de Reuille) Date: Mon, 14 Aug 2006 09:42:47 +0100 Subject: Nested if and expected an indent block In-Reply-To: <1155522148.957303.203620@m79g2000cwm.googlegroups.com> References: <1155511725.874993.140020@b28g2000cwb.googlegroups.com> <1155512775.186869.69190@m79g2000cwm.googlegroups.com> <1155514407.728107.196600@i42g2000cwa.googlegroups.com> <1155515929.791561.5300@m79g2000cwm.googlegroups.com> <1155517461.229483.18900@i3g2000cwc.googlegroups.com> <1155519055.451320.111050@b28g2000cwb.googlegroups.com> <1155522148.957303.203620@m79g2000cwm.googlegroups.com> Message-ID: <44e03789$0$6069$636a55ce@news.free.fr> kagard at gmail.com wrote: > Simon Forman wrote: >>> I got rid of the triple quote string at the start of the function, and >>> that cleared up the problem, though I don't know why. >>> >> Ah, yes. The docstring for a function (or at least its first >> triple-quote) must be indented to the same degree as its statements. >> (If you're using IDLE it should have indented it for you when you hit >> return after the def statement.) >> >> HTH, >> ~Simon > > Hi Simon: > > Thanks. I code in VB / VBA, and use indented structure, but it's not > enforced they way it is in Python - still getting used to that. Also, I > got goofed up editing some of the code in VIM, indenting with tabs, and > then switching to IDLE, with space indentation. Whoops... > > Thanks for all the help everyone, my first Python program is now > working! > > Keith > Tips: if you're coding with VIM, put "set expandtab" in your config file. That way, each tab will be expanded into the corresponding number of spaces ... Whatever the language, I find it always a bad idea to mix spaces and tabs, and I prefer spaces ... Pierre From ms at cerenity.org Sun Aug 20 18:20:08 2006 From: ms at cerenity.org (Michael) Date: Sun, 20 Aug 2006 23:20:08 +0100 Subject: cloning generator iterators References: <cXMFg.14720$gY6.373@newssvr11.news.prodigy.com> Message-ID: <44e8dead$0$3594$ed2e19e4@ptn-nntp-reader04.plus.net> Bernhard Mulder wrote: > [ attempt to clone/fork a generator ] You can do this, but you can't pickle the results. (If you want pickling, use Stackless - I've not tried pickling generators in stackless because I don't use stackless, but it looks pretty clear you can pickle them there) > Question: What is the best way to implement this clone operation? However you should be able to do what you want using the small extension "statesaver" which you can grab from * http://www.gosubway.org/install/statesaver.c The statesaver allows you to clone generators in the way that you want. FWIW, I can see lots of situations where this would be useful - mainly in the area of dealing with search spaces (After all, this effectively allows you to fork the generator). Michael. -- http://kamaelia.sourceforge.net/Home - Concurrency, Networking, Simplicity From pedro.werneck at terra.com.br Mon Aug 7 18:28:46 2006 From: pedro.werneck at terra.com.br (Pedro Werneck) Date: Mon, 7 Aug 2006 19:28:46 -0300 Subject: Class attributes, instances and metaclass __getattribute__ Message-ID: <20060807192846.600de3c1.pedro.werneck@terra.com.br> Hi all I noticed something strange here while explaining decorators to someone. Not any real use code, but I think it's worth mentioning. When I access a class attribute, on a class with a custom metaclass with a __getattribute__ method, the method is used when acessing some attribute directly with the class object, but not when you do it from the instance. <code type='prompt'> >>> class M(type): ... def __getattribute__(cls, attr): ... print cls, attr ... return type.__getattribute__(cls, attr) ... >>> class C(object): ... __metaclass__ = M ... >>> C.x = 'foo' >>> C.x <class '__main__.C'> x 'foo' >>> o = C() >>> o.x 'foo' >>> </code> Someone at freenode #python channel involved with python-dev sprint suggested it might be a bug, worth mentioning... to me it seems like a decision to avoid some problems with method and descriptors creation, since someone using metaclasses and custom __getattribute__ at the same time is asking for trouble, but... I googled for it and tried to find something on the list but, nothing. From the source it seems like a generic wrapper is used. What's the real case here ? Regards, -- Pedro Werneck From figo_wei01 at 126.com Sun Aug 20 13:18:27 2006 From: figo_wei01 at 126.com (figo_wei01 at 126.com) Date: 20 Aug 2006 10:18:27 -0700 Subject: import In-Reply-To: <1156093799.775420.51970@m73g2000cwd.googlegroups.com> References: <1156093283.529579.80600@i42g2000cwa.googlegroups.com> <1156093799.775420.51970@m73g2000cwd.googlegroups.com> Message-ID: <1156094307.576025.3430@i3g2000cwc.googlegroups.com> bugnthecode ??? > How are you trying to import it? Is it in the same directory as your > other script? If not is your python path set correctly? > > When importing a module that you have written you exlude the .py > extension. You should be using: > import hello > > Hope that helps, > Will i am on a windows platform. i have written scrip named 123.py. it can be run. ok i save it to C:\Python24 ,exactly the same dir where python works. but " import 123" doesnt work. From onurb at xiludom.gro Tue Aug 8 14:27:33 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 08 Aug 2006 20:27:33 +0200 Subject: Newbie question: what's with "self"? In-Reply-To: <1155061535.512389.260040@p79g2000cwp.googlegroups.com> References: <1155054411.511813.203270@i42g2000cwa.googlegroups.com> <1155061535.512389.260040@p79g2000cwp.googlegroups.com> Message-ID: <44d8d796$0$21144$7a628cd7@news.club-internet.fr> Miki wrote: (snip) > If you know C++/Java then "self" is like "this". But in Python, it's mandatory and must be the first arg for instance methods. From rogue_pedro at yahoo.com Mon Aug 14 14:29:35 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 14 Aug 2006 11:29:35 -0700 Subject: outputting a command to the terminal? References: <44df99f7$0$25025$c3e8da3@news.astraweb.com> <ebo75n$src$1@news-int2.gatech.edu> <44dfc1cb$0$2397$c3e8da3@news.astraweb.com> Message-ID: <1155580175.313400.136900@m79g2000cwm.googlegroups.com> John Salerno wrote: > Yu-Xi Lim wrote: > > > I assume you're using a Debian-based distro with aptitude as the front > > end. In which case, all dpkg operations should be logged in > > /var/log/dpkg.log > > Yes, I'm using Ubuntu. But I checked this log file and I'm a bit > confused. It has a lot of listings for 5-31-06, but I didn't even > install Linux until last Saturday. The next date after 5-31 is 8-5-06, > and I know I installed things between last Saturday and Aug. 5. > > (But this is OT, so don't worry about it.) > > > I'm wondering about the need to "output the bash command to the > > terminal". It would probably suffice if your Python script just spawned > > an instance of the shell with the necessary command line. Take a look at > > the subprocess module. > > > > But this really calls for a bash script: > > > > #!/bin/bash > > echo $@ >> /path/to/manual_install.log > > sudo aptitude install $@ > > > > > > Shorter than the equivalent Python code. You could probably declare this > > as a function in your bash initialization files too, if you know how to > > do this. > > Hmm, interesting. I figured I could do this with a bash script, but I > don't know bash at all and I'm trying to stick with Python. I don't > quite understand your bash script (not familiar with the $@ syntax). > > I think I'll take a look at the subprocess module, just for fun. :) Hey John, Yu-Xi Lim's right. This is one of those (thankfully few) cases where bash makes more sense to use than python (at least IMHO.) To figure out about that $@, fire up your teminal and type "man bash" ("!man bash" in IPython) (BTW, apropos of nothing, "man bash" is one of my all time favorite commands ever. I always think of some comic-book hero/monster shouting it, "MAN BASH!!" lol. Anyway...) So, now you're looking at the man page for bash. It's very very long and ubergeeky. Deep and amazing mysteries are contained (and kind of explained) within it. You want information on $@ so we'll use the search incantation to find and reveal it. Type "/\$@" without the quotes, then press return. (What this means/does: "/" is the manpage search command, it uses a regular expression syntax not dissimilar to python's own. "\" escapes the next character ("$", in this case) and we need to do that because "$" is regular expression syntax for "end of line". The "$@" will now match, um, "$@" correctly.) Once you press return, man will scroll to put the first occurance of "$@" at the top of your terminal and highlight it. On my system it's this line (I narrowed my terminal so that quoted portions wouldn't wrap badly in this posting): "$@" as explained below under Special Parameters. So far so good, '"$@" as explained below' looks promising. Rather than scrolling down to find this "Special Parameters" section, let's keep using the search. Press "n" to scroll to the next occurance of our pattern "$@". On my system this brings me to: separate word. That is, "$@" is equivalent to "$1" "$2" ... If the double-quoted expansion Ah ha! Scrolling up a few lines, we see: @ Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" ... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed). Not extraordinarily enlightening, maybe, but better than sitting in the dark, lighting your farts. :-D (Hit "q" to exit man.) Basically what this means is that $@ will become the positional arguments that you pass to your script. You can play with this by writing a simple bash script like this #!/bin/bash echo $@ and passing it args to see what it echos. (Remember to chmod +x it..) So, long story short, Yu-Xi Lim's bash script echos your package names to the /path/to/manual_install.log file (">>" in bash means "append the output of the command to the left to the file on the right",) then it calls aptitude with those same package names. It's simple, short, and to-the-point. The equivalent python script would be much longer, for no appreciable gain. I write most of my tiny little helper scripts in python, but in this case, bash is the clear winnar. (And on *nix. man pages are your best friend. Plus you get to feel all l33t when you grok them. lol) Peace, ~Simon From anthra.norell at tiscalinet.ch Fri Aug 11 05:24:35 2006 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Fri, 11 Aug 2006 11:24:35 +0200 Subject: using python to edit a word file? References: <aJKCg.2673$No6.52073@news.tufts.edu> <87slk4tp45.fsf@smsnet.pl><LeLCg.2674$No6.52085@news.tufts.edu> <GuLCg.2675$No6.51938@news.tufts.edu> Message-ID: <011401c6bd27$f64db5e0$0201a8c0@mcuf7> John, I have a notion about translating stuff in a mess and could help you with the translation. But it may be that the conversion from DOC to formatted test is a bigger problem. Loading the files into Word and saving them in a different format may not be a practical option if you have many file to do. Googling for batch converters DOC to RTF I couldn't find anything. If you can solve the conversion problem, pass me a sample file. I'll solve the translation problem for you. Frederic ----- Original Message ----- From: "John Salerno" <johnjsal at NOSPAMgmail.com> Newsgroups: comp.lang.python To: <python-list at python.org> Sent: Thursday, August 10, 2006 9:08 PM Subject: Re: using python to edit a word file? > John Salerno wrote: > > > But if I save the file to text, won't it lose its formatting? > > It looks like I can save it as an XML file and it will retain all the > formatting. Now I just need to decipher where the dates are in all that > mess and replace them, just using a normal text file! :) > -- > http://mail.python.org/mailman/listinfo/python-list From tomi.lindberg.NO_SPAM at pp.inet.fi.invalid Wed Aug 2 08:37:30 2006 From: tomi.lindberg.NO_SPAM at pp.inet.fi.invalid (Tomi Lindberg) Date: Wed, 02 Aug 2006 12:37:30 GMT Subject: Class definition within function In-Reply-To: <eaq51a$mc3$03$1@news.t-online.com> References: <Su0Ag.121$fe3.114@read3.inet.fi> <eaq51a$mc3$03$1@news.t-online.com> Message-ID: <e01Ag.145$fe3.7@read3.inet.fi> Peter Otten wrote: > By the way you get an instance of a different class C every time you call f, > so that > > isinstance(f(), type(f()) > > is False. That I didn't know. Well, that theory won't be seeing much practice I guess. -- Tomi Lindberg From sjmachin at lexicon.net Tue Aug 8 20:33:54 2006 From: sjmachin at lexicon.net (John Machin) Date: 8 Aug 2006 17:33:54 -0700 Subject: Class data being zapped by method In-Reply-To: <1155080710.437461.155300@m79g2000cwm.googlegroups.com> References: <1155065906.910642.77320@75g2000cwc.googlegroups.com> <mailman.9111.1155066643.27775.python-list@python.org> <1155076971.519157.92540@i42g2000cwa.googlegroups.com> <1155080710.437461.155300@m79g2000cwm.googlegroups.com> Message-ID: <1155083634.822521.24100@n13g2000cwa.googlegroups.com> John Machin wrote: > print [i, len(x.data), id(x) for i, x in enumerate(arrTests)] but should have written: print [(i, len(x.data), id(x)) for i, x in enumerate(arrTests)] From skip at pobox.com Wed Aug 9 19:18:59 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 9 Aug 2006 18:18:59 -0500 Subject: Image concatenation in PIL Message-ID: <17626.28003.72332.531725@montanaro.dyndns.org> Looking through the PIL docs I didn't see any obvious (one-line) way of concatenating two images. Given im1 and im2 which I wish to concatenate left-to-right, is this the simplest I can do? def imconcat(im1, im2): # concatenate im1 and im2 left-to-right h1, w1 = im1.size h2, w2 = im2.size im3 = PIL.Image.new("RGB", (max(h1, h2), w1+w2)) im3.paste(im1) im3.paste(im2, (0, w1, h2, w2)) return im3 I was hoping for something almost as simple as the netpbm command pnmcat -lr im1 im2 Thx, Skip From RentInGhent at gmail.com Sun Aug 13 22:22:29 2006 From: RentInGhent at gmail.com (kagard@gmail.com) Date: 13 Aug 2006 19:22:29 -0700 Subject: Nested if and expected an indent block In-Reply-To: <1155519055.451320.111050@b28g2000cwb.googlegroups.com> References: <1155511725.874993.140020@b28g2000cwb.googlegroups.com> <1155512775.186869.69190@m79g2000cwm.googlegroups.com> <1155514407.728107.196600@i42g2000cwa.googlegroups.com> <1155515929.791561.5300@m79g2000cwm.googlegroups.com> <1155517461.229483.18900@i3g2000cwc.googlegroups.com> <1155519055.451320.111050@b28g2000cwb.googlegroups.com> Message-ID: <1155522148.957303.203620@m79g2000cwm.googlegroups.com> Simon Forman wrote: > > I got rid of the triple quote string at the start of the function, and > > that cleared up the problem, though I don't know why. > > > Ah, yes. The docstring for a function (or at least its first > triple-quote) must be indented to the same degree as its statements. > (If you're using IDLE it should have indented it for you when you hit > return after the def statement.) > > HTH, > ~Simon Hi Simon: Thanks. I code in VB / VBA, and use indented structure, but it's not enforced they way it is in Python - still getting used to that. Also, I got goofed up editing some of the code in VIM, indenting with tabs, and then switching to IDLE, with space indentation. Whoops... Thanks for all the help everyone, my first Python program is now working! Keith From claird at lairds.us Thu Aug 10 18:52:25 2006 From: claird at lairds.us (Cameron Laird) Date: Thu, 10 Aug 2006 22:52:25 +0000 Subject: semi-Newbie question References: <1155229897.356144.183750@m79g2000cwm.googlegroups.com> <1155240906.769756.294620@74g2000cwt.googlegroups.com> <1155245290.532108.75560@75g2000cwc.googlegroups.com> Message-ID: <9upsq3-9ng.ln1@lairds.us> In article <1155245290.532108.75560 at 75g2000cwc.googlegroups.com>, len <lsumnler at gmail.com> wrote: >I appoligize I don't think I have done a very good job of explaining my >problem. . . . >The program I am writing is nothing more than a conversion program to >take the value out of the CSV file and map it into the appropriate >field in my SQL files. Rather than creating some huge if than else >(there are over 1000 tagnames) I created the xreffile. > >Now when I read a record from the tagfile I use the data in the tagname >field to lookup the tagname in my xreffile. The data in the >SQL_fieldname is the fieldname in my SQL files I want to place the data >from the tagfile in the tagfile.value field into this field in my SQL >files; > >data referenced by(xreffile.SQL_fieldname) = tagfile.value > >what I see as the problem is I want to use what is the data reference >by xreffile.SQL.fieldname and now make it part of the python code as a >reference variable in an assignement code statement. . . . 1. Take Daniel Wong's advice, elsewhere in this thread, and use the Python CSV module. 2. "what I see as the problem is I want ...": what you want *is* rather a problem, because it's a troublesome way to achieve what I understand to be your larger aims. It was certainly good that you didn't create "some huge if than else". Once you have an SQL_fieldname, and a tagfile.value, what do you want to do? Are you stuffing data into an SQL table? Continuing on with Python computations? In almost any case, it sounds as though you will profit greatly from study of Python's dictionaries <URL: http://www.developer.com/lang/other/article.php/630721 > <URL: http://www.diveintopython.org/getting_to_know_python/dictionaries.html >. From bytter at gmail.com Sun Aug 6 17:06:35 2006 From: bytter at gmail.com (Hugo Ferreira) Date: Sun, 6 Aug 2006 22:06:35 +0100 Subject: Proposal: [... for ... while cond(x)] In-Reply-To: <20060806223616.EEB7.SLAWOMIR.NOWACZYK.847@student.lu.se> References: <1154886383.696899.171490@i3g2000cwc.googlegroups.com> <Xns9817CB6E2A9DEduncanbooth@127.0.0.1> <20060806223616.EEB7.SLAWOMIR.NOWACZYK.847@student.lu.se> Message-ID: <4e8efcf50608061406x129bcba6g4ee91fe58bff1f2e@mail.gmail.com> I actually like the proposal... If the argument to remove map, lambda and filter can be that list comprehension is more "readable", then why can't this one also use it? Which reminds me this discussion: http://awkly.org/archive/can-python-take-advantage-of-mapreduce/ Cheers! Hugo On 8/6/06, Slawomir Nowaczyk <slawomir.nowaczyk.847 at student.lu.se> wrote: > > On Sun, 06 Aug 2006 18:59:39 +0000 (GMT) > Duncan Booth <duncan.booth at invalid.invalid> wrote: > > #> >> > I suggest a new extension of the list comprehension syntax: > #> >> > > #> >> > [x for x in xs while cond(x)] > #> >> > > #> >> > which would be equivalent to > #> >> > > #> >> > list(itertools.takewhile(cond, xs)) > #> >> > #> >> What would this syntax offer that: > #> >> > #> >> [x for x in takewhile(cond, xs)] > #> >> > #> >> doesn't currently offer? > #> > > #> > The same thing that [f(x) for x in xs] offers that map(f, xs) > doesn't, > #> > and the same thing that [x for x in xs if f(x)] offers that filter(f, > #> > xs) doesn't. It's more "pythonic". You can use an expression for cond > #> > instead of a lambda. > #> > > #> No, the list comprehension lets you write an expression directly > #> avoiding a function call, and it also allows you to add in a > #> condition which can be used to filer the sequence. > > I am not sure if I understand you correctly, but... Does it? > > >>> a = [0,1,2,3,7,8,9] > >>> [x for x in takewhile(lambda x: x in a, range(10))] > [0, 1, 2, 3] > >>> [x for x in takewhile(x in a, range(10))] > Traceback (most recent call last): > File "<stdin>", line 1, in ? > TypeError: 'bool' object is not callable > > Did I miss something? Notice that using "if" gives different result: > > >>> [x for x in range(10) if x in a] > [0, 1, 2, 3, 7, 8, 9] > > #> Your proposal adds nothing. > > Well, I am not sure how useful the proposal really is, but it seems to > add *something* if it would allow for things like: > [x for x in range(10) while x in a] > > -- > Best wishes, > Slawomir Nowaczyk > ( Slawomir.Nowaczyk at cs.lth.se ) > > Women who seek to be equal to men lack ambition. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- GPG Fingerprint: B0D7 1249 447D F5BB 22C5 5B9B 078C 2615 504B 7B85 -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060806/27f6357c/attachment.html> From rpdooling at gmail.com Sun Aug 13 11:12:24 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 13 Aug 2006 08:12:24 -0700 Subject: Installed correctly In-Reply-To: <53eud29hhhqqv7vi99dl9nhjjkl1of49ik@4ax.com> References: <i87ud25fkbif2rk2daul8t1rc5nmv7msj1@4ax.com> <1155476706.812107.276950@b28g2000cwb.googlegroups.com> <53eud29hhhqqv7vi99dl9nhjjkl1of49ik@4ax.com> Message-ID: <1155481944.557258.305980@75g2000cwc.googlegroups.com> Rich wrote: >> But command line still says "unrecognized command", You don't say which installer you are using? I know the ActiveState installer puts the python directory in your environment automatically, and I bet the Python.org installer does too. Do you see Python24 in your path? If you get desperate, try: http://dooling.com/index.php/category/geekophilia It's a hand-holding install guide. rd From antroy at gmail.com Wed Aug 2 11:48:09 2006 From: antroy at gmail.com (Ant) Date: 2 Aug 2006 08:48:09 -0700 Subject: need help of regular expression genius In-Reply-To: <1154532421.096157.289570@i42g2000cwa.googlegroups.com> References: <1154532421.096157.289570@i42g2000cwa.googlegroups.com> Message-ID: <1154533689.556399.310990@m79g2000cwm.googlegroups.com> GHUM wrote: > I need to split a text at every ; (Semikolon), but not at semikolons > which are "escaped" within a pair of $$ or $_$ signs. Looking at you example SQL code, it probably isn't possible with regexes. Consider the code: $$ blah blah ... $$ blah; <split here> xxx $$ blah blah $$ Regexes aren't clever enough to count the number of backreferences, and so won't help in the above case. You'd be better off creating a custom parser using a stack or counter of some sort to decide whether or not to split the text. From rpdooling at gmail.com Sun Aug 13 09:45:06 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 13 Aug 2006 06:45:06 -0700 Subject: Installed correctly In-Reply-To: <i87ud25fkbif2rk2daul8t1rc5nmv7msj1@4ax.com> References: <i87ud25fkbif2rk2daul8t1rc5nmv7msj1@4ax.com> Message-ID: <1155476706.812107.276950@b28g2000cwb.googlegroups.com> Ray wrote: > are there any > problems with this? Apparently, yes ;) >> Do you know how to set up the %PATH% variable in win2k? In case you don't, this is from another thread: Sequence on XP is Start | Control Panel | System | Advanced | Environmental Variables. Then in the lower half of the dialogue box is the "System Variables" Select Path, and then edit and enter the path to Python.exe. I used ActiveState which puts it in c:\python24 >From what you've told us you should try c:\Program Files\Python But as the wise man says, the spaces in path names will haunt you on windows. Good luck. From arenium at gmail.com Tue Aug 8 15:38:26 2006 From: arenium at gmail.com (arenium at gmail.com) Date: 8 Aug 2006 12:38:26 -0700 Subject: Class data being zapped by method Message-ID: <1155065906.910642.77320@75g2000cwc.googlegroups.com> Hi, I'll cut to the chase. I have a class named Foo(). I create an instance of this class named bar, and I set bar.data to a large list of tuples. Within Foo() there is a method which operates on self.data. I need to call this method after I set self.data from the "outside" (bar.data), which isn't a problem. However, I have found through simple debugging procedures that while bar.data exists fine before the said method is called, self.data within the class method is EMPTY. In my class constructor I do declare self.data to be an empty list ([]), but shouldn't self.data contain the populated list? Basically... -------------------------------------------------------------------------- class Foo(): __init__(self): self.data = [] a_count(self): .... print self.data .... bar = Foo() bar.data = [(-74.0015, 1), (123.451, 18), ...] print bar.data # Get what I expect bar.a_count() # [] -------------------------------------------------------------------------- This is a *highly* simplified version of what I'm actually doing. If more code is needed just ask. Thanks in advance. From nicogrubert at gmail.com Thu Aug 31 12:26:29 2006 From: nicogrubert at gmail.com (Nico Grubert) Date: Thu, 31 Aug 2006 18:26:29 +0200 Subject: Searching a string and extract all occurancies of a substring In-Reply-To: <7.0.1.0.0.20060831130033.05175028@yahoo.com.ar> References: <44F703C8.3080504@gmail.com> <7.0.1.0.0.20060831130033.05175028@yahoo.com.ar> Message-ID: <44F70DB5.30302@gmail.com> > Try Beautiful Soup, or if your input is simple enough, the re module. Hi Gabriel, I first tried "HTMLParser" and wrote this short script: from HTMLParser import HTMLParser from htmlentitydefs import entitydefs class MyDocParser(HTMLParser): def __init__(self): self.paths = [] self.readingpaths = 0 # flag HTMLParser.__init__(self) def handle_starttag(self, tag, attrs): if tag == 'parameter': self.readingpaths = 1 def handle_endtag(self, tag): if tag == 'parameter': self.readingpaths = 0 def handle_data(self, data): if self.readingpaths: self.paths.append(data) def handle_entityref(self, name): " handle values like 'Home & Products' " if entitydefs.has_key(name): self.handle_data(entitydefs[name]) else: self.handle_data('&' + name + ';') def handle_charref(self, name): """ handle values like 'Home & Products®' Ignores invalid character references """ try: charnum = int(name) except ValueError: return if charnum < 1 or charnum > 255: return def get_paths(self): return self.paths def parse_content(content): """ parse """ parser = MyDocParser() parser.feed(content) paths = parser.get_paths() return paths # /end This works as long as there are no other <paramter> Tags in the content that I parse. Nico From prestonh at gmail.com Fri Aug 25 13:45:02 2006 From: prestonh at gmail.com (Preston Hagar) Date: Fri, 25 Aug 2006 12:45:02 -0500 Subject: couple more questions about sqlite In-Reply-To: <MqnFg.2703$No6.52653@news.tufts.edu> References: <MqnFg.2703$No6.52653@news.tufts.edu> Message-ID: <8f5897560608251045k11a5569drff6b13b798f3747b@mail.gmail.com> It looks like most of your questions have been answered, but I might also suggest the APress book on SQLite: http://www.amazon.com/gp/product/1590596730/sr=8-2/qid=1142277203/ref=pd_bbs_2/002-3764084-7189633?%5Fencoding=UTF8 ***MAJOR DISCLAIMER: I was the technical reviewer on this book.*** The book is really well written and will take you through all facets of sqlite. It also includes two sections on using SQLite and python. Preston On 8/18/06, John Salerno <johnjsal at nospamgmail.com> wrote: > > I've been looking around and reading, and I have a few more questions > about SQLite in particular, as it relates to Python. > > 1. What is the current module to use for sqlite? sqlite3? or is that not > out until Python 2.5? > > 2. What's the difference between sqlite and pysqlite? Do you need both, > just one, or is one an older version of the same thing? > > 3. What's the difference between the command line program called sqlite3 > and the module you would use with Python? (I know that the former let's > you do normal database things without dealing with Python, but is it > necessary if you are using Python to interact with the DB?) > > Thanks! > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060825/cda383d3/attachment.html> From jorge.vargas at gmail.com Thu Aug 31 00:38:34 2006 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Thu, 31 Aug 2006 00:38:34 -0400 Subject: Truly platform-independent DB access in Python? In-Reply-To: <1156748466.739709.117850@h48g2000cwc.googlegroups.com> References: <1156748466.739709.117850@h48g2000cwc.googlegroups.com> Message-ID: <32822fe60608302138v12ea8535oc33aed45ed866222@mail.gmail.com> On 28 Aug 2006 00:01:06 -0700, bobrik <boris.dusek at gmail.com> wrote: > Hello, > > I am using the Python DB API for access to MySQL. But it is not > platform-independent - I need a module not included in Python by > default - python-mysql, and it uses a compiled binary _mysql.so. So it > is not platform-independent because for each web-server on different > platform, I would have to download it and extra compile it specifically > for that platform. Do you know of any Python solution for MySQL access > that is 100% platform-independent? > I'm sorry but since when is MySQL platform independent? if mysql-python will be pure python then it will probably be slower because it will have to use sockets, or other type of IPC instead Andy used mysql C API which is fast. on the other hand all big *NIX distros have mysql-python on their packages/tree, and I made a windows installer of the last version, which you can get from sourceforge. so the only problem I see here is if your on a mac, on which the source should compile without problems since it's *NIX now. at this moment installing on any mayor platform is 2-3 commands/clicks away. > Thanks for any suggestions. > Boris Du?ek > > -- > http://mail.python.org/mailman/listinfo/python-list > From andychambers2002 at yahoo.co.uk Thu Aug 17 15:58:02 2006 From: andychambers2002 at yahoo.co.uk (andychambers2002 at yahoo.co.uk) Date: 17 Aug 2006 12:58:02 -0700 Subject: sqlite3 or mysqldb? References: <uR%Eg.2697$No6.52598@news.tufts.edu> Message-ID: <1155844682.243035.264130@p79g2000cwp.googlegroups.com> > I was using mysqldb just because MySQL seems to be a pretty big > standard, but now that sqlite3 is coming with Python 2.5, I might > switch, since it seems to be easier to use. Yes and No. Sqlite takes less to configure and manage but you have to consider your needs for concurrent processing. If memory/disk space is no object then I would stick to mysql. If its learning SQL that you want, you should try postgres. It has a very interesting "RULE" system that you can play with. Regards, Andy From bearophileHUGS at lycos.com Fri Aug 11 07:08:46 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 11 Aug 2006 04:08:46 -0700 Subject: Python checking for None/Null values In-Reply-To: <1155292928.980276.228690@p79g2000cwp.googlegroups.com> References: <1155291204.446003.93760@m73g2000cwd.googlegroups.com> <pan.2006.08.11.10.25.42.64571@gmx.net> <1155292928.980276.228690@p79g2000cwp.googlegroups.com> Message-ID: <1155294526.685912.143450@75g2000cwc.googlegroups.com> Fuzzydave: > I am trying to check all of the historyRep items > to check if they are empty/null/None (whatever the term is in python) An item can't be empty in Python,and null doesn't exist, it can be the object None. But probly that's not your case. > I did print > historyRep[8] out and it falls over, I am assuming if its an array and > if the SQL query only returns 8 records instead of 10 then the last > two array values i am checking for litterly don't exist instead of > being null but i can't find a if exists style function either? A way to solve your problem is to see how many elements the list contains with len(sequence) then act accordingly with the elements that exist. Even better is to work on the elements that exist, with something like: for element in sequence: do_stuff Note: sometimes having a clean and readable program is better than having a running program that you can't read, because you can fix the the first one, and it can teach you something. Bye, bearophile From g.brandl-nospam at gmx.net Fri Aug 18 08:35:23 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Fri, 18 Aug 2006 14:35:23 +0200 Subject: Clean way to not get object back from instantiation attempt gone bad In-Reply-To: <44e245c0$0$20991$88260bb3@free.teranews.com> References: <44e245c0$0$20991$88260bb3@free.teranews.com> Message-ID: <ec4c6c$9cr$1@news.albasani.net> tobiah wrote: > Suppose I do: > > > myfoo = Foo('grapes', 'oranges') > > And in the __init__() of Foo, there is > a real problem with the consumption of fruit. > Is there a clean way to ensure that myfoo > will be None after the call? Would the > __init__() just do del(self), or is there > a better way to think about this? There is a way, of course, that results in myfoo being None in case of an error, but it is not a one-liner and I'd not recommend it. If something goes wrong, raising an exception is the best thing to do. Georg From scott.daniels at acm.org Mon Aug 28 13:36:49 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 28 Aug 2006 10:36:49 -0700 Subject: Is this a good idea or a waste of time? In-Reply-To: <slrnef5hep.4tu.apardon@rcpc42.vub.ac.be> References: <1156449402.022781.292840@p79g2000cwp.googlegroups.com> <1156485945.967160.238790@m73g2000cwd.googlegroups.com> <slrnef5hep.4tu.apardon@rcpc42.vub.ac.be> Message-ID: <44f322cd$1@nntp0.pdx.net> Antoon Pardon wrote: > On 2006-08-25, Simon Forman <rogue_pedro at yahoo.com> wrote: >> ... >> Generally asserts should be used to "enforce" invariants of your code >> (as opposed to typechecking), or to check certain things while >> debugging. > > I don't understand this argument. Can't type checking be seen as > enforcing a code invariant? > But it is practically never the "right" invariant. You don't usually mean type(x) == int, but rather something like x is a prime between 2 and 923. Or 5< x**4 < 429, or _something_ problem specific. saying that x must be an int is almost always simultaneously too specific and too general. --Scott David Daniels scott.daniels at acm.org From boris.dusek at gmail.com Mon Aug 28 03:01:06 2006 From: boris.dusek at gmail.com (bobrik) Date: 28 Aug 2006 00:01:06 -0700 Subject: Truly platform-independent DB access in Python? Message-ID: <1156748466.739709.117850@h48g2000cwc.googlegroups.com> Hello, I am using the Python DB API for access to MySQL. But it is not platform-independent - I need a module not included in Python by default - python-mysql, and it uses a compiled binary _mysql.so. So it is not platform-independent because for each web-server on different platform, I would have to download it and extra compile it specifically for that platform. Do you know of any Python solution for MySQL access that is 100% platform-independent? Thanks for any suggestions. Boris Du?ek From cwildsmith at westnet.com.au Fri Aug 11 10:41:56 2006 From: cwildsmith at westnet.com.au (Colin Wildsmith) Date: Fri, 11 Aug 2006 22:41:56 +0800 Subject: Tab delimited file Message-ID: <000f01c6bd54$4b514e40$6501a8c0@mshome> Hello, I am making a gui for the purpose that I can change the values in a list of different criteria which is found in a text file, such as: Name(tab)rating(tab)breast size(tab)occurrences . . . However as far as I know Python does not allow you to easily change a specific line in a text file. You have to place the whole file to memory, change what you need to and then write the file back after deleting the previous information. Assuming this is true, how do i find where the tabs are in the file so that I can distinguish between the different criteria? Assuming this is not true, does anyone suggest another way to do it? CoLe -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060811/bb5a2c64/attachment.html> From timr at probo.com Sat Aug 5 21:25:13 2006 From: timr at probo.com (Tim Roberts) Date: Sun, 06 Aug 2006 01:25:13 GMT Subject: More int and float attributes References: <1154780600.348169.158150@i42g2000cwa.googlegroups.com> Message-ID: <10had2d2e8vagckm34l0lh17t518iaaqct@4ax.com> bearophileHUGS at lycos.com wrote: > >sys.maxint gives the largest positive integer supported by Python's >regular integer type. But maybe such attribute, with few others (they >can be called min and max) can be given to int type itself. >D is a very nice language, that I hope to see more used. It is copying >lot of things from Python. I don't see that. It looks rather like an incremental improvement to C and C++ rather than a language influenced by Python. >D Floating point values have some proprieties: > >http://www.digitalmars.com/d/property.html > >Properties for Floating Point Types: >.init initializer (NaN) >.infinity infinity value >.nan NaN value >.dig number of decimal digits of precision >.epsilon smallest increment >... There's an interesting philosophical difference here. D is defined as a "systems programming language". It is compiled to native machine code, like C. In such a case, the programmer necessarily needs to concern himself with the processor's representation of integers and floats. Python has a rather different focus. I certainly use it for system programming tasks, but in most cases, a Python programmer shouldn't need to worry about the internal representation of variables. Look, for example, at the blurred distinction between integers and long integers. I'm not arguing for or against the proposal, but I suspect these properties would be rarely used. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From kay.schluehr at gmx.net Thu Aug 31 15:16:24 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 31 Aug 2006 12:16:24 -0700 Subject: python loops In-Reply-To: <1157051115.635459.215920@p79g2000cwp.googlegroups.com> References: <1157050085.120921.31840@h48g2000cwc.googlegroups.com> <JcGJg.21533$ED.7604@read2.cgocable.net> <1157051115.635459.215920@p79g2000cwp.googlegroups.com> Message-ID: <1157051784.609953.196100@h48g2000cwc.googlegroups.com> bearophileHUGS at lycos.com wrote: > AlbaClause wrote: > > > for i in range(length): > > print i > > Or usually better: > > for ii in xrange(length): ~~ I hate ii ;) Regards, Kay From glenn at tangelosoftware.net Tue Aug 29 10:33:32 2006 From: glenn at tangelosoftware.net (glenn) Date: 29 Aug 2006 07:33:32 -0700 Subject: refering to base classes Message-ID: <1156862012.068397.284040@m73g2000cwd.googlegroups.com> hi - Im quite new to python, wondering if anyone can help me understand something about inheritance here. In this trivial example, how could I modify the voice method of 'dog' to call the base class 'creatures' voice method from with in it? class creature: def __init__(self): self.noise="" def voice(self): return "voice:" + self.noise class dog(creature): def __init__(self): self.noise="bark" def voice(self): print "brace your self:" thanks glenn From martin.hoefling at gmx.de Mon Aug 7 10:57:10 2006 From: martin.hoefling at gmx.de (=?UTF-8?B?TWFydGluIEjDtmZsaW5n?=) Date: Mon, 07 Aug 2006 16:57:10 +0200 Subject: is it possible to dividing up a class in multiple files? In-Reply-To: <4jouimF8ue5nU1@uni-berlin.de> References: <eb7ftn$t15$1@news.lrz-muenchen.de> <4jouimF8ue5nU1@uni-berlin.de> Message-ID: <eb7kbf$vil$1@news.lrz-muenchen.de> Thanks for your suggestions, precompiling is not an option, cause I can't introduce extra dependencies from a precompiler. > Better yet is to not write huge classes and getting rid of strange > conventions or views that make the problem appear as such. To explain that: > I've never felt the need to spread a class over several files - au > contraire, I despise Java for forcing me to only have one top level class > per file. You're probably right. I'll think about it if it's possible to move some stuff out of the class. Thanks Martin From email at christoph-haas.de Thu Aug 3 10:39:30 2006 From: email at christoph-haas.de (Christoph Haas) Date: Thu, 3 Aug 2006 16:39:30 +0200 Subject: Running queries on large data structure In-Reply-To: <200608022224.00925.email@christoph-haas.de> References: <200608022224.00925.email@christoph-haas.de> Message-ID: <200608031639.30477.email@christoph-haas.de> On Wednesday 02 August 2006 22:24, Christoph Haas wrote: > I have written an application in Perl some time ago (I was young and > needed the money) that parses multiple large text files containing > nested data structures and allows the user to run quick queries on the > data. [...] I suppose my former posting was too long and concrete. So allow me to try it in a different way. :) The situation is that I have input data that take ~1 minute to parse while the users need to run queries on that within seconds. I can think of two ways: (1) Database (very quick, but the input data is deeply nested and it would be ugly to convert it into some relational shape for the database) (2) cPickle (Read the data every now and then, parse it, write the nested Python data structure into a pickled file. The let the other application that does the queries unpickle the variable and use it time and again.) So the question is: would you rather force the data into a relational database and write object-relational wrappers around it? Or would you pickle it and load it later and work on the data? The latter application is currently a CGI. I'm open to whatever. :) Thanks for any enlightenment. Christoph From joel.hedlund at gmail.com Thu Aug 31 11:47:33 2006 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Thu, 31 Aug 2006 17:47:33 +0200 Subject: sys.argv[0] doesn't always contain the full path of running script. In-Reply-To: <1156967974.600841.148460@p79g2000cwp.googlegroups.com> References: <1156873037.590351.158120@i42g2000cwa.googlegroups.com> <1156967974.600841.148460@p79g2000cwp.googlegroups.com> Message-ID: <ed7032$3hu$1@news.lysator.liu.se> >> How can I find where exactly the current python script is running? > > Doesnt __file__ attribute of each module contain the full filepath of > the module? > Yes indeed! But the path to the module will not be the same as the path to the script if you are currently in an imported module. Consider this: my_script.py: --------------------------- import my_module --------------------------- my_module.py: --------------------------- print __file__ --------------------------- Running "python test.py" now prints /path/to/my_module.py, not /path/to/my_script.py. Cheers! /Joel Hedlund From tjreedy at udel.edu Fri Aug 25 16:38:33 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 25 Aug 2006 16:38:33 -0400 Subject: Newbie programmer question: How do parsers work?(Python examples?) References: <1156535724.221400.175230@m79g2000cwm.googlegroups.com> Message-ID: <ecnn49$lh0$1@sea.gmane.org> "bio_enthusiast" <lancepickens at gmail.com> wrote in message news:1156535724.221400.175230 at m79g2000cwm.googlegroups.com... >I was wondering exactly how you create a parser. I'm learning > Python and I recently have come across this material. I'm interested > in the method or art of writing a parser. > > If anyone has some python code to post for an abstract parser, or links > to some informative tutorials, that would be great. I believe the book 'Text Processing in Python" (or something like that) by Mertz has info on parsing and modules written in Python that does such. tjr From fredrik at pythonware.com Sun Aug 27 16:55:18 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 27 Aug 2006 22:55:18 +0200 Subject: Pros/Cons of Turbogears/Rails? In-Reply-To: <WXmIg.20772$gY6.18513__39314.2653898851$1156709508$gmane$org@newssvr11.news.prodigy.com> References: <WXmIg.20772$gY6.18513__39314.2653898851$1156709508$gmane$org@newssvr11.news.prodigy.com> Message-ID: <ect0rn$oij$1@sea.gmane.org> kenneth.m.mcdonald at sbcglobal.net wrote: > + Built-in Rubydoc system would make documenting the > system easier. (IMHO, developers almost always > underestimate the need for good documentation that > is written along withe the system.) Is there a > Python doc system that has received Guido's blessing > yet? afaik, TurboGears has standardized on PythonDoc markup in docstrings: http://effbot.org/zone/pythondoc.htm > P.S. If I wanted to provide an image by streaming the > file data directly over the connection, rather than by > referring to an image file, how would I do that? I'd > like to build code that would allow images to be assembled > into a single-file photo album (zip or bsddb file), and > so can't refer to them as individual image files. some browsers support special data URL:s for images, but that doesn't work well for large images, and isn't portable. on the other hand, I don't really see why there has to be 1:1 mapping between URL:s and image files on your machine, especially if you're using a web application framework... </F> From fabiofz at gmail.com Wed Aug 23 07:31:17 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Wed, 23 Aug 2006 08:31:17 -0300 Subject: idutils and Python In-Reply-To: <624934630608220305k31b91a2ao9263c19cb342b662@mail.gmail.com> References: <mailman.9627.1156207047.27775.python-list@python.org> <1156226173.596437.266680@75g2000cwc.googlegroups.com> <624934630608220305k31b91a2ao9263c19cb342b662@mail.gmail.com> Message-ID: <cfb578b20608230431y3474a6aaj8b239a3e1958bcd3@mail.gmail.com> > > > > What exactly are you trying to accomplish? If you want to index > > function/class names, variables, etc then you should take a look at > > "exuberant ctags" http://ctags.sourceforge.net53 --although it started > > off as a C indexer, it has excellent Python support, it's free, and as > > a bonus its indices are well supported from inside major editors (vim, > > emacs, etc) so you can easily follow code flow, find function/class > > definitions, etc. > > > Sorry for not being clear enough. I want the following: > > a) have my editor go to the point where a function/whatever is defined Pydev Extensions (http://www.fabioz.com/pydev) should do that without any problems with F3 (it first tries a 'context-sensitive' match, trying to find it in locals, globals, current class, etc and if not found like that, it goes and looks for the signature in a context-insensitive way, as if it was a simple text-search) b) see all places where a function/whatever is used. This can be handed pretty well with the search that is builtin into Eclipse (ctrl+h). Cheers, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060823/0577f354/attachment.html> From bearophileHUGS at lycos.com Thu Aug 10 06:54:14 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 10 Aug 2006 03:54:14 -0700 Subject: Easy image rendering? In-Reply-To: <1155175964.455569.198430@i42g2000cwa.googlegroups.com> References: <1155166070.085423.37420@b28g2000cwb.googlegroups.com> <pan.2006.08.10.00.55.57.560672@users.sf.net> <1155172010.495135.274230@75g2000cwc.googlegroups.com> <mailman.9176.1155172834.27775.python-list@python.org> <1155175964.455569.198430@i42g2000cwa.googlegroups.com> Message-ID: <1155207254.831407.87130@i3g2000cwc.googlegroups.com> jaysherby at gmail.com: > my eventual goal is > to be able to put the pictures on the screen with a full-screen > interface. Not in a visible window, with just the picture and then a > black backdrop for it. Pygame (plus PIL if you need) can do that, Pygame manages full screens too. Bye, bearophile From remarkability at gmail.com Fri Aug 4 07:06:46 2006 From: remarkability at gmail.com (Remarkable) Date: Fri, 4 Aug 2006 12:06:46 +0100 Subject: Web Crawling/Threading and Things That Go Bump in the Night Message-ID: <eav9oa$8s3$1$8300dec7@news.demon.co.uk> Hello all I am trying to write a reliable web-crawler. I tried to write my own using recursion and found I quickly hit the "too many sockets" open problem. So I looked for a threaded version that I could easily extend. The simplest/most reliable I found was called Spider.py (see attached). At this stage I want a spider that I can point at a site, let it do it's thing, and reliable get a callback of sorts... including the html (for me to parse), the url of the page in question (so I can log it) and the urls-found-on-that-page (so I can strip out any ones I really don't want and add them to the "seen-list". Now, this is my question. The code above ALMOST works fine. The crawler crawls, I get the data I need BUT... every now and again the code just pauses, I hit control-C and it reports an error as if it has hit an exception and then carries on!!! I like the fact that my spider_usage.py file has the minimum amount of spider stuff in it... really just a main() and handle() handler. How does this happen... is a thread being killed and then a new one is made or what? I suspect it may have something to do with sockets timing out, but I have no idea... By the way on small sites (100s of pages) it never gets to the stall, it's on larger sites such as Amazon that it "fails" This is my other question It would be great to know, when the code is stalled, if it is doing anything... is there any way to even print a full stop to screen? This is my last question Given python's suitability for this sort of thing (isn't google written in it?) I can't believe that that there isn't a kick ass crawler already out there... regards tom http://www.theotherblog.com/Articles/2006/08/04/python-web-crawler-spider/ From jmpurser at gmail.com Wed Aug 30 10:33:41 2006 From: jmpurser at gmail.com (John Purser) Date: Wed, 30 Aug 2006 07:33:41 -0700 Subject: dictionary with object's method as thier items In-Reply-To: <1156944917.152606.213600@i42g2000cwa.googlegroups.com> References: <1156944917.152606.213600@i42g2000cwa.googlegroups.com> Message-ID: <20060830073341.78d31d12.jmpurser@gmail.com> On 30 Aug 2006 06:35:17 -0700 "noro" <amit.man at gmail.com> wrote: > Is it possible to do the following: > > for a certain class: > > ---------------------------- > class C: > > def func1(self): > pass > def func2(self): > pass > def func4(self): > pass > > obj=C() > ---------------------------- > > by some way create a dictionary that look somthing like that: > > d= {'function one': <reference to C.func1()>, \ > 'function two': <reference to C.func2()>, \ > 'function three': <reference to C.func3()>} > > and so i could access every method of instances of C, such as obj with > sometiing like: > (i know that this syntax wont work ) > > obj.(d['function one']) > obj.(d['function two']) > etc.. > Sure. But the syntax would be: d['function one'] = c.func1 d['function one']() I'm not sure what this gets you but it works. John Purser From python.list at tim.thechases.com Wed Aug 9 15:04:26 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 09 Aug 2006 14:04:26 -0500 Subject: Escape sequences (colour) and padding with "%8s"% In-Reply-To: <ebd74s$1u1d$1@gwdu112.gwdg.de> References: <ebd74s$1u1d$1@gwdu112.gwdg.de> Message-ID: <44DA31BA.9020002@tim.thechases.com> > I used escape sequences to produce colour output, but a construct like > > print "%8s" % str_with_escape > > doesn't do the right thing. I suppose the padding counts the escape > characters, too. > > What could be a solution? You omit half of the equation: the contents of str_with_escape. >>> print "hello %c[1mworld%c[0m" % (27, 27) works just fine for me in Linux (it chokes a bit on Win32 under cmd.exe, printing the actual escape character, rather than interpreting it as an ANSI control sequence). One can even do fancy stuff like: >>> mapping = {'bold': '\x1b[1m', 'normal':'\x1b[0m', 'blue':'\x1b[34m'} >>> print "this has some %(bold)sbold%(normal)s text and some %(blue)sblue%(normal)s text and some %(bold)s%(blue)stext that is bold and blue%(normal)s in it" % mapping and it works with %8s as well. You might prefer to use the standard curses library rather than try and roll your own... -tkc From st at tobiah.org Fri Aug 25 17:16:59 2006 From: st at tobiah.org (tobiah) Date: Fri, 25 Aug 2006 14:16:59 -0700 Subject: RE Module In-Reply-To: <1156539112.253232.321820@i3g2000cwc.googlegroups.com> References: <1156478366.165463.277480@h48g2000cwc.googlegroups.com> <44ef3f95$0$8926$88260bb3@free.teranews.com> <1156539112.253232.321820@i3g2000cwc.googlegroups.com> Message-ID: <44ef5ba7$0$8907$88260bb3@free.teranews.com> Roman wrote: > This is excellent. Thanks a lot. > > Also, what made the expression greedy? They usually are, by default. It means that when there are more than one ways to match the pattern, choose the one that matches the most text. Often there are flags available to change that behavior. I'm not sure off hand how to do it with the re module. -- Posted via a free Usenet account from http://www.teranews.com From diffuser78 at gmail.com Thu Aug 10 15:02:28 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 10 Aug 2006 12:02:28 -0700 Subject: Client/Server Question In-Reply-To: <1154191141.209741.202460@m79g2000cwm.googlegroups.com> References: <1154116446.226996.226410@s13g2000cwa.googlegroups.com> <1154191141.209741.202460@m79g2000cwm.googlegroups.com> Message-ID: <1155236548.312507.71760@h48g2000cwc.googlegroups.com> > The recv() might return "MaxiSimDriving Sim". It could return > "MaxiS" on one call, and "im" on the next. If the remote side > closes the connection, recv() will keep returning the empty > string, and your program will be stuck in an infinite loop. How to overcome this problem ? > Did you understand Faulkner's suggustion? Anyone who connects to > TCP port 2000 can invoke "shutdown -s" (which I assume shuts down > your host). I did, anyone who connects to port 2000 might be able to send a shutdown and close the computer. I am aware that its not the best way to achieve this but my app runs on a small network without actually connecting to internet. Can you give any tips to overcome the above mentioned problem. > --Bryan From paddy3118 at netscape.net Thu Aug 17 17:39:58 2006 From: paddy3118 at netscape.net (Paddy) Date: 17 Aug 2006 14:39:58 -0700 Subject: List match In-Reply-To: <1155824154.577194.320060@b28g2000cwb.googlegroups.com> References: <1155823451.766317.7640@74g2000cwt.googlegroups.com> <1155824154.577194.320060@b28g2000cwb.googlegroups.com> Message-ID: <1155850798.819088.79510@h48g2000cwc.googlegroups.com> thunderfoot at gmail.com wrote: > OriginalBrownster wrote: > > Hi there: > > > > I know this probably is a very easy thing to do in python, but i wanted > > to compare 2 lists and generate a new list that does not copy similar > > entries. An example below > > > > list= ["apple", "banana", "grape"] > > list2=["orange","banana", "pear"] > > > > now I want to compare these lits and generate a third list after > > comparison > > > > list3 would be ["apple", "banana","grape","orange", "pear"] > > > > hence the double entry would not show up? > > > > Is there a way to do this?? > > > > Stephen > > How about: > > list3 = list1 + [item for item in list2 if item not in list1] > > print list3: > > ['apple', 'banana', 'grape', 'orange', 'pear'] It works with the data given, but if list1 contains duplicates... - Pad From bdesth.quelquechose at free.quelquepart.fr Wed Aug 2 18:24:19 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 03 Aug 2006 00:24:19 +0200 Subject: Programming newbie coming from Ruby: a few Python questions In-Reply-To: <1154539652.256975.155200@i3g2000cwc.googlegroups.com> References: <mailman.8824.1154472963.27775.python-list@python.org> <1154494954.082706.283750@b28g2000cwb.googlegroups.com> <44d06f9f$0$19127$626a54ce@news.free.fr> <1154539223.873418.286830@i42g2000cwa.googlegroups.com> <1154539652.256975.155200@i3g2000cwc.googlegroups.com> Message-ID: <44d12416$0$1322$626a54ce@news.free.fr> BartlebyScrivener a ?crit : > simonharri... at fastmail.co.uk wrote: > > >>>The Ruby crowd says you guys are no where >>> near as friendly as them! > > > Slander! Defamation! > I'd rather say cluelessness and jealousy !-) From bedouglas at earthlink.net Thu Aug 10 21:37:20 2006 From: bedouglas at earthlink.net (bruce) Date: Thu, 10 Aug 2006 18:37:20 -0700 Subject: python/mysql/list question... Message-ID: <278e01c6bce6$b1bbe960$0301a8c0@Mesa.com> hi. i have the following sample code. i'm trying to figure out if there's a way to use a 'list of lists' in a mysql execute... i've tried a variety of combinations but i get an error: Error 1241: Operand should contain 1 column(s) the test code is: insertSQL = """insert into appTBL (appName, universityID) values(%s,%s)""" a = [] b = [] a.append('qqa') a.append(222) b.append(a) a=[] a.append('bbb') a.append(66) b.append(a) try: c.execute(insertSQL, (b[0],b[1])) <<<<<<<<<<<<<<<<<<< except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) print b sys.exit (1) i've tried to use b, (b), etc... using b[0] works for the 1st row... any thoughts/comments... thanks From sjmachin at lexicon.net Mon Aug 14 15:16:43 2006 From: sjmachin at lexicon.net (John Machin) Date: 14 Aug 2006 12:16:43 -0700 Subject: Memory problem In-Reply-To: <mailman.9320.1155580347.27775.python-list@python.org> References: <mailman.9320.1155580347.27775.python-list@python.org> Message-ID: <1155583003.744004.218330@h48g2000cwc.googlegroups.com> Yi Xing wrote: > Hi, > > I need to read a large amount of data into a list. So I am trying to > see if I'll have any memory problem. When I do > x=range(2700*2700*3) I got the following message: > > Traceback (most recent call last): > File "<stdin>", line 1, in ? > MemoryError > > Any way to get around this problem? I have a machine of 4G memory. The > total number of data points (float) that I need to read is in the order > of 200-300 millions. > 2700*2700*3 is only 21M. Your computer shouldn't have raised a sweat, let alone MemoryError. Ten times that got me a MemoryError on a 1GB machine. A raw Python float takes up 8 bytes. On a 32-bit machine a float object will have another 8 bytes of (type, refcount). Instead of a list, you probably need to use an array.array (which works on homogenous contents, so it costs 8 bytes each float, not 16), or perhaps numeric/numpy/scipy/... HTH, John From justin.mailinglists at gmail.com Thu Aug 17 22:35:51 2006 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: 17 Aug 2006 19:35:51 -0700 Subject: How to fill a form References: <20060815034051.89ef7e18.sulsa@gazeta.pl> <mailman.9336.1155608567.27775.python-list@python.org> <20060815050733.10e14112.sulsa@gazeta.pl> <12e2gau4jouhmcf@corp.supernews.com> <20060815054343.1c31f3f7.sulsa@gazeta.pl> Message-ID: <1155868551.258324.175340@74g2000cwt.googlegroups.com> Sulsa wrote: > On Tue, 15 Aug 2006 03:37:02 -0000 > Grant Edwards <grante at visi.com> wrote: > > > On 2006-08-15, Sulsa <sulsa at gazeta.pl> wrote: > > > > > I want to fill only one smiple form so i would like not to use > > > any non standard libraries. > > > > Then just send the HTTP "POST" request containing the fields > > and data you want to submit. > > but i don't know how to post these data if i knew there there would > be no topic. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 From lionel.duroyon at gmail.com Thu Aug 3 05:08:39 2006 From: lionel.duroyon at gmail.com (Shalyd) Date: 3 Aug 2006 02:08:39 -0700 Subject: karrigell and multi-threading Message-ID: <1154596119.164830.129970@i3g2000cwc.googlegroups.com> Hello, Here is my problem :-) : i am actually using karrigell, and i use Karrigell.py server, i have a page running a script (which takes around 5 min to execute), when i launch this script (by the page) then, i cant acces to any other page of the site until the script ends. so i tried the karrigell-ThreadingSocketServer.py and i have the same problem, exept that i can access the pages but they are "blank" until the script ends. i just want to allow different users to launch the script even if the script isnt multi-threaded. for example, 1 launch the script, then another launches i,t goes take a cofee and then when the first script ends, the second is proceeded. Any idea to solve that? Thanks by advance :-) . From paul at boddie.org.uk Wed Aug 2 14:08:10 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 2 Aug 2006 11:08:10 -0700 Subject: Using Python for my web site References: <1154361480.915174.262720@b28g2000cwb.googlegroups.com> <44ce3a5c$0$18952$626a54ce@news.free.fr> <pan.2006.08.01.23.30.45.679440@nothanks.org> <44d0e0a3$0$32434$626a54ce@news.free.fr> Message-ID: <1154542090.924003.47670@i3g2000cwc.googlegroups.com> Bruno Desthuilliers wrote: > > To make a long story short, my opinion is that the only sensible thing > to do with Windows is to wipe it out and install an OS instead. If you're convinced you won't be running Windows, why deal with the problem so late in the game? Instead, order a system from a vendor who won't ship an operating system you aren't going to use. Otherwise, we'll just keep hearing from vendors about there being no demand for anything other than Windows, and thus supposedly no reason to offer any real choice of operating systems. Paul P.S. One good reason for using something UNIX-like is the apparently superior availability of Web and database server solutions for such platforms, and Python works rather well with many of them, of course. From rupole at hotmail.com Tue Aug 22 06:47:16 2006 From: rupole at hotmail.com (Roger Upole) Date: Tue, 22 Aug 2006 06:47:16 -0400 Subject: How can I enumerate all windows services and disable some of them? References: <1156232360.032758.176760@m73g2000cwd.googlegroups.com> Message-ID: <1156243111_7181@sp6iad.superfeed.net> <could.net at gmail.com> wrote in message news:1156232360.032758.176760 at m73g2000cwd.googlegroups.com... >I know that Module win32service has some functions on manipulating > win32 services. > But I still have 2 questions: > 1. how to enumerate all services? > 2. how to disable a certain one? > > Thanks in advance! > win32service.EnumServicesStatus lists services, and ChangeServiceConfig lets you change the start type to disabled. import win32service hscm=win32service.OpenSCManager(None,None,win32service.SC_MANAGER_ALL_ACCESS) svcs=win32service.EnumServicesStatus(hscm) for svc in svcs: if svc[0]=='PyPipeTestService': hsvc=win32service.OpenService(hscm, svc[0], win32service.SERVICE_CHANGE_CONFIG) win32service.ChangeServiceConfig(hsvc, win32service.SERVICE_NO_CHANGE, win32service.SERVICE_DISABLED, win32service.SERVICE_NO_CHANGE, None, None,0, None,None,None,None) win32service.CloseServiceHandle(hsvc) win32service.CloseServiceHandle(hscm) Roger From skip at pobox.com Tue Aug 15 16:43:32 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 15 Aug 2006 15:43:32 -0500 Subject: programming with Python 3000 in mind In-Reply-To: <1155672987.522793.47080@74g2000cwt.googlegroups.com> References: <1155672987.522793.47080@74g2000cwt.googlegroups.com> Message-ID: <17634.12788.36736.31241@montanaro.dyndns.org> >> The current beta version of Python is 2.5 . How can a Python >> programmer minimize the number of changes that will be needed to run >> his code in Python 3000? Since we don't know what Python 3000 will look like yet (it's still in very early development), that is a question that can't be answered today. Skip From namam0205 at gmail.com Sun Aug 27 21:12:04 2006 From: namam0205 at gmail.com (namam0205 at gmail.com) Date: Mon, 28 Aug 2006 09:12:04 +0800 Subject: Python-list Digest, Vol 35, Issue 410 In-Reply-To: <mailman.35914.1156547402.27774.python-list@python.org> References: <mailman.35914.1156547402.27774.python-list@python.org> Message-ID: <da8d48fe0608271812q33cd2a31qc502008952d83b13@mail.gmail.com> Thank you Fredrik for answering. Actually the "form.py" was copied from an example inside one of the URL for non-programmer provided by python.org documentation site. I'm not familiar with the method to convert an MD5 token to it original state inside form.py. So, if I try to authenticate using referer, does the referer="/form.html" ? ---------- Forwarded message ---------- From: Fredrik Lundh <fredrik at pythonware.com> To: python-list at python.org Date: Sat, 26 Aug 2006 00:46:16 +0200 Subject: Re: prevent unauthorized call to script kudincendol at gmail.com wrote: > I have copy-paste a script called "form.py" from somewhere else. sounds a bit dangerous. > This script is called from " form.html". Both are running in my Apache > server. How do I prevent other html files from other server to call my > "form.py" script ? usual approaches include checking the referrer field, using server- generated tokens in hidden fields, etc. this won't keep the determined hacker to issue requests to your server, but at least it makes it a bit harder to just post a HTML form somewhere else and point that to your server. it's probably best if you look for a form script that already supports things like this. </F> -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060828/516170f3/attachment.html> From bearophileHUGS at lycos.com Mon Aug 7 20:00:16 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 7 Aug 2006 17:00:16 -0700 Subject: do people really complain about significant whitespace? In-Reply-To: <1154994477.450666.226550@b28g2000cwb.googlegroups.com> References: <1154986984.740638.241130@m79g2000cwm.googlegroups.com> <1154989015.347690.109930@b28g2000cwb.googlegroups.com> <1154991523.887791.9640@i42g2000cwa.googlegroups.com> <1154994477.450666.226550@b28g2000cwb.googlegroups.com> Message-ID: <1154995216.341980.4730@75g2000cwc.googlegroups.com> Jason wrote: > But newsgroup managers are certainly an issue. > For comment thingies online, the preformat tag is your friend, too. Time ago I used to add a | or something similar at the beginning of lines, to avoid the leading whitespace stripping done by Google Groups. Other (silly) solutions are to add explicitely the number of indents at the beginning of a line (2 digits suffice), or to even add explicit #end comments just under the dedents, so a script can read such ending comments and reconstruct the original Python indentations... (lines splitted with \ and similar require some extra care). Bye, bearophile From onurb at xiludom.gro Tue Aug 29 11:10:32 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 29 Aug 2006 17:10:32 +0200 Subject: Extending the dict class In-Reply-To: <1156858083.338457.66590@b28g2000cwb.googlegroups.com> References: <1156852916.254032.172390@b28g2000cwb.googlegroups.com> <44f4313e$0$26985$626a54ce@news.free.fr> <1156854958.228815.107090@m73g2000cwd.googlegroups.com> <Xns982E8CDD96042duncanbooth@127.0.0.1> <1156856325.095181.303140@p79g2000cwp.googlegroups.com> <Xns982E918CA9DC2duncanbooth@127.0.0.1> <1156858083.338457.66590@b28g2000cwb.googlegroups.com> Message-ID: <44f458e9$0$12791$626a54ce@news.free.fr> chosechu wrote: > Duncan Booth wrote: >> No, you weren't able to extend the builtin dict class nor touch any its >> constructor. > > Yes, sorry. Forgot the negation. > >> All you did was to create a subclass with its own constructor and hide the >> name for the builtin dictionary type. The original type was still unchanged >> as you can see since anything which constructed a dictionary without using >> the name you had overwritten still got the original type. >> >> If you had looked at type(dict()) and type({}) after your subclassing, you >> would see that they are different types. > > ... which prompted my question. > > And prompts yet another one: seems like it > is not possible with Python to modify behaviour > for base classes without recompiling the > interpreter. Forgive me for asking what must > surely have been asked already, but are there > plans to implement something like that, > <teasing>like Ruby</teasing>? > > I would not feel too safe navigating in a source > where base object behaviour might have been > re-defined, but it sure is a powerful way of > adding behaviour to third-party code which you > may not have possibility to modify. It's usually possible to modify third-parts classes behaviour on the fly (googling for 'monkey-patching' should get you started). But true, this doesn't work with builtins. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From david_wahler at bic.ky Wed Aug 9 01:49:19 2006 From: david_wahler at bic.ky (david_wahler at bic.ky) Date: 9 Aug 2006 00:49:19 -0500 Subject: =?utf-8?Q?Re:_ANN:_xtopdf:_PDF_creation_=2F_conversion_toolkit:_alpha_release_of_v1.3?= Message-ID: <20060809054919.5441.qmail@BICSRV1011.bic.ky> I'll be out of the office until approximately August 20th. If you have any questions, please email support at bic.ky. -- David Wahler From jcmendez at gmail.com Mon Aug 7 14:50:47 2006 From: jcmendez at gmail.com (jcmendez) Date: 7 Aug 2006 11:50:47 -0700 Subject: Resource temporarily unavailable launching idle under cygwin In-Reply-To: <1154976453.055076.186560@p79g2000cwp.googlegroups.com> References: <1154976453.055076.186560@p79g2000cwp.googlegroups.com> Message-ID: <1154976647.223442.193530@n13g2000cwa.googlegroups.com> PS: I already tried what suggested in a previous message on the groups "Python 2.3.2 spawn problem" - Uninstalling and reinstalling python without luck. Python 2.4.3 (#1, May 18 2006, 07:40:45) [GCC 3.3.3 (cygwin special)] on cygwin Thanks! jcmendez wrote: > Hello everyone. Trying to run idle from a cygwin session on Win2k > (yuk, but I must) I'm getting the following error message. It seems > something more Windoze-driven that Python driven, and I'm not and don't > wanna be an expert on that OS. Since the group has a good mix of users > in different platforms, perhaps someone can help. > > Python runs fine, my programs run fine, and I can edit in vim and run > my code. However, would be nice to have idle available from time to > time > > Thanks in advance!! > > $ idle > 23367 [main] python2.4 1668 C:\cygwin\bin\python2.4.exe: *** fatal > error - C:\ > cygwin\bin\python2.4.exe: *** unable to remap C:\cygwin\bin\tk84.dll to > same add > ress as parent(0x18890000) != 0x18D20000 > 18 [main] python2.4 2236 fork: child 1668 - died waiting for dll > loading, e > rrno 11 > Traceback (most recent call last): > File "/usr/bin/idle", line 5, in ? > main() > File "/tmp/python.340/usr/lib/python2.4/idlelib/PyShell.py", line > 1361, in mai > n > File "/tmp/python.340/usr/lib/python2.4/idlelib/PyShell.py", line > 277, in open > _shell > File "/tmp/python.340/usr/lib/python2.4/idlelib/PyShell.py", line > 962, in begi > n > File "/tmp/python.340/usr/lib/python2.4/idlelib/PyShell.py", line > 372, in star > t_subprocess > File "/tmp/python.340/usr/lib/python2.4/idlelib/PyShell.py", line > 350, in spaw > n_subprocess > File "/usr/lib/python2.4/os.py", line 552, in spawnv > return _spawnvef(mode, file, args, None, execv) > File "/usr/lib/python2.4/os.py", line 520, in _spawnvef > pid = fork() > OSError: [Errno 11] Resource temporarily unavailable > > As a sidenote, I sent twice this message as an email to > comp.lang.python at googlegroups.com as instructed on the group digests, > and it bounced immediately. Did this method of posting change? > > Thanks! > > Juan C. From deets at nospam.web.de Fri Aug 25 04:59:05 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 25 Aug 2006 10:59:05 +0200 Subject: OS X and Python - what is your install strategy? In-Reply-To: <1156469382.356341.281450@i3g2000cwc.googlegroups.com> References: <1156460483.616400.120160@i3g2000cwc.googlegroups.com> <1156469382.356341.281450@i3g2000cwc.googlegroups.com> Message-ID: <4l7sepFm908U1@uni-berlin.de> > These days, I install the OS X universal binary provided on the Python > language web site. You can find it at > http://www.python.org/download/releases/2.4.3. It's more comprehensive > and much more up-to-date than the version included in OS X. It is. But don't fall for the temptation to remove or even only re-link the installed version with the new one, OSX needs it's own build for some things. Diez From duncan.booth at invalid.invalid Tue Aug 29 08:05:27 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 29 Aug 2006 12:05:27 GMT Subject: Extending the dict class References: <1156852916.254032.172390@b28g2000cwb.googlegroups.com> Message-ID: <Xns982E85271E108duncanbooth@127.0.0.1> chosechu wrote: > Is it possible to force dictionary creation in these case to use > my own dict class instead of the default one? No > I guess we can formulate this as a more generic question: if I > want to modify the behaviour of the dictionary class, is there > any way to do it interpreter-wide so that special dict constructors > like those mentioned above use the modified version? Not without modifying and recompiling the interpreter. From support at mathworks.co.uk Tue Aug 1 06:06:00 2006 From: support at mathworks.co.uk (support at mathworks.co.uk) Date: 1 Aug 2006 06:06:00 -0400 Subject: Python-list Digest, Vol 35, Issue 10 Message-ID: <200608011006.k71A60C02110@mail-vif.mathworks.com> This is an automated response. Thank you for contacting the Technical Support team at The MathWorks Ltd. A technical support representative will be contacting you within 1 business day. The following information will help us in responding to your request. If you have already provided the information requested below, no further action is required. 1) License number, release number, and operating system. Typing ?ver? at the MATLAB command prompt will list this information. 2) Exact text of any error message(s) received 3) All files (M-files, Simulink models, data files) and steps to reproduce the issue. If you need to send in an executable or a zip file, please wait until a support engineer contacts you. To provide this information, reply to this message keeping the Thread Id listed at the bottom of this message intact. STUDENT VERSION USERS: If you are a student using the Student Version, please note that email and phone support is available for product installation, software crashes, or bug reporting. For all other enquiries, contact your lecturer or visit the support web site at http://www.mathworks.co.uk/support/. If you have any concerns about our technical support services, write to tsmanagers at mathworks.com. Technical Support Team The MathWorks Ltd Email: support at mathworks.co.uk Tel: 01223 423200 Fax: 01223 423250 http://www.mathworks.co.uk/support [THREAD ID: 1-2ZJL6R] -----Original Message----- From: python-list-request at python.org Sent: 8/1/2006 6:00:26 AM To: support at mathworks.co.uk Subject: Python-list Digest, Vol 35, Issue 10 Send Python-list mailing list submissions to python-list at python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/python-list or, via email, send a message with subject or body 'help' to python-list-request at python.org You can reach the person managing the list at python-list-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Python-list digest..." From http Wed Aug 30 22:57:41 2006 From: http (Paul Rubin) Date: 30 Aug 2006 19:57:41 -0700 Subject: Allowing ref counting to close file items bad style? References: <9U6Jg.951$Xw6.283@trndny02> <7x4pvvylrh.fsf@ruckus.brouhaha.com> <1156910432.917443.259720@p79g2000cwp.googlegroups.com> <7xmz9mkgnv.fsf@ruckus.brouhaha.com> <1156921226.069647.233550@p79g2000cwp.googlegroups.com> <7xodu2ekb6.fsf@ruckus.brouhaha.com> <1156957638.345092.169460@m73g2000cwd.googlegroups.com> Message-ID: <7xlkp5mx22.fsf@ruckus.brouhaha.com> "sjdevnull at yahoo.com" <sjdevnull at yahoo.com> writes: > I disagree strongly with this assertion. It's not as efficient overall > as other GC implementations, but it's not a case of "less efficient to > do the same task". Reference counting buys you deterministic GC in the > pretty common case where you do not have circular references--and > determinism is very valuable to programmers. Other GCs be faster, but > they don't actually accomplish the same task. GC is supposed to create the illusion that all objects stay around forever. It releases unreachable objects since the application can't tell whether those objects are gone or not. Closing a file is a state change in which stuff is supposed to actually happen (buffers flushed, CLOSE message sent over socket, etc.) That's independent of releasing it. In your example (simplified): def func(x): f = open_some_file(x) # do stuff with f it might even be that the open call saves the file handle somewhere, maybe for logging purposes. You presumably still want it closed at function exit. The GC can't possibly do that for you. Relying on GC to close files is simply a kludge that Python users have been relying on, because doing it "manually" has been messy prior to 2.5. > I can come up with plenty of "superior" algorithms for all kinds of > tasks if I'm not bound to any particular semantics, but losing > correctness for speed is rarely a good idea. Then don't write incorrect code that relies on the GC's implementation accidents to make it work ;-). PEP 343 really is the right way to handle this. From s.lipnevich at gmail.com Tue Aug 1 07:23:23 2006 From: s.lipnevich at gmail.com (s.lipnevich at gmail.com) Date: 1 Aug 2006 04:23:23 -0700 Subject: Any gotchas in returning a subclass instance from __new__? Message-ID: <1154431403.035779.176330@h48g2000cwc.googlegroups.com> Hi All, Is anything wrong with the following code? class Superclass(object): def __new__(cls): # Questioning the statement below return super(Superclass, cls).__new__(Subclass) class Subclass(Superclass): pass if __name__ == '__main__': instance = Superclass() print instance It works here, and even constructors for Subclass and Superclass are invoked (in correct order), even though such behavior is not explicitly stated here http://docs.python.org/ref/customization.html. So, am I asking for trouble or is it /the/ way to go about transforming base class into a factory? Thank you, Sergey. From chosechu at gmail.com Tue Aug 29 09:03:34 2006 From: chosechu at gmail.com (chosechu) Date: 29 Aug 2006 06:03:34 -0700 Subject: Extending the dict class In-Reply-To: <mailman.10050.1156856005.27775.python-list@python.org> References: <1156852916.254032.172390@b28g2000cwb.googlegroups.com> <1156854958.228815.107090@m73g2000cwd.googlegroups.com> <mailman.10050.1156856005.27775.python-list@python.org> Message-ID: <1156856614.655469.13380@p79g2000cwp.googlegroups.com> > (the exact set of methods you need to override depends on how SOAPpy > fetches the members). [fakedict class] This I did. And checking out the source it seems SOAPpy retrieves named parameters through keys(), which is the method I tried to overload. Trouble is: something happens to my fakedict object when getting through this: d = fakedict(...) SOAPmethod(**d) I have the impression **d acts like a dict constructor, taking over my fakedict class. I know I could find the answer by scrutinizing the source, call me lazy. From cowie.rob at gmail.com Sat Aug 19 06:27:52 2006 From: cowie.rob at gmail.com (Rob Cowie) Date: 19 Aug 2006 03:27:52 -0700 Subject: Documenting a package with Pydoc In-Reply-To: <1155912351.433504.265020@h48g2000cwc.googlegroups.com> References: <1155912351.433504.265020@h48g2000cwc.googlegroups.com> Message-ID: <1155983272.664424.237560@m79g2000cwm.googlegroups.com> Anyone? From sjmachin at lexicon.net Wed Aug 9 18:54:30 2006 From: sjmachin at lexicon.net (John Machin) Date: 9 Aug 2006 15:54:30 -0700 Subject: technique to enter text using a mobile phone keypad (T9 dictionary-based disambiguation) References: <mailman.9116.1155077147.27775.python-list@python.org> <1155095477.440347.149350@m79g2000cwm.googlegroups.com> <1155154447.409931.55750@p79g2000cwp.googlegroups.com> <1155156341.298792.188280@75g2000cwc.googlegroups.com> Message-ID: <1155164070.665244.193080@b28g2000cwb.googlegroups.com> bearophileHUGS at lycos.com wrote: > I've tested that sorting just the strings instead of the tuples (and > removing the stripping) reduces the running time enough: > > def __init__(self): > numbers = '22233344455566677778889999' > conv = string.maketrans(string.lowercase, numbers) > lines = > file("/usr/share/dict/words").read().lower().splitlines() > # lines = map(str.strip, lines) > lines.sort() > self.dict = [(word.translate(conv), word) for word in lines] > > If the words file is already sorted you can skip the sorting line. > If the file contains extraneous spaces, you can strip them uncommenting > that line. > 1. Wouldn't it be a good idea to process the raw dictionary *once* and cPickle the result? 2. All responses so far seem to have missed a major point in the research paper quoted by the OP: each word has a *frequency* associated with it. When there are multiple choices (e.g. "43" -> ["he", "if", "id", ...]), the user is presented with the choices in descending frequency order. Note that if one of the sort keys is (-frequency), the actual frequency doesn't need to be retained in the prepared dictionary. 3. Anyone interested in the techniques & heuristics involved in this type of exercise might like to look at input methods for languages like Chinese -- instead of 26 letters mapped to 8 digits, you have tens of thousands of characters of wildly varying frequency mapped to e.g. 400+ Pinyin "words" entered on a "standard" keyboard. Cheers, John From sjmachin at lexicon.net Thu Aug 31 17:07:34 2006 From: sjmachin at lexicon.net (John Machin) Date: 31 Aug 2006 14:07:34 -0700 Subject: re.compile() doesn't work under Windows? References: <h3lef25kbmd0ehobognupq0rg2f9fvpoch@4ax.com> Message-ID: <1157058453.919399.27480@m79g2000cwm.googlegroups.com> ddtl wrote: > Hello everybody. > > My script uses re.compile() function, and while it rans without errors > under Linux, when I ran that script under Windows I get the following > error: > > Traceback (most recent call last): > File "C:\a\projects\re.py", line 4, in ? > import re > File "C:\a\projects\re.py", line 95, in ? > main() > File "C:\a\projects\re.py", line 37, in main > s_exp = re.compile(op['-s']) > AttributeError: 'module' object has no attribute 'compile' > > What is the problem here? re module is installed and is on the path - > for example, the following code works and doesn't cause any errors: > > import re > re.compile('a') > > What else could cause such an error? Change the name of your script file from re.py to not_the_name_of_a_module.py -- you are importing your script, not the re module. This is shown in the traceback: import re executes the main() function in your script. Worked on Linux? Maybe the script wasn't called re.py on Linux. Alternatively: (1) In Windows at least, the current directory is placed first on the Python module search path. I would have expected the same to happen on *x. (2) Did you run it using an IDE on Linux? An IDE may fiddle with sys.path. Bottom line: however you ran it on Linux: insert import sys print "sys.path is", sys.path at the top of your script and see what it produces. Note: '' (empty string) means current directory. Also it's a good idea to make scripts guard against inappropriate code being executed when the script is imported (whether deliberately or accidentally). The standard idiom is something like this: if __name__ == "__main__": # being run as script, not imported def main(): do_something() HTH, John From rogue_pedro at yahoo.com Sat Aug 26 12:51:05 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 26 Aug 2006 09:51:05 -0700 Subject: rollover effect In-Reply-To: <1156609368.745082.324510@h48g2000cwc.googlegroups.com> References: <1156607403.741240.25000@74g2000cwt.googlegroups.com> <1156608042.466471.210270@m73g2000cwd.googlegroups.com> <1156608554.489516.243640@h48g2000cwc.googlegroups.com> <1156609000.477885.289150@h48g2000cwc.googlegroups.com> <1156609368.745082.324510@h48g2000cwc.googlegroups.com> Message-ID: <1156611065.857764.129500@b28g2000cwb.googlegroups.com> groves wrote: > Sorry, as I am new to python so couldn't understand what yu were > asking. > Now the problem is that i annot use pmw in my project..is thre anyother > alternative by which I can have a rollover mouse effect on the canvas. > thanks Not a problem. Although "IDE" and "GUI" are terms that are not specific to python. But you still haven't answered my question? Are you using Tkinter? wxWidgets? Gtk bindings? Assuming that you're using Tkinter, what prevents you from using Pmw? Peace, ~Simon From johannes.wollard at gmail.com Mon Aug 14 21:03:24 2006 From: johannes.wollard at gmail.com (jwoolard) Date: 14 Aug 2006 18:03:24 -0700 Subject: Crunchy version 0.7 is here! Message-ID: <1155603804.452122.166700@i42g2000cwa.googlegroups.com> Version 0.7 of Crunchy has been released. It is available on Sourceforge (http://sourceforge.net/project/showfiles.php?group_id=169458) Crunchy, the Interactive Python Tutorial Maker, is an application that transforms an ordinary html-based Python tutorial into an interactive session within a web browser. Currently, only Firefox is supported. Crunchy is developed and tested on Windows XP and Ubuntu Dapper Drake, but should work on any suitable windows or UNIX system. Apart from Firefox and Python, Crunchy's only dependency is Elementtree, available from http://effbot.org/zone/element-index.htm. This still applies if you are using Python 2.5 because we use parts of Elementtree that are not included in the Python 2.5 standard library. 0. Name change To prevent confusion with an existing program named CrunchyFrog, "Crunchy Frog" has been renamed as "Crunchy", short for "Crunchy, the Interactive Python Tutorial Maker". 1. *Security fix* The previous versions of Crunchy allowed tutorials containing arbitrary (and hidden) javascript code to be loaded within a browser window. The new version removes any existing javascript code prior to processing for display within a browser. Feel free to try and break this - and please report any findings back to us. 2. New functionality. * It is possible to run external programs from within the browser; sample demos include GUI programs with 1. Tkinter, 2. pyGtk, 3. wxPython, 4. Pygame * Automatic syntax colouring of (static) Python code, including (as an option) line numbering. * New plotting canvas with simple to use api to draw mathematical functions * Drawing & plotting canvas can be set to arbitrary size. * Multiple canvas can now appear on same page. * New addition and simplification to the sound api. * Simplification of error message (tracebacks) more suitable for beginners. 3. New visual design: * Integrated menu which can be styled through custom css * Three sample css styles now included (selectable via the browser menu) 4. New content: * First draft sound tutorial exploring concepts of frequency, beats, harmonics (Fourier series), etc. * New addition to the basic "Crunchy user" tutorial * Additions to all reference documentation (sound & graphics api, vlam options, etc.) Please send bug reports and feedback to Andr? Roberge (andre.roberge at gmail.com) and/or Johannes Woolard (johannes.wollard at gmail.com). From miki.tebeka at gmail.com Tue Aug 8 15:23:26 2006 From: miki.tebeka at gmail.com (Miki) Date: 8 Aug 2006 12:23:26 -0700 Subject: Import module with non-standard file name In-Reply-To: <mailman.9069.1154999229.27775.python-list@python.org> References: <mailman.9069.1154999229.27775.python-list@python.org> Message-ID: <1155065005.986204.201470@m73g2000cwd.googlegroups.com> Hello Ben, > Question: I have Python modules named without '.py' as the extension, > and I'd like to be able to import them. How can I do that? http://docs.python.org/lib/module-imp.html (hint: load_source :) HTH, Miki http://pythonwise.blogspot.com/ From sumesh.chopra at gmail.com Tue Aug 15 19:51:29 2006 From: sumesh.chopra at gmail.com (unexpected) Date: 15 Aug 2006 16:51:29 -0700 Subject: Printing n elements per line in a list Message-ID: <1155685889.626881.37040@m73g2000cwd.googlegroups.com> If have a list from 1 to 100, what's the easiest, most elegant way to print them out, so that there are only n elements per line. So if n=5, the printed list would look like: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 etc. My search through the previous posts yields methods to print all the values of the list on a single line, but that's not what I want. I feel like there is an easy, pretty way to do this. I think it's possible to hack it up using while loops and some ugly slicing, but hopefully I'm missing something From tim.golden at viacom-outdoor.co.uk Thu Aug 10 07:00:50 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: 10 Aug 2006 04:00:50 -0700 Subject: sys.platform documentation? In-Reply-To: <mailman.9183.1155198457.27775.python-list@python.org> References: <mailman.9183.1155198457.27775.python-list@python.org> Message-ID: <1155207649.983067.55840@h48g2000cwc.googlegroups.com> Michiel Sikma wrote: > Hello everybody, > > I was thinking about making a really insignificant addition to an > online system that I'm making using Python: namely, I would like it > to print the platform that it is running on in a human-readable > manner. I was thinking of doing it like this: [... snip ...] > However, in order to populate the list of platforms, I need to know > which strings sys.platform can return. I haven't found any > documentation on this Not that this answers your question directly, but is the platform module of any more use to you? http://docs.python.org/lib/module-platform.html TJG From skip at pobox.com Wed Aug 23 12:20:40 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 23 Aug 2006 11:20:40 -0500 Subject: Python and STL efficiency In-Reply-To: <1156300663.405909.39350@74g2000cwt.googlegroups.com> References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <eccb9u$kjs$1@gemini.csx.cam.ac.uk> <1hkh28d.xscw4v1y4v9a6N%riko@despammed.com> <mailman.9640.1156247569.27775.python-list@python.org> <1hkh6lb.6dsnh51lj8z96N%riko@despammed.com> <1156252193.524186.107520@b28g2000cwb.googlegroups.com> <1156299389.336939.211670@i42g2000cwa.googlegroups.com> <1156300663.405909.39350@74g2000cwt.googlegroups.com> Message-ID: <17644.32856.379041.664125@montanaro.dyndns.org> Ray> Same here, although that said Python's implementation of those data Ray> structure must already be as optimal as mortals can do it. Perhaps more optimal. We've had (tim)bots working on the problem for years. Skip From sinor1 at REMOVElycos.com Sun Aug 13 10:44:35 2006 From: sinor1 at REMOVElycos.com (Rich) Date: Sun, 13 Aug 2006 16:44:35 +0200 Subject: Installed correctly References: <i87ud25fkbif2rk2daul8t1rc5nmv7msj1@4ax.com> <1155476706.812107.276950@b28g2000cwb.googlegroups.com> Message-ID: <53eud29hhhqqv7vi99dl9nhjjkl1of49ik@4ax.com> Well thanks for all your replies. I've now uninstalled Python, and reinstalled it using the default path (C:\pythoh24). But command line still says "unrecognized command", when typng "pythoin". so maybe you have to From yxing at stanford.edu Mon Aug 14 15:49:55 2006 From: yxing at stanford.edu (Yi Xing) Date: Mon, 14 Aug 2006 12:49:55 -0700 Subject: Memory problem Message-ID: <1155584995.44e0d3e3e88a1@webmail.stanford.edu> I tried the following code: >>> i=0 >>> n=2600*2600*30 >>> a=array.array("f") >>> while (i<=n): .. i=i+1 .. a.append(float(i)) .. Traceback (most recent call last): File "<stdin>", line 3, in ? MemoryError to see the size of the array at the time of memory error: >>>len(a) 8539248. I use Windows XP x64 with 4GB RAM. From mrmakent at cox.net Tue Aug 8 16:21:45 2006 From: mrmakent at cox.net (Mike Kent) Date: 8 Aug 2006 13:21:45 -0700 Subject: newb question: file searching In-Reply-To: <1155067111.892386.130610@n13g2000cwa.googlegroups.com> References: <1155067111.892386.130610@n13g2000cwa.googlegroups.com> Message-ID: <1155068505.141479.5210@m79g2000cwm.googlegroups.com> jaysherby at gmail.com wrote: > I'm new at Python and I need a little advice. Part of the script I'm > trying to write needs to be aware of all the files of a certain > extension in the script's path and all sub-directories. What you want is os.walk(). http://www.python.org/doc/current/lib/os-file-dir.html From claird at lairds.us Thu Aug 17 13:16:25 2006 From: claird at lairds.us (Cameron Laird) Date: Thu, 17 Aug 2006 17:16:25 +0000 Subject: Subprocess confusion: how file-like must stdin be? Message-ID: <9sker3-7g8.ln1@lairds.us> Question: import subprocess, StringIO input = StringIO.StringIO("abcdefgh\nabc\n") # I don't know of a compact, evocative, and # cross-platform way to exhibit this behavior. # For now, depend on cat(1). p = subprocess.Popen(["cat"], stdout = subprocess.PIPE, stdin = response) Why this is a question: A. it tosses an AttributeError. B. I *expected* it to do the equivalent of cat << HERE abcdefgh abc HERE In <URL: http://docs.python.org/dev/lib/node530.html >, I read "Valid values are ... an existing file object ..." Even though StringIO is a "file-like object", it lacks a fileno. Is there a way to get what I'm after? From deets at nospam.web.de Wed Aug 2 08:11:32 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 02 Aug 2006 14:11:32 +0200 Subject: Class definition within function References: <Su0Ag.121$fe3.114@read3.inet.fi> Message-ID: <4jbitvF73bhvU1@uni-berlin.de> Tomi Lindberg wrote: > Hi, > > With the following function definition, is it possible to > create an instance of class C outside the function f (and if > it is, how)? And yes, I think this is one of those times > when the real question is why :) > > >>> def f(): > class C(object): > def __init__(self): > self.a = 'a' > return C() > > >>> x = f() > >>> x.a > 'a' > >>> y=f.C() > > Traceback (most recent call last): > File "<pyshell#22>", line 1, in -toplevel- > y=f.C() > AttributeError: 'function' object has no attribute 'C' No, its not. Only inside of it. And the question really is: why? If you need a class that can be instantiated regardless of the execution of f, make it a globally visible class. If it depends on something f computes, make it a function-local one (if you like) Diez From ask at me Tue Aug 8 22:03:58 2006 From: ask at me (alf) Date: Tue, 08 Aug 2006 22:03:58 -0400 Subject: SocketServer and timers In-Reply-To: <1154063826.816047.254210@p79g2000cwp.googlegroups.com> References: <lMCdnSBQ7NhY4lTZnZ2dnUVZ_sCdnZ2d@comcast.com> <1154063826.816047.254210@p79g2000cwp.googlegroups.com> Message-ID: <0ZqdnSJw5PVE00TZnZ2dnUVZ_qWdnZ2d@comcast.com> bryanjugglercryptographer at yahoo.com wrote: > alf wrote: > >>I have one thread app using SocketServer and use server_forever() as a >>main loop. All works fine, but now I need certain timer checking let's >>say every 1 second something and stopping the main loop. So questions are: >> -how to stop serve_forever > > > Override serve_forever() and replace "while 1:" with something like > "while self.continue_flag:". > > >> -how to implement timers > > > You could override get_request(), and use select.select() to wait for > either the socket to become readable (so the accept() won't block), or > a timeout to expire. If you are not already, use the threading or > forking > mixin so that the request handler won't stop everthing if it blocks. > > thx for a suggestion, will try it out ... From michiel at thingmajig.org Tue Aug 8 09:44:17 2006 From: michiel at thingmajig.org (Michiel Sikma) Date: Tue, 8 Aug 2006 15:44:17 +0200 Subject: Looking for an intellisense with good help IDE for Python In-Reply-To: <cfb578b20608080636m3d6088a6qcdbdabf5396ebd0d@mail.gmail.com> References: <1155022590.845074.256900@i42g2000cwa.googlegroups.com> <cfb578b20608080636m3d6088a6qcdbdabf5396ebd0d@mail.gmail.com> Message-ID: <8BE9936D-7110-46A5-BB4D-89AE17C548C3@thingmajig.org> I can attest to PyDev being an excellent extension to Eclipse. But Eclipse kind of requires a heavy machine to run, being a gigantic Java program. Michiel Op 8-aug-2006, om 15:36 heeft Fabio Zadrozny het volgende geschreven: > Have you checked pydev: http://pydev.sf.net > > Cheers, > > Fabio From ajaksu at gmail.com Sat Aug 12 14:07:14 2006 From: ajaksu at gmail.com (ajaksu) Date: 12 Aug 2006 11:07:14 -0700 Subject: matplotlib, wxPanel inside a wxPanel References: <1155391052.938133.284080@b28g2000cwb.googlegroups.com> <1155399727.044367.99770@m79g2000cwm.googlegroups.com> Message-ID: <1155406034.212466.274560@m73g2000cwd.googlegroups.com> It seems to work (only tested with embedding_in_wx4.py). I guess it's something related to things nesting in a slightly wrong way, right enough to show up but wrong enough to only show up :) I hope this helps. Daniel Substitute embedding_in_wx4.py's CanvasFrame with: class CanvasFrame(wxFrame): def __init__(self): # Begin just like embedding_in_wx4.py wxFrame.__init__(self,None,-1, 'CanvasFrame',size=(550,350)) self.figure = Figure(figsize=(5,4), dpi=100) self.axes = self.figure.add_subplot(111) t = range(0,30) s = [randint(1, 30)* random() * x for x in t] self.axes.plot(t,s) # Add panels from deepest level self.main_panel = wxPanel(self, -1) # Parent is main_panel: self.graph_panel = wxPanel(self.main_panel, -1) # self.canvas is child of graph_panel... self.canvas = FigureCanvas(self.graph_panel, -1, self.figure) # ... as is textgraph self.text_graph = wxTextCtrl(self.graph_panel, -1, "Hello!\n" + "I'm in graph_panel", style=wxTE_MULTILINE) self.toolbar = MyNavigationToolbar(self.canvas, True) self.toolbar.Realize() self.graph_panel_sizer = wxBoxSizer(wxVERTICAL) tw, th = self.toolbar.GetSizeTuple() fw, fh = self.canvas.GetSizeTuple() self.toolbar.SetSize(wxSize(fw, th)) self.graph_panel_sizer.Add(self.toolbar, 0, wxEXPAND) # After the toolbar, add its siblings to graph_panel_sizer self.graph_panel_sizer.Add(self.canvas, 1, wxEXPAND) self.graph_panel_sizer.Add(self.text_graph) self.graph_panel.SetSizer(self.graph_panel_sizer) self.graph_panel.Fit() # graph_panel is done, just add it to main_panel's sizer. self.main_panel_sizer = wxBoxSizer(wxVERTICAL) self.text_in = wxTextCtrl(self.main_panel, -1, "Inside main_panel", style=wxTE_MULTILINE) # Here: self.main_panel_sizer.Add(self.graph_panel,1, wxEXPAND) self.main_panel_sizer.Add(self.text_in,0, wxEXPAND) self.main_panel.SetSizer(self.main_panel_sizer) self.main_panel.Fit() self.sizer = wxBoxSizer(wxVERTICAL) self.sizer.Add(self.main_panel, 1, wxEXPAND) self.sizer_text = wxBoxSizer(wxHORIZONTAL) self.text_hi = wxTextCtrl(self, -1, "Hello :)", style=wxTE_MULTILINE) self.text_out = wxTextCtrl(self, -1,"Outside main_panel", style=wxTE_MULTILINE|wxEXPAND) self.sizer_text.Add(self.text_hi, 0, wxEXPAND) self.sizer_text.Add(self.text_out, 0, wxEXPAND) self.sizer.Add(self.sizer_text, 0, wxEXPAND) EVT_PAINT(self, self.OnPaint) self.toolbar.update() self.SetSizer(self.sizer) self.Fit() def OnPaint(self, event): self.canvas.draw() event.Skip() From fivenastydisco at hotmail.com Tue Aug 15 03:13:15 2006 From: fivenastydisco at hotmail.com (donkeyboy) Date: 15 Aug 2006 00:13:15 -0700 Subject: Newbie: calling the originating class ... Message-ID: <1155625995.101230.256210@74g2000cwt.googlegroups.com> This is probably very straightforwards to someone with experience, but I will try to explain my predicament: I'm trying to code a simulation, where you have a Simulation class that knows everything about the simulation, and in turn classes that the Simulation calls when it wants to make new instances -- for the time being, let's call the called classes Agents (sorry, saw the Matrix again last night!). In the Simulation class, there's information about the simulation that each Agent wants to know. As such, I wrote a method in the Simulation class for the Agents to call, to get the said required information. However, I can't figure out a way for the Agents to call the Simulations methods -- is this even possible? The pseudo-code I'm using is as follows: s = Simulation() class Simulation: # create a number of agents ... # Simulation information important_stuff = 10 def showImportant(self): return important_stuff class Agents: my_stuff = s.showImportant ... which fails: I get errors saying the global name 's' is not defined. Any thoughts? Is what I'm trying to do even possible, or should I be doing something else? Thanks in advance!! DB From paul at boddie.org.uk Wed Aug 2 10:25:32 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 2 Aug 2006 07:25:32 -0700 Subject: upgrading python... References: <mailman.8843.1154526612.27775.python-list@python.org> Message-ID: <1154528732.828607.163700@s13g2000cwa.googlegroups.com> bruce wrote: > > i'min a situation where i might need to upgrade python. i have the current > version of python for FC3. i might need to have the version for FC4. i built > the version that's on FC4 from the python source RPM. In principle this is a good idea, since you're aiming to manage your installed software correctly, allowing the package management system to permit uninstalls and the dependency management system to control dependencies. (In fact, I go as far as to make Debian/Ubuntu packages for virtually all Python packages I obtain independently of the system's package management utilities, just so that I can then use such utilities to install the software "properly".) > however, when i simply try to install the resulting RPM, the app gives me > dependency issues from apps that are dependent on the previous/current > version of python. This is one of the main issues with upgrading things upon which large numbers of other components or applications are dependent. Really, in order to preserve those applications, there would need to be an upgrade path for them (and their libraries) based on the newer version of Python, and I imagine that a lot of dependency management systems might refuse to offer a bulk upgrade, especially if some of the applications or libraries weren't available in an updated form. > i'm trying to figure out if there's a 'best' way to proceed. > > do i simply do the install, and force it to overwrite the current version of > python? No: you'll probably break various important applications. As you've seen, you'd need to offer yum all the potentially upgradable packages, and although various "distribution upgrade" operations are often possible, it's a major step just to try something out. > is there a way to point 'yum' at my new python RPM, and let yum take care of > dealing with any dependcy issues? and how would yum handle weird dependency > issues with RPMs that don't exist.. does yum have the ability to actually > build required apps from source? I don't really recall many details about yum, since its introduction came at the end of my Red Hat user experience, but yum is surely a dependency manager that itself doesn't build packages, although I can imagine it having features that could ask rpm (the package manager) to do so. As I note above, to get yum to understand the missing packages, you'd need to tell it about the Fedora Core 4 repository, but this is probably only done safely via a "distribution upgrade" that would be quite drastic. > comments/thoughts/etc... [...] > ps. the reason for this is that i'm looking at some of the newer > functionality in the 2.4 version of python over the 2.3 If I were in your position, I'd either do a "make altinstall" of Python 2.4 which should put Python 2.4 (as python2.4) alongside Python 2.3 (as python, python2.3) in /usr/bin (where you would give /usr as the installation prefix when configuring Python). Otherwise, I'd choose a different installation prefix (by default, Python installs into /usr/local) and then change your environment variables for affected users or programs to use Python from this new location in preference to the system installation of Python. In other words, you probably want to install an isolated version of Python for the special purpose of using newer functionality in your own applications. Anything else may be a lot of work, disruption and a lot more besides. Paul From python at hope.cz Thu Aug 3 08:26:31 2006 From: python at hope.cz (Lad) Date: 3 Aug 2006 05:26:31 -0700 Subject: Datetime question Message-ID: <1154607991.404201.23400@p79g2000cwp.googlegroups.com> In a datetime object I would like to change days and hours. Or in other words, I would like to copy this datetime object but increase days and hours. Is it possible? For example:If I have a datetime object like this datetime.datetime(2006, 8, 3, 14, 13, 56, 609000) I would like to make a new ,for example like this datetime.datetime(2006, 8, 12, 10, 13, 56, 609000) is it possible to do so? Thank you L From boris.dusek at gmail.com Mon Aug 28 11:41:06 2006 From: boris.dusek at gmail.com (=?iso-8859-1?B?Qm9yaXMgRHWaZWs=?=) Date: 28 Aug 2006 08:41:06 -0700 Subject: Truly platform-independent DB access in Python? References: <1156748466.739709.117850@h48g2000cwc.googlegroups.com> <mailman.9974.1156775518.27775.python-list@python.org> Message-ID: <1156779665.977489.300090@74g2000cwt.googlegroups.com> skip at pobox.com wrote: > I don't think you mean "platform-independent". I suspect you mean > "batteries included". Prior to the release of Python 2.5, no modules to > access SQL databases were distributed with core Python. Starting with 2.5, > sqlite access will be available: > > >>> import sqlite3 > >>> sqlite3.__file__ > '/Users/skip/local/lib/python2.5/sqlite3/__init__.pyc' > > So, if what you were really asking was "what SQL databases can I access > without installing any software other than Python?", then the answer is "No > SQL databases were distributed with Python prior to 2.5. Starting with > Python 2.5, access to sqlite databases is available by default." Python 2.5 > is due out soon (according to PEP 356, on 12 September). Yes, you excactly got my point. The thing is that I can't rely on Python 2.5 to be installed soon. So the only solution for me at this moment is to use jython and from there use Java JDBC API (sorry :-) But it would be great if the Python DB API compliant-modules would become parts of core python quickly. Python DB API itself is a great thing. From rpdooling at gmail.com Tue Aug 1 15:33:53 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 1 Aug 2006 12:33:53 -0700 Subject: Programming newbie coming from Ruby: a few Python questions In-Reply-To: <1154458926.738922.156910@h48g2000cwc.googlegroups.com> References: <1154458926.738922.156910@h48g2000cwc.googlegroups.com> Message-ID: <1154460833.050610.181100@m73g2000cwd.googlegroups.com> simonharrison at fastmail.co.uk wrote: > 'Clever is not considered a compliment in Python.' (don't know where I > read that...) "To describe something as clever is NOT considered a compliment in the Python culture."--Alex Martelli, Python Cookbook 2nd Ed. pg. 230 (a great book for learning by doing, after you have the basics down) Do you have Python installed yet? If not, consider http://www.richarddooling.com/index.php/category/geekophilia. You sound like a nonprogrammer (except for your Ruby experience), so you probably want: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Good luck! Have fun. rd From bruce.who.hk at gmail.com Mon Aug 28 02:48:37 2006 From: bruce.who.hk at gmail.com (bruce.who.hk) Date: Mon, 28 Aug 2006 14:48:37 +0800 Subject: [ANN] NumPy 1.0b4 now available References: <44F01802.8050505@ieee.org> Message-ID: <200608281448353906004@gmail.com> Hi, Travis I just wonder if NumPy 1.0b4 can get along with py2exe? Just a few weeks ago I made a application in Python. At first I used Numpy, it works OK, but I cannot pack it into a workable executable with py2exe and the XXX.log saied that numpy cannot find some module. I found some hints in py2exe wiki, but it still doesn't work. At Last I tried Numeric instead and it got OK. I just hope that you donnot stop the maintenance of Numeric before you are sure that Numpy can work with py2exe. ------------------------------------------------------------- > ????Travis E. Oliphant > ?????2006-08-26 17:45:03 > ???[ANN] NumPy 1.0b4 now available >The 4th beta release of NumPy 1.0 has just been made available. > >NumPy 1.0 represents the culmination of over 18 months of work to unify >the Numeric and Numarray array packages into a single best-of-breed >array package for Python. > >NumPy supports all the features of Numeric and Numarray with a healthy >dose of it's own improved features. > >It's time to start porting your applications to use NumPy as Numeric is >no longer maintained and Numarray will only be maintained for a few more >months. > >Porting is not difficult especially using the compatibility layers >numpy.oldnumeric and numpy.numarray and the alter_code1.py modules in >those packages. The full C-API of Numeric is supported as is the C-API >of Numarray. > >More information is available at http://numpy.scipy.org > > >NumPy Developers > > > >-- >http://mail.python.org/mailman/listinfo/python-list ------------------ bruce.who.hk 2006-08-28 From steve at holdenweb.com Wed Aug 16 20:40:07 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 17 Aug 2006 01:40:07 +0100 Subject: How do I catch ExpatError exception? In-Reply-To: <1155771384.487253.152630@i42g2000cwa.googlegroups.com> References: <1155771384.487253.152630@i42g2000cwa.googlegroups.com> Message-ID: <ec0dsg$u9n$1@sea.gmane.org> Shuaib wrote: > Hey! > > I am getting this exception. > > xml.parsers.expat.ExpatError > > But I am not able to catch it with "except > xml.parsers.expat.ExpatError:" It says "NameError: global name 'xml' is > not defined". > > I am also not able to catch it with "except ExpatError:" Gives > "NameError: global name 'xml' is not defined" > > How do I catch it? (I am parsing an xml file) > import xml.parsers.expat That way the interpreter will be able to resolve the reference to the exception. > Also, how do I get the line number where an exception was thrown? > # # Exception traceback test # def r(): return 1/0 try: print r() except: import sys t, v, tb = sys.exc_info() print "exception on line", tb.tb_lineno regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From ian at excess.org Wed Aug 23 11:18:34 2006 From: ian at excess.org (Ian Ward) Date: Wed, 23 Aug 2006 11:18:34 -0400 Subject: ANN: Urwid 0.9.6 - Console UI Library Message-ID: <44EC71CA.9050008@excess.org> Announcing Urwid 0.9.6 ---------------------- Urwid home page: http://excess.org/urwid/ Tarball: http://excess.org/urwid/urwid-0.9.6.tar.gz About this release: =================== This release improves Unicode support with Python < 2.4 and new features were added to the tutorial and reference generation scripts. The graph.py example program introduced in 0.9.5 should now work properly for everyone. Please let me know if you have any trouble with it. New in this release: ==================== - Fixed Unicode conversion and locale issues when using Urwid with Python < 2.4. The graph.py example program should now work properly with older versions of Python. - The docgen_tutorial.py script can now write out the tutorial example programs as individual files. - Updated reference documentation table of contents to show which widgets are flow and/or box widgets. - Columns.set_focus(..) will now accept an integer or a widget as its parameter. - Added detection for rxvt's HOME and END escape sequences. - Added support for setuptools (improved distutils). About Urwid =========== Urwid is a console UI library for Python. It features fluid interface resizing, UTF-8 support, multiple text layouts, simple attribute markup, powerful scrolling list boxes and flexible interface design. Urwid is released under the GNU LGPL. From timr at probo.com Wed Aug 30 01:04:20 2006 From: timr at probo.com (Tim Roberts) Date: Wed, 30 Aug 2006 05:04:20 GMT Subject: unicode "table of character" implementation in python References: <mailman.9642.1156252389.27775.python-list@python.org> <44F31B76.1050506@v.loewis.de> Message-ID: <n17af25re60tmm4fsg35h4beopaskpv8iq@4ax.com> "Martin v. L?wis" <martin at v.loewis.de> wrote: > >In any case, somebody pointed you to the Unicode code blocks. I think >these are Asian scripts (I may have missed some): > >0530..058F; Armenian >0590..05FF; Hebrew >... This is a fabulously useful list, Martin. Did you get this from a web page? Can you tell me where? -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From grflanagan at yahoo.co.uk Sun Aug 27 08:59:52 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 27 Aug 2006 05:59:52 -0700 Subject: unpaking sequences of unknown length In-Reply-To: <mailman.9934.1156672890.27775.python-list@python.org> References: <mailman.9934.1156672890.27775.python-list@python.org> Message-ID: <1156683592.650594.259560@h48g2000cwc.googlegroups.com> Anthra Norell wrote: > Hi, > > I keep working around a little problem with unpacking in cases in which I don't know how many elements I get. Consider this: > > def tabulate_lists (*arbitray_number_of_lists): > table = zip (arbitray_number_of_lists) > for record in table: > # etc ... > > This does not work, because the zip function also has an *arg parameter, which expects an arbitrary length enumeration of arguments maybe I don't understand the problem properly, but you can use '*args' as 'args' or as '*args', if you see what I mean!, ie. def tabulate_lists (*arbitray_number_of_lists): table = zip (*arbitray_number_of_lists) for record in table: # etc ... for example: def sum_columns(*rows): for col in zip(*rows): yield sum(col) for i, s in enumerate( sum_columns( [1,2], [3,2], [5,1] ) ): print 'Column %s: SUM=%s' % (i,s) Column 0: SUM=9 Column 1: SUM=5 ----------------------------------------------------- alternatively: import itertools as it def sum_columns2( iterable ): for col in it.izip( *iterable ): yield sum(col) def iter_rows(): yield [1,2] yield [3,2] yield [5,1] print list( sum_columns2( iter_rows() ) ) #(izip isn't necessary here, zip would do.) ----------------------------------- Gerard From timgee at pobox.com Sun Aug 6 20:13:03 2006 From: timgee at pobox.com (Timothy Gee) Date: Sun, 06 Aug 2006 20:13:03 -0400 Subject: pycrust xmlrpclib problem Message-ID: <gAvBg.319$dQ4.201@bignews1.bellsouth.net> Have do a lot of lab work making use of xmlrpclib and am quite dependent on it. I just started working with pycrust under Linux RH9, and wanted to use it as my standard python environment, however, when I import xmlrpclib, I get a segmentation fault. Command line still works fine however. Details for pycrust are: PyCrust 0.9.5 Yet another Python shell, only flakier. Half-baked by Patrick K. O'Brien, the other half is still in the oven. Shell Revision: 1.9.2.10 Interpreter Revision: 1.6.2.1 Platform: linux2 Python Version: 2.4.1 wxPython Version: 2.6.3.3 (wxGTK, unicode, gtk2, wx-assertions-on, SWIG-1.3.27) Linux Info: Linux rtphostb06 2.4.20-18.9 #1 Thu May 29 07:08:16 EDT 2003 i686 i686 i386 GNU/Linux Anyone had a similar problem? Any workarounds? -Tim- From skip at pobox.com Sat Aug 26 16:28:54 2006 From: skip at pobox.com (skip at pobox.com) Date: Sat, 26 Aug 2006 15:28:54 -0500 Subject: Don't use __slots__ (was Re: performance of dictionary lookup vs. object attributes) In-Reply-To: <1156621904.481215.243080@m73g2000cwd.googlegroups.com> References: <mailman.9853.1156495094.27775.python-list@python.org> <1156508104.583914.323700@b28g2000cwb.googlegroups.com> <ecn1qa$ksp$1@panix2.panix.com> <7.0.1.0.0.20060825122244.03790010@yahoo.com.ar> <mailman.9880.1156520034.27775.python-list@python.org> <1156621904.481215.243080@m73g2000cwd.googlegroups.com> Message-ID: <17648.44806.903001.340169@montanaro.dyndns.org> Aahz> Taking a look at __slots__ is fine as long as you don't actually Aahz> use them. Gabriel> Why? Skip> http://groups.google.com/group/comp.lang.python/browse_thread/thread/451ad25f9c648404/f4ac2dfde32b16fd?lnk=st&q=Python+__slots__+aahz&rnum=2#f4ac2dfde32b16fd Patrick> The subject of __slots__ really seems to get some people's Patrick> dander up, to the extent where the heat/light ratio in the Patrick> discussion becomes uncomfortably high. Right here, we have Patrick> Skip referring to a post by Aahz, where Aahz says that Guido Patrick> says that slots are bad mojo, without anybody ever giving Patrick> concrete examples about why this may be the case. The only Patrick> assertion that was made explicitly enough to be testable came Patrick> about in a followup to Aahz's original post, only AFTER someone Patrick> asked what the side-effects associated with __slots__ were. Patrick> Aahz responded: No dander on my part. I was just pointing out an earlier thread on the topic. Note however that the ultimate source of the anti-slots fervor in that thread is Guido himself (may he live long and prosper as BDFL). If Guido thinks it's bad mojo, that's good enough for me. Also, if he thinks it's bad mojo now, my suspicion is that you won't see it in Py3k. That said, It's not mentioned on the Python3.0 page of the wiki: http://wiki.python.org/moin/Python3.0 or in PEP 3000: http://www.python.org/dev/peps/pep-3000/ and I see no discussion about it in the Python 3000 mailing list archives: http://mail.python.org/pipermail/python-3000/ though Ian Bicking asks about it here: http://wiki.python.org/moin/Python3%2e0Suggestions#head-fc89a0fe3f697418776925f4828ea863031fbbd2 Skip From adonis at DELETETHISTEXTearthlink.net Tue Aug 8 20:11:46 2006 From: adonis at DELETETHISTEXTearthlink.net (Adonis) Date: Wed, 09 Aug 2006 00:11:46 GMT Subject: How to reverse tuples in a list? In-Reply-To: <1155081671.728757.228050@p79g2000cwp.googlegroups.com> References: <1155081671.728757.228050@p79g2000cwp.googlegroups.com> Message-ID: <6L9Cg.1732$Qf.62@newsread2.news.pas.earthlink.net> Noah wrote: > I have a list of tuples > [('a', 1.0), ('b', 2.0), ('c', 3.0)] > I want to reverse the order of the elements inside the tuples. > [(1.0,'a'), (2.0, 'b'), (3.0, 'c')] > > I know I could do this long-form: > q = [] > y = [('a', 1.0), ('b', 2.0), ('c', 3.0)] > for i in y: > t=list(t) > t.reverse() > q.append(tuple(t)) > y = q > > But it seems like there should be a clever way to do this with > a list comprehensions. Problem is I can't see how to apply > reverse() to each tuple in the list because reverse() a > list method (not a tuple method) and because it operates > in-place (does not return a value). This kind of wrecks doing > it in a list comprehension. What I'd like to say is something like > this: > y = [t.reverse() for t in y] > Even if reverse worked on tuples, it wouldn't work inside a > list comprehension. > > Yours, > Noah > Provided the data remains the same [(a, b), ...] Python 2.5a2 (r25a2:45740, May 24 2006, 19:50:20) [GCC 3.3.6] on linux2 >>> x = [('a', 1.0), ('b', 2.0), ('c', 3.0)] >>> y = [(b, a) for a, b in x] >>> y [(1.0, 'a'), (2.0, 'b'), (3.0, 'c')] Hope this helps, Adonis From chris.cavalaria at free.fr Tue Aug 29 05:36:39 2006 From: chris.cavalaria at free.fr (Christophe) Date: Tue, 29 Aug 2006 11:36:39 +0200 Subject: Pros/Cons of Turbogears/Rails? In-Reply-To: <1156842974.103231.86930@m73g2000cwd.googlegroups.com> References: <WXmIg.20772$gY6.18513@newssvr11.news.prodigy.com> <1156726071.579429.44650@b28g2000cwb.googlegroups.com> <1156740469.645955.52080@i3g2000cwc.googlegroups.com> <1156768355.275370.129680@h48g2000cwc.googlegroups.com> <1156819473.592153.141940@i42g2000cwa.googlegroups.com> <1156842974.103231.86930@m73g2000cwd.googlegroups.com> Message-ID: <44f40a8f$0$17167$626a54ce@news.free.fr> Paul Boddie a ?crit : > [comp.lang.ruby snipped] > > Ray wrote: >> I've met a number of >> people who've told me they'd program in Eiffel if they could. And hey, >> perhaps in its day Eiffel *was* the best OO language out there. >> Certainly it looked cleaner than C++! :) > > So why don't they? Management pressure? Why don't people write more > Python in their day job? Any suggestions? Probably because of the extreme Bondange And Disciplineness of Eiffel, the incredible cost of each user license, lack of generic programing ( you know, the thing easy to do in Python/Ruby but requires templates in C++ ) and the complete lack of a correct debugger. By now, it seems that some of those problems have been fixed in various ways but we now have even better : incompatible implementations of the language! Eiffel is for all purposes a niche language only used by some fanatics here and there :) From tim at tdw.net Mon Aug 21 18:16:36 2006 From: tim at tdw.net (Tim Williams) Date: Mon, 21 Aug 2006 23:16:36 +0100 Subject: Unclear on argument passing to "sendmail' In-Reply-To: <W50294580.789.631.1@mx-extra> References: <W50294580.789.631.1@mx-extra> Message-ID: <9afea2ac0608211516h1bdaa365ua13a5207f1b85026@mail.gmail.com> On 21/08/06, John Draper <lists at webcrunchers.com> wrote: > In "smtplib" module, the "sendmail" method of function is to be passed > host, but it is the Domain name > for the SMTP Server as gotten from the "dig" command? IE: dig -tMX > would give me the SMTP > server. In my code I have: > > try: > print "Sending message to host: %s" % mailHost > server=smtplib.SMTP(mailHost) > server.sendmail(reply_email,email,body) > server.quit() > except: > print "Uunable to send" > > Is mailHost like "mail.t-mobile.com" which I get from the MX record for > a given domain? > But also, is the "email" just the mail account, ie: the username? > without the @<domain>? > > I need to be able to query the mail server? Also, I want to be able > to handle > the "SMTPRecipientsRefused" exception. What is the proper syntax for > handling > this? > > Do I do it like this? > > try: > print "Sending message to host: %s" % mailHost > server=smtplib.SMTP(mailHost) > server.sendmail(reply_email,email,body) > server.quit() > except SMTPRecipientsRefused: > print "Recipient refused" > > Is that the right syntax? I have severe problems with not enough > example code. > mailHost is the name of the mail server server you are sending the email to/via, for internet mail this will be a server from the recipient's domain's mx records (or your ISP server). reply_email is the full email address of the sender, or the email address you wish to appear as the sender. It does not have to be the same address as used in the body headers email is a bad choice for a variable name, try something like to_email, in your case it should contain the full email address of the recipeint or a list of recipients. The address(es) do not have to be the same address as used in the body headers server.sendmail returns a list of failed recipient email addresses if only some failed, if all the recipients failed you get an exception. Apologies for the bad formatting below, its untested but should show you the structure for managing an SMTP msg send. You could tidy it up without too much effort import sys for mailHost in MX_records: try: print "Sending message to host: %s" % mailHost server=smtplib.SMTP(mailHost) failed = server.sendmail(reply_email,email,body) server.quit() break except smtplib.SMTPRecipientsRefused, x : #all recips failed for recip in x.recipients: print recip server.quit() break except smtplib.SMTPDataError, x: # an error at the end of the # message body = MSG Failed # all recips failed print x[0], x[1] server.quit() break except smtplib.SMTPSenderRefused, x : # the sender was refused = #MSG failed # all recips failed print x[0], x[1] server.quit() break except: #can't connect so continue to next MX server - don't fail !!! e_error = str(sys.exc_info()[0]) print e_error server.quit() continue for recip in failed: # some failed, some didn't print recip -- Tim Williams From vatamane at gmail.com Wed Aug 2 15:36:44 2006 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 2 Aug 2006 12:36:44 -0700 Subject: Is there an obvious way to do this in python? References: <mailman.8853.1154537129.27775.python-list@python.org> Message-ID: <1154547404.749534.320700@m79g2000cwm.googlegroups.com> HJ, As someone already posted, the backend sounds very much like a database, so why not use a database: transactions, specific views for different users, limited access and so on = database! Give PostgresSQL a try... As far as presenting a different GUI to users, you can also do it based on the database. In other words have a common login screen and if the usertype from the database is returned as 'restricted' draw one interface, if it is returned as 'full' draw the full interface. Even if the restricted user will get the full interface up it won' t be functional because the database would restrict writes to certain tables/columns. Remote update of code is also possible, but you'll have to implement some kind of update server to which you can periodically send Python files, those files will be installed on the machine by the update server. You can try playing with Twisted to handle the networking. Or just write a simple script to send stuff over scp/ssh -- that's what I would do (start the ssh server, install public keys and then just scp stuff over to the machines assuming they are online most of the time...). The problem will be if something goes wrong in the updated file or with the update server then the whole system will be down (an off-by-one error in the GUI db client code and all of the sudden all your users will be writing bad data to the database... all at the same time). So you will need to do frequent backups of the database, but you probably know this already... Hope this helps, Nick Vatamaniuc H J van Rooyen wrote: > Hi, > > I want to write a small system that is transaction based. > > I want to split the GUI front end data entry away from the file handling and > record keeping. > > Now it seems almost trivially easy using the sockets module to communicate > between machines on the same LAN, so that I want to do the record keeping on one > machine. > > I want to keep the "server" machine as simple as possible - just doing record > keeping on a stimulus response basis - I would prefer it to do one thing at a > time to completion because this style of operation, though limited in > performance, keeps a lot of hassles out of life - a transaction has either > completed, or it has not - recovery scenarios are relatively easy... > > Up to this point, I don't have a problem - my toy system can create a dummy > transaction, and I can echo it from the "server" machine, with more than one > "user" machine running - so I think it is feasible to have several tens of "data > entry terminal" systems running, served by one not very strong machine. > > Now what I would really like to do is to differentiate between the 'User" > machines, so that some can do a full range of transactions, and others a limited > range. > > And I would like to make this flexible, so that it becomes easy to introduce new > transactions, without having to run around updating the code in all the user > machines, with the concomitant version number hassles. > > And I would like to do the whole thing in python - so my question is this - is > it possible to do the equivalent of dynamic linking? - i.e. if I keep a list of > what a user is allowed to do - can I somehow send him just the bits he needs to > do the job, without having to change the static code on his machine? - it seems > to me that the eval() thingy could possibly do this for me, by sending it data > that makes it do import statements followed by calls to whatever... - will this > work, or is there a better way? > > Or has all this been done already? - and no I don't want a web server and php > and browsers and Java and html or xml... - I want to write something that works > simply and reliably - its just short message accounting type data... > > - Hendrik From rogue_pedro at yahoo.com Wed Aug 16 04:00:17 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 16 Aug 2006 01:00:17 -0700 Subject: Very weird behavior that's driving me crazy In-Reply-To: <44e2c4c3$0$20039$9b4e6d93@newsspool4.arcor-online.net> References: <44e2c4c3$0$20039$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <1155715217.411002.120590@h48g2000cwc.googlegroups.com> Pupeno wrote: > Hello, > I am experiencing a weird behavior that is driving me crazy. I have module > called Sensors containing, among other things: > > class Manager: > def getStatus(self): > print "getStatus(self=%s)" % self > return {"a": "b", "c": "d"} > > and then I have another module called SensorSingleton that emulates the > hard-to-code-on-python singleton in this way: > > manager = Manager() > print "manager=%s" % manager > def getStatus(): > print "getStatus()" > return manager.getStatus() > > and then in some other module, I import SensorSingleton and I do, among > other things: > > print SensorSingleton.getStatus() > > and the output is more or less like this. First, the manager: > > manager: <Sensor.Manager object at 0xb7b9efec> > > ok, then > > Manager.getStatus(self=<Sensor.Manager object at 0xb77cde8c>) => > {"a": "b", "c": "d"} > None > > None is the return of SensorSingleton.getStatus(), now, my questions are: > > - Shouldn't the manager be the same in the first print and the second, that > is, the id is different, shouldn't it be the same ? > - What happened with all the output of SensorSingleton.getStatus() ? there's > no trace of it (but there's output of the method it calls). > - Why doesn't the SensorSingleton.getStatus() return the return value of > manager.getStatus(), it's a very straight forward call to it and return it. > > Thank you. > -- > Pupeno <pupeno at pupeno.com> (http://pupeno.com) The code you posted doesn't match the output you posted. Try coding the smallest version of what you're trying to do and post its output. Peace, ~Simon From foolscreen at gmail.com Wed Aug 23 01:07:37 2006 From: foolscreen at gmail.com (bEngO) Date: Wed, 23 Aug 2006 14:07:37 +0900 Subject: Embedding Python in an application plug-in ( .so ) Message-ID: <39ae57c30608222207w72d4eda8rae59987a0c93f17a@mail.gmail.com> Dear all, When embedding we must link with the python library AND USE -rdynamic OR -Wl,-export-dynamic OR -Xlinker -export-dynamic to export ALL symbols from the Python library even if we do not use all of them. This is needed when the embedded Python import modules to avoid undefined symbol errors. But it doesn't work when embedding Python into a plug-in ( .so ) for an application. I want to embed Python in a shared object which will be dynamically loaded by an application. So when i build my share object, i link with the python library ( btw should i link with the .a or .so ? ) and i use the flag to export all symbols and Python is accessible from the application when my share object is loaded. But i can't import Python modules ( example: import socket ), i get some undefined symbols errors. I dont know exactly why. Is it because the rdynamic/export-dynamic flags have no effect when building a shared object ? Or is it a problem with my compiler: GCC 4.1.0, Linux 2.6.17 ? Or is it because the application is loading my plug-in without the RTLD_GLOBAL flag ? Or what ? Please help :) I found some people having the same problem but no workaround... Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060823/463a331d/attachment.html> From robert.kern at gmail.com Thu Aug 24 12:25:30 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 24 Aug 2006 11:25:30 -0500 Subject: Newbie question about numpy In-Reply-To: <44EDD0C4.1070606@yahoo.fr> References: <e4hre29hpv4ef1spfbqsu2hq0ee4apgdpv@4ax.com> <44EDD0C4.1070606@yahoo.fr> Message-ID: <eckjtm$uqn$1@sea.gmane.org> Avell Diroll wrote: > For matrices multiplication, you could get a hint by typing the > following in the interpreter : > >>>> import numpy >>>> dir(numpy) >>>> help(numpy.matrixmultiply) #type "q" to exit Note that the name matrixmultiply() has been deprecated in favor of dot() for many, many years now even in Numeric, numpy's predecessor. It has finally been removed in recent versions of numpy. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From sjmachin at lexicon.net Wed Aug 16 19:03:26 2006 From: sjmachin at lexicon.net (John Machin) Date: 16 Aug 2006 16:03:26 -0700 Subject: Calling a python script, and getting the returned result in C In-Reply-To: <1155768471.647074.246660@i42g2000cwa.googlegroups.com> References: <1155764701.509056.207140@h48g2000cwc.googlegroups.com> <1155768090.801185.101990@75g2000cwc.googlegroups.com> <1155768471.647074.246660@i42g2000cwa.googlegroups.com> Message-ID: <1155769406.592732.191340@i3g2000cwc.googlegroups.com> Shuaib wrote: > John Machin wrote: > > Shuaib wrote: > > > Hi! > > > > > > I have a python script which returns an Integer value. How do I call > > > this script from a C programe, and use the result returned? > > > > To avoid confusion and possible irrelevant responses, please say which > > of the following options best matches your requirement: > > > > (a) your Python script is capable of being run from the command line, > > and "returns" an integer value by calling sys.exit(that_value) -- you > > wish to execute the script from a C program [the same way you would > > execute a shell script / awk script / ...] and pick up the return value > > [which may be limited by the OS to range(0, 128)] > > > > (b) your script is a module, containing a function that returns an > > integer. You wish to create an embedded Python interpreter, import > > yourmodule, call yourmodule.yourfunc, convert the returned Python int > > to a C int, and use it. > > (b) it is. :) Then you need to read the Python manuals (surprise, surprise); in particular here's a section that gives you most if not all of what you want : http://docs.python.org/ext/pure-embedding.html but I'd suggest that you start reading a few pages back from there. HTH, John From sp1d3rx at gmail.com Tue Aug 15 19:29:18 2006 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 15 Aug 2006 16:29:18 -0700 Subject: Why do I require an "elif" statement here? In-Reply-To: <060807000121920.07Aug06$rookswood@suburbian.com> References: <1154712731.375032.203570@m79g2000cwm.googlegroups.com> <1154714902.770382.162110@m73g2000cwd.googlegroups.com> <060807000121920.07Aug06$rookswood@suburbian.com> Message-ID: <1155684558.438824.27970@p79g2000cwp.googlegroups.com> John Savage wrote: > "sp1d3rx at gmail.com" <sp1d3rx at gmail.com> writes: > >------------------------------- > >whitespace = " " > >old_indent = 3 > >new_indent = 5 > > > >x = " starts with 3 spaces" > > > >x = x.replace(whitespace*old_indent, whitespace*new_indent) > >------------------------------- > > > >In this example though, it will replace the 3 spaces no matter where > >they are at, not just in the beginning... still, it's probably more > >practical for most use cases. > > You'd corner it with: > > if x.startswith(' '*3): x=x.replace(' '*3,' '*5,1) As others have stated, this will only get lines that start with only 1 set of "old_indent" and not multiples of "old_indent". > -- > John Savage (my news address is not valid for email) From antroy at gmail.com Mon Aug 7 12:21:28 2006 From: antroy at gmail.com (Ant) Date: 7 Aug 2006 09:21:28 -0700 Subject: screensaver in Python In-Reply-To: <rhJBg.8967$zo5.129151@phobos.telenet-ops.be> References: <HKIBg.8915$fx6.203916@phobos.telenet-ops.be> <1154963777.637581.306290@n13g2000cwa.googlegroups.com> <rhJBg.8967$zo5.129151@phobos.telenet-ops.be> Message-ID: <1154967688.904011.166980@75g2000cwc.googlegroups.com> daniel Van der Borght wrote: > are you Chris ? anyway : thank you... No - I really am Ant. :-) From kw at kevin-walzer.com Sun Aug 27 18:03:44 2006 From: kw at kevin-walzer.com (Kevin Walzer) Date: Sun, 27 Aug 2006 18:03:44 -0400 Subject: IDLE on Mac OS X In-Reply-To: <MbnIg.65514$fV1.23660@fe1.news.blueyonder.co.uk> References: <MbnIg.65514$fV1.23660@fe1.news.blueyonder.co.uk> Message-ID: <44F216C0.5000706@kevin-walzer.com> Furbybrain wrote: > I'm running 10.3.9 and I've just installed Python 2.4. IDLE won't start- > it bounces in the dock once or twice then goes away. > I'm new to Python, and I'm trying to learn. Thanks. You need to install Tcl/Tk--it doesn't come with 10.3 by default. Get a Panther-compatible version at http://tcltkaqua.sourceforge.net. -- Kevin Walzer Poetic Code http://www.kevin-walzer.com From simonharrison at fastmail.co.uk Wed Aug 2 13:20:23 2006 From: simonharrison at fastmail.co.uk (simonharrison at fastmail.co.uk) Date: 2 Aug 2006 10:20:23 -0700 Subject: Programming newbie coming from Ruby: a few Python questions In-Reply-To: <44d06f9f$0$19127$626a54ce@news.free.fr> References: <mailman.8824.1154472963.27775.python-list@python.org> <1154494954.082706.283750@b28g2000cwb.googlegroups.com> <44d06f9f$0$19127$626a54ce@news.free.fr> Message-ID: <1154539223.873418.286830@i42g2000cwa.googlegroups.com> thanks very much for all the comments, links to articles and other help.The Ruby crowd says you guys are no where near as friendly as them! I was half expecting a nervous breakdown after writing my first post here. Cheers again From levub137 at wi.rr.com Sat Aug 19 12:26:54 2006 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Sat, 19 Aug 2006 16:26:54 GMT Subject: [ANN] rpncalc-2.4 RPN Calculator for Python Message-ID: <iZGFg.17026$zg.6668@tornado.rdc-kc.rr.com> The rpncalc package adds an interactive Reverse Polish Notation (RPN) interpreter to Python. This interpreter allows the use of Python as an RPN calculator. You can easily switch between the RPN interpreter and the standard Python interpreter. Home page: http://calcrpnpy.sourceforge.net/ Changes in 2.4 * Update the included clnum package. * Added combinatorial functions. From hxianping at gmail.com Wed Aug 2 19:48:07 2006 From: hxianping at gmail.com (steve) Date: 2 Aug 2006 16:48:07 -0700 Subject: Are there any AOP project in python community? Message-ID: <1154562487.677431.274440@i3g2000cwc.googlegroups.com> I mean Aspect-Oriented Programming. If any please give me some of links. Thanks a lot. From gelists at gmail.com Fri Aug 4 09:10:45 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Fri, 4 Aug 2006 10:10:45 -0300 Subject: Nested function scope problem References: <20060803154632.A998.SLAWOMIR.NOWACZYK.847@student.lu.se> <5ucltr8vdu2n$.dlg@gelists.gmail.com> <20060804094245.A9AF.SLAWOMIR.NOWACZYK.847@student.lu.se> Message-ID: <1okvniwl5zgqj.dlg@gelists.gmail.com> On 2006-08-04 07:36:25, Slawomir Nowaczyk wrote: > #> The address operator is probably for a C programmer the closest to > #> what the id() function is to a Python programmer. > > I disagree. At least in my understanding, which, up to now, was > perfectly enough to explain everything about how Python variables > behave: > > The address operator in C is what textual representation (i.e. what > you type, like "a") is in Python. Equivalent of id() is a dereference > operator. But then you are not talking about C variables. Using a normal C variable, this doesn't work: int c = 5; printf( "id(c)=%x", *c ); You can hardly claim that what gets printed is the "id" of the variable c. (Well, you can claim, but few C programmers would follow you.) What would be analogous in Python to the textual representation of the variable in C? The address operator in C in analog to the textual representation in Python. The textual representation in C is analog to ??? in Python? You may be talking about C pointers and call the locations they point to "variables". That's a big difference; those are /not/ C variables. And they still are not the same. What is analog in Python (using your analogy) to the address of the pointer variable in C (&a in your example)? Note that in standard C/C++ language, a and b in your example are variables (in fact the only variables), not *a and *b. (three and four should have been declared as constants, to be analogous to Python.) So the only variables in your example (a and b) don't really behave according to your analogy. What behaves somewhat like your analogy are *a and *b -- neither of which are C/C++ variables. (Well, they are in your example, but only because of sloppily applying your analogy. And they are not in the general case: pointers don't care whether they point to actual C/C++ variables, or to any other memory location.) Gerhard From support at mathworks.co.uk Tue Aug 1 03:06:19 2006 From: support at mathworks.co.uk (support at mathworks.co.uk) Date: 1 Aug 2006 03:06:19 -0400 Subject: Python-list Digest, Vol 35, Issue 8 Message-ID: <200608010706.k7176KC26169@mail-vif.mathworks.com> This is an automated response. Thank you for contacting the Technical Support team at The MathWorks Ltd. A technical support representative will be contacting you within 1 business day. The following information will help us in responding to your request. If you have already provided the information requested below, no further action is required. 1) License number, release number, and operating system. Typing ?ver? at the MATLAB command prompt will list this information. 2) Exact text of any error message(s) received 3) All files (M-files, Simulink models, data files) and steps to reproduce the issue. If you need to send in an executable or a zip file, please wait until a support engineer contacts you. To provide this information, reply to this message keeping the Thread Id listed at the bottom of this message intact. STUDENT VERSION USERS: If you are a student using the Student Version, please note that email and phone support is available for product installation, software crashes, or bug reporting. For all other enquiries, contact your lecturer or visit the support web site at http://www.mathworks.co.uk/support/. If you have any concerns about our technical support services, write to tsmanagers at mathworks.com. Technical Support Team The MathWorks Ltd Email: support at mathworks.co.uk Tel: 01223 423200 Fax: 01223 423250 http://www.mathworks.co.uk/support [THREAD ID: 1-2ZJ107] -----Original Message----- From: python-list-request at python.org Sent: 8/1/2006 3:06:04 AM To: support at mathworks.co.uk Subject: Python-list Digest, Vol 35, Issue 8 Send Python-list mailing list submissions to python-list at python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/python-list or, via email, send a message with subject or body 'help' to python-list-request at python.org You can reach the person managing the list at python-list-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Python-list digest..." From larry.bates at websafe.com Mon Aug 14 16:14:10 2006 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 14 Aug 2006 15:14:10 -0500 Subject: Memory problem In-Reply-To: <mailman.9320.1155580347.27775.python-list@python.org> References: <mailman.9320.1155580347.27775.python-list@python.org> Message-ID: <85mdnb4jzcpTRH3ZnZ2dnUVZ_t6dnZ2d@comcast.com> Yi Xing wrote: > Hi, > > I need to read a large amount of data into a list. So I am trying to see > if I'll have any memory problem. When I do > x=range(2700*2700*3) I got the following message: > > Traceback (most recent call last): > File "<stdin>", line 1, in ? > MemoryError > > Any way to get around this problem? I have a machine of 4G memory. The > total number of data points (float) that I need to read is in the order > of 200-300 millions. > > Thanks. > On my 1Gb machine this worked just fine, no memory error. -Larry Bates From rosedb0 at gmail.com Sat Aug 19 21:54:07 2006 From: rosedb0 at gmail.com (hiaips) Date: 19 Aug 2006 18:54:07 -0700 Subject: Permission Denied In-Reply-To: <mailman.9557.1156032685.27775.python-list@python.org> References: <mailman.9557.1156032685.27775.python-list@python.org> Message-ID: <1156038847.616137.61800@m79g2000cwm.googlegroups.com> Tom Strickland wrote: > Hopefully this is a simple question. I've started to program in Python > after an absence of about a year, so I'm very rusty. I wrote a short > program and tried to run it using Python2.4 in Linux. I keep getting > "permission denied" messages after entering the path to the program. I > switched to the root directory and tried again, but got the same > result.I ran a very similar program earlier and it ran fine. > > What am I doing wrong? The program is: > > > #!/usr/bin/python2.4 > i=1 > while i<10000: > print 'step 1',i > i+=1 > raw_input() > print 'step 2' > > > Thank you. > > Tom Is your script executable? From aleax at mac.com Tue Aug 22 10:27:54 2006 From: aleax at mac.com (Alex Martelli) Date: Tue, 22 Aug 2006 07:27:54 -0700 Subject: What do you want in a new web framework? References: <1156100331.329889.216340@p79g2000cwp.googlegroups.com> <pan.2006.08.20.19.48.34.996227@gmx.net> <1156156636.515678.118210@75g2000cwc.googlegroups.com> <4jele2pe011di99c5dnq4olclglrkieggc@4ax.com> Message-ID: <1hkgnbt.ebn4o1111ftp0N%aleax@mac.com> Tim Roberts <timr at probo.com> wrote: ... > themselves. However, in the case of web frameworks, I believe Marc is > fundamentally correct: the web framework proliferation in Python is > actually doing the language a huge disservice. Indeed, it has been truthfully observed that Python's the only language with more web frameworks than keywords. I have already suggested to the BDFL that he can remedy this situation in Py3k: all he has to do, of course, is to add a LOT more keywords. Alex From penneys at bigfoot.com Mon Aug 21 09:18:47 2006 From: penneys at bigfoot.com (MrBlueSky) Date: 21 Aug 2006 06:18:47 -0700 Subject: Modules... paths... newbie confusion Message-ID: <1156166327.327422.149470@b28g2000cwb.googlegroups.com> I wonder if someone could clarify how Python "knows" where modules are - or at least point to some documentation that might help me? Here's what I've been trying: I've installed Python 2.4 Windows, and have also installed tkinter, pmw, cx_Oracle, mssql and pytz (phew!) all under my c:\python24 folder. But when I try to "import pytz" or "import MSSQL" in a Python shell (via IDLE) it's not recognised - yet "import Tkinter", "import Pmw" and "import cx_Oracle" all work. I've experimented with "sys.path" to get the import of pytz to work, but without success so far. I feel as if I'm missing some key piece of information on how this all fits together! Please, help! John From hpsekhon at googlemail.com Tue Aug 1 18:01:12 2006 From: hpsekhon at googlemail.com (Hari Sekhon) Date: Tue, 1 Aug 2006 22:01:12 +0000 Subject: xml.sax problem, help needed. Message-ID: <4f45772d0608011501w5866b97lcee4777b735cb4b8@mail.gmail.com> I've written an xml parser using xml.sax which works most of the time but often traces back when trying to read a file. The output of the traceback is below: Traceback (most recent call last): File "/usr/lib/python2.4/site-packages/cherrypy/_cphttptools.py", line 271, in run main() File "/usr/lib/python2.4/site-packages/cherrypy/_cphttptools.py", line 502, in main body = page_handler(*args, **cherrypy.request.paramMap) File "netscan.py", line 160, in index parse() File "netscan.py", line 117, in parse parser.parse ( scan_results ) File "/usr/lib/python2.4/xml/sax/expatreader.py", line 107, in parse xmlreader.IncrementalParser.parse(self, source) File "/usr/lib/python2.4/xml/sax/xmlreader.py", line 125, in parse self.close() File "/usr/lib/python2.4/xml/sax/expatreader.py", line 217, in close self.feed("", isFinal = 1) File "/usr/lib/python2.4/xml/sax/expatreader.py", line 211, in feed self._err_handler.fatalError(exc) File "/usr/lib/python2.4/xml/sax/handler.py", line 38, in fatalError raise exception SAXParseException: /var/log/netscan/scanresults.txt:8:0: no element found I don't understand why it's telling me that no element is found. It looks like a problem inside xml.sax, but I'm not sure if I've caused it or how. The xml file is good and is generated by nmap, it's not missing tags or anything and is quite small. My script code which has generated this is below: #!/usr/bin/env python import xml.sax import sys import os dir = '/var/log/netscan' scan = 'scanresults.txt' temp = 'tempscan.txt' scan_results = dir + '/' + scan temp_results = dir + '/' + temp if not os.path.isdir(dir): sys.exit("%s does not exist! exiting..." % dir) network = [ # { # "status" : "", # "address" : "", # "hostname" : "", # "port[0]" : "", # "protocol[0]" : "", # "service[0]" : "", # "state[0]" : "", # "product[0]" : "", # "version[0]" : "", # "extrainfo[0]" : "" # } ] class scanparser( xml.sax.ContentHandler ): def __init__(self): self.host = {} self.host['status'] = "" self.host['address'] = "" self.host['hostname'] = "" self.host['port'] = [] self.host['protocol'] = [] self.host['service'] = [] self.host['state'] = [] self.host['product'] = [] self.host['version'] = [] self.host['extrainfo'] = [] def startElement(self,name,attributes): global scan_start,scan_stop if name =='nmaprun': scan_start = attributes.getValue('startstr') elif name == 'finished': scan_stop = attributes.getValue('timestr') elif name =='status': self.host['status'] = attributes.getValue('state') elif name == 'address': if attributes.getValue('addrtype') == 'ipv4': self.host['address'] = attributes.getValue('addr') elif name == 'hostname': self.host['hostname'] = attributes.getValue('name') elif name == 'port': self.host['port'].append( attributes.getValue('portid') ) self.host['protocol'].append( attributes.getValue('protocol') ) elif name == 'service': self.host['service'].append( attributes.getValue('name') ) if attributes.has_key('product'): self.host['product'].append( attributes.getValue('product') ) else: self.host['product'].append("") if attributes.has_key('version'): self.host['version'].append( attributes.getValue('version') ) else: self.host['version'].append('') if attributes.has_key('extrainfo'): self.host['extrainfo'].append( attributes.getValue('extrainfo') ) else: self.host['extrainfo'].append('') elif name == 'state': self.host['state'].append( attributes.getValue('state') ) def endElement(self,name): if name == 'host': network.append(self.host.copy()) self.host = {} self.host['status'] = "" self.host['address'] = "" self.host['hostname'] = "" self.host['port'] = [] self.host['protocol'] = [] self.host['service'] = [] self.host['state'] = [] self.host['product'] = [] self.host['version'] = [] self.host['extrainfo'] = [] def parse(): global network parser = xml.sax.make_parser() parser.setContentHandler( scanparser() ) network = [] parser.parse ( scan_results ) parse() (Well, really it runs from cherrypy but for brevity I've left that out) Any help or pointers anybody could give would be greatly appreciated... Hari From snmishra at XXXhotYYYpop.com Sun Aug 13 21:21:31 2006 From: snmishra at XXXhotYYYpop.com (Satya) Date: Sun, 13 Aug 2006 19:21:31 -0600 Subject: Compiling wxPython app for Windows; Single EXE References: <g21vd2ps3nedou94o7fbgdv52t5k4l9pb6@4ax.com> Message-ID: <44dfc2ec$0$20760$88260bb3@free.teranews.com> Vincent Delporte wrote: <snip> > - there's no way to build a single EXE, to make deployment easier (if > multiple files, I need to build an installer with eg. NSIS or > InnoSetup)? > I am using InnoSetup. The included example script (I believe in py2exe) is adequate for simple applications. I just modified a few lines and I had a neat Windows Installer. Satya -- Posted via a free Usenet account from http://www.teranews.com From ells.david at gmail.com Sat Aug 26 12:05:59 2006 From: ells.david at gmail.com (David Ells) Date: 26 Aug 2006 09:05:59 -0700 Subject: Duck typing alows true polymorfisim In-Reply-To: <mailman.9893.1156540508.27775.python-list@python.org> References: <1156532721.879808.40990@i3g2000cwc.googlegroups.com> <1156534086.698353.81850@m73g2000cwd.googlegroups.com> <mailman.9893.1156540508.27775.python-list@python.org> Message-ID: <1156608359.177167.126900@i3g2000cwc.googlegroups.com> Terry Reedy wrote: > "David Ells" <ells.david at gmail.com> wrote in message > news:1156534086.698353.81850 at m73g2000cwd.googlegroups.com... > > def increment(x): > > return x += 1 > > 'return x+1' works better ;-) > > tjr Heh, woops... thanks From t.mitchell at aranz.com Thu Aug 31 21:15:10 2006 From: t.mitchell at aranz.com (t.mitchell at aranz.com) Date: 31 Aug 2006 18:15:10 -0700 Subject: AttributeError: 'Attributes' object has no attribute 'saveFile' In-Reply-To: <1157068216.700072.248740@m79g2000cwm.googlegroups.com> References: <1157068216.700072.248740@m79g2000cwm.googlegroups.com> Message-ID: <1157073310.497557.196440@74g2000cwt.googlegroups.com> Hi Sounds like you've got a wizard-type interface thing happening. I haven't used wxGlade but I have done similar things in GTK several times. Try putting all the windows in a notebook widget with hidden tabs. Put the 'Next Page' button and the filename outside the notebook. This makes the filename always available and the 'Next Page' button would just switch pages in the notebook widget. Hope this is helpful Cheers Tim From alexandre.guimond at siemens.com Tue Aug 15 05:57:40 2006 From: alexandre.guimond at siemens.com (Alexandre Guimond) Date: 15 Aug 2006 02:57:40 -0700 Subject: how to deepcopy a slice object? In-Reply-To: <1155633086.985976.59960@m79g2000cwm.googlegroups.com> References: <1155629155.207232.50400@m79g2000cwm.googlegroups.com> <1155633086.985976.59960@m79g2000cwm.googlegroups.com> Message-ID: <1155635860.046177.109830@74g2000cwt.googlegroups.com> Here is my reason: I have an object that contrains a 2D regular grid (matrix). In this regular grid, I place points at regular intervals. In essence, i have something like (my code is obviously more complex, this is just to show what I want to do) obj.grid = numpy.zeros( ( 100, 100 ) ) obj.grid[ obj.y1: obj.y2 : obj.ys, obj.x1 : obj.x2 : obj.xs ] = embedded_parameters result = somefunc( obj.grid ) My goal was to reduce the number of elements in my obj object by replacing y1, y2, ys, and x1, x2, xs by 2 slice objects, and then do: obj.grid[ obj.slicey, obj.slicex ] = embedded_parameters But when I do this and then try to deepcopy my object, it doesn't work, as in the example below. Its not a big thing. I just liked the idea of having less elements in my obj class and actually modeling my slice concept by a slice object, specially since i'm going to 3D and 4D grid, and its somewhat annoying to carry so many indices in my class definition. Simon Forman wrote: > Alexandre Guimond wrote: > > Hi all, > > > > i'm trying to deepcopy a slice object but i get the following error. > > Does anyone know a workaround? > > > > ActivePython 2.4.3 Build 12 (ActiveState Software Inc.) based on > > Python 2.4.3 (#69, Apr 11 2006, 15:32:42) [MSC v.1310 32 bit (Intel)] > > on win32 > > Type "help", "copyright", "credits" or "license" for more information. > > >>> import copy > > >>> copy.deepcopy( slice( 1, 10, 2 ) ) > > Traceback (most recent call last): > > File "<stdin>", line 1, in ? > > File "C:\Program Files\Python\lib\copy.py", line 204, in deepcopy > > y = _reconstruct(x, rv, 1, memo) > > File "C:\Program Files\Python\lib\copy.py", line 336, in _reconstruct > > y = callable(*args) > > File "C:\Program Files\Python\lib\copy_reg.py", line 92, in > > __newobj__ > > return cls.__new__(cls, *args) > > TypeError: slice expected at least 1 arguments, got 0 > > > > thx for any help. > > Why would you want to [deep]copy a slice object? > > Anyway, I don't know much about them, other than that they are > slightly unusual objects that play a very restricted role in python, > rather like the Ellipsis. > > Workarounds are possible, I think, but really you almost certainly > don't need to do this. > > Peace, > ~Simon From cginboston at hotmail.com Tue Aug 29 12:45:51 2006 From: cginboston at hotmail.com (Chaz Ginger) Date: Tue, 29 Aug 2006 16:45:51 GMT Subject: refering to base classes In-Reply-To: <1156868822.451018.139280@m73g2000cwd.googlegroups.com> References: <1156862012.068397.284040@m73g2000cwd.googlegroups.com> <44F454D6.5040606@hotmail.com> <44F45603.6050504@hotmail.com> <1156868822.451018.139280@m73g2000cwd.googlegroups.com> Message-ID: <44F46F3F.8010306@hotmail.com> Jason wrote: > Chaz Ginger wrote: >> Chaz Ginger wrote: >>> glenn wrote: >>>> hi - Im quite new to python, wondering if anyone can help me understand >>>> something about inheritance here. In this trivial example, how could I >>>> modify the voice method of 'dog' to call the base class 'creatures' >>>> voice method from with in it? >>>> >>>> class creature: >>>> def __init__(self): >>>> self.noise="" >>>> def voice(self): >>>> return "voice:" + self.noise >>>> >>>> class dog(creature): >>>> def __init__(self): >>>> self.noise="bark" >>>> >>>> def voice(self): >>>> print "brace your self:" >> I did forget to mention that in 'dog"s' __init__ you had better call >> creature's __init__. You might make it look like this: >> >> def __init__(self): >> self.noise = 'bark' >> creature.__init__(self) >> > > There's a problem with Chaz's __init__() method. Notice that the > creature class's __init__ sets self.noise to the empty string. In this > case, the superclass's __init__() method should be called first: > > class dog(creature): > def __init__(self): > creature.__init__(self) > self.noise = "bark" > def voice(self): > print "brace your self:" > creature.voice(self) > > --Jason > Very true....I was showing him in "spirit only"...lol. Chaz. From jzgoda at o2.usun.pl Fri Aug 4 01:23:30 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 04 Aug 2006 07:23:30 +0200 Subject: Can Your Programming Language Do This? Joel on functional programming and briefly on anonymous functions! In-Reply-To: <1hjikws.n7a5lfm2v0yuN%aleax@mac.com> References: <kg33d21jvu9g5mhabvcvtm1irhq8e8unvq@4ax.com> <eatbr5$9bl$1@atlantis.news.tpi.pl> <1hjikws.n7a5lfm2v0yuN%aleax@mac.com> Message-ID: <eaulp8$r7p$1@nemesis.news.tpi.pl> Alex Martelli napisa?(a): >>>Joel on functional programming and briefly on anonymous functions! >>> >>>http://www.joelonsoftware.com/items/2006/08/01.html >> >>Ridiculos. That's how single-programming-mood people react when they >>find that you can program in procedural or functional way and get your >>work done. I always had a fun seeing these "all-java-kids" fighting >>CRTJVAPGM or RUNJVAPGM on OS/400. ;) > > Uh?-( Are you calling *Joel* an "all-java kid"?! He's an old clunker, > just like me!, and HIS background is primarily in C and some kind of > LISP -- he makes that quite clear in some of his books. I am sure he wouldn't have a hard time on OS/400. I think he shows a bit of exaggeration in this article, as he is too smart to believe that the world is all object-oriented, but this is writer's right to grab readers attention. This "all-java-kids" was a remark to his statement from some earlier article (mentioned also in this one), where he writes on people being taught only java on programming courses. -- Jarek Zgoda http://jpa.berlios.de/ From cginboston at hotmail.com Thu Aug 24 16:44:12 2006 From: cginboston at hotmail.com (Chaz Ginger) Date: Thu, 24 Aug 2006 20:44:12 GMT Subject: When is a subclass not right? In-Reply-To: <mailman.9826.1156450885.27775.python-list@python.org> References: <1156387621.568779.191420@m73g2000cwd.googlegroups.com> <1156393371.550249.138930@75g2000cwc.googlegroups.com> <1156394781.155152.313080@i3g2000cwc.googlegroups.com> <Xns98293000DF07castleamber@130.133.1.4> <44ede9b8$0$8925$88260bb3@free.teranews.com> <Xns982990962CE4castleamber@130.133.1.4> <w0nHg.2718$HW1.1810@trndny03> <mailman.9826.1156450885.27775.python-list@python.org> Message-ID: <44EE0F9C.1030200@hotmail.com> Gabriel Genellina wrote: > At Thursday 24/8/2006 16:23, Chaz Ginger wrote: > >> I was writing some code that used someone else class as a subclass. He >> wrote me to tell me that using his class as a subclass was incorrect. I >> am wondering under what conditions, if ever, does a class using a >> subclass not work. >> >> class B1(A); >> def __init__(self,a1,a2) : >> self.c = a1 >> A.__init__(self,ag) >> >> class B2: >> def __init__(self,a1,a2): >> self.c = a1 >> self.t = A(a2) >> >> def bar(self) : >> self.t.bar() >> >> Other than the obvious difference of B2 having an attribute 't', I can't >> see any other obvious differences. Is there something I am missing? > > Look any OO book for the difference between 'inheritance' and > 'delegation'. In short, you should inherit when B 'is an' A (a Car is a > Vehicle), and delegate/compose in other cases (a Car has an Engine; or > more precisely, a Car instance has an Engine instance). > > > Gabriel Genellina > Softlab SRL > > > p5.vert.ukl.yahoo.com uncompressed Thu Aug 24 19:27:05 GMT 2006 > > __________________________________________________ Pregunt?. Respond?. > Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en > Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas That is merely a logical use of OO after all when would a car and an orange be the same? I was wondering more about the mechanics of Python: when does B1 show different characteristics than B2 (forgoing the obvious simple things, like 't' above). Chaz From fredrik at pythonware.com Fri Aug 25 02:25:44 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Aug 2006 08:25:44 +0200 Subject: pickling and endianess In-Reply-To: <c56a14170608242317p10facdadl5beef9b6d2aa0130@mail.gmail.com> References: <c56a14170608242219t764fa281x74e1eb4725a1ac68@mail.gmail.com> <1f7befae0608242304p3ad8cffdh123f3577daa78dca@mail.gmail.com> <c56a14170608242317p10facdadl5beef9b6d2aa0130@mail.gmail.com> Message-ID: <ecm558$f59$1@sea.gmane.org> Chandrashekhar Kaushik wrote: > Thank you for the information. > A request though. > > I am actually looking to implement serialization routines in C++. > An am facing the problem of how to tackle endianess and sizeof issues. > > Could you give me a overview of how pickling is done in python ? Reading > pickle.py is obviously the option , but its getting daunting as i am not > that proficient in python :( . wouldn't it make more sense to *use* an existing C++ serialization library ? e.g. http://www.boost.org/libs/serialization/doc/index.html (or at least look at that one, or one of the other libraries linked from that page, instead of asking Python developers to help you solve a C++ task.) </F> From bobrien18 at yahoo.com Tue Aug 15 12:49:47 2006 From: bobrien18 at yahoo.com (KraftDiner) Date: 15 Aug 2006 09:49:47 -0700 Subject: file object and eof Message-ID: <1155660586.941712.114410@b28g2000cwb.googlegroups.com> I open a file in python by f = open('filename', mode='rb') how can I tell if I am at the end of file? f.eof() isn't implmented. How can I implement its functionallity? Thanks. B. From mlacunza at gmail.com Thu Aug 24 14:43:07 2006 From: mlacunza at gmail.com (Mario Lacunza) Date: Thu, 24 Aug 2006 13:43:07 -0500 Subject: [wxPython-users] [ANN]UliPad 3.3 is released In-Reply-To: <mailman.9759.1156396752.27775.python-announce-list@python.org> References: <mailman.9759.1156396752.27775.python-announce-list@python.org> Message-ID: <771741b20608241143i673ef58fo205621c373fca8bb@mail.gmail.com> Hi, Is possible then you correct the path for download the sources Zip file?? I want to test this tool but I dont could donwload it... Thansk! 2006/8/23, limodou <limodou at gmail.com>: > > What's it? > ======== > > It's an Editor based on wxPython. NewEdit is the old name, and UliPad > is the new name. UliPad uses Mixin and Plugin technique as its > architecture. Most of its classes can be extended via mixin and plugin > components, and finally become an integrity class at > creating the instance. So UliPad is very dynamic. You can write the > new features in new files, and hardly need to modify the existing > code. And if you want to extend the existing classes, you could write > mixins and plugins, and this will be bound to the target class that I > call "Slot Class". This technique will make the changes centralized > and easily managed. > > What are its features? > ================ > > * Cross platform > o based on wxPython, so it can run anywhere that wxPython > works, such as: Windows, Linux. > o Unicode support. > > * Most features of wxStyledTextCtrl(Scintilla) > o Syntax highlighting, support Python, c/c++, html, plain > text, perl, ruby, css, javascript > o Folding > o Brace Matching > o ... > > * Extended selection > o Extended word selection -- You can press > Ctrl+MouseDoubleClick to select a word including '.' > o Matched selection -- Select text in quoted chars like: > (), [], {}, '', "". > * Other editing extension > o Duplicating text -- Just like Vim Ctrl+V, Ctrl+P, and > more. You can duplicate above or below char, word, line > o Quoting text -- Add some quoted chars before and after > selected text, just as: "", '', (), [], {}, and > o Text convertion and view -- python -> html, reStructured > Text -> html, textile -> html, and you can output or view > o Utf-8 encoding auto detect > o Changing document encoding > o Auto backup > o Last session support -- It'll save all the filenames as > closed, and reopen the files as next started. > o Smart judge the indent char -- It'll auto guess the > indent char, and sets it. > o Finding in files > o Bookmark support > > * Python support > o built-in python interactive window based on ?PyShell, > support Unicode > o Auto completion > o Function syntax calltips > o Run, run with argument, stop python source > o Auto change current path > o Python class browser > o Indent pasting support(New) > > * Code snippets > o You can manage your code snippets with categories, and > each category can have many items. Every item will represent a code > snippet. You can insert an item just by double-clicking on it. It even > supports importing and exporting. > > * Simple project support > o Can create a special file _project, so every file and > folder under the folder which has the _project can be considered as a > whole project. > > * Extension mechanism > o Script -- You can write easy script to manipulate the all > resource of UliPad, just like: text conversion, etc. > o Plugin -- Customized function. More complex but more > powerful. Can easily merge with UliPad, and can be managed via menu. > o Shell command -- Add often used shell commands, and execute > them. > > * Ftp support > o You can edit remote files through ftp. You can add, > rename, delete, upload, download file/directory. > > * Multilanguage support > o Currently supports two languages: English and Chinese, > which can be auto-detected. > > * Shipped plugins(must be configed as used them before) > o Document links -- Python documentation and wxPython > documentation. > o Many plugins can be found at UliPad wiki page. > > * Shipped scripts > o Many scripts can be found at UliPad wiki page. > > * Wizard (New) > o You can make your own wizard template. The wizard can > input user data, combine with template, and output the result. And > wizard also support code framework created. This feature will help you > improving coding efficiency. > > * Direcotry Browser(New) > o Browse multiple directories, and you can really add, > delete, rename directories and files. Double click will open the file > in Editor window. > o Support Copy, Cut, and Paste. > o Search in Directory > > * AutoComPlete(acp)(New) > o Suport user autocomplete file, it can help to input code > very helpful and functional. Just like EditPlus, but may be more > powerful. > o Manually apply some acp files to current document > > * Column Edit Mode(New) > > Where to download it? > ================ > > download lastest version 3.3: > > http://wiki.woodpecker.org.cn/moin/UliPad?action=AttachFile&do=get&target=UliPad_3.3.zip > also have windows installer: > > http://wiki.woodpecker.org.cn/moin/UliPad?action=AttachFile&do=get&target=UliPad3.3.exe > wiki: http://wiki.woodpecker.org.cn/moin/UliPad > svn: http://cvs.woodpecker.org.cn/svn/woodpecker/ulipad/trunk > maillist: http://groups.google.com/group/ulipad > > If you have any problem as using UliPad, welcome to join the UliPad > maillist to discuss. > > Hope fun! > > > > -- > I like python! > My Blog: http://www.donews.net/limodou > My Django Site: http://www.djangocn.org > NewEdit Maillist: http://groups.google.com/group/NewEdit > > --------------------------------------------------------------------- > To unsubscribe, e-mail: wxPython-users-unsubscribe at lists.wxwidgets.org > For additional commands, e-mail: wxPython-users-help at lists.wxwidgets.org > > -- Saludos / Best regards Mario Lacunza Desarrollador de Sistemas - Webmaster Desarrollador 2 Estrellas VS2005 Email: mlacunza [AT] gmail [DOT] com Website: mlacunzav[AT]cogia[AT]net Blog: http://mlacunza.blogspot.com/ Lima - Peru -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060824/6d315e88/attachment.html> From pavlovevidence at gmail.com Tue Aug 22 18:02:29 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 22 Aug 2006 15:02:29 -0700 Subject: Can, and if yes how could this be done elegant? References: <d07sr3-g58.ln1@darkstargames.dnsalias.net> Message-ID: <1156284149.058038.227460@75g2000cwc.googlegroups.com> Wolfgang Draxinger wrote: > I'm currently developing vegetation creation scripts for the > Blender 3D modelling software. The first attempts work nice, but > they're far to inflexible IMHO. > > First let me introduce how the system works: The user supplies a > series of building elements of the plants to be generated (e.g. > stem, stipe, leaf, branches, blossom) and associated those with > template 3D models. For each of those elements there is a list, > which elements can be attached with the current element, and a > probability function, that takes the various parameters for the > element to be constructed (distance to the last branch, distance > to the root, thickness of the last stipe, how much light is > there). Then a pseudo random generator chooses one of the given > elements with the given probability, the element is aligned to > various physical conditions (gravity, light direction). It is > important, that the tree is constructed with a equal distance to > the root, i.e. not whole branches and subbranches at a time, but > first branching level 0, then level 1 and so on. The reason is, > that with every construction level some of the environment > condictions (weight of the material, amount of light) change, so > it's reasonable, that the grow process of the virtual plant > resembles the real one, even if it's a simplified modell. > > Now one cool thing would be, if one could use python to describe > the plant model itself, too. > > Since the Elements are not to be instanciated, but a collection > of parameters and functions that are fed with the environment > variables. > > class Branch(BasicPlantElement): > def p(): > return light_scale * light()**light_exponent * > k/distance_to_root() > def geom(): > return (light_track * light_vector() - weight() * gravity(), > position()) > > But obviously this is not valid python (it lacks the self > argument). One might now think of a dictionary > > Branch = { "p"=lambda:..., "geom"=lambda:..., } > > If you look closely, you also see, that the functions are not > prameterized. Instead, they use some global scope functions. > Here the idea is, that the environment parameters are put on a > stack and each recursion copies the topmost element on the stack > and changes happening there are carried on the stack. But this > is of course very memory consuming. But the real problem is, to > bring those values somehow into the scope of the PED (Plant > Element Descriptor) > > Now the challenge: > - I'd like to write the Plant Element Descriptors in a > class/member like notation, but don't instanciate it - not > directly at least. Eventually there will be factory functions, > that take a PED and create a reparameterized version of it. > - Calling the functions in the PED somehow needs to bring the > branching stack into the scope. I have no idea how to do that. > > Of course all this might not be possible directly, but that would > then mean, that I can't use python to describe plants, but have > to invent a custom language for that then. (Something like POV > Scene Description Language or similair). Let me see if I understand: You have a bunch of physical parameters (gravity, light direction,etc.). Every time you recurse to a deeper level, all these physical parameters change (I suppose because there's a transformation of coordinates). When creating a new Branch, using some data called Element as a kind of template, you want to first update the parameters to their new values, then use those parameters to create a new Branch. And you hope that you can do both things (update parameters, generate branch) with a single class. How close am I? You're doing this recursively, so there's really no way to get rid of the stack entirely. I don't know much about your code, but I quite doubt that it would put much strain your memory at all. We can, perhaps, help you organize your code better, though. But I think you'll need to make another pass at describing your problem. Carl Banks From Bulkan at gmail.com Thu Aug 10 23:25:38 2006 From: Bulkan at gmail.com (placid) Date: 10 Aug 2006 20:25:38 -0700 Subject: ALLAH In-Reply-To: <1155117922.061942.100370@n13g2000cwa.googlegroups.com> References: <1155117922.061942.100370@n13g2000cwa.googlegroups.com> Message-ID: <1155266738.533763.229330@p79g2000cwp.googlegroups.com> faruk.nur at mynet.com wrote: > > Ey insanlar ve cinler ezeli ve ebedi cennete girmek,ebedi ya?amak,her > istedi?ini yapmak ve Allah'? g?rmek istemezmisiniz. > Ey sevgili ruh,bunun i?in Allah'a ??kretmeli ve iman etmeli > de?ilmisin. > > HULASA : > Allah,birdir, hi?bir?eye ihtiyac? yoktur,ne birba?kas? O'nu > yaratm??t?r nede O'nun bir ?ocu?u vard?r.O'nun e?i ve > benzeri yoktur. I dont know why post a subject like this here! Anyway, the post is in Turkish and talks about Islam, with the format, sub-heading (which is a main topic in Islamic belief) and then a story relating to the sub-heading, which is used to explain the topic. <rough translation of above> Humans and ghosts(?translation) dont you want to enter infinite Heaven, be immortal do anything you want and see God? Beatiful soul! For this give thanks to God and pray Thus; God is single, needs nothing, no one has created God, and has no child. God has no one like HIM. </translation> Cheers From tim.golden at viacom-outdoor.co.uk Wed Aug 2 11:36:51 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 2 Aug 2006 16:36:51 +0100 Subject: Windows vs. Linux Message-ID: <CCAC78D42E32184F8E26DC163DB98306C1B333@vogbs009.gb.vo.local> | bryanjugglercryptographer at yahoo.com wrote: | | >>From a WinXP command prompt: | > | > C:\> | > C:\>cd /windows/system32 | > | > C:\WINDOWS\system32> | > | > | Not from my Windows XP command prompt it doesn't. Do you have | anything | strange installed on your system? FWIW: <dump> Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. c:\temp>cd \ C:\>cd /windows/System32 C:\windows\system32> </dump> TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From duncan.booth at invalid.invalid Tue Aug 29 16:02:00 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 29 Aug 2006 20:02:00 GMT Subject: Generator chaining? References: <ed259i$mvn$1@news2.netvision.net.il> Message-ID: <Xns982ED5FA1687Eduncanbooth@127.0.0.1> John Doe wrote: > This is sort of a feature request/idea: Chaining generators. > > If you have two lists (or tuples) and you add them, the result is a > concatenation of the two. > I think it would be nice if it was possible to do something similar with > generators. The best way to explain is by code example: > > def add_generators(gen1, gen2): > for x in gen1: > yield x > for y in gen2: > yield y > > Just a thought... > itertools.chain From johnjsal at NOSPAMgmail.com Thu Aug 10 10:22:56 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 10 Aug 2006 14:22:56 GMT Subject: converting a nested try/except statement into try/except/else In-Reply-To: <44da5e3f$0$19111$626a54ce@news.free.fr> References: <s8qCg.2663$No6.52066@news.tufts.edu> <44da4329$0$702$626a54ce@news.free.fr> <44da5e3f$0$19111$626a54ce@news.free.fr> Message-ID: <4jHCg.2669$No6.52073@news.tufts.edu> Bruno Desthuilliers wrote: > try: > if int(text) <= 0: raise ValueError > except ValueError: > self.error_message() > return False > else: > return True Nice! Thanks! From dylanhughes at gmail.com Thu Aug 24 10:58:36 2006 From: dylanhughes at gmail.com (DH) Date: 24 Aug 2006 07:58:36 -0700 Subject: Taking data from a text file to parse html page In-Reply-To: <mailman.9767.1156402497.27775.python-list@python.org> References: <1156378275.662140.214650@h48g2000cwc.googlegroups.com> <mailman.9767.1156402497.27775.python-list@python.org> Message-ID: <1156431516.121577.282890@b28g2000cwb.googlegroups.com> Frederic, Good points... I have a plain text file containing the html and words that I want removed(keywords) from the html file, after processing the html file it would save it as a plain text file. So the program would import the keywords, remove them from the html file and save the html file as something.txt. I would post the data but it's secret. I can post an example: index.html (html page) " <div><p><em>"Python has been an important part of Google since the beginning, and remains so as the system grows and evolves. "</em></p> <p>-- Peter Norvig, <a class="reference" " replace.txt (keywords) " <div id="quote" class="homepage-box"> <div><p><em>" "</em></p> <p>-- Peter Norvig, <a class="reference" " something.txt(file after editing) " Python has been an important part of Google since the beginning, and remains so as the system grows and evolves. " Larry, I've looked into using BeatifulSoup but came to the conculsion that my idea would work better in the end. Thanks for the help. Anthra Norell wrote: > DH, > Could you be more specific describing what you have and what you want? You are addressing people, many of whom are good at > stripping useless junk once you tell them what 'useless junk' is. > Also it helps to post some of you data that you need to process and a sample of the same data as it should look once it is > processed. > > Frederic > > ----- Original Message ----- > From: "DH" <dylanhughes at gmail.com> > Newsgroups: comp.lang.python > To: <python-list at python.org> > Sent: Thursday, August 24, 2006 2:11 AM > Subject: Taking data from a text file to parse html page > > > > Hi, > > > > I'm trying to strip the html and other useless junk from a html page.. > > Id like to create something like an automated text editor, where it > > takes the keywords from a txt file and removes them from the html page > > (replace the words in the html page with blank space) I'm new to python > > and could use a little push in the right direction, any ideas on how to > > implement this? > > > > Thanks! > > > > -- > > http://mail.python.org/mailman/listinfo/python-list From johnjsal at NOSPAMgmail.com Tue Aug 8 15:08:59 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 08 Aug 2006 19:08:59 GMT Subject: #!/usr/bin/python or #!/usr/bin/env python? Message-ID: <fj5Cg.2658$No6.51984@news.tufts.edu> I understand the difference, but I'm just curious if anyone has any strong feelings toward using one over the other? I was reading that a disadvantage to the more general usage (i.e. env) is that it finds the first python on the path, and that might not be the proper one to use. I don't know if that's a real issue most of the time, but it's at least something to consider. And is Python found in directories other than /usr/bin often enough to justify using the more general form? From bob at passcal.nmt.edu Mon Aug 14 13:14:09 2006 From: bob at passcal.nmt.edu (Bob Greschke) Date: Mon, 14 Aug 2006 11:14:09 -0600 Subject: tkinter: Button color Solaris/Linux References: <luydnW5-6-gTNX3ZnZ2dnUVZ_rudnZ2d@nmt.edu> Message-ID: <nYidnWKdV77QMn3ZnZ2dnUVZ_vadnZ2d@nmt.edu> "Bob Greschke" <bob at passcal.nmt.edu> wrote in message news:luydnW5-6-gTNX3ZnZ2dnUVZ_rudnZ2d at nmt.edu... >I have a GUI where the background of the "GO" button, for example, turns >green while the associated action is running. On Windows it works fine, >but on Solaris and Linux the button background turns white (or whatever) >when the mouse pointer enters the button, the background stays that color >while Button-1 is being held down, and the background continues to stay >that color when Button-1 is released. The background only turns green when >the user moves the pointer off of the button. Can that be fixed, or is >that an X-Windows thing? > > Thanks! > > Bob activebackground. At least this time it was a couple of minutes after the Return key was pressed. :) Bob From schaffer at optonline.net Thu Aug 31 11:24:20 2006 From: schaffer at optonline.net (Les Schaffer) Date: Thu, 31 Aug 2006 11:24:20 -0400 Subject: GC and security In-Reply-To: <7xlkp5h91p.fsf@ruckus.brouhaha.com> References: <44F61EEB.8040207@optonline.net> <7x4pvtpxnc.fsf@ruckus.brouhaha.com> <44F63356.6060400@optonline.net> <7xlkp5h91p.fsf@ruckus.brouhaha.com> Message-ID: <iaDJg.9$062.6@newsfe10.lga> Paul Rubin wrote: > GC simply releases the memory for other uses in the application. It > doesn't necessarily zero the memory. release is followed by some probability of eventual overwrite; check. > > Just what attack are you trying to protect against, if swap space is > less of a problem than leaving keys around in ram? keys are on a USB drive key ring. gpg accesses the key ring as needed, but in a separate process. and gpg is done with its work early on in our app lifetime. comes back at end to encrypt and then app is done. > Keep in mind that the weakest part of this application is likely to be > the passphrase itself. Is there a way to get rid of it? we got some suggestions from other parts of this thread. or do you mean getting rid of the need for a passphrase? the passhprase protects the private key on the USB drive. > Is this data on a laptop? Why do you want to do encryption in the > application, instead of using an encrypted file system? i looked at EFS and TrueCrypt. There was some questions (from MySQL pro) about how MySQL writes would interact with EFS. also, EFS seems to store key pairs on disk, and the passphrase was limited to the Windows user login password. i remember looking at TrueCrypt and deciding against it. couldn't see how to interact with it via python script. vaguely recall being dissatisfied with keys and passphrase. but the main reason? we were asked to encrypt the MySQL tables carrying sensitive information. > Is there some > obstacle to using a token (like a smart card) to hold the key? USB drive holds the GPG key. the drive must be inserted at start of application, and must be pulled after authentication otherwise the app warns and shuts down. The USB drive carries a digital signature, and also encrypted identifying information for the user. Les Schaffer From apardon at forel.vub.ac.be Fri Aug 4 13:06:26 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Aug 2006 17:06:26 GMT Subject: Nested function scope problem References: <20060804094245.A9AF.SLAWOMIR.NOWACZYK.847@student.lu.se> <1okvniwl5zgqj.dlg@gelists.gmail.com> <mailman.8983.1154702472.27775.python-list@python.org> <slrned6ovc.vkd.apardon@rcpc42.vub.ac.be> <mailman.8996.1154709878.27775.python-list@python.org> Message-ID: <slrned6vkh.9p.apardon@rcpc42.vub.ac.be> On 2006-08-04, Gerhard Fiedler <gelists at gmail.com> wrote: > On 2006-08-04 12:12:44, Antoon Pardon wrote: > >>> That's possible. I wouldn't expect too many C programmers to have any >>> notion of "id of a variable". I, for example, never thought about such >>> thing before this thread. >> >> But even in Python we don't speak of "id of a variable". It is not the >> variable that has an id. It is the object that is currently attached to >> the variable that has an id. Yes we can use "id of a variable" as a >> shortcut for the correct formulation as long as you keep in mind that it >> is not the variable itself that has an id. > > This sounds a bit like saying "yes we can use the term 'variable' as a > shortcut for the correct formulation (object associated to a name) A variable is not an object associated to a name. It is not the object that is the variable. > as long as we keep in mind that it is not actually a variable" :) Variable is a term that comes from mathematics. No language variable is exactly like the mathematical notion, but if I had to choose I would say that lisp, smalltalk and python variables come closer than C, ada or pascal variables. -- Antoon Pardon From deets at nospam.web.de Thu Aug 3 08:55:18 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 03 Aug 2006 14:55:18 +0200 Subject: Datetime question In-Reply-To: <1154607991.404201.23400@p79g2000cwp.googlegroups.com> References: <1154607991.404201.23400@p79g2000cwp.googlegroups.com> Message-ID: <4jea1mF7kic5U1@uni-berlin.de> Lad schrieb: > In a datetime object I would like to change days and hours. > Or in other words, I would like to copy this datetime object but > increase days and hours. > Is it possible? > For example:If I have a datetime object like this > datetime.datetime(2006, 8, 3, 14, 13, 56, 609000) > > I would like to make a new ,for example like this > > datetime.datetime(2006, 8, 12, 10, 13, 56, 609000) > > is it possible to do so? you'd been pointed to the resources yesterday - please read manuals carefully! a = datetime.datetime(2006, 8, 12, 10, 13, 56, 609000) b = a + datetime.timedelta(days=-2, hours=-4) Diez From paul at boddie.org.uk Wed Aug 23 13:01:32 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 23 Aug 2006 10:01:32 -0700 Subject: Python and STL efficiency References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <eccb9u$kjs$1@gemini.csx.cam.ac.uk> <1hkh28d.xscw4v1y4v9a6N%riko@despammed.com> <mailman.9640.1156247569.27775.python-list@python.org> <1hkh6lb.6dsnh51lj8z96N%riko@despammed.com> <1156252193.524186.107520@b28g2000cwb.googlegroups.com> <1156299389.336939.211670@i42g2000cwa.googlegroups.com> <1hkildy.73vcuzyxlsgeN%riko@despammed.com> <1156319484.165195.80540@p79g2000cwp.googlegroups.com> <mailman.9714.1156351329.27775.python-list@python.org> Message-ID: <1156352492.186304.303580@m73g2000cwd.googlegroups.com> skip at pobox.com wrote: > >> Yes it is. But of course you can't sat that "Python is faster than > >> C++". > > Harald> Of course not. Python is faster then assembler. Proofed @ > Harald> EuroPython 2006 in CERN, near the LHC Beta, in the same room > Harald> many Nobel laurates gave their presentations before. > > Harald, do you have a reference to a talk abstract or a paper? Via the lightning talks page: http://wiki.python.org/moin/EuroPy2006LightningTalks Here's a direct link: http://wiki.python.org/moin/EuroPy2006LightningTalks?action=AttachFile&do=get&target=%3AFasterThenAssemblerLightning.odp Of course, Harald's interpretation of the "faster than" qualification is broader than a pure assessment of raw performance, so I wouldn't expect too many technical revelations. And while footage exists of at least one talk in the CERN Auditorium which led to a Nobel prize, I don't think that any footage of the EuroPython lightning talks (or of any of the other talks) has been released just yet. Paul From amichail at gmail.com Sun Aug 27 10:51:18 2006 From: amichail at gmail.com (Amir Michail) Date: 27 Aug 2006 07:51:18 -0700 Subject: avoiding file corruption References: <1156664673.325201.271140@i42g2000cwa.googlegroups.com> <12f3bo1t1ccr858@corp.supernews.com> Message-ID: <1156690278.496811.221660@b28g2000cwb.googlegroups.com> Grant Edwards wrote: > On 2006-08-27, Amir Michail <amichail at gmail.com> wrote: > > > Trying to open a file for writing that is already open for writing > > should result in an exception. > > MS Windows seems to do something similar, and it pisses me off > no end. Trying to open a file and read it while somebody else > has it open for writing causes an exception. If I want to open > a file and read it while it's being writtent to, that's my > business. > > Likewise, if I want to have a file open for writing twice, > that's my business as well. I certainly don't want to be > hobbled to prevent me from wandering off in the wrong direction. > > > It's all too easy to accidentally open a shelve for writing > > twice and this can lead to hard to track down database > > corruption errors. > > It's all to easy to delete the wrong element from a list. It's > all to easy to re-bind the wrong object to a name. Should > lists be immutable and names be permanently bound? > How often do you need to open a file multiple times for writing? As a high-level language, Python should prevent people from corrupting data as much as possible. Amir > -- > Grant Edwards grante Yow! I'm in a twist > at contest!! I'm in a > visi.com bathtub! It's on Mars!! I'm > in tip-top condition! From taleinat at gmail.com Fri Aug 4 06:23:31 2006 From: taleinat at gmail.com (taleinat) Date: Fri, 4 Aug 2006 10:23:31 +0000 (UTC) Subject: help - iter & dict References: <1154641320.44d26da8d8605@www1.helsinki.fi> Message-ID: <loom.20060804T121653-822@post.gmane.org> <aking <at> mappi.helsinki.fi> writes: > CDSitdict = {28.473823598317392: "'2.4869999999999832'", 40.06163037274758: > "'0.2910000000000002'", 27.756248559438422: "'2.8349999999999964'", > 33.2299196586726: "'1.1249999999999962'", 29.989685187220061: > "'1.9139999999999677'", 31.502319473614037: "'1.490999999999983'", > 28.487341570327612: "'2.480999999999983'", 30.017763818271245: > "'1.9049999999999681'", 32.943466663842266: "'1.1789999999999943'", > 30.520103712886584: "'1.7519999999999736'", 31.453205956498341: > "'1.5029999999999826'", 29.484222697359598: "'2.084999999999968'", > 28.413513489228706: "'2.5139999999999842'", 28.314852455260802: > "'2.558999999999986'", 28.652931545003508: "'2.4089999999999803'"} > > heres the error i get after entering Cpcb > > Traceback (most recent call last): > File "elementalDS.py", line 156, in ? > CDS = findClosest(CDSitdict, Cpcb) > File "elementalDS.py", line 142, in findClosest > distance = (target - v) ** 2 > TypeError: unsupported operand type(s) for -: 'float' and 'str' > alicat <at> linux:~/Desktop> The Python interpreter is being friendly and explaining exactly what the problem is and where it occured. It's telling you that it can't subtract a string from a float, in line 142 of your code (in the findClosest function). So the problem is that 'target' is a float while 'v' is a string. 'v' should be a float as well, but it's a string since the values in your dictionary are strings instead of numbers. Try removing the quotes around the values in your dict (both the double-quotes and the single-quotes). From steve at holdenweb.com Tue Aug 22 09:41:42 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 22 Aug 2006 14:41:42 +0100 Subject: How to get database metadata information (i.e. existing tables and columns in tables) In-Reply-To: <1156248215.222902.60330@i3g2000cwc.googlegroups.com> References: <1156248215.222902.60330@i3g2000cwc.googlegroups.com> Message-ID: <ecf1hq$des$2@sea.gmane.org> Chris Brat wrote: > Hi, > > Is it possible to retrieve details about the database, specifically a > list of the tables in the database; and then to retrieve the columns > and their types for the tables? > > Is this dependant on the database? > As far as locating the field names goes, this should work with most DBAPI modules: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81189 thought hat doesn't help wiht getting the table names ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From fredrik at pythonware.com Sat Aug 19 01:54:55 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 19 Aug 2006 07:54:55 +0200 Subject: efficient memoize decorator? In-Reply-To: <1155931932.349283.27700@h48g2000cwc.googlegroups.com> References: <1155931932.349283.27700@h48g2000cwc.googlegroups.com> Message-ID: <ec693f$r5f$1@sea.gmane.org> thattommyhallll at gmail.com wrote: > all of the memoize decorators at the python cookbook seem to make my > code slower. if you want good performance, use the following pattern: def col(n, count, memo={}): try: return memo[n, count] except KeyError: # ... calculate value ... memo[n, count] = value return value for some access patterns, the following may be faster: def col(n, count, memo={}): value = memo.get((n, count)) if value is None: # ... calculate value ... memo[n, count] = value return value to get maximum performance, make the memo dictionary public, and make the check at the original call site. > is using a decorator a lazy and inefficient way of doing memoization? lazy, yes. inefficient? it depends. </F> From johnjsal at NOSPAMgmail.com Tue Aug 1 09:48:45 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 01 Aug 2006 13:48:45 GMT Subject: first book about python In-Reply-To: <mailman.8785.1154417048.27775.python-list@python.org> References: <mailman.8785.1154417048.27775.python-list@python.org> Message-ID: <1ZIzg.2611$No6.51371@news.tufts.edu> wesley chun wrote: > if you want a large case study (tons of > examples, i.e., everything *plus* the kitchen sink), look for Lutz' > massive Programming Python. which is also coming out in a new edition soon From luismgz at gmail.com Wed Aug 2 16:10:36 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 2 Aug 2006 13:10:36 -0700 Subject: Programming newbie coming from Ruby: a few Python questions In-Reply-To: <1154539652.256975.155200@i3g2000cwc.googlegroups.com> References: <mailman.8824.1154472963.27775.python-list@python.org> <1154494954.082706.283750@b28g2000cwb.googlegroups.com> <44d06f9f$0$19127$626a54ce@news.free.fr> <1154539223.873418.286830@i42g2000cwa.googlegroups.com> <1154539652.256975.155200@i3g2000cwc.googlegroups.com> Message-ID: <1154549436.073418.202840@s13g2000cwa.googlegroups.com> BartlebyScrivener wrote: > simonharri... at fastmail.co.uk wrote: > > >> The Ruby crowd says you guys are no where > >> near as friendly as them! > > Slander! Defamation! The time to crush our enemies has come. This is the Jihad! Death to the infidels!!!! From miki.tebeka at gmail.com Tue Aug 22 09:07:50 2006 From: miki.tebeka at gmail.com (Miki) Date: 22 Aug 2006 06:07:50 -0700 Subject: How to get database metadata information (i.e. existing tables and columns in tables) In-Reply-To: <1156248215.222902.60330@i3g2000cwc.googlegroups.com> References: <1156248215.222902.60330@i3g2000cwc.googlegroups.com> Message-ID: <1156252070.197671.239430@m79g2000cwm.googlegroups.com> Hello Chris, > Is it possible to retrieve details about the database, specifically a > list of the tables in the database; and then to retrieve the columns > and their types for the tables? > > Is this dependant on the database? Yes and Yes. However some toolkits like SQLObject (http://www.sqlobject.org/) and SQLAlchemy (http://www.sqlalchemy.org/) can do this work for you (IIRC). HTH, Miki http://pythonwise.blogspot.com/ From giles_brown at hotmail.com Fri Aug 25 05:30:48 2006 From: giles_brown at hotmail.com (Giles Brown) Date: 25 Aug 2006 02:30:48 -0700 Subject: how do you get the name of a dictionary? In-Reply-To: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> Message-ID: <1156498248.861054.106440@m79g2000cwm.googlegroups.com> jojoba wrote: > Does anyone know how to find the name of a python data type. > Conside a dictionary: > Banana = {} > > Then, how do i ask python for a string representing the name of the > above dictionary (i.e. 'Banana')? As many people have already said this question doesn't really make sense, but I thought I'd add my explanation of why in the hope that it might help... Think of python objects as being like mobile phones. They only really have a number. Asking what their name is like asking for the name of a mobile phone (bluetooth excepted). A particular mobile phone only has a name when entered into the address book (aka namespace) of another mobile (or whatever) and the choice of name is down to the owner of the address book. Now I'm going to eat my cake. Giles From zxo102 at gmail.com Mon Aug 14 11:35:14 2006 From: zxo102 at gmail.com (zxo102) Date: 14 Aug 2006 08:35:14 -0700 Subject: why the method get() of python Queue is hang on there? In-Reply-To: <1155568212.888733.79920@b28g2000cwb.googlegroups.com> References: <1155568212.888733.79920@b28g2000cwb.googlegroups.com> Message-ID: <1155569714.033758.94090@m79g2000cwm.googlegroups.com> Thanks for your guys. I got it. I thought Queue can be used anywhere in the code and the second b.get() would return a "None". Ouyang zxo102 ??? > Hi, > I am using Queue from python2.4. Here is what happen to me: > > import Queue > b = Queue.Queue(0) > b.put(9999) > b.get() # this is ok, it pops out 9999 > b.get() # this one does not return anything and is hang on there > > Anybody knows what is going on with the second b.get()? > > ouyang From bearophileHUGS at lycos.com Wed Aug 9 15:35:42 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 9 Aug 2006 12:35:42 -0700 Subject: Two Classes In Two Files In-Reply-To: <1155151480.848276.52650@75g2000cwc.googlegroups.com> References: <1155151480.848276.52650@75g2000cwc.googlegroups.com> Message-ID: <1155152142.709903.85490@n13g2000cwa.googlegroups.com> dhable at gmail.com: > Is there > a way to avoid having to use the "from xxx import yyy" syntax from > files in the same directory? You can just use: import xxx and then: class Two(xxx.One): ... If you don't want to use the import line, you have to put the two classes into the same module. Bye, bearophile From exarkun at divmod.com Wed Aug 16 19:25:34 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 16 Aug 2006 19:25:34 -0400 Subject: Anyone have a link handy to an RFC 821 compliant email address regex for Python? In-Reply-To: <1155769779.041598.17970@m79g2000cwm.googlegroups.com> Message-ID: <20060816232534.1717.1622367804.divmod.quotient.23800@ohm> On 16 Aug 2006 16:09:39 -0700, Simon Forman <rogue_pedro at yahoo.com> wrote: >fuzzylollipop wrote: >> I want to do email address format validations, without turning to ANTLR >> or pyparsing, anyone know of a regex that is COMPLIANT with RFC 821. >> Most of the ones I have found from google searches are not really as >> robust as I need them to be. > >Would email.Utils.parseaddr() fit the bill? > >http://docs.python.org/lib/module-email.Utils.html#l2h-3944 > This is for RFC 2822 addresses. http://divmod.org/trac/browser/sandbox/exarkun/smtp.py Jean-Paul From rmuschall at tecont.de Tue Aug 29 15:18:07 2006 From: rmuschall at tecont.de (Ralf Muschall) Date: Tue, 29 Aug 2006 21:18:07 +0200 Subject: time.clock() going backwards?? In-Reply-To: <12f64pkr124f358@corp.supernews.com> References: <vkFHg.82529$_J1.759243@twister2.libero.it> <ecnla4$fv2$1@sea.gmane.org> <mailman.9894.1156540900.27775.python-list@python.org> <dht4f25nlkc4outso2o30mpug033umdh8b@4ax.com> <ecu546$sn9$1@newsreader2.netcologne.de> <mailman.9975.1156776621.27775.python-list@python.org> <ecv2lg$mk1$1@newsreader2.netcologne.de> <12f6455mjvuqv72@corp.supernews.com> <12f64pkr124f358@corp.supernews.com> Message-ID: <ggges3-o77.ln1@prcm.tecont.de> Grant Edwards wrote: > This is a _Microsoft_Product_. There doesn't have to be a > reason for something to be done in a half-assed manner. No, it is a quantum effect. If the energy of a clock has a lower bound, there must be a nonzero probability for it to run backwards. See <93ld7n$gv0$1 at news.state.mn.us> SCNR, Ralf From tim.golden at viacom-outdoor.co.uk Tue Aug 22 04:09:40 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 22 Aug 2006 09:09:40 +0100 Subject: Add users to directory/folder and set permissions in Windows Message-ID: <CCAC78D42E32184F8E26DC163DB98306C1B3B1@vogbs009.gb.vo.local> [Adam Jones] | | Gallagher, Tim (NE) wrote: | > I was wondering if there was a way to add a user in active | directory to | > a folder and set the permissions. | | It should be possible. If you can use VBScript or JScript it will be | easier to find resources for those. You will probably need, at the | least, the win32 extension for Python, which you can find here: | http://www.python.net/crew/mhammond/win32/ | | A quick google search for "python active directory" turned up the | following page, which would probably also prove helpful: | http://tgolden.sc.sabren.com/python/ad_cookbook.html I must shamefacedly admit that the active_directory module which that page represents is a little stale. It does work, but I haven't even added in the one or two patches people have sent. Welcome to use it, but YMMV. Try searching the python-win32 archives for posts by Roger Upole (or anyone else) on the subject of AD and/or security. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From emmanuel.astier at gmail.com Sun Aug 13 15:38:24 2006 From: emmanuel.astier at gmail.com (eastier) Date: 13 Aug 2006 12:38:24 -0700 Subject: Py_Initialize crashes with winpdb Message-ID: <1155497904.212702.240750@74g2000cwt.googlegroups.com> Hi all, I've an application with embedded python. In order to reload the python scripts, I end the python session, and reopen one just after : <...release used modules...> Py_Finalize(); Py_Initialize(); <...Acquire relevant modules...> In order to debug the python script, I recently tried winPdb, which is pretty decent for a free debugger working with embedded python. So I just have : import rpdb2; rpdb2.start_embedded_debugger("toto", True) in my python script But when I use it, the Py_Finalize / Py_initialize sequence crashes in py_initialize. I didn't have Python sources to have more complete informations, but perhaps some one knows about this problem, and what I can do to avoid this ? When using a custom debugger, and a custom Trace function, is there something particular to do when Finalizing Python ? Any help really welcomed, Emmanuel From martin at v.loewis.de Mon Aug 28 12:48:16 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 28 Aug 2006 18:48:16 +0200 Subject: how to get the os file icon for a given content-type? In-Reply-To: <1156770929.202576.298640@m79g2000cwm.googlegroups.com> References: <1156753983.080547.306100@h48g2000cwc.googlegroups.com> <44f2b8cc$0$11818$636a55ce@news.free.fr> <1156759387.819060.266380@m73g2000cwd.googlegroups.com> <1156770929.202576.298640@m79g2000cwm.googlegroups.com> Message-ID: <44f31e50$0$17268$9b622d9e@news.freenet.de> Paul Boddie schrieb: > neoedmund wrote: > > [File icons for a given content type] > >> So what? Java 5.0 has the method, why python has not? > > I'd be generally surprised if whichever Java API responsible for this > managed to work it out correctly for the different free desktop > environments (KDE, GNOME, etc.) Just because nobody said it so far (although it's probably obvious to everybody): I doubt neoedmund is talking about free desktop environments... Regards, Martin From martin at v.loewis.de Mon Aug 7 08:14:14 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 07 Aug 2006 14:14:14 +0200 Subject: Subtyping a non-builtin type in C/C++ In-Reply-To: <1154822507.152920.182940@i3g2000cwc.googlegroups.com> References: <1154822507.152920.182940@i3g2000cwc.googlegroups.com> Message-ID: <44D72E96.6090703@v.loewis.de> johan2sson at gmail.com schrieb: > I am trying to create a subclass of a python class, defined in python, > in C++, but I am having some problems. Is the base class a classic class or a new-style class? Depending on the answer, the code you should write varies significantly. To create a new type, it might be easiest to do the same as the interpreter. Take, for example, a look at the code that gets executed for new.classobj("Foo", (), {}). Regards, Martin From jzgoda at o2.usun.pl Fri Aug 18 15:30:33 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 18 Aug 2006 21:30:33 +0200 Subject: MS SQL Server: NT Authentication. Possible? In-Reply-To: <mailman.9507.1155904737.27775.python-list@python.org> References: <mailman.9507.1155904737.27775.python-list@python.org> Message-ID: <ec54hj$e63$1@atlantis.news.tpi.pl> Tim Golden napisa?(a): > import adodbapi > > db = adodbapi.connect ("Provider=sqloledb;Data Source=VODEV1;Initial > Catalog=EVOBACK;Integrated Security=SSPI;") This kind of connection doesn't work for me. I think it's some misconfiguration on AD side, but I still get "not associated with trusted connection" and I don't know what to ask my sysadmin, so I'd rather stay with SQL login. -- Jarek Zgoda http://jpa.berlios.de/ From jaysherby at gmail.com Wed Aug 9 22:12:44 2006 From: jaysherby at gmail.com (jaysherby at gmail.com) Date: 9 Aug 2006 19:12:44 -0700 Subject: Easy image rendering? In-Reply-To: <mailman.9176.1155172834.27775.python-list@python.org> References: <1155166070.085423.37420@b28g2000cwb.googlegroups.com> <pan.2006.08.10.00.55.57.560672@users.sf.net> <1155172010.495135.274230@75g2000cwc.googlegroups.com> <mailman.9176.1155172834.27775.python-list@python.org> Message-ID: <1155175964.455569.198430@i42g2000cwa.googlegroups.com> I think that you've put me on the right track, but my eventual goal is to be able to put the pictures on the screen with a full-screen interface. Not in a visible window, with just the picture and then a black backdrop for it. skip at pobox.com wrote: > >> If you are using PIL you could use im.show(); but all that does is > >> saving the image data to a file and opening that file in an external > >> application (xv on UNIX). At least you don't have to do it yourself. > > jay> No good. No external applications. What else is there? Worst case > jay> scenario, what's the easiest way to do GUI? > > You can still use PIL. Just feed the result to Tkinter. Check out the > ImageTk module that's part of PIL: > > http://www.pythonware.com/library/pil/handbook/imagetk.htm > > Check this thread for some hints from Fredrik Lundh on combining PIL and > Tkinter: > > http://mail.python.org/pipermail/python-list/1999-July/007379.html > > I'm sure when he gets up in Europe he'll be able to provide some more useful > pointers. > > Skip From skip at pobox.com Fri Aug 25 11:00:56 2006 From: skip at pobox.com (skip at pobox.com) Date: Fri, 25 Aug 2006 10:00:56 -0500 Subject: How to handle wrong input in getopt package in Python? In-Reply-To: <1156516414.702940.50940@74g2000cwt.googlegroups.com> References: <1156516414.702940.50940@74g2000cwt.googlegroups.com> Message-ID: <17647.4264.661787.25530@montanaro.dyndns.org> Daniel> getopt.GetoptError: option --imageDir requires argument Which is precisely what the getopt module should do. Daniel> Is there any method in getopt or Python that I could easily Daniel> check the validity of each command line input parameter? Getopt already did the validity check for you. Just catch its exception, display a meaningful usage message, then exit, e.g.: try: o, a = getopt.getopt(sys.argv[1:], 'h', ['imageDir=']) except getopt.GetoptError, msg: usage(msg) raise SystemExit # or something similar My usual definition of usage() looks something like this: def usage(msg=""): if msg: print >>sys.stderr, msg print >>sys.stderr print >> sys.stderr, __doc__.strip() This will display the module-level doc string for the user. I find that a convenient place to document the usage of scripts. For more complex programs where command line arg processing is in a separate module you may have to do something like: def usage(msg=""): if msg: print >>sys.stderr, msg print >>sys.stderr import __main__ print >> sys.stderr, __main__.__doc__.strip() Skip From fredrik at pythonware.com Thu Aug 17 08:35:11 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 17 Aug 2006 14:35:11 +0200 Subject: PySequence_SetItem References: <1155754847.392950.266180@h48g2000cwc.googlegroups.com><1155755905.233229.93440@74g2000cwt.googlegroups.com><1155761144.583994.260150@m73g2000cwd.googlegroups.com><mailman.9442.1155763376.27775.python-list@python.org><1155764364.775366.76070@i3g2000cwc.googlegroups.com><mailman.9443.1155765750.27775.python-list@python.org><1155767139.084992.133200@i42g2000cwa.googlegroups.com><mailman.9459.1155798028.27775.python-list@python.org> <1155808223.670377.199770@i42g2000cwa.googlegroups.com> Message-ID: <ec1npv$bod$1@sea.gmane.org> John Machin wrote: > 1. It's also documented as being the recommended way of filling up a > list after PyList_New. since it doesn't work in any existing Python release, it's hardly "recommended". the Python documentation has never been formally binding; if the documentation doesn't match the code, it's usually the documentation that's flawed. > 2. So you'd rather not change the code, and just let it segfault if > someone calls it (or PyObject_SetItem) instead of PyList_SetItem? as I said, you're using an API that's designed for use on *properly initialized* objects on an object that *hasn't been initialized*. if you're going to patch all places where that can happen, you might as well rewrite the entire interpreter. the documentation is broken, and *must* be fixed. catching this specific case in the code is a lot less important; it's just one of many possible errors you can make when writing C-level code. there's simply no way you can catch them all. </F> From meyer at acm.org Wed Aug 16 03:05:52 2006 From: meyer at acm.org (Andre Meyer) Date: Wed, 16 Aug 2006 09:05:52 +0200 Subject: state of SOAP and python? In-Reply-To: <IvsEg.1018$q63.404@newssvr13.news.prodigy.com> References: <ivACg.5503$9T3.560@newssvr25.news.prodigy.net> <mailman.9182.1155193197.27775.python-list@python.org> <IvsEg.1018$q63.404@newssvr13.news.prodigy.com> Message-ID: <7008329d0608160005p4fb711abqdecb8d93e24b4dde@mail.gmail.com> I had success with ZSI: http://pywebsvcs.sourceforge.net/ It worked very nicely for publishing a SOAP we service and accessing it from a client writtenusing the same library. What I didn't manage to achieve was to write the client in AJAX (tried http://www-128.ibm.com/developerworks/webservices/library/ws-wsajax/). regards Andre On 8/16/06, Mark Harrison <mh at pixar.com> wrote: > > Gabriel Genellina <gagsl-py at yahoo.com.ar> wrote: > > At Thursday 10/8/2006 03:38, Mark Harrison wrote: > > > > >So I'm investigating doing some SOAP work... Any concensus on > > >what the best python libraries are for doing this? > > > > > >Too bad, xmlrpc is choking on our long longs. :-( > > > > Just thinking, if you have control over the two ends, and dont need > > real interoperability, maybe just extending <int> to support long > > integers could be easier... > > I remember extending <double> once to support NaN's, moving to SOAP > > was too much effort for that application. > > Good thinking! It turns out all you have to do is comment > out the range check: > > def dump_int(self, value, write): > # in case ints are > 32 bits > ##if value > MAXINT or value < MININT: > ## raise OverflowError, "int exceeds XML-RPC limits" > write("<value><int>") > write(str(value)) > write("</int></value>\n") > > Thanks, > Mark > > -- > Mark Harrison > Pixar Animation Studios > -- > http://mail.python.org/mailman/listinfo/python-list > -- Dr. Andre P. Meyer http://python.openspace.nl/meyer TNO Defence, Security and Safety http://www.tno.nl/ Delft Cooperation on Intelligent Systems http://www.decis.nl/ Ah, this is obviously some strange usage of the word 'safe' that I wasn't previously aware of. - Douglas Adams -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060816/faba3b82/attachment.html> From mh at pixar.com Thu Aug 10 02:38:06 2006 From: mh at pixar.com (Mark Harrison) Date: Thu, 10 Aug 2006 06:38:06 GMT Subject: state of SOAP and python? Message-ID: <ivACg.5503$9T3.560@newssvr25.news.prodigy.net> So I'm investigating doing some SOAP work... Any concensus on what the best python libraries are for doing this? Too bad, xmlrpc is choking on our long longs. :-( Many TIA, Mark -- Mark Harrison Pixar Animation Studios From avelldiroll at yahoo.fr Thu Aug 24 12:16:04 2006 From: avelldiroll at yahoo.fr (Avell Diroll) Date: Thu, 24 Aug 2006 18:16:04 +0200 Subject: Newbie question about numpy In-Reply-To: <e4hre29hpv4ef1spfbqsu2hq0ee4apgdpv@4ax.com> References: <e4hre29hpv4ef1spfbqsu2hq0ee4apgdpv@4ax.com> Message-ID: <44EDD0C4.1070606@yahoo.fr> Paul Johnston wrote: (snip) > I noted the lack of matrices so installed numpy (snip) > _________________________________________________________ > from numpy import * > > a = array([[1,2,3],[4,5,6],[1,2,3]]) > b = array([[1,3,6],[2,5,1],[1,1,1]]) (snip) > print "a * b is \n", a * b > _________________________________________________________ (snip) > a * b is > [[ 1 6 18] > [ 8 25 6] > [ 1 2 3]] > _________________________________________________________ > > > I know its a long time since my degree but that's not matrix > multiplication is it ? You consider that a and b are matrices, but for the python interpreter they are arrays so a*b returns the multiplication of 2 arrays. For matrices multiplication, you could get a hint by typing the following in the interpreter : >>> import numpy >>> dir(numpy) >>> help(numpy.matrixmultiply) #type "q" to exit which could make you want to try the following code : >>> from numpy import * >>> a = array([[1,2,3],[4,5,6],[1,2,3]]) >>> b = array([[1,3,6],[2,5,1],[1,1,1]]) >>> print matrixmultiply(a,b) ... output : ... array([[ 8, 16, 11], [20, 43, 35], [ 8, 16, 11]]) ... HIH, avell From ty.2006 at yahoo.com Thu Aug 17 10:54:24 2006 From: ty.2006 at yahoo.com (T) Date: 17 Aug 2006 07:54:24 -0700 Subject: How to delete a directory tree in FTP In-Reply-To: <1155770872.609546.324240@75g2000cwc.googlegroups.com> References: <1155742012.987806.236060@75g2000cwc.googlegroups.com> <1155770872.609546.324240@75g2000cwc.googlegroups.com> Message-ID: <1155826464.065829.94210@m73g2000cwd.googlegroups.com> That looks useful. Thanks! From claird at lairds.us Wed Aug 2 13:46:54 2006 From: claird at lairds.us (Cameron Laird) Date: Wed, 2 Aug 2006 17:46:54 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Aug 2) References: <eap13t$hgb$1@lairds.us> Message-ID: <e157q3-hrj.ln1@lairds.us> In article <eap13t$hgb$1 at lairds.us>, Cameron Laird <python-url at phaseit.net> wrote: . . . > Python2.5final is under two weeks away. Watch for it. . . . ... or maybe not, although it remains of high quality: <URL: http://www.python.org/dev/peps/pep-0356/ > (thanks to the reader who helped correct this item). From skip at pobox.com Wed Aug 16 15:48:59 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 16 Aug 2006 14:48:59 -0500 Subject: getting database column names from query In-Reply-To: <44E371EC.4060801@adapt.com> References: <44E371EC.4060801@adapt.com> Message-ID: <17635.30379.34233.164647@montanaro.dyndns.org> Jason> I'm using MySQLdb and can connect and issue queries that return Jason> result sets, but I how do I get the column names for those result Jason> sets? >>> c = MySQLdb.connect(*creds) >>> k = c.cursor() >>> k.execute("select * from account") 3L >>> k.fetchall() ((1L, 'test', -1L), (2L, 'Test', -1L), (3L, 'Test2', -1L)) For MySQLdb you can initialize the connection so that result rows are returned as dictionaries. (See the MySQLdb.cursorclass - I think - module). There is also a description attribute of the cursor object. See the DB API for details: http://www.python.org/dev/peps/pep-0249/ Skip From jcollett at oshtruck.com Mon Aug 14 16:15:41 2006 From: jcollett at oshtruck.com (Hoop) Date: 14 Aug 2006 13:15:41 -0700 Subject: Basic Boost.Python Question Message-ID: <1155586541.415711.14950@i42g2000cwa.googlegroups.com> Hi, I have been working in getting Boost.Python running on my PC, seems to work now. I have what I believe is somewhat of basic question here. I am starting on an application that will developed in VS2005, probably using C++/CLI. I want to be able to exchange data in between Python and C++. The user when running the C++ app will be able to call a python script, set some values, that will then be communicated to running application, it will have to run the python code, and send some data to the applicationfrom Python to vary the performance. And probably the C++ end will have to call a python script and pass some data to it. So, is Boost.Python the way to go here or is there something else that will accomplish this? Thanks for your help Jeff From chosechu at gmail.com Tue Aug 29 08:01:56 2006 From: chosechu at gmail.com (chosechu) Date: 29 Aug 2006 05:01:56 -0700 Subject: Extending the dict class Message-ID: <1156852916.254032.172390@b28g2000cwb.googlegroups.com> Hello Pythoneers: I need to pass a list of named arguments to a function in a given order, and make sure these named arguments are retrieved using keys() in the same order they were given. Example: keyargs={} keyargs['one']=1 keyargs['two']=2 keyargs['three']=3 myfunc(**keyargs) -> myfunc would retrieve key arguments with keys() in the same order as they were set, i.e. keyargs.keys() == ['one', 'two', 'three'] To achieve that, I subclassed dict and added the required lines in __init__(), __setitem__() and keys(). I then assigned dict to my new class but only get the desired behaviour for dictionaries created like: d=dict() but not for dictionaries created like: d={} or myfunc(**keyargs) Is it possible to force dictionary creation in these case to use my own dict class instead of the default one? I guess we can formulate this as a more generic question: if I want to modify the behaviour of the dictionary class, is there any way to do it interpreter-wide so that special dict constructors like those mentioned above use the modified version? Thanks for helping From gagsl-p32 at yahoo.com.ar Sat Aug 19 08:23:59 2006 From: gagsl-p32 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 19 Aug 2006 09:23:59 -0300 Subject: efficient memoize decorator? In-Reply-To: <1155985003.246729.167540@m73g2000cwd.googlegroups.com> References: <1155931932.349283.27700@h48g2000cwc.googlegroups.com> <1155932056.313643.81420@i3g2000cwc.googlegroups.com> <mailman.9528.1155958334.27775.python-list@python.org> <1155985003.246729.167540@m73g2000cwd.googlegroups.com> Message-ID: <7.0.1.0.0.20060819090906.05b0e758@yahoo.com.ar> At Saturday 19/8/2006 07:56, thattommyhallll at gmail.com wrote: >does not seem to work for standalone functions, this is a method >decorator only then? > >Traceback (most recent call last): > File "prob14memoize.py", line 94, in ? > length = col(i,1) > File "prob14memoize.py", line 49, in __call__ > object = self.cache[args] = self.fn(self.instance, *args) >AttributeError: 'Memoize' object has no attribute 'instance' For a standalone function, you should remove __del__ and self.instance, but I haven't tried it... Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From f.braennstroem at gmx.de Sat Aug 5 14:00:07 2006 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Sat, 5 Aug 2006 20:00:07 +0200 Subject: email client like mutt Message-ID: <eb2mb7$267$1@sea.gmane.org> Hi, I am looking for a python email client for the terminal... something like mutt; maybe, so powerfull ;-) Would be nice, if anybody has an idea! Greetings! Fabian From antroy at gmail.com Thu Aug 10 09:56:48 2006 From: antroy at gmail.com (Ant) Date: 10 Aug 2006 06:56:48 -0700 Subject: Two Classes In Two Files In-Reply-To: <1155217917.870642.199000@75g2000cwc.googlegroups.com> References: <1155151480.848276.52650@75g2000cwc.googlegroups.com> <44DA3937.5040901@mxm.dk> <1155152148.014855.166690@p79g2000cwp.googlegroups.com> <mailman.9170.1155161647.27775.python-list@python.org> <1155217917.870642.199000@75g2000cwc.googlegroups.com> Message-ID: <1155218208.404310.274010@m79g2000cwm.googlegroups.com> dhable at gmail.com wrote: > Yes, I have been ruined for the last 5 years with Java and C#. Perl was > my only salvation, but now I can't read the programs I wrote. ROFL! That's got to be a contender for Quote of the week. From gagsl-py at yahoo.com.ar Wed Aug 23 00:37:50 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 23 Aug 2006 01:37:50 -0300 Subject: Can I do this with list comprehension? In-Reply-To: <1156306056.165984.37820@h48g2000cwc.googlegroups.com> References: <1156306056.165984.37820@h48g2000cwc.googlegroups.com> Message-ID: <7.0.1.0.0.20060823011933.01e29130@yahoo.com.ar> At Wednesday 23/8/2006 01:07, barberomarcelo at gmail.com wrote: >a = [0, 1, 0, 1, 1, 0] >b = [2, 4, 6, 8, 10, 12] > >I want a list comprehension that has the elements in b where a[element] >== 1. > >That's to say, in the example above, the result must be: [4, 8, 10] print [belem for aelem,belem in zip(a,b) if aelem==1] print [belem for i,belem in enumerate(b) if a[i]==1] Or itertools.izip... Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From mystilleef at gmail.com Fri Aug 25 06:51:34 2006 From: mystilleef at gmail.com (mystilleef) Date: 25 Aug 2006 03:51:34 -0700 Subject: Best Editor References: <44ed8db6$0$75034$14726298@news.sunsite.dk> Message-ID: <1156503094.126131.299230@m73g2000cwd.googlegroups.com> I recommend Scribes on Linux. It's simple, fast and powerful. Website: http://scribes.sf.net/ Flash Demo: http://scribes.sf.net/snippets.htm GIF Demo: http://www.minds.may.ie/~dez/images/blog/scribes.html JAG CHAN wrote: > Friends, I am trying to learn Python. > It will be of great help to me if you let me know which one would be best > editor for learning Python. > Plese note that I would like to have multiplatform editor which will be > useful for both LInux and Windows XP. > Thanks. From metaperl at gmail.com Tue Aug 8 03:36:30 2006 From: metaperl at gmail.com (metaperl) Date: 8 Aug 2006 00:36:30 -0700 Subject: Looking for an intellisense with good help IDE for Python Message-ID: <1155022590.845074.256900@i42g2000cwa.googlegroups.com> Hi, I would like an IDE that shows me all methods and functions I can call on a particular data item. For instance, iter() can be called on any sequence, but it is not a method. Nonetheless, I would like for something to show me every thing that I can call on a particular data item. This includes % after a string. I would also like browseable help with good examples on whatever methods and functions and operators it pops up. Thanks, Terrence From fredrik at pythonware.com Tue Aug 29 05:47:38 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 29 Aug 2006 11:47:38 +0200 Subject: The lib email parse problem... References: <1156837260.222395.305960@b28g2000cwb.googlegroups.com><1156842395.855885.183330@p79g2000cwp.googlegroups.com><mailman.10045.1156843990.27775.python-list@python.org> <1156844353.171699.326750@74g2000cwt.googlegroups.com> Message-ID: <ed12go$aqq$1@sea.gmane.org> "????" wrote: > btw, i know how to use walk(), and the question is not this. so what is the question? </F> From sjmachin at lexicon.net Thu Aug 17 00:18:31 2006 From: sjmachin at lexicon.net (John Machin) Date: 16 Aug 2006 21:18:31 -0700 Subject: Newbie needs Help In-Reply-To: <1155787759.021791.140600@m79g2000cwm.googlegroups.com> References: <1155783551.689026.273260@m73g2000cwd.googlegroups.com> <1155787122.316436.292080@i3g2000cwc.googlegroups.com> <1155787759.021791.140600@m79g2000cwm.googlegroups.com> Message-ID: <1155788311.386036.176800@i42g2000cwa.googlegroups.com> johnzen... at gmail.com wrote: > Also, it may be easier to use string interpolation, as in: > > return "INSERT INTO statecode (state, name) VALUES ('%(state)s', > '%(name)s')" % insert_dict > > ...after all necessary escaping, of course. > Excuse me!? "statecode" needs to come from the first argument. Likewise the words "state" and "name" are *variables*. The OP has a gazillion other tables to process -- are you suggesting he should type in a gazillion different hard-coded return statements when he's already on the right track and just needs a bit of help with dict.keys() and dict.values()? From david_wahler at bic.ky Wed Aug 16 01:52:47 2006 From: david_wahler at bic.ky (david_wahler at bic.ky) Date: 16 Aug 2006 00:52:47 -0500 Subject: =?utf-8?Q?Re:_Abstracts_=2D_Leipzig_Python_Workshop?= Message-ID: <20060816055247.23393.qmail@BICSRV1011.bic.ky> I'll be out of the office until approximately August 20th. If you have any questions, please email support at bic.ky. -- David Wahler From fredrik at pythonware.com Fri Aug 25 18:08:28 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 26 Aug 2006 00:08:28 +0200 Subject: sum and strings In-Reply-To: <008301c6c816$4cb4f080$03000080@hendrik> References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <slrneeatf3.nbt.sybrenUSE@schuimige.stuvel.eu> <1155922208.930580.135080@m79g2000cwm.googlegroups.com> <mailman.9516.1155930431.27775.python-list@python.org> <1156365271.487489.62640@m73g2000cwd.googlegroups.com> <44ECC789.1010202@tim.thechases.com><ecjga9$558$1@sea.gmane.org> <44EDCFDE.9060604@tim.thechases.com><7.0.1.0.0.20060824132656.050af940@yahoo.com.ar> <eckmlg$brf$1@sea.gmane.org> <008301c6c816$4cb4f080$03000080@hendrik> Message-ID: <ecnscr$3kn$3@sea.gmane.org> Hendrik van Rooyen wrote: > | (I still think a "join" built-in would be nice, though. but anyone who > | argues that "join" should support numbers too will be whacked with a > | great big halibut.) > > Strange this - you don't *LOOK* like a Gaulish Blacksmith... no, but I have a nice safari outfit. (hint: this is comp.lang.python, not comp.lang.asterix) </F> From brett at python.org Mon Aug 7 20:27:45 2006 From: brett at python.org (Brett Cannon) Date: Mon, 7 Aug 2006 17:27:45 -0700 Subject: Four issue trackers submitted for Infrastructue Committee's tracker search Message-ID: <bbaeab100608071727t64c1064dwdb2c69861c50d303@mail.gmail.com> Back in June, the Python Software Foundation's Infrastructure Committee asked for help in the search for a new issue tracker to replace SourceForge (see http://wiki.python.org/moin/CallForTrackers for details). We asked people who wished to help with the search to install their favourite issue tracker and import a data dump of our issues from SourceForge. We placed a deadline of August 7th to have the installation up and going. We realized that this was a large request to make of the community, but we needed to make sure that we got to evaluate any candidate trackers with the amount of issues that Python has so as to get a real-world feel. Not surprisingly, the community stepped up to the challenge with four different test tracker installations by the deadline! We have one for JIRA, Roundup, Trac, and Launchpad. The current schedule calls for the Infrastructure Committee to spend the next month evaluating the four trackers and making a decision on which one to go with. This might slip, though, since this overlaps with traditional American and European vacation time. But the slippage will not go beyond October 1. On behalf of the Infrastructure committee I thank the people who took the time and effort to set up a test tracker to help improve the development of Python. - Brett Cannon Chairman, PSF Infrastructure Committee -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060807/dd080e69/attachment.html> From grante at visi.com Mon Aug 28 12:00:52 2006 From: grante at visi.com (Grant Edwards) Date: Mon, 28 Aug 2006 16:00:52 -0000 Subject: time.clock() going backwards?? References: <vkFHg.82529$_J1.759243@twister2.libero.it> <ecnla4$fv2$1@sea.gmane.org> <mailman.9894.1156540900.27775.python-list@python.org> <dht4f25nlkc4outso2o30mpug033umdh8b@4ax.com> <ecu546$sn9$1@newsreader2.netcologne.de> <mailman.9975.1156776621.27775.python-list@python.org> <ecv2lg$mk1$1@newsreader2.netcologne.de> <12f6455mjvuqv72@corp.supernews.com> Message-ID: <12f64pkr124f358@corp.supernews.com> On 2006-08-28, Grant Edwards <grante at visi.com> wrote: >>> For processors that run at (say) 2GHz, several million (say 10 >>> million) represents a difference of 10e6/2e9 = 0.005 seconds >>> between when the processors were sufficiently powered up to >>> start counting cycles. > >> If it were so, than why can't the delta of time between the >> processors be set to exact zero? > > This is Oops. Hit the wrong key. I meant to say: This is a _Microsoft_Product_. There doesn't have to be a reason for something to be done in a half-assed manner. >> I assume, that it is known how many cycles adjusting the value >> will take, so it could be done exactly Yup. -- Grant Edwards grante Yow! People humiliating at a salami! visi.com From skip at pobox.com Thu Aug 31 10:33:03 2006 From: skip at pobox.com (skip at pobox.com) Date: Thu, 31 Aug 2006 09:33:03 -0500 Subject: Any relational database design tool written in Python In-Reply-To: <1157013403.490468.59760@m73g2000cwd.googlegroups.com> References: <1157013403.490468.59760@m73g2000cwd.googlegroups.com> Message-ID: <17654.62239.30568.448617@montanaro.dyndns.org> metaperl> I am hoping for something that can create database deltas. What is a database delta? I know about SELECT, CREATE, INSERT, UPDATE, joins, normalization, etc, but have never heard this term before. Skip From bytter at gmail.com Fri Aug 11 06:53:59 2006 From: bytter at gmail.com (Bytter) Date: 11 Aug 2006 03:53:59 -0700 Subject: Rendering Vector Graphics Message-ID: <1155293639.748785.316170@m73g2000cwd.googlegroups.com> Hi ppl, I've already posted this message through the mailing-list, but it seems it never arrived here. Strange... Anyway: I need to render high-quality vector graphics with Python. I was thinking of something like 'cairo', though I need to run under win32 and can't find a pycairo package for it. Suggestions? Thanks, Hugo Ferreira From mlacunza at gmail.com Thu Aug 24 14:48:29 2006 From: mlacunza at gmail.com (Mario Lacunza) Date: Thu, 24 Aug 2006 13:48:29 -0500 Subject: [wxPython-users] [ANN]UliPad 3.3 is released In-Reply-To: <771741b20608241143i673ef58fo205621c373fca8bb@mail.gmail.com> References: <mailman.9759.1156396752.27775.python-announce-list@python.org> <771741b20608241143i673ef58fo205621c373fca8bb@mail.gmail.com> Message-ID: <771741b20608241148v35d1f2b6p714debeb34197cc4@mail.gmail.com> Sorry, I correct me: Your link in the message not found, but the link in the web site work Ok. Thanks! 2006/8/24, Mario Lacunza <mlacunza at gmail.com>: > > Hi, > > Is possible then you correct the path for download the sources Zip file?? > > I want to test this tool but I dont could donwload it... > > Thansk! > > 2006/8/23, limodou < limodou at gmail.com>: > > > What's it? > > ======== > > > > It's an Editor based on wxPython. NewEdit is the old name, and UliPad > > is the new name. UliPad uses Mixin and Plugin technique as its > > architecture. Most of its classes can be extended via mixin and plugin > > components, and finally become an integrity class at > > creating the instance. So UliPad is very dynamic. You can write the > > new features in new files, and hardly need to modify the existing > > code. And if you want to extend the existing classes, you could write > > mixins and plugins, and this will be bound to the target class that I > > call "Slot Class". This technique will make the changes centralized > > and easily managed. > > > > What are its features? > > ================ > > > > * Cross platform > > o based on wxPython, so it can run anywhere that wxPython > > works, such as: Windows, Linux. > > o Unicode support. > > > > * Most features of wxStyledTextCtrl(Scintilla) > > o Syntax highlighting, support Python, c/c++, html, plain > > text, perl, ruby, css, javascript > > o Folding > > o Brace Matching > > o ... > > > > * Extended selection > > o Extended word selection -- You can press > > Ctrl+MouseDoubleClick to select a word including '.' > > o Matched selection -- Select text in quoted chars like: > > (), [], {}, '', "". > > * Other editing extension > > o Duplicating text -- Just like Vim Ctrl+V, Ctrl+P, and > > more. You can duplicate above or below char, word, line > > o Quoting text -- Add some quoted chars before and after > > selected text, just as: "", '', (), [], {}, and > > o Text convertion and view -- python -> html, reStructured > > Text -> html, textile -> html, and you can output or view > > o Utf-8 encoding auto detect > > o Changing document encoding > > o Auto backup > > o Last session support -- It'll save all the filenames as > > closed, and reopen the files as next started. > > o Smart judge the indent char -- It'll auto guess the > > indent char, and sets it. > > o Finding in files > > o Bookmark support > > > > * Python support > > o built-in python interactive window based on ?PyShell, > > support Unicode > > o Auto completion > > o Function syntax calltips > > o Run, run with argument, stop python source > > o Auto change current path > > o Python class browser > > o Indent pasting support(New) > > > > * Code snippets > > o You can manage your code snippets with categories, and > > each category can have many items. Every item will represent a code > > snippet. You can insert an item just by double-clicking on it. It even > > supports importing and exporting. > > > > * Simple project support > > o Can create a special file _project, so every file and > > folder under the folder which has the _project can be considered as a > > whole project. > > > > * Extension mechanism > > o Script -- You can write easy script to manipulate the all > > resource of UliPad, just like: text conversion, etc. > > o Plugin -- Customized function. More complex but more > > powerful. Can easily merge with UliPad, and can be managed via menu. > > o Shell command -- Add often used shell commands, and execute > > them. > > > > * Ftp support > > o You can edit remote files through ftp. You can add, > > rename, delete, upload, download file/directory. > > > > * Multilanguage support > > o Currently supports two languages: English and Chinese, > > which can be auto-detected. > > > > * Shipped plugins(must be configed as used them before) > > o Document links -- Python documentation and wxPython > > documentation. > > o Many plugins can be found at UliPad wiki page. > > > > * Shipped scripts > > o Many scripts can be found at UliPad wiki page. > > > > * Wizard (New) > > o You can make your own wizard template. The wizard can > > input user data, combine with template, and output the result. And > > wizard also support code framework created. This feature will help you > > improving coding efficiency. > > > > * Direcotry Browser(New) > > o Browse multiple directories, and you can really add, > > delete, rename directories and files. Double click will open the file > > in Editor window. > > o Support Copy, Cut, and Paste. > > o Search in Directory > > > > * AutoComPlete(acp)(New) > > o Suport user autocomplete file, it can help to input code > > very helpful and functional. Just like EditPlus, but may be more > > powerful. > > o Manually apply some acp files to current document > > > > * Column Edit Mode(New) > > > > Where to download it? > > ================ > > > > download lastest version 3.3: > > > > http://wiki.woodpecker.org.cn/moin/UliPad?action=AttachFile&do=get&target=UliPad_3.3.zip > > also have windows installer: > > > > http://wiki.woodpecker.org.cn/moin/UliPad?action=AttachFile&do=get&target=UliPad3.3.exe > > wiki: http://wiki.woodpecker.org.cn/moin/UliPad > > svn: http://cvs.woodpecker.org.cn/svn/woodpecker/ulipad/trunk > > maillist: http://groups.google.com/group/ulipad > > > > If you have any problem as using UliPad, welcome to join the UliPad > > maillist to discuss. > > > > Hope fun! > > > > > > > > -- > > I like python! > > My Blog: http://www.donews.net/limodou > > My Django Site: http://www.djangocn.org > > NewEdit Maillist: http://groups.google.com/group/NewEdit > > > > --------------------------------------------------------------------- > > To unsubscribe, e-mail: wxPython-users-unsubscribe at lists.wxwidgets.org > > For additional commands, e-mail: wxPython-users-help at lists.wxwidgets.org > > > > > > > > > -- > Saludos / Best regards > > Mario Lacunza > Desarrollador de Sistemas - Webmaster > Desarrollador 2 Estrellas VS2005 > > Email: mlacunza [AT] gmail [DOT] com > Website: mlacunzav[AT]cogia[AT]net > Blog: http://mlacunza.blogspot.com/ > Lima - Peru > -- Saludos / Best regards Mario Lacunza Desarrollador de Sistemas - Webmaster Desarrollador 2 Estrellas VS2005 Email: mlacunza [AT] gmail [DOT] com Website: mlacunzav[AT]cogia[AT]net Blog: http://mlacunza.blogspot.com/ Lima - Peru -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060824/ea2fc20b/attachment.html> From ask at me Fri Aug 11 18:22:09 2006 From: ask at me (alf) Date: Fri, 11 Aug 2006 18:22:09 -0400 Subject: iterator wrapper Message-ID: <8cednRaDbu_RkkDZnZ2dnUVZ_sKdnZ2d@comcast.com> Hi, I have a following task: let's say I do have an iterator returning the some objects: >>i=<iterator> >>i.next() 1 >>i.next() 'abgfdgdfg' >>i.next() <some object> For some reason I need to wrap thos objects with a list. I thought I could have a smart lamda or simple function class yielding following result: >>i=<iterator> >>i=list_wrapper(i) >>i.next() [1] >>i.next() ['abgfdgdfg'] >>i.next() [<some object>] What would thesolution? Thx, A. From tjreedy at udel.edu Sun Aug 20 16:59:23 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 20 Aug 2006 16:59:23 -0400 Subject: Help in using introspection to simplify repetitive code References: <1156090845.875872.41220@75g2000cwc.googlegroups.com> Message-ID: <ecaifb$eqs$1@sea.gmane.org> <jsceballos at gmail.com> wrote in message news:1156090845.875872.41220 at 75g2000cwc.googlegroups.com... > Hello. > I'm writing a proxy class, i.e: a class whose methods mostly delegate > their functionality to other class object. Most of the methods (which > are quite a lot) defined in the class would end up being: > > def thisIsTheMethodName(self): > self._handlerClass.thisIsTheMethodName() Are these parameterless static methods or should this be self._handlerClass.thisIsTheMethodName(self) or does self get auto-bound even though not a _handlerClass instance? (I have never needed or done such delegation.) > The handler object is the same in all methods. > > I was wondering if there is a way to simplify this proxy class, maybe > using some pythonic technique like metaclasses, introspection... any > suggestion is appreciated. My immediate thought would be to start with _forwarded = set(......) # of forwarded method names def __getattr__(self, name): if name in _forwarded: return getattr(self._handlerClass, name) but I am not sure if this gives the right wrapping and binding. Terry Jan Reedy From paul at boddie.org.uk Thu Aug 17 07:19:53 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 17 Aug 2006 04:19:53 -0700 Subject: hide python code ! References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155300852.497741.73230@74g2000cwt.googlegroups.com> <1155301468.870340.82920@b28g2000cwb.googlegroups.com> <1155307415.855555.124760@i3g2000cwc.googlegroups.com> <1155309563.898182.195950@p79g2000cwp.googlegroups.com> <1155313092.743230.33950@m73g2000cwd.googlegroups.com> <1155320948.142524.124990@p79g2000cwp.googlegroups.com> <1155564295.361980.279350@m73g2000cwd.googlegroups.com> <1155570126.905733.137850@m79g2000cwm.googlegroups.com> <1155657616.103285.40040@75g2000cwc.googlegroups.com> <pan.2006.08.16.04.51.27.33734@REMOVEME.cybersource.com.au> <1155760750.172859.172920@h48g2000cwc.googlegroups.com> Message-ID: <1155813593.559451.84740@p79g2000cwp.googlegroups.com> danielx wrote: > > But we have only considered the economics of such a decision. Even if > there is no market value to a work, a person has an understandable > desire to exercise the rights of ownership over a work, given the > amount of personal investment one makes in producing it. There are other motivations, too. An author might wish that their work convey a particular message and that others should not be able to make derived works which distort or contradict that message. However, there are various established principles of fair use which limit the author's control over such derived works. [...] > I think the above idea is frequently missed in discussions about > copyrights/patents in the open source world. There, the focus seems to > be on the marketability granted by protections (legal or physical). The > post I am responding to illustrates this focus. Do we believe an author > forfeits ownership of a work merely by sharing it? As a matter of > conscience, I don't believe the answer can be imposed on anyone. Every > person must answer this for him or herself. As we've mentioned above, one crucial issue is control over published works and over the potentially related works of others. With software, such control is mediated by the licence which is often prominent, even unavoidable when using proprietary software; thus, people using or distributing software should be aware of the licence which applies to the work. In contrast, works in areas such as popular music are not prominently "labelled" with licensing information if you're listening to that music playing on the radio, television, in a public space, and so on. This apparent "promiscuity" with such works leads people to believe that they are freely exchangeable and that the author is not exercising control, even if that isn't really the case due to the framework established by the recording industry for broadcasters. So, people perceive an apparent lack of control as some kind of lack of ownership, that the work has, by being shared in an apparently unconditional way, become part of their common culture - a sentiment or an understanding that can presumably be traced back throughout the history of human culture itself. At the opposite end of the spectrum of control, when mechanisms of control are used to restrict the distribution of derived works or the production of coincidentally related works, is it unfair that people wish to disregard such apparently counter-intuitive mechanisms? An interesting example in popular culture was the legal argument about whether silence constitutes an original work (http://news.bbc.co.uk/1/hi/entertainment/music/2133426.stm), but things like patents affect the ability of others to create works in a fashion that can be much harder to predict. Paul From sile_brennan at hotmail.com Wed Aug 16 12:04:30 2006 From: sile_brennan at hotmail.com (Sile) Date: 16 Aug 2006 09:04:30 -0700 Subject: python-dev and setting up setting up f2py on Windows XP Message-ID: <1155744270.092818.256290@i42g2000cwa.googlegroups.com> Hi, I've been trying to get f2py working on Windows XP, I am using Python 2.3. I'm new to python so I'm not too sure what I'm doing yet. I need the python-dev package to run f2py. I have been told this is just the header files and .dll and I need to put them somewhere my C compiler can find them. I've searched the web and none of the python-dev packages I've found are for windows. I was wondering is this automatically part of the windows version and if so how I set it up so my C compiler can find them. If it is not part of the standard package does anyone know where I can find it??? Any help at all would be much appreciated. Thanks, Sile From zetalimit at charter.net Wed Aug 2 20:39:11 2006 From: zetalimit at charter.net (switzerland qunatium computer) Date: 2 Aug 2006 17:39:11 -0700 Subject: The most powerful question to ask A.I is: Message-ID: <1154565551.190375.168570@75g2000cwc.googlegroups.com> The most powerful question to ask A.I is: 1.How is a hammer connected to everything and what network map would it build for the next question. 2.How is everything connected in the universe by the way of magnetism can we build a quantum ADDRESS of everything in space time If numbers go on too the end of time then that states there are infinite solutions to infinite problems and infinite problems to infinite solutions so maybe one day we will find it in time.14 billion A.I quantum computers fall in love what happens? http://www.beyond-science.com/ From akameswaran at gmail.com Wed Aug 9 12:28:04 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 9 Aug 2006 09:28:04 -0700 Subject: threading.Event usage causing intermitent exception In-Reply-To: <mailman.9118.1155081575.27775.python-list@python.org> References: <1155072235.904227.303090@m73g2000cwd.googlegroups.com> <mailman.9118.1155081575.27775.python-list@python.org> Message-ID: <1155140884.130226.283080@h48g2000cwc.googlegroups.com> Tim Peters wrote: > [akameswaran at gmail.com] > > Admittedly this problem causes no actual functional issues aside from > > an occasional error message when the program exits. The error is: > > > > Unhandled exception in thread started by > > Error in sys.excepthook: > > Original exception was: > > > > Yes all that info is blank. > > That's typical when the interpreter has torn so much of itself down > that there's not enough left in the `sys` module even to print > exception info gracefully. The easiest way to stop that is to stop > /trying/ to run Python code while the interpreter is tearing itself > down. > > > The application is a console application that is waiting for some > > condition on the machine to happen. However, I leave open the > > possiblitiy to cancel by a single key press at which > > point the program terminates. Suffice it to say, I cannot perform both > > checks without invoking threads as the key press gets "missed" > > sometimes. Below is a simplification of the code > > > > canceled = False > > myEvent = threading.Event() > > > > def watchForCancel() > > global canceled > > # turn of terminal buffering and capture key presses here > > canceled = True > > myEvent.set() > > Presumably this is some kind of poll-and-sleep loop? If so, add a > check to get out of the loop if myEvent.isSet(). Or if not, make it > some kind of poll-and-sleep loop ;-) after setting up the terminal correctly, ie changing buffering settings etc. (I want to cancel with a single key-press with no "return" hit. This was suprisingly difficult to do. The wait code is simply: while keyPressed != 'q': keyPressed = sys.stdin.read(1) The really annoying thing here, is that I cannot put in any other steps in the while loop without sometimes missing the key press. I have to unbuffer the terminal(otherwise the read doesn't return until the enter key is pressed), and for whatever reason performing any action no matter how trivial leads to missing the key stroke on occasion - that's why I pursued the daemon route. > > > def watchForCondition() > > # do a bunch of stuff checking the system > > myEvent.set() > > Ditto. > > > cancelThread = threading.Thread(target = watchForCancel) > > cancelThread.setDaemon(True) # so I can exit the program when I want to > The conditional thread will never terminate without making the threads aware of eachother. Setting them daemon allows the interpreter to shutdown with one of them running - and ocaisonally cuases the error. What I find interesting, the behavior only happens when I cancel, not when the condition is reached. > And get rid of that. The comment doesn't make sense to me, and > forcing a thread to be a daemon is exactly what /allows/ the thread to > keep running while the interpreter is tearing itself down. That's why > "daemonism" isn't the default: it's at best delicate. I don't see a > real reason for wanting this here. > > > cancelThread.start() > > conditionThread = threading.Thread(target = watchForCondition) > > conditionThread.setDaemon(True) > > Ditto. > > > conditionThread.start() > > > > myEvent.wait() > > > > if cancelled: > > sys.exit(2) > > > > # do more stuff if the condition returned instead of cancel and then > > I'm done > > > > > > I've left out most of the active code, just cuz I think it muddies the > > water. Now about 9 out of 10 times this works just fine. However, > > every once in a while I get the exceptions mentioned above, but only > > when I cancel out of the operation. I think the conditionThread is in > > the process of shutting down and gets hosed up somehow and spits out an > > exception, but the interpreter no longer has access to the info since > > it is shutting down. > > At this point it's likely that even sys.stdout and sys.stderr no > longer exist. The "Unhandled exception" message is printed directly > to the C-level `stderr` instead. > exactly - giving me no way to swallow it. > > ... > > I suppose I could make the threads aware of each other, but that just > > seems stupid. Any suggestions on how to eliminate this intermittent > > error? > > Stop forcing them to be daemon threads. The interpreter won't start > to tear itself down then before both threads terminate on their own. > To arrange for that, it's not necessary for the threads to become > aware of each other, but it is necessary for the threads to become > aware of another (shared) reason /for/ exiting. The most natural way > to do that, given what you said above, is to make both threads aware > that their shared myEvent event may get set "externally", and to stop > when they find it has been set. Due to the oddities of capturing that keypress at the console, I suspect I can un-daemonize the conditional thread and check for cancelled=True and have it return. Since the error only occurs when the conditional thread is still running, undaemonizing it will prevent that and allow the interpreter to shut down more gracefully. Thanks for the advice. From fhurley at gmail.com Sat Aug 5 13:23:02 2006 From: fhurley at gmail.com (fhurley at gmail.com) Date: 5 Aug 2006 10:23:02 -0700 Subject: Can't get LCHARVAR's with InformixDB In-Reply-To: <mailman.8821.1154467313.27775.python-list@python.org> References: <1154437329.471918.35150@h48g2000cwc.googlegroups.com> <mailman.8792.1154437891.27775.python-list@python.org> <1154438862.714569.9130@b28g2000cwb.googlegroups.com> <mailman.8794.1154439925.27775.python-list@python.org> <1154446906.915203.13790@m73g2000cwd.googlegroups.com> <1154447228.669652.169320@75g2000cwc.googlegroups.com> <mailman.8811.1154450805.27775.python-list@python.org> <1154455511.213889.270500@m73g2000cwd.googlegroups.com> <mailman.8821.1154467313.27775.python-list@python.org> Message-ID: <1154798582.577171.47210@h48g2000cwc.googlegroups.com> Carsten Haese wrote: > I'd suggest upgrading to the newest version of CSDK. Please let me know > what happens after the upgrade. That did the trick.... thanks very much. From http Fri Aug 25 00:40:16 2006 From: http (Paul Rubin) Date: 24 Aug 2006 21:40:16 -0700 Subject: sum and strings References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <slrneeatf3.nbt.sybrenUSE@schuimige.stuvel.eu> <1155922208.930580.135080@m79g2000cwm.googlegroups.com> <mailman.9516.1155930431.27775.python-list@python.org> <1156365271.487489.62640@m73g2000cwd.googlegroups.com> <44ECC789.1010202@tim.thechases.com> <ecjga9$558$1@sea.gmane.org> <44EDCFDE.9060604@tim.thechases.com> <mailman.9795.1156436731.27775.python-list@python.org> <pan.2006.08.25.04.19.25.572629@REMOVEME.cybersource.com.au> Message-ID: <7xd5apfmxb.fsf@ruckus.brouhaha.com> Steven D'Aprano <steve at REMOVEME.cybersource.com.au> writes: > There is an alternative: raise a warning instead of an exception. That > permits the admirable strategy of educating users that join() is > generally a better way to concatenate a large number of strings, while > still allowing programmers who want to shoot themselves in the foot to do so. This is reasonable, but why not just do the right thing and use the right algorithm? There is, after all, no guarantee in the docs that ''.join() uses the right algorithm either. I've come to the view that the docs should explicitly specify this type of thing, per the Stepanov interview mentioned earlier. You may be right that even when it's not clear what the best algorithm is, using a correct but slow algorithm is preferable to throwing an error. But I think for strings, we should rethink how this kind of operation is done, and build up the sum of strings in terms of some kind of mutable string object resembling Java's StringBuf or Python's cStringIO objects. From pekka.niiranen at wlanmail.com Thu Aug 3 05:52:50 2006 From: pekka.niiranen at wlanmail.com (Pekka Niiranen) Date: Thu, 03 Aug 2006 12:52:50 +0300 Subject: serial ports, threads and windows In-Reply-To: <mailman.8872.1154560051.27775.python-list@python.org> References: <mailman.8872.1154560051.27775.python-list@python.org> Message-ID: <44D1C772.6000501@wlanmail.com> Tom Brown wrote: > Hey people, > > I've written a python app that r/w eight serial ports to control eight devices > using eight threads. This all works very nicely in Linux. I even put a GUI on > it using PyQt4. Still works nicely. > > Then I put the app on on a virtual Windows machine running inside of vmware on > the same Linux box. Vmware only lets me have four serial ports so I run the > app against four serial ports using four threads. The app did not respond > quick enough to data from the serial ports and eventually hung. > > So, I tried one serial port and the app still did not respond quick enough to > the single serial port. It eventually hangs. > > When the app hung, in each case, it was not hogging the cpu nor reading any > data off the serial ports. The task manager didn't show it was doing anything > at all. > > When it runs on Windows, could it be: > > 1) Just struggling to run inside of VMware? > > 2) Using threads with Qt on Windows is a problem? > > 3) Threads in python on Windows is a problem? > > Any ideas? > > Thanks, > Tom Hi, I have been using wxpython myself with pyserial in Windows 2000/XP. No problems. Below are (edited) code segments. The "self.jam" is used for stopping serial port processing without stopping the thread. -------- thread example starts -------------------- class T1Thread(Thread): def __init__(self, inport): Thread.__init__(self) self._want_abort = 0 self.inprt = inport # COMx self.inprt.flushInput() self.run_count = 0 # self.jam = false # self.start() def run(self): while self._want_abort == 0: if not self.jam: self.read_simulations() sleep(1) def abort(self): self._want_abort = 1 # Stop from GUI def read_simulations(self): ..blah..blah.. self.inprt.flushInput() sleep(5) -------- thread example ends -------------------- -------- Wxpython code starts -------------------- def OnRun(self, event): if self.in_port != "No" and not self.T1worker: self.T1worker = T1Thread(self.inprt) if self.out_port != "No" and not self.T2worker: self.T2worker = T2Thread(self.outprt) if self.in2_port != "No" and not self.T3worker: self.T3worker = T3Thread(self.in2prt) def OnStop(self, event): if self.T1worker: self.T1worker.abort() if self.T2worker: self.T2worker.abort() if self.T3worker: self.T3worker.abort() sleep(3) self.T1worker= None self.T2worker= None self.T3worker= None print "\nSTOPPED\n" -------- Wxpython code ends -------------------- -pekka- From bobrien18 at yahoo.com Mon Aug 14 12:43:51 2006 From: bobrien18 at yahoo.com (KraftDiner) Date: 14 Aug 2006 09:43:51 -0700 Subject: A little assistance with os.walk please. In-Reply-To: <mailman.9313.1155573627.27775.python-list@python.org> References: <1155566679.139086.279430@h48g2000cwc.googlegroups.com> <44E09561.1030902@websafe.com> <1155571727.168983.103480@m73g2000cwd.googlegroups.com> <mailman.9313.1155573627.27775.python-list@python.org> Message-ID: <1155573831.587574.316950@b28g2000cwb.googlegroups.com> Tim Chase wrote: > > 1) there seems to be an optional topdown flag. Is that passed to > > os.walk(path, topdownFlag) > > Yes. > > > 2) I only want to process files that match *.txt for example... Does > > that mean I need to parse the list of files for the .txt extention or > > can I pass a wildcard in the path parameter? > > >>> for path, dirs, files in os.walk("."): > ... for f in files: > ... if not f.lower().endswith(".txt"): continue > ... print os.path.join(path, f) > > If you want to be more complex: > > > >>> from os.path import splitext > >>> allowed = ['.txt', '.sql'] > >>> for path, dirs, files in os.walk("."): > ... for f in files: > ... if splitext(f)[1].lower() not in allowed: continue > ... fn = os.path.join(path, f) > ... print "do something with %s" % fn > > > Just a few ideas, > > -tkc Many thanks all. B. From micahc at gmail.com Mon Aug 28 16:51:58 2006 From: micahc at gmail.com (micahc at gmail.com) Date: 28 Aug 2006 13:51:58 -0700 Subject: How to store ASCII encoded python string? In-Reply-To: <mailman.9991.1156793338.27775.python-list@python.org> References: <1156792022.792854.90700@i42g2000cwa.googlegroups.com> <mailman.9991.1156793338.27775.python-list@python.org> Message-ID: <1156798318.624785.25210@m79g2000cwm.googlegroups.com> Fredrik Lundh wrote: > 3) convert the data to Unicode before passing it to the database > interface, and leave it to the interface to convert it to whatever > encoding your database uses: > > data = ... get encoded string from email ... > text = data.decode("iso-8859-1") > ... write text to database ... Wouldn't that have to assume that all incoming data is in iso-8859-1? If someone sends me an email with chinese characters would that still work (I don't know the character set at data insert time)? Marc 'BlackJack' Rintsch wrote: > In [6]: '\tsome text\xa7some more text\n'.encode('string_escape') > Out[6]: '\\tsome text\\xa7some more text\\n' Thanks, I think this is what I will end up doing just for simplicity, though I'm still curious about the above question. From jjl at pobox.com Thu Aug 17 16:29:57 2006 From: jjl at pobox.com (John J. Lee) Date: Thu, 17 Aug 2006 20:29:57 GMT Subject: How to fill a form References: <20060815034051.89ef7e18.sulsa@gazeta.pl> <mailman.9336.1155608567.27775.python-list@python.org> <20060815050733.10e14112.sulsa@gazeta.pl> <12e2gau4jouhmcf@corp.supernews.com> <20060815054343.1c31f3f7.sulsa@gazeta.pl> Message-ID: <87ac63f6m2.fsf@pobox.com> Sulsa <sulsa at gazeta.pl> writes: > On Tue, 15 Aug 2006 03:37:02 -0000 > Grant Edwards <grante at visi.com> wrote: > > > On 2006-08-15, Sulsa <sulsa at gazeta.pl> wrote: > > > > > I want to fill only one smiple form so i would like not to use > > > any non standard libraries. > > > > Then just send the HTTP "POST" request containing the fields > > and data you want to submit. > > but i don't know how to post these data if i knew there there would > be no topic. Something like this (UNTESTED, and I can never remember all the details, which are fiddlier than they may look): import urllib, urllib2 query = urllib.urlencode([ ("username", "sulsa"), ("password", "sulsa"), ("redirect", ""), ("login", "Login"), ]) r = urllib2.urlopen("http://example.com/login.php", query) print r.read() Note that urllib and urllib2 both, as their main job in life, open URLs. urllib also has miscellaneous functions related to URLs &c. I use urllib2 above because I know it better and because it can handle some stuff that urllib doesn't (it's designed more for extensibility than is urllib). John From sjmachin at lexicon.net Fri Aug 11 09:39:31 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 11 Aug 2006 23:39:31 +1000 Subject: datetime to timestamp In-Reply-To: <44dc87b7$1@news.eftel.com> References: <mailman.9246.1155302262.27775.python-list@python.org> <44dc87b7$1@news.eftel.com> Message-ID: <44dc8891$1@news.eftel.com> On 11/08/2006 11:35 PM, John Machin wrote: > On 11/08/2006 11:10 PM, Simen Haugen wrote: >> Hi. >> >> How can I convert a python datetime to a timestamp? It's easy to convert >> a timestamp to datetime (datetime.datetime.fromtimestamp(), but the >> other way around...?) >> >> -Simen >> > > Is the timetuple() method what you want? > > #>>> import datetime > #>>> n = datetime.datetime.now() > #>>> n > datetime.datetime(2006, 8, 11, 23, 32, 43, 109000) > #>>> n.timetuple() > (2006, 8, 11, 23, 32, 43, 4, 223, -1) Aaaarrrggghhh no it's not what you want -- looks like you have to do the arithmetic yourself, starting with toordinal() From http Fri Aug 18 22:35:06 2006 From: http (Paul Rubin) Date: 18 Aug 2006 19:35:06 -0700 Subject: text editor suggestion? References: <44e66724$0$2363$c3e8da3@news.astraweb.com> <1155953803.525289.64490@h48g2000cwc.googlegroups.com> Message-ID: <7xveopfo6d.fsf@ruckus.brouhaha.com> "Simon Forman" <rogue_pedro at yahoo.com> writes: > Have you tried IDLE? It ships with python, meets your 5 criteria(*), > can be customized (highlighting colors and command keys and more), and > includes a usable GUI debugger. It's got some warts, but I like it a > lot, it's pretty much all I use for my python coding. I use it too, but have never gotten the debugger to work reliably. From skip at pobox.com Wed Aug 9 21:19:28 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 9 Aug 2006 20:19:28 -0500 Subject: Easy image rendering? In-Reply-To: <1155172010.495135.274230@75g2000cwc.googlegroups.com> References: <1155166070.085423.37420@b28g2000cwb.googlegroups.com> <pan.2006.08.10.00.55.57.560672@users.sf.net> <1155172010.495135.274230@75g2000cwc.googlegroups.com> Message-ID: <17626.35232.451429.66177@montanaro.dyndns.org> >> If you are using PIL you could use im.show(); but all that does is >> saving the image data to a file and opening that file in an external >> application (xv on UNIX). At least you don't have to do it yourself. jay> No good. No external applications. What else is there? Worst case jay> scenario, what's the easiest way to do GUI? You can still use PIL. Just feed the result to Tkinter. Check out the ImageTk module that's part of PIL: http://www.pythonware.com/library/pil/handbook/imagetk.htm Check this thread for some hints from Fredrik Lundh on combining PIL and Tkinter: http://mail.python.org/pipermail/python-list/1999-July/007379.html I'm sure when he gets up in Europe he'll be able to provide some more useful pointers. Skip From christian.convey at gmail.com Mon Aug 28 16:15:44 2006 From: christian.convey at gmail.com (Christian Convey) Date: Mon, 28 Aug 2006 16:15:44 -0400 Subject: Anonymous dynamic import Message-ID: <6addebae0608281315q798cfd8dof0b51fa16969304f@mail.gmail.com> Anyone know how to do this?: I want a way to dynamically import modules (module names not known until runtime). I want to end up with a handle to the resulting module object, without having poluted my global module namespace in the process. Basically I want to something like this: def call_all_user_supplied_foo_functions(user_script_pathanmes): for f in user_script_pathanmes: a_module = magic_module_import_function(f) a_module.foo() Any ideas? I've looked at using imp.load_source() or imp.load_module(), but it looks to me like all of these polute the global namespace with the names of the modules I'm importing. Thanks, Christian -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060828/fa345fee/attachment.html> From aisaac0 at verizon.net Wed Aug 9 12:51:23 2006 From: aisaac0 at verizon.net (David Isaac) Date: Wed, 09 Aug 2006 16:51:23 GMT Subject: __contains__ vs. __getitem__ Message-ID: <fooCg.18589$qw5.15856@trnddc06> I have a subclass of dict where __getitem__ returns None rather than raising KeyError for missing keys. (The why of that is not important for this question.) I was delighted to find that __contains__ still works as before after overriding __getitem__. So even though instance['key'] does not raise KeyError, I still get (as desired) 'key' in instance == False. Looking forward: Can I count on this independence of __getitem__ and __contains__? I would like to understand whether it will be safe to count on this behavior. Thank you, Alan Isaac From david_wahler at bic.ky Thu Aug 17 15:10:26 2006 From: david_wahler at bic.ky (david_wahler at bic.ky) Date: 17 Aug 2006 14:10:26 -0500 Subject: =?utf-8?Q?Re:_ANN:_Pybots_=2D=2D_Python_Community_Buildbots?= Message-ID: <20060817191026.27995.qmail@BICSRV1011.bic.ky> I'll be out of the office until approximately August 20th. If you have any questions, please email support at bic.ky. -- David Wahler From aaronwmail-usenet at yahoo.com Fri Aug 18 12:53:37 2006 From: aaronwmail-usenet at yahoo.com (aaronwmail-usenet at yahoo.com) Date: 18 Aug 2006 09:53:37 -0700 Subject: Need a compelling argument to use Django instead of Rails In-Reply-To: <44d9771f$0$15788$14726298@news.sunsite.dk> References: <mailman.8642.1154064538.27775.python-list@python.org> <1154077105.746752.153440@h48g2000cwc.googlegroups.com> <1154080209.603694.161170@i42g2000cwa.googlegroups.com> <1154092298.714808.158250@75g2000cwc.googlegroups.com> <44ca3420$0$30140$636a55ce@news.free.fr> <jeokc2tisel285nois1ini5qhh0o70m2s6@4ax.com> <5hnlc25hfj56btkhdamfdi5gb5a3b8ts45@4ax.com> <mailman.8731.1154352939.27775.python-list@python.org> <1154354727.457387.142840@h48g2000cwc.googlegroups.com> <3scsc252be3d7a814ogj1ibnud3aothc1l@4ax.com> <1154512062.251725.177140@m73g2000cwd.googlegroups.com> <7xejvz5mwj.fsf@ruckus.brouhaha.com> <44d3817d$0$13470$636a55ce@news.free.fr> <44d4bdee$0$15790$14726298@news.sunsite.dk> <1154973660.634765.68700@i42g2000cwa.googlegroups.com> <44d9771f$0$15788$14726298@news.sunsite.dk> Message-ID: <1155920017.666288.229350@m79g2000cwm.googlegroups.com> Damjan wrote:> > Starting a new Apache process with python included (trough mod_python) is > even worse than CGI. Yes, but I think only for the first interaction after being dormant for a period. In fact I've noticed that hitting http://www.xfeedme.com the first time is usually slow. But once the apache is up it seems to stay up until it has been inactive for a good while, and it's fast. I'm inferring all this from what I see using "ps" and other indirect tools. -- Aaron Watters === as the poet said: "Everybody have fun tonight Everybody Wang Chung tonight" From skip at pobox.com Thu Aug 10 11:24:45 2006 From: skip at pobox.com (skip at pobox.com) Date: Thu, 10 Aug 2006 10:24:45 -0500 Subject: Eval (was Re: Question about the use of python as a scripting language) In-Reply-To: <17D29C4E-1481-4E52-B522-E881357376E2@carnegielearning.com> References: <mailman.33888.1155215103.27774.python-list@python.org> <CC0D63AF-2F0C-4B84-A8BA-BFE5BBE1036B@carnegielearning.com> <17627.14233.684281.17915@montanaro.dyndns.org> <16E7238C-8601-4A9D-B244-E9D8668966DE@carnegielearning.com> <17627.18125.510532.334070@montanaro.dyndns.org> <17D29C4E-1481-4E52-B522-E881357376E2@carnegielearning.com> Message-ID: <17627.20413.614511.456636@montanaro.dyndns.org> Brendon> Am I missing a third option? I can't think of one, but I'm not very smart. ;-) Skip From martin at v.loewis.de Wed Aug 2 15:17:13 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 02 Aug 2006 21:17:13 +0200 Subject: ElementTree and Unicode In-Reply-To: <1154532671.351968.142890@b28g2000cwb.googlegroups.com> References: <1154530195.741884.34350@h48g2000cwc.googlegroups.com> <eaqeh4$lsc$1@south.jnrs.ja.net> <1154532671.351968.142890@b28g2000cwb.googlegroups.com> Message-ID: <44D0FA39.8030504@v.loewis.de> S?bastien Boisg?rault schrieb: > I am trying to embed an *arbitrary* (unicode) strings inside > an XML document. Of course I'd like to be able to reconstruct > it later from the xml document ... If the naive way to do it does > not work, can anyone suggest a way to do it ? XML does not support arbitrary Unicode characters; a few control characters are excluded. See the definiton of Char in http://www.w3.org/TR/2004/REC-xml-20040204 [2] Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] Now, one might thing you could use a character reference (e.g. �) to refer to the "missing" characters, but this is not so: [66] CharRef ::= '&#' [0-9]+ ';' | '&#x' [0-9a-fA-F]+ '; Well-formedness constraint: Legal Character Characters referred to using character references must match the production for Char. As others have explained, if you want to transmit arbitrary characters, you need to encode it as text in some way. One obvious solution would be to encode the Unicode data as UTF-8 first, and then encode the UTF-8 bytes using base64. The receiver of the XML document then must do the reverse. Regards, Martin From elliot.hughes at gmail.com Mon Aug 21 04:09:25 2006 From: elliot.hughes at gmail.com (elliot.hughes at gmail.com) Date: 21 Aug 2006 01:09:25 -0700 Subject: Send to all clients using UDP in Twisted In-Reply-To: <44e8edb0$0$4530$e4fe514c@news.xs4all.nl> References: <1156096030.610574.279220@h48g2000cwc.googlegroups.com> <44e8edb0$0$4530$e4fe514c@news.xs4all.nl> Message-ID: <1156147765.869152.294510@p79g2000cwp.googlegroups.com> Thanks for the responce, I am sending over the internet so I can't use that method. Thanks for the reply anyway! Martin P. Hellwig wrote: > Elliot Hughes wrote: > > Hi Everyone, I am trying to right a server that can receive a message > > and send it to all clients using UDP on twisted. I have got it so far > > that it can echo to the client that sent the message but not to the > > rest. I tried using multicast but that requires almost total rewrite, > > and the client which is not in python can't handle it. Are there any > > alternative methods or a workaround? > > > > Thanks alot for your time! > > > Depends on you network topology and infrastructure, one possible option > is that if the clients are on the same subnet you could send it to the > broadcast address, however that wouldn't make your netadmin happy, if he > didn't filter broadcast in the first place (many switches default filter > that). > > -- > mph From polychrom at softhome.net Thu Aug 31 05:30:42 2006 From: polychrom at softhome.net (mistral) Date: 31 Aug 2006 02:30:42 -0700 Subject: Python for Windows In-Reply-To: <44F617B1.5000805@websafe.com> References: <1156889674.296093.5390@74g2000cwt.googlegroups.com> <12fb95ba4q18i53@corp.supernews.com> <FNhJg.121908$LF4.61023@dukeread05> <1156954258.821092.112660@p79g2000cwp.googlegroups.com> <44F617B1.5000805@websafe.com> Message-ID: <1157016642.172882.38010@i3g2000cwc.googlegroups.com> Larry Bates ?????(?): > mistral wrote: > > hg ?????(?): > >> Grant Edwards wrote: > >>>> Will the msi installer modify registry or other system files? > >>>> Does it possible install Python not touching registry and > >>>> system files? > >> You can make your own installer to install Python, and make sure the > >> registry is not touched - I think the current installer modifies at > >> least the .py .pyw file association. > >> hg > > > > -------------------- > > not sure how to make custom installer to install Python on windows. Is > > there some ready one? > > If msi installer modify just pair of keys, and not touch system files, > > then OK. Have it uninstaller also? > > mistral ---------------------------------------------- > If you really want to install Python on Windows, I would recommend that > you get ActiveState Python, it comes as .MSI installer and has > uninstaller. > http://www.activestate.com/Products/ActivePython/ > It does minimal registry changes and I know of no system file changes > (but I could be wrong). If you want to put a program written in python > on a workstation you don't have to put python on it. Use py2exe to > package it and create an installer with Inno Setup. > -Larry ok, I just want run Python file, which will generate html file. mistral From antroy at gmail.com Wed Aug 2 09:32:23 2006 From: antroy at gmail.com (Ant) Date: 2 Aug 2006 06:32:23 -0700 Subject: Zipping files/zipfile module In-Reply-To: <eap58h$e7p$1@eeyore.INS.cwru.edu> References: <1154483883.796081.35140@p79g2000cwp.googlegroups.com> <eap58h$e7p$1@eeyore.INS.cwru.edu> Message-ID: <1154525543.380887.101330@i3g2000cwc.googlegroups.com> Enabling directory recursion: > from os import listdir, mkdir > from os.path import join, basename, isfile > from zipfile import ZipFile > > def zip_dir(path, output_path, include_hidden=True): > try: > mkdir(output_path) > except OSError, e: > if e.errno == 17: # Path exists > pass > zip_file = ZipFile(join(output_path, 'temp.zip'), 'w') for root, dirs, files in os.walk(dir): for f in files: fp = path.join(root, f) zip_file.write(fp, fp[len(dir):]) # Write to zip as a path relative to original dir. > zip_file.close() From riko at despammed.com Thu Aug 24 11:18:45 2006 From: riko at despammed.com (Mc Osten) Date: Thu, 24 Aug 2006 17:18:45 +0200 Subject: Python and STL efficiency References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <eccb9u$kjs$1@gemini.csx.cam.ac.uk> <1hkh28d.xscw4v1y4v9a6N%riko@despammed.com> <mailman.9640.1156247569.27775.python-list@python.org> <1hkh6lb.6dsnh51lj8z96N%riko@despammed.com> <1156252193.524186.107520@b28g2000cwb.googlegroups.com> <1hkhexv.18m65rl61swqyN%riko@despammed.com> <1156265848.875774.251640@i42g2000cwa.googlegroups.com> <1156290607.269119.88710@b28g2000cwb.googlegroups.com> <1hkil6j.xm4l6y1kwo13dN%riko@despammed.com> <1156317315.946762.215690@p79g2000cwp.googlegroups.com> <1hkioxy.42be4c1lg0jq5N%riko@despammed.com> <1156320792.011620.141030@m79g2000cwm.googlegroups.com> <1hkitqt.c17kl5o30nr4N%riko@despammed.com> <1156340217.774595.282950@75g2000cwc.googlegroups.com> <1156343260.399048.182310@m73g2000cwd.googlegroups.com> <1hkjdnl.1pw8bkv892pxcN%riko@despammed.com> <slrneer7g7.1is.horpner@FIAD06.norwich.edu> Message-ID: <1hkl3wk.1fbeeip1c95a3fN%riko@despammed.com> Neil Cerutti <horpner at yahoo.com> wrote: > Those of you experiencing a temporary obsession with this topic > are encouraged to study The Great Language Shootout, until the > obsession goes away. ;) I think that everybody knows GLS. However, when I have results different from what I expected, I try to understand where I did the wrong assumption. However, a recent post kind of explains what the problem is. -- blog: http://www.akropolix.net/rik0/blogs | Uccidete i filosofi, site: http://www.akropolix.net/rik0/ | tenetevi riso e forum: http://www.akropolix.net/forum/ | bacchette per voi. From noway at onthenet.com Mon Aug 14 02:26:09 2006 From: noway at onthenet.com (Jive Dadson) Date: Mon, 14 Aug 2006 06:26:09 GMT Subject: Drawing a grid on a picture In-Reply-To: <N9UDg.155357$c82.96049@fe07.news.easynews.com> References: <N9UDg.155357$c82.96049@fe07.news.easynews.com> Message-ID: <5IUDg.314851$1Q1.70663@fe03.news.easynews.com> I also found a reference to something called PIL. Maybe that's the ticket. If so, where can I find it (with documentation)? Thanks. From Bulkan at gmail.com Tue Aug 1 03:01:48 2006 From: Bulkan at gmail.com (placid) Date: 1 Aug 2006 00:01:48 -0700 Subject: suppressing the console in a GUI program In-Reply-To: <44cece23$0$1490$c3e8da3@news.astraweb.com> References: <44cecd53$0$11833$c3e8da3@news.astraweb.com> <44cece23$0$1490$c3e8da3@news.astraweb.com> Message-ID: <1154415708.698430.318420@p79g2000cwp.googlegroups.com> John Salerno wrote: > John Salerno wrote: > > Hi guys. I tried naming my file with a .pyw extension, but the console > > still shows up. Why doesn't this work? And is there another, more > > programmatic way to suppress it? > > > > Thanks. > > I just noticed that the console that opens isn't the normal one, it's > IPython. Now how would I suppress that one as well? Again, any way to do > it in the program, or is that not a good idea for when it gets ported > to another platform? <try> via Explorer --> File Options --> File Types find PYW entry in the list and change the associated program to pythonw </try> Cheers From mr.roboto.ny at gmail.com Fri Aug 25 14:20:55 2006 From: mr.roboto.ny at gmail.com (Mr. Roboto) Date: 25 Aug 2006 11:20:55 -0700 Subject: [Q] About an Installer Script for PyWin Message-ID: <1156530055.277322.303340@i42g2000cwa.googlegroups.com> I need PyWin under the covers, that is, to install it as part of an application, but in such a way that it isn't visible to users. I'm concerned about a so-called "power-user", seeing the Python directory and/or the corresponding entry in the 'Add/Remove Programs' list, breaking my app by uninstalling what he/she thinks is removing an 'unnecessary program.' Unfortunately, I don't see any installer scripts, like for Inno Setup or NSIS in the source archive I just downloaded from SourceForge. I'd love to volunteer to do something like this for the larger community of Pythonista, but I can't find any info (via Google) about this. AFAIK, the critical info is related to the registry settings for the Win32-related elements. I'm especially concerned about installation of the COM infrastructure, as getting the other registry settings is mostly tedious (but doable), trial-and-error exports from the Registry. The rest "should" be simply a matter of creating the primary directory structure and copying the archive files to it. Does anyone have pointers ? TIA.... From gelists at gmail.com Sat Aug 5 17:54:01 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Sat, 5 Aug 2006 18:54:01 -0300 Subject: Nested function scope problem References: <20060804094245.A9AF.SLAWOMIR.NOWACZYK.847@student.lu.se> <1okvniwl5zgqj.dlg@gelists.gmail.com> <20060804155855.EE80.SLAWOMIR.NOWACZYK.847@student.lu.se> <mailman.8997.1154711381.27775.python-list@python.org> <vs27d2ls81p6jhugp1et05qkpe11d0mebb@4ax.com> <mailman.9003.1154731508.27775.python-list@python.org> <slrned93s3.2k4.apardon@rcpc42.vub.ac.be> Message-ID: <vx0igw0wjbsn$.dlg@gelists.gmail.com> On 2006-08-05 09:30:59, Antoon Pardon wrote: >> But this means that C variables are not analog to Python variables, >> [...] > > Yes they are. Nobody so far has been able to create a simple table with analog operations Python vs C that operates on C /variables/ (not dereferenced pointers) and makes any sense. (Similar to the one Dennis just posted.) Just do it (I mean state a few operations on/with variables in either language, and what the analog operation in the other language is), and I may be a convert :) >> [...] C dereferenced pointers are. > > No they are not. a = b in Python translates to: a = b in C. It doesn't > translate to *a = *b in C. Hold this thought for a little while... > It is true that a = b + c in Python doesn't translate to a = b + c in > C, but since this really is a shortcut of a = b.__add__(c) there > is nothing wrong with tranlating it into something like: > a = IntPlus(b, c) for C, where the IntPlus will provide a new pointer > that points to the sum [...] Did you hold that thought? Now IntPlus() returns a "new pointer", which means that c is a pointer variable, not a value variable. Didn't you write above that it wasn't a pointer? > or we could provide the necessary structures so that we could translate > is as: a = b->__add__(c) Which of course again requires b to be a pointer. You seem not to be clear whether you want to create a C analogy (to Python variables) of C variables (as you stated above) or of C dereferenced pointers (as your code examples show). > [...] then there is something in C deserving the term variable which > behaves like variables do in Python. ?? There /is/ something in C called a variable. And there is something in Python (at least commonly) called variable. But IMO they don't behave in a similar way. (It is obviously possible to create something in C that behaves like a Python variable, but that's then not a C variable. It's a more complex C construct.) Gerhard From david_wahler at bic.ky Thu Aug 10 09:46:40 2006 From: david_wahler at bic.ky (david_wahler at bic.ky) Date: 10 Aug 2006 08:46:40 -0500 Subject: ChiPy Chicago Python User Group Meeting Tomorrow Message-ID: <20060810134640.22732.qmail@BICSRV1011.bic.ky> I'll be out of the office until approximately August 20th. If you have any questions, please email support at bic.ky. -- David Wahler From g.brandl-nospam at gmx.net Sun Aug 20 13:45:58 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Sun, 20 Aug 2006 19:45:58 +0200 Subject: import In-Reply-To: <1156094307.576025.3430@i3g2000cwc.googlegroups.com> References: <1156093283.529579.80600@i42g2000cwa.googlegroups.com> <1156093799.775420.51970@m73g2000cwd.googlegroups.com> <1156094307.576025.3430@i3g2000cwc.googlegroups.com> Message-ID: <eca74o$uje$2@news.albasani.net> figo_wei01 at 126.com wrote: > bugnthecode ??? > >> How are you trying to import it? Is it in the same directory as your >> other script? If not is your python path set correctly? >> >> When importing a module that you have written you exlude the .py >> extension. You should be using: >> import hello >> >> Hope that helps, >> Will > > i am on a windows platform. i have written scrip named 123.py. it can > be run. ok i save it to C:\Python24 ,exactly the same dir where python > works. but " import 123" doesnt work. You can't import modules whose names have non-identifier names with plain "import". Or would you like "123" to refer to a module? If you have to do this (and I have a strong feeling that you haven't) use the built-in function __import__(). Georg From nyamatongwe+thunder at gmail.com Fri Aug 11 19:19:48 2006 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Fri, 11 Aug 2006 23:19:48 GMT Subject: Boost Install In-Reply-To: <1155308267.236139.206650@i3g2000cwc.googlegroups.com> References: <1155308267.236139.206650@i3g2000cwc.googlegroups.com> Message-ID: <og8Dg.10685$rP1.5775@news-server.bigpond.net.au> Jeff: > I have attempted to follow some online install directions which do not > seem to work. I am using VS2005. VS2003 is more likely to work since that was the compiler used for the python executables distributed by python.org. > I have tried, bjam "--with-python-version[=2.4] and just get a > statement saying that bjam is not recognized. Really is no batch file > or executable with that name in the boost directory. IIRC it was an extra step although I remember getting quite confused installing Boost.Python. http://www.boost.org/more/getting_started.html#step2 Neil From roy at panix.com Tue Aug 1 13:25:56 2006 From: roy at panix.com (Roy Smith) Date: Tue, 1 Aug 2006 17:25:56 +0000 (UTC) Subject: Railroad track syntax diagrams References: <PzLzg.29035$rp4.24346@tornado.texas.rr.com> Message-ID: <eao2r4$rpb$1@reader2.panix.com> Paul McGuire <ptmcg at austin.rr._bogus_.com> wrote: > For those who are not familiar with railroad syntax diagrams, they > show a grammar's syntax using arrows and blocks, instead of BNF I've always liked railroad diagrams. Oracle used to use them (maybe they still do?) in their SQL reference manuals. I find them much easier to understand than BNF. From rafal at ewipo.pl Wed Aug 16 13:50:43 2006 From: rafal at ewipo.pl (=?ISO-8859-2?Q?=22Rafa=B3_Janas=22?=) Date: Wed, 16 Aug 2006 19:50:43 +0200 Subject: drawingarea problem Message-ID: <190311477344e35af34e0972.59986229.Active.mail@poczta.nazwa.pl> Is somebody try to paint filled boxes in drawingarea? I don't know how to paint line or someting like this. Maybe somebody have tutorial or samples? Thanks Rafal From gagsl-py at yahoo.com.ar Thu Aug 31 12:02:01 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 31 Aug 2006 13:02:01 -0300 Subject: Searching a string and extract all occurancies of a substring In-Reply-To: <44F703C8.3080504@gmail.com> References: <44F703C8.3080504@gmail.com> Message-ID: <7.0.1.0.0.20060831130033.05175028@yahoo.com.ar> At Thursday 31/8/2006 12:44, Nico Grubert wrote: >in a text with no carriage returns I need to look for all occurancies of >this string: > ><source id="box"><parameter key="path">...</parameter></source> Try Beautiful Soup, or if your input is simple enough, the re module. Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From nnorwitz at gmail.com Mon Aug 28 23:43:30 2006 From: nnorwitz at gmail.com (nnorwitz at gmail.com) Date: 28 Aug 2006 20:43:30 -0700 Subject: How ahead are you guys in the (Python) real world? In-Reply-To: <1156821234.820929.299740@p79g2000cwp.googlegroups.com> References: <1156821234.820929.299740@p79g2000cwp.googlegroups.com> Message-ID: <1156823010.100780.101840@74g2000cwt.googlegroups.com> Ray wrote: > > Is it the same in the Python world? What version of Python is used in, > say, Google? Is it even 2.4 yet? Google uses many versions of Python including 2.2, 2.3 and 2.4. Though 2.4 is relatively new. I hope to start introducing Python 2.5 sometime next year. Mid-year is about as early as it could possibly happen, and is likely to be much later. We need to kill off older versions (2.2 and 2.3) first. Mostly it depends on the size of the company/source code base/installations. The smaller these are, the easier it is (should be) to move to a new version. n From steve at holdenweb.com Mon Aug 28 04:41:37 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 28 Aug 2006 09:41:37 +0100 Subject: Segmentation Fault In-Reply-To: <1156737764.729811.297280@m79g2000cwm.googlegroups.com> References: <1156737764.729811.297280@m79g2000cwm.googlegroups.com> Message-ID: <ecua71$pkb$1@sea.gmane.org> pycraze wrote: > I would like to ask a question. How do one handle the exception due to > Segmentation fault due to Python ? Our bit operations and arithmetic > manipulations are written in C and to some of our testcases we > experiance Segmentation fault from the python libraries. > > If i know how to handle the exception for Segmentation fault , it will > help me complete the run on any testcase , even if i experiance Seg > Fault due to any one or many functions in my testcase. > You will observe, if you look at the list of Python exceptions, that a segfault isn't among them. A segfault is a trap to the hardware, and generally indicates that a program is so badly hosed that it wouldn't make much sense to rely on any further computation in it. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From fredrik at pythonware.com Tue Aug 15 17:44:20 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 15 Aug 2006 23:44:20 +0200 Subject: Reference Variables In Python Like Those In PHP In-Reply-To: <1155669800.977938.75450@74g2000cwt.googlegroups.com> References: <1155651471.605912.46640@m73g2000cwd.googlegroups.com> <1155669800.977938.75450@74g2000cwt.googlegroups.com> Message-ID: <ebtf7a$1fm$3@sea.gmane.org> Luke Plant wrote: > You should note that, to a nearest equivalent, all variables are > reference variables in Python. The difference is in what assignment > does - += in Python does an assignment of a new object for immutable > objects. For mutable objects like lists, += does an in place > modification. that depends on the object implementation, though -- the "+=" statement does not, in itself, distinguish between mutable and immutable objects. </F> From andre at svn2.wasy.de Tue Aug 22 02:45:26 2006 From: andre at svn2.wasy.de (Andre Poenitz) Date: Tue, 22 Aug 2006 08:45:26 +0200 Subject: Loading module via full path References: <nk4or3-hr4.ln1@svn2.wasy.de> Message-ID: <6plqr3-jq7.ln1@svn2.wasy.de> Andre Poenitz <andre at svn2.wasy.de> wrote: > Hi all. > > Is there a way to load a module given a full path to the module > without extending sys.path first? Ok. imp.find_module() and imp.load_module() seem to do what I need. Andre' From slawomir.nowaczyk.847 at student.lu.se Wed Aug 9 10:23:22 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Wed, 09 Aug 2006 16:23:22 +0200 Subject: do people really complain about significant whitespace? In-Reply-To: <1155124820.123151.140580@p79g2000cwp.googlegroups.com> References: <mailman.9132.1155120873.27775.python-list@python.org> <1155124820.123151.140580@p79g2000cwp.googlegroups.com> Message-ID: <20060809161037.EF02.SLAWOMIR.NOWACZYK.847@student.lu.se> On Wed, 09 Aug 2006 05:00:20 -0700 "brianmce at gmail.com" <brianmce at gmail.com> wrote: #> Slawomir Nowaczyk wrote: #> > #> > I must admit I do not get this "indicate intentions twice" argument, #> > even though I heard it a number of times now... It's not that braces #> > require more work or more typing or something, after all -- at least #> > not if one is using a decent editor. #> #> Its not the typing, its the fact that when you say the same thing #> twice, there is the potential for them to get out of sync. Which, in my book, is the *right* thing... if I see a wrongly indented piece of code, that's a good sign that it needs to be checked. It's the same principle as in "if documentation and code disagree, both are probably wrong." YMMV, of course. #> If the method the compiler uses (braces) and the method the human #> uses (indentation) to determine what the code does don't agree, #> then a reader will be likely to misunderstand what it will actually #> do. Well, not in my experience. In my experience, such discrepancies usually only show up in places where something bad happens anyway. #> One of the driving principles behind Python is that, because code #> will be read more often than written, readability is more #> important. That's exactly my point :) -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) Today advance is so rapid that even the astronauts who set foot on the moon in 1969 had never seen a digital watch From jiangnutao at gmail.com Wed Aug 23 13:44:54 2006 From: jiangnutao at gmail.com (Jiang Nutao) Date: Wed, 23 Aug 2006 10:44:54 -0700 Subject: swapping numeric items in a list References: <mailman.9675.1156291509.27775.python-list@python.org> <pan.2006.08.23.10.13.15.854509@gmx.net> Message-ID: <eci46s$ejs$1@sea.gmane.org> Thank you all guys for the help. Guess I'm gonna pick bearophile's way. It's fast, neat, and easy to read. array.byteswap() won't work for me easily. I tried this before my 1st post. I defined aa = array('H', [0x12, 0x34, 0x56, 0x78]) Then did byteswap aa.byteswap(). The result was array('H', [0x1200, 0x3400, 0x5600, 0x7800]) You can see it byteswapped within each item. Jason "Marc 'BlackJack' Rintsch" <bj_666 at gmx.net> wrote in message news:pan.2006.08.23.10.13.15.854509 at gmx.net... > In <mailman.9675.1156291509.27775.python-list at python.org>, Jiang Nutao > wrote: > >> To convert list >> aa = [0x12, 0x34, 0x56, 0x78] >> into >> [0x34, 0x12, 0x78, 0x56] >> >> How to do it fast? My real list is huge. > > Use the `array` module and the `array.byteswap()` method. > > Ciao, > Marc 'BlackJack' Rintsch > -- > http://mail.python.org/mailman/listinfo/python-list > From saketh.bhamidipati at gmail.com Mon Aug 7 16:25:57 2006 From: saketh.bhamidipati at gmail.com (Saketh) Date: 7 Aug 2006 13:25:57 -0700 Subject: distutils setup.py Message-ID: <1154982357.370514.73060@n13g2000cwa.googlegroups.com> I'm having trouble getting the data_files argument of my setup.py to work with "python setup.py sdist" under Windows XP. Here is the data_files argument that I pass to setup(). data_files = [\ ('res','app.ico'), ('', 'preferences.xml'), ('res', glob.glob(os.path.join('res','*.png')))], ) My setup.py is in the same directory as "preferences.xml". I use this setup.py for both py2exe and sdist. When I use it for py2exe, the data_files are properly copied to the target directory. However, when I use it for sdist, none of the data_files are copied. If this were a directory problem, then setup.py would have failed earlier when I specified Application.py in the "scripts" argument. How can I get the data_files copied properly without having to manually edit the MANIFEST file? Thanks, Saketh From paddy3118 at netscape.net Tue Aug 1 15:35:20 2006 From: paddy3118 at netscape.net (Paddy) Date: 1 Aug 2006 12:35:20 -0700 Subject: Railroad track syntax diagrams In-Reply-To: <1154459109.126048.35320@p79g2000cwp.googlegroups.com> References: <PzLzg.29035$rp4.24346@tornado.texas.rr.com> <1154459109.126048.35320@p79g2000cwp.googlegroups.com> Message-ID: <1154460920.066267.220330@p79g2000cwp.googlegroups.com> Paddy wrote: > Paul McGuire wrote: > > Back in the mid-90's, Kees Blom generated a set of railroad syntax diagrams > > for Python > > (http://python.project.cwi.nl/search/hypermail/python-1994q3/0286.html). > > This pre-dates any Python awareness on my part, but I'm sure this would have > > been version 1.3 or something. > > > > For those who are not familiar with railroad syntax diagrams, they show a > > grammar's syntax using arrows and blocks, instead of BNF - here's an excerpt > > from the Python grammar, plus "ASCII-art" diagrams - must be viewed in > > non-prop font to be appreciated: > > > > suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT > > > > ----+--> simple_stmt --------------------------------->\ > > | | > > \--> NEWLINE --> INDENT --+--> stmt --+--> DEDENT --+--> > > / | > > \----<-------/ > > > > if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] > > > > > > --> 'if' -> test --> ':' --> suite -->+ > > | > > ------------<-------------------+ > > / > > + > > | ------------<------------------------ > > |/ \ > > + | > > | | > > +-> 'elif' -> test -> ':' --> suite -->/ > > | > > | > > +-> 'else' -> ':' --> suite --> > > | \ > > \---------------->--------------+-------> > > > > > > I was recently contacted by a volunteer in Banda Aceh teaching tsunami > > refugees how to program in Python (new job skills and all that), and he > > asked if there were any updated versions of these diagrams, or if it would > > be difficult to generate them anew. It seems that railroad diagrams are > > nice and unambiguous for his students to use, in the face of verbal language > > barriers. > > > > I have written a pyparsing parser that reads the grammar file that ships > > with Python - the parser is included in the latest release of pyparsing, and > > also online at the pyparsing.wikispaces.com - but I have no graph-generating > > tools to go the next step: generation of the railroad diagrams (in something > > more legible/appealing than ASCII-art!). > > > > Anyone interested in helping complete this last step? > > > > Thanks, > > -- Paul > I googlled and got these: > http://www.informatik.uni-freiburg.de/~thiemann/haskell/ebnf2ps/ > http://www.antlr.org/share/1107033888258/SDG2-1.5.zip > > - Paddy. And this suite includes a digram generator: http://www.research.philips.com/technologies/syst_softw/elegant/index.html - Pad. From cga2000 at optonline.net Mon Aug 21 16:48:00 2006 From: cga2000 at optonline.net (cga2000) Date: Mon, 21 Aug 2006 16:48:00 -0400 Subject: text editor suggestion? In-Reply-To: <ecc77l$l47$1@sunnews.cern.ch> References: <44e66724$0$2363$c3e8da3@news.astraweb.com> <mailman.9525.1155953260.27775.python-list@python.org> <44e6ab26$0$12557$c3e8da3@news.astraweb.com> <ecc77l$l47$1@sunnews.cern.ch> Message-ID: <20060821204800.GM12939@turki.gavron.org> On Mon, Aug 21, 2006 at 07:59:49AM EDT, Roberto Bonvallet wrote: > John Salerno wrote: > > I'd really like to learn vim, but I spent days just trying to figure out > > how to get the syntax highlighting and indentation working, where these > > settings are and how to edit them, and it still doesn't work for me. It > > just feels so insurmountable that I can't even start working with it yet > > because I don't know how to tailor the settings. > > Create a vimrc file (if you use Unix: ~/.vimrc) with the following lines in > it: > > syntax on > set autoindent > set smartindent > > If you find that using vim is hard, try using evim (easy vim). It is part > of the standard vim distribution (actually it's the same program). Anyway, > I suggest learning the classic modal vim, it's really worth it. I'm not sure anyone else mentioned it. One additional feature of Vim that you soon will appreciate is that you get high quality (and timely) support from very knowledgeable users on the vim at vim.org mailing list. I am unsure whether simpler editors provide this type of thing. As to creating one's own color schemes .. there are hundreds that can be downloaded and installed in a matter of minutes and they're likely much better than what I would be able to come up with. Some people are just good at this kind of stuff and I'm not one of 'em. :-) So, I tried out the ones that looked nice .. selected a few that I liked more than the others .. and changed a few things that didn't suit me to create my own modified versions of the originals. Thanks cga From steve at holdenweb.com Tue Aug 15 06:15:20 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 15 Aug 2006 11:15:20 +0100 Subject: Newbie: calling the originating class ... In-Reply-To: <1155625995.101230.256210@74g2000cwt.googlegroups.com> References: <1155625995.101230.256210@74g2000cwt.googlegroups.com> Message-ID: <ebs6r2$lvt$1@sea.gmane.org> donkeyboy wrote: > This is probably very straightforwards to someone with experience, but > I will try to explain my predicament: > > I'm trying to code a simulation, where you have a Simulation class that > knows everything about the simulation, and in turn classes that the > Simulation calls when it wants to make new instances -- for the time > being, let's call the called classes Agents (sorry, saw the Matrix > again last night!). > > In the Simulation class, there's information about the simulation that > each Agent wants to know. As such, I wrote a method in the Simulation > class for the Agents to call, to get the said required information. > However, I can't figure out a way for the Agents to call the > Simulations methods -- is this even possible? > > The pseudo-code I'm using is as follows: > > s = Simulation() > > class Simulation: > # create a number of agents > ... > # Simulation information > important_stuff = 10 > > def showImportant(self): > return important_stuff > > class Agents: > my_stuff = s.showImportant > > .... which fails: I get errors saying the global name 's' is not > defined. Any thoughts? Is what I'm trying to do even possible, or > should I be doing something else? > Well obviously your agents each need a reference to the simulation. In the simulation methods the simulation instance can be referred to as self, so you can pass that as an argument to the agent creator. As in: sholden at bigboy ~/Projects/Python $ !cat cat test44.py # # Calling all reactive agents (with apologies to William Burroughs) # class Simulation: def __init__(self, howmany): self.agents = [] for i in range(howmany): self.agents.append(Agent(self, i)) def showImportant(self, agent): return agent.number, self def listAgents(self): for a in self.agents: a.showMe() class Agent: def __init__(self, sim, number): self.sim = sim self.number = number def showMe(self): print "Agent", self.number, "reporting:" result = self.sim.showImportant(self) print result s = Simulation(5) s.listAgents() sholden at bigboy ~/Projects/Python $ python test44.py Agent 0 reporting: (0, <__main__.Simulation instance at 0x186c6c8c>) Agent 1 reporting: (1, <__main__.Simulation instance at 0x186c6c8c>) Agent 2 reporting: (2, <__main__.Simulation instance at 0x186c6c8c>) Agent 3 reporting: (3, <__main__.Simulation instance at 0x186c6c8c>) Agent 4 reporting: (4, <__main__.Simulation instance at 0x186c6c8c>) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From tim.leeuwvander at nl.unisys.com Mon Aug 21 09:16:52 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 21 Aug 2006 06:16:52 -0700 Subject: Python and STL efficiency In-Reply-To: <1156165101.702758.148420@74g2000cwt.googlegroups.com> References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <mailman.9595.1156153010.27775.python-list@python.org> <1156162237.274636.17850@i3g2000cwc.googlegroups.com> <1156165101.702758.148420@74g2000cwt.googlegroups.com> Message-ID: <1156166212.219325.62580@75g2000cwc.googlegroups.com> Tim N. van der Leeuw wrote: > Ray wrote: > > Fredrik Lundh wrote: > > > in the Python example, the four strings in your example are shared, so > > > you're basically copying 40000 pointers to the list. > > > > > > in the C++ example, you're creating 40000 string objects. > > > > > > </F> > > > > In which case, Licheng, you should try using the /GF switch. This will > > tell Microsoft C++ compiler to pool identical string literals together. > > > > > > :) > > The code still creates a new string - instance each time it tries to > append a const char* to the vector<string> ... > > You should instead create the string-objects ahead of time, outside of > the loop. > > Regards, > > --Tim Alternatively, slow down the Python implementation by making Python allocate new strings each time round: a.append('%s' % 'What do you know') ... for each of your string-appends. But even then, the python-code is still near-instant. Cheers, --Tim From larry.bates at websafe.com Wed Aug 23 17:00:16 2006 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 23 Aug 2006 16:00:16 -0500 Subject: CONSTRUCT - Module Attributes and Execution Environment In-Reply-To: <ecfadm$gh0$1@news.albasani.net> References: <1156253227.092971.36510@74g2000cwt.googlegroups.com> <FbydnandyMuUtHbZnZ2dnUVZ_smdnZ2d@comcast.com> <ecfadm$gh0$1@news.albasani.net> Message-ID: <woedncvA9rxuXHHZnZ2dnUVZ_oWdnZ2d@comcast.com> Georg Brandl wrote: > Larry Bates wrote: >> lazaridis_com wrote: >>> I would like to change the construct: >>> >>> if __name__ == '__main__': >>> >>> to something like: >>> >>> if exec.isMain(): >>> >>> My (OO thought) is to place a class in an separate code module and to >>> instantiate an singleton instance which would keep th something like >>> this: >>> >>> class ExecutionEnv: >>> def isMain(self) >>> if CALLING_MODULE.__name__ == '__main__': >>> return true >>> else >>> return false >>> >>> exec = ExecutionEnv() >>> >>> How to I get access to the CALLING_MODULE ? >>> >>> - >>> >>> Are ther alternative constructs/mechanism available, which could be >>> used to add this functionality possiby directly to a code-module? >>> >> Two thoughts: >> >> 1) Don't call a class instance exec, it will mask the built-in >> exec statement. > > He won't be able to ;) > > Georg You are correct exec is a reserved word and can't be used as a variable name. Thanks for pointing that out. -Larry From geli at tasmail.com Tue Aug 22 01:26:26 2006 From: geli at tasmail.com (gel) Date: 21 Aug 2006 22:26:26 -0700 Subject: What would be the best way to run python client in the background In-Reply-To: <mailman.9408.1155715768.27775.python-list@python.org> References: <mailman.9408.1155715768.27775.python-list@python.org> Message-ID: <1156224386.721982.127320@i3g2000cwc.googlegroups.com> Tim Golden wrote: > | Tim Golden wrote: > | > | > [gel] > | > > | > | I have written a python client server app [...] > | > | I want to run the client end of the app more or less invisibly > | > | (no console) on the XP clients when ever a users logs on. > > [Tim G] > | > The normal way is to run a Win32 service. There are several > | > posts on the subject around the Python and Python-Win32 > | > mailing lists / newsgroups. The alternative is to set something > | > to run when any user logs in to run without a window. Again, > | > there are posts on the subject, including one I seem to remember > | > from Robin Becker, which tell how to do this kind of thing. > > [gel] > | Yes running the client as a service seems to be the way to go. I have > | had a bit of a look at the py2exe way of doing it, but have not got my > | head around it yet. What would be your preferred way of creating a > | service for an XP client? > > I've always coded pretty much from scratch, reusing a tried-and-trusted > skeleton and fitting things in. That said, I've never had to put > together > a service that was anything more than lightweight. The attached template > I > culled from someone's webpage, can't remember where I'm afraid. I > believe > people have had success in using py2exe to create a service but I > haven't > tried it myself. > > Hopefully more experienced service-writers will chime in with coherent > advice. You might also try the python-win32 mailing list, since not > everyone who reads that reads this I imagine. > > TJG > Can I give you a look at the client side and ask for a suggestion as how best to plug this into the template that you have supplied The attempts that I made failed to start without much in the way of error messages. Any suggestion to do with my python style that you have would be appreciated too. # Import needed modules import EasyDialogs import wmi import pythoncom import threading import time import Pyro.core import Pyro.naming, Pyro.core from Pyro.errors import NamingError # locate the NS locator = Pyro.naming.NameServerLocator() print 'Searching Name Server...', ns = locator.getNS() # resolve the Pyro object print 'finding object' try: URI=ns.resolve('test') print 'URI:',URI except NamingError,x: print 'Couldn\'t find object, nameserver says:',x raise SystemExit # make and instance of Pyro object o = Pyro.core.getProxyForURI(URI) #instance of wmi and get mac address of enabled NIC c = wmi.WMI() for interface in c.Win32_NetworkAdapterConfiguration (IPEnabled=1): # print interface.Description, interface.MACAddress for ip_address in interface.IPAddress: mac = interface.MACAddress # put current time into var current_time colItems = c.ExecQuery("SELECT UserName FROM Win32_ComputerSystem") for objItem in colItems: if objItem.UserName != None: usr_name = str(objItem.UserName) print "UserName: " + usr_name # assign the dictionary object that o.r_l() returns to d_licence_numbers d_licence_numbers = o.r_l() # So I can see how many licences are available for each piece of software print d_licence_numbers print d_licence_numbers # Define the create class that watches for new processes to start def diag(mesg): EasyDialogs.Message(mesg) def create(): global usr_name pythoncom.CoInitialize() c = wmi.WMI() while 1 : current_time = time.time() d_clnt = {'MAC':mac, 'time':current_time, 'usr_name': usr_name} print d_clnt print "watching creation" watcher = c.watch_for(notification_type="Creation", wmi_class="Win32_Process", delay_secs=1) proc = watcher() name = proc.Name if d_licence_numbers.has_key(name): print "Process being watched = " + name if len(o.r_d()[name]) != 0: li = o.r_d()[name] registered = False for i in li: print usr_name print i['usr_name'] if mac == i['MAC'] or i['usr_name'] == usr_name: print "Already in there" registered = True if registered != True: for i in li: #ps_id = ps_li.index(sw) if len(o.r_d()[name]) < o.r_l()[name]: o.a_d(name, d_clnt) print "There is a license avialable for " + name print o.r_d() else: print "There are no licenses avialable for " + name for process in c.Win32_Process (): if process.Name == name: print process.ProcessId, process.Name result = process.Terminate () n = str(name) mes = 'there are no copies of ' + n + ' available, try again later' threading.Thread(target=diag(mes)).start() else: o.a_d(name, d_clnt) else: print "Process " + name + " is not being watched" # Define the delete() class that watches for processes stopped def delete(): global mac pythoncom.CoInitialize() d = wmi.WMI() while 1 : current_time = time.time() print "watching deletion" watcher = d.watch_for(notification_type="Deletion", wmi_class="Win32_Process", delay_secs=1) proc = watcher() name = proc.Name if d_licence_numbers.has_key(name): print "Process being watched = " + name still_running = False for process in d.Win32_Process (): if process.Name == name: still_running = True print name + ' is still running ' if still_running == False: perm = False li = o.r_d()[name] for i in li: if i['time'] != 0 and i['MAC'] == mac: o.dd_d(name,mac) print name + " licence is being released " perm = False else: perm = True if perm: print "Not releasing licence - it is a permenant licence" else: print "Process " + name + " not being watched" # Start a thread for each create and delete classes to run in and watch for processes starting and stopping threading.Thread(target=create).start() threading.Thread(target=delete).start() From sjdevnull at yahoo.com Wed Aug 30 00:00:32 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 29 Aug 2006 21:00:32 -0700 Subject: Allowing ref counting to close file items bad style? In-Reply-To: <7x4pvvylrh.fsf@ruckus.brouhaha.com> References: <9U6Jg.951$Xw6.283@trndny02><7x4pvvylrh.fsf@ruckus.brouhaha.com> Message-ID: <1156910432.917443.259720@p79g2000cwp.googlegroups.com> Paul Rubin wrote: > Dan <bounces at foo.org> writes: > > Is this discouraged?: > > > > for line in open(filename): > > <do something with line> > > Yes. > > > Can I count on the ref count going to zero to close the file? > > You really shouldn't. It's a CPython artifact. I disagree, somewhat. No, you shouldn't count on the "ref count" per se going to 0. And you shouldn't count on the file object being GC'd _immediately_ after the last reference is destroyed. You should be able to rely on it being GC'd at some point in the not-horribly-distant future, though. Doing an explicit .close() is not normally useful and muddies the code (and introduces more lines for potential bugs to infest). And yes, I know that the language spec technically allows for no GC at all--it's a QOI issue, not a spec issue, but any implementation that didn't GC would be useless as a general Python platform (perhaps useful for specific embedded uses, but programming for such an environment would be different from programming for rational python platforms in bigger ways than this). (And personally I think the benefits to programmers of guaranteeing ref-counting semantics would outweigh the additional headaches for Jython and other alternative implementations). From fuzzyman at gmail.com Fri Aug 11 09:16:26 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 11 Aug 2006 06:16:26 -0700 Subject: hide python code ! In-Reply-To: <mailman.9245.1155301627.27775.python-list@python.org> References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155300852.497741.73230@74g2000cwt.googlegroups.com> <mailman.9245.1155301627.27775.python-list@python.org> Message-ID: <1155302186.352955.111180@p79g2000cwp.googlegroups.com> Tim Chase wrote: > >> can we hide a python code ? > >> if i want to write a commercial software can i hide my source code from > >> users access ? > >> we can conver it to pyc but this file can decompiled ... so ...!! > > > > All of these make it hard enough to deter most people who will ever > > want to abuse your source code. Until you have *lots* of users this is > > probably enough. > > > > I never understand the knee-jerk reaction on this mailing list to > > answer people who ask this question by telling them they don't really > > want to do it... > > I think the reaction is based mostly in reality...an honest > answer: If you give people the program, then you also give them > the ability to reverse engineer it. It's as simple as that. > [snip..] But until your number of users gets beyond quite a high level, it's just extremely likely that any of your individual users will have that sort of ability - or anyone else will have the motivation to do it. What you can do with Python is almost certainly *good enough* for most people who ask this question - and that fact never seems to be included in the 'reality' propogated by the knee jerk reactionists... :-p Fuzzyman http://www.voidspace.org.uk/python/index.shtml From bj_666 at gmx.net Sat Aug 19 11:42:31 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 19 Aug 2006 17:42:31 +0200 Subject: How to get the ascii code of Chinese characters? References: <1155986298.643983.157460@i3g2000cwc.googlegroups.com> <1155990488.395220.178810@74g2000cwt.googlegroups.com> <1155999554.486951.303480@i42g2000cwa.googlegroups.com> Message-ID: <pan.2006.08.19.15.42.29.167353@gmx.net> In <1155999554.486951.303480 at i42g2000cwa.googlegroups.com>, many_years_after wrote: > what I want to do is just to make numbers as people input some Chinese > character(hanzi,i mean).The same character will create the same > number.So I think ascii code can do this very well. No it can't. ASCII doesn't contain Chinese characters. http://en.wikipedia.org/wiki/ASCII Ciao, Marc 'BlackJack' Rintsch From larry.bates at websafe.com Mon Aug 21 11:13:34 2006 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 21 Aug 2006 10:13:34 -0500 Subject: uploading files to file system/zipping/downloading problems In-Reply-To: <1156106962.684908.311950@m73g2000cwd.googlegroups.com> References: <1156106962.684908.311950@m73g2000cwd.googlegroups.com> Message-ID: <44E9CD9E.2010302@websafe.com> OriginalBrownster wrote: > I am currently uploading a file from a users computer to the file > system on my server using python, just reading the file and writing the > binaries. > > total_data=' ' > while True: > data = upload_file.file.read(8192) > if not data: > break > total_data += data > f = open(target_file_name, 'wb') > f.write(total_data) > f.close > > However when i download the file from the server it is not intact and > it cannot be opened. It is happening with every type of file. > > It seemed to be working before and now it is..maybe I goofed up and > deleted something. > However I can't seem to find it. > > any ideas?? > Two problems: First, If you start total_data with a single space (as it shows in your posted code). Then the output file has a space prepended to the file's contents and that is NOT what you probably wanted. Secondly, You are overwriting the files contents every time through the loop. Your open, would need to be outside the loop (above the while) and your close should be outside the loop also. Something more like: total_data='' f = open(target_file_name, 'wb') while True: data = upload_file.file.read(8192) if not data: break total_data += data f.write(total_data) f.close You should take a look at shutil module. It is copyfile method that makes your code must simpler (and faster I'm sure). do import shutl help(shutil.copyfile) import shutil shutil.copyfile(uload_file_name, target_file_name) -Larry Bates From sjmachin at lexicon.net Wed Aug 9 00:57:07 2006 From: sjmachin at lexicon.net (John Machin) Date: 8 Aug 2006 21:57:07 -0700 Subject: Class data being zapped by method In-Reply-To: <1155094292.614160.49320@75g2000cwc.googlegroups.com> References: <1155065906.910642.77320@75g2000cwc.googlegroups.com> <mailman.9111.1155066643.27775.python-list@python.org> <1155076971.519157.92540@i42g2000cwa.googlegroups.com> <1155081910.390971.249200@p79g2000cwp.googlegroups.com> <1155094292.614160.49320@75g2000cwc.googlegroups.com> Message-ID: <1155099427.204715.113250@n13g2000cwa.googlegroups.com> Kevin M wrote: > Inline > > > 1.) Why are you removing the .pyc file? > > After I had run the script once and subsequently changed the class > file, I would run the script again, and it would use the pyc file from > the older revision of the script. I got frustrated with having to > manually delete the pyc file before rerunning the script after every > edit, so I built it in. Huh? Something funny is going on here. (1) You should never need to delete a pyc file (2) A script run from the command line doesn't create a pyc file, only imported modules get that. So: What platform are you running it on? What version of Python? Are you running the script from the command line, or in an IDE? Which IDE? > > > 2.) Reading lines from a file is better done like so: > > > > arrLines = open('datafiles/'+filename+'.tabdata').readlines() > > > > and the 'r' flag is the default, you can omit it. > > I know. In fact, this was the original code. However, I have read in > many places that if the file is *massive*, which is true in my case, it > is far more efficient to use the line-by-line implicit method I used. > On a decent machine it doesn't really make a noticeable difference, but > some of the ".tabdata" files I'm parsing are > 20MB plain text, so I > figured that warranted the alternative approach. Firstly, 20MB is not massive. Secondly, the problem with large files is keeping a list like arrLines hanging about when you only need one line at a time. If you insist on keeping the list, get it in one hit using readlines(), instead of assembling it yourself manually. > > > John M, I realized what you meant about splitting the code between the > class and the processing file. At first it seemed intuitive, but > stepping back, it doesn't really make sense that a test would be able > to analyze and take an inventory of *itself*. I think I'm going to > reorganize the code such that the Test class does nothing but provide a > barebones data structure with which to work. > > And regarding the file separation, it's totally personal preference. It > scales well, at least. One class per file does *not* scale well, even when you're not being driven silly by having to flick backwards & forwards furiously between files :-) > > Another Aside -- > > Does anybody see any major bottlenecks in the code? I'd like to be able > to speed up the program considerably. Psyco was really no help. > 1. Get it refactored and working correctly first. "except IndexError: pass" certainly won't help you win the Grand Prix; how many of those were you doing per 20MB of data? 2. How long does it take to run ? How long would you prefer it to take? How many lines x how many tests == 20 MB? Cheers, John From ptmcg at austin.rr._bogus_.com Mon Aug 21 12:00:58 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 21 Aug 2006 16:00:58 GMT Subject: Problem of function calls from map() References: <mailman.9606.1156169593.27775.python-list@python.org> <LHkGg.20826$ph.8213@tornado.texas.rr.com> Message-ID: <_MkGg.20858$ph.14540@tornado.texas.rr.com> >>tmp is the function that split will call once per list item should be tmp is the function that *map* will call once per list item -- Paul From usenet-2004 at lithe.de Tue Aug 1 16:39:15 2006 From: usenet-2004 at lithe.de (Jan Niklas Fingerle) Date: 01 Aug 2006 20:39:15 GMT Subject: Jumping over in the class hierarchy References: <44cf7481$0$24888$9b4e6d93@newsread4.arcor-online.net> Message-ID: <44cfbbf3$0$18516$9b4e6d93@newsread2.arcor-online.net> Pupeno <pupeno at pupeno.com> wrote: > be correct to do: super(A, super(B, self)).method() in C ? Why do you want to use super? Is there any diamond shaped inheritance in sight? Anyway, have you actually tried, what you suggested? Well, ... ----------------------8<------------------------------------ class A(object): def my_method(self): print 'in A' class B(A): def my_method(self): print 'in B' super(B, self).my_method() class C(B): def my_method(self): print 'in C' super(A, super(B, self)).my_method() print "A..." A().my_method() print "B..." B().my_method() print "C..." C().my_method() ---------------------->8------------------------------------ leads to ----------------------8<------------------------------------ A... in A B... in B in A C... in C Traceback (most recent call last): File "test.py", line 20, in ? C().my_method() File "test.py", line 13, in my_method super(A, super(B, self)).my_method() TypeError: super(type, obj): obj must be an instance or subtype of type ---------------------->8------------------------------------ , at least on my machine ;-) "obj must be an instance or subtype of type". So, what's the type of "super(B, self)"? Let's see... ----------------------8<------------------------------------ class A(object): def my_method(self): print 'in A' class B(A): def my_method(self): print 'in B' super(B, self).my_method() class C(B): def my_method(self): print 'in C' print type(super(B, self)) C().my_method() ---------------------->8------------------------------------ ----------------------8<------------------------------------ in C <type 'super'> ---------------------->8------------------------------------ Seems, that super is a class. In fact "help(super)" at the interactive prompt tells you that "super(type, obj) -> bound super object; requires isinstance(obj, type)". Now, the interactive help isn't much more help, if you don't know what super does. This isn't the interactive help's (aka super's doc string's) fault. It's just that the docstring would become veeeery long if it wanted to introduce the concepts behind super. Well, now, what does super do? Let's take a simple example. Well, at least the simplest example super was really meant to handle: (real) diamond shape inheritance. ----------------------8<------------------------------------ class A(object): def my_method(self): print 'in A' class B(A): def my_method(self): print 'in B' super(B, self).my_method() class C(A): def my_method(self): print 'in C' super(C, self).my_method() class D(B,C): def my_method(self): print 'in D' super(D, self).my_method() obj = D() obj.my_method() ---------------------->8------------------------------------ ----------------------8<------------------------------------ in D in B in C in A ---------------------->8------------------------------------ What happens here? (1) We instantiate a D object named "obj" and call its my_method. (2) We instantiate a super object. We tell it, that we are "in" 'obj' and that we are interested in the next base class after handling "D". Super "asks" obj for it's ancestry (which is D-B-C-A). The next ancestor in this list is B. Therefore super(D, self).my_method() delegates the call to B.my_method. (3) We're in B.my_method now. We instantiate a super object. We tell it, that we are "in" 'obj' and that we are interested in the next base class after handling "B". Super "asks" obj for it's ancestry (which is D-B-C-A). The next ancestor in this list is C. Therefore super(B, self).my_method() delegates the call to C.my_method. (4) We're in C.my_method now. We instantiate a super object. We tell it, that we are "in" 'obj' and that we are interested in the next base class after handling "C". Super "asks" obj for it's ancestry (which is D-B-C-A). The next ancestor in this list is A. Therefore super(B, self).my_method() delegates the call to A.my_method. (5) We're in A.my_method now. Nothing more of interest will happen... Note: (a) C.my_method "gets called by" B.my_method, even though these two classes don't "know" anything about each other. (b) C.my_method would never have been called, if D used super, but B didn't (but called its parent directly). (c) Even though B and C don't know anything about each other, they have to care for each other's argument lists. Well, yes, this seems to be no problem, since a child classes method should have "the same" argument list as the base class anyway. Yet, this doesn't hold for __init__, so you have to handle __init__ with special care (i.e. you should only use **kwargs and propagate *all* parameters). (d) "super()" *does not* "cast" a child class object to the parent class (or something like this). "super(B, self)" *does not* return self as "B's super class" object. This wouldn't work correctly for diamond shapes anyway. Now that we've understood, what super() does, you could use ----------------------8<------------------------------------ class A(object): def my_method(self): print 'in A' class B(A): def my_method(self): print 'in B' super(B, self).my_method() class C(B): def my_method(self): print 'in C' super(B, self).my_method() print "A..." A().my_method() print "B..." B().my_method() print "C..." C().my_method() ---------------------->8------------------------------------ ----------------------8<------------------------------------ A... in A B... in B in A C... in C in A ---------------------->8------------------------------------ , but: Is it really the super magic, that you need? As long, as you don't have diamond shape inheritance, you can always call the base classes method directly. And casually using super doesn't help, either, because (see note (b)) all classes in the diamond shape *must* use super for the magic to work. In my world, this is only worth it, whenever I really need this magic. So, to cut a long story short, I would just use: ----------------------8<------------------------------------ class A(object): def my_method(self): print 'in A' class B(A): def my_method(self): print 'in B' A.my_method(self) class C(A): def my_method(self): print 'in C' A.my_method(self) print "A..." A().my_method() print "B..." B().my_method() print "C..." C().my_method() ---------------------->8------------------------------------ ----------------------8<------------------------------------ A... in A B... in B in A C... in C in A ---------------------->8------------------------------------ I hope, this helped. FWIW, i think super is a cool tool. Like a chain saw. Use it where appropriate, then it will be real help. I also don't consider super() "harmful" (Google will tell you, what I'm referring to.) I just consider it to be named misleadingly, since it does *not* return the super class or an object re-typed to the super class. But, then again, Python is not Java... ;-) Cheers, --Jan Niklas From fredrik at pythonware.com Mon Aug 28 03:26:16 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 28 Aug 2006 09:26:16 +0200 Subject: import function from user defined modules In-Reply-To: <1156717616.491849.137460@p79g2000cwp.googlegroups.com> References: <1156717616.491849.137460@p79g2000cwp.googlegroups.com> Message-ID: <ecu5qo$aso$1@sea.gmane.org> groves wrote: > Can anybody give me an example of how to import a function of module X > in module y. And please if yu can use classes(Object oriented approach) > would be great. > > The problem is that I have created a text on canvas, and now I want > that whenever a user right clicks on it, the option COMMAND should > invoke a function defined in some other module say Y. import Y widget = Canvas(..., command=Y.function) for more on this, see the tutorial: http://docs.python.org/tut/node8.html </F> From johnjsal at NOSPAMgmail.com Fri Aug 18 14:13:00 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 18 Aug 2006 18:13:00 GMT Subject: couple more questions about sqlite Message-ID: <MqnFg.2703$No6.52653@news.tufts.edu> I've been looking around and reading, and I have a few more questions about SQLite in particular, as it relates to Python. 1. What is the current module to use for sqlite? sqlite3? or is that not out until Python 2.5? 2. What's the difference between sqlite and pysqlite? Do you need both, just one, or is one an older version of the same thing? 3. What's the difference between the command line program called sqlite3 and the module you would use with Python? (I know that the former let's you do normal database things without dealing with Python, but is it necessary if you are using Python to interact with the DB?) Thanks! From bj_666 at gmx.net Wed Aug 16 04:08:38 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 16 Aug 2006 10:08:38 +0200 Subject: using python at the bash shell? References: <44d7e364$0$24980$c3e8da3@news.astraweb.com> <mailman.9071.1155002101.27775.python-list@python.org> <R31Cg.2645$No6.51906@news.tufts.edu> <1155054162.683298.21760@m73g2000cwd.googlegroups.com> <mailman.9383.1155674099.27775.python-list@python.org> <1155681933.117671.54450@i3g2000cwc.googlegroups.com> <mailman.9403.1155709688.27775.python-list@python.org> Message-ID: <pan.2006.08.16.08.08.38.553825@gmx.net> In <mailman.9403.1155709688.27775.python-list at python.org>, cga2000 wrote: > and also some bash built-ins such as "cd" do not do anything .. maybe > ipython starts a subprocess that switches and then immediately exits .. > so when I get the prompt back I'm back where I started. If you put a ``!`` in front of ``cd`` this is what happens. Just leave out the ``!``. IPython has it's own built-in ``cd`` command. Ciao, Marc 'BlackJack' Rintsch From david_wahler at bic.ky Fri Aug 4 11:37:38 2006 From: david_wahler at bic.ky (david_wahler at bic.ky) Date: 4 Aug 2006 10:37:38 -0500 Subject: =?utf-8?Q?Re:_python=2Ddev_Summary_for_2006=2D06=2D16_through_2006=2D06=2D30?= Message-ID: <20060804153738.22190.qmail@BICSRV1011.bic.ky> I'll be out of the office until approximately August 20th. If you have any questions, please email support at bic.ky. -- David Wahler From anthra.norell at tiscalinet.ch Thu Aug 31 18:29:53 2006 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Fri, 1 Sep 2006 00:29:53 +0200 Subject: Using eval with substitutions References: <1157022920.299174.22860@m73g2000cwd.googlegroups.com> Message-ID: <020a01c6cd4c$fb4eeca0$0201a8c0@mcuf7> Abhishek, I hesitate to propose this idea, because there's got to be a better (more conventional) way of doing this. Anyway consider this: >>> x = "a+b"; y = "x*a; z = "x+y" # Your definitions >>> import SE >>> def f (x, y, z): substitutions = 'z=(%s) | y=(%s) | x=(%s)' % (z, y, x) print 'substitutions:', substitutions Formula_Expander = SE.SE (substitutions) formula = 'x + y + z' expanded_formula = Formula_Expander (formula) print 'expanded_formula:', expanded_formula a = 3; b = 4 print 'eval (expanded_formula):', eval (expanded_formula) w = eval (Formula_Expander ('y * b')) print 'w', w >>> f (x, y, z) substitutions: z=(x+y) | y=(x*a) | x=(a+b) expanded_formula: (a+b) + ((a+b)*a) + ((a+b)+((a+b)*a)) eval (expanded_formula): 56 w 84 Well--- it's kind of neat the way it expands the formula. But why not just write functions? As you say, the expansion has to be done in exactly the right order to complete. If you want to run this example you'll find SE here: http://cheeseshop.python.org/pypi/SE/2.2%20beta Regards Frederic ----- Original Message ----- From: <abhishek at ocf.berkeley.edu> Newsgroups: comp.lang.python To: <python-list at python.org> Sent: Thursday, August 31, 2006 1:15 PM Subject: Using eval with substitutions > >>> a,b=3,4 > >>> x="a+b" > >>> eval(x) > 7 > >>> y="x+a" > > Now I want to evaluate y by substituting for the evaluated value of x. > eval(y) will try to add "a+b" to 3 and return an error. I could do > this, > >>> eval(y.replace("x",str(eval(x)))) > 10 > > but this becomes unwieldy if I have > >>> w="y*b" > and so on, because the replacements have to be done in exactly the > right order. Is there a better way? > > Thanks, > Abhishek > > -- > http://mail.python.org/mailman/listinfo/python-list From onurb at xiludom.gro Thu Aug 10 04:05:23 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Thu, 10 Aug 2006 10:05:23 +0200 Subject: __contains__ vs. __getitem__ In-Reply-To: <mdqCg.8775$7m5.817@trnddc05> References: <fooCg.18589$qw5.15856@trnddc06> <44da144b$0$21143$7a628cd7@news.club-internet.fr> <mdqCg.8775$7m5.817@trnddc05> Message-ID: <44dae8c3$0$21151$7a628cd7@news.club-internet.fr> David Isaac wrote: >> Alan Isaac wrote: >>> I have a subclass of dict where __getitem__ returns None rather than >>> raising KeyError for missing keys. (The why of that is not important > for >>> this question.) > > "Bruno Desthuilliers" <onurb at xiludom.gro> wrote: >> Well, actually it may be important... What's so wrong with d.get('key') >> that you need this behaviour ? > > I want to use the mapping with string interpolation. > Well, this makes sens... But then why not use a plain dict to collect data, and wrap it in a special one just before using it for interpolation ? ie: class MyDictWrapper(object): def __init__(self, d, default=None): self._d = d self._default = default def __getitem__(self, key): return self._d.get(key, self._default) def render(d): tpl = "%(who)s says '%(say)s' and the %(what)s is %(state)s." return tpl % MyDictWrapper(d) This would avoid any potential trouble with using a strange kind of dict in other parts of the code... My 2 cents... From tal.no.no.spam at gmail.com Mon Aug 28 18:54:02 2006 From: tal.no.no.spam at gmail.com (Tal Einat) Date: 28 Aug 2006 15:54:02 -0700 Subject: Coding style and else statements In-Reply-To: <44f355d6$0$8812$88260bb3@free.teranews.com> References: <44f355d6$0$8812$88260bb3@free.teranews.com> Message-ID: <1156805642.757393.276610@i3g2000cwc.googlegroups.com> tobiah wrote: > def foo(thing): > > if thing: > return thing + 1 > else: > return -1 > > def foo(thing): > > if thing: > return thing + 1 > return -1 > > Obviously both do the same thing. The first is > possibly clearer, while the second is more concise. > > Comments? I usually prefer the second option because it is more scalable - it is possible to later add code to the function to return other values elsewhere in its code, and still have -1 returned by default, without changing the original code. As for structure, in the second example there is a clear point at which the function return a value, unless some other value is return elsewhere. In the first one you have to comprehend the entire if-else statement to understand that a value will always be returned at this point. Another worthy alternative mentioned is: def foo(thing): if thing: result = thing + 1 else: result = -1 return result This is scalable as described above, and also has only one exit point, which makes it a much simpler function. However, it forces someone reading the code to backtrack from the return statement and search for places where "result" could be set. I usually start with your second example, and if I need more control over the returned value I change the code to use this last method. ("More control" could be many things - checking the value for debugging, applying some transformation on the returned value before returning it...) - Tal From rhamph at gmail.com Sun Aug 20 06:18:44 2006 From: rhamph at gmail.com (Rhamphoryncus) Date: 20 Aug 2006 03:18:44 -0700 Subject: sum and strings In-Reply-To: <1156067043.386056.129320@i42g2000cwa.googlegroups.com> References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <slrneeatf3.nbt.sybrenUSE@schuimige.stuvel.eu> <7xr6zel2r2.fsf@ruckus.brouhaha.com> <ec4b27$7lr$1@news.albasani.net> <1155971485.709068.255140@b28g2000cwb.googlegroups.com> <1156038134.216383.80960@h48g2000cwc.googlegroups.com> <1156067043.386056.129320@i42g2000cwa.googlegroups.com> Message-ID: <1156069124.744004.118670@i3g2000cwc.googlegroups.com> Paddy wrote: > Rhamphoryncus wrote: > > > > > It's worthwhile to note that the use of + as the concatenation operator > > is arbitrary. It could just have well been | or &, and has no > > relationship with mathematically addition. > > The effect of the string concatenation operator is only secondary. > Secondary to the use of the word sum; and what could be 'reasonably' > concieved as sum's effect on non-numeric types. > > > > It's also worth stressing (not in response to your post, but others) > > that sum([[1],[2],[3]], []) is just as bad as attempting to sum > > strings, both conceptually (it's not mathematical addition) > > Unfortunately, the words sum and summation are linked to other words > that are commonly used to describe what is happening to the numders, > the lists, and the strings. > Words such as accumulate, concatenate, aggregate, collect, assemble, as > well as add. String concatenation and numeric addition only group together under the most vague of english terms, "putting things together". String concatenation violates many mathematical properties of addition/summation, and simply isn't related. It is unfortunate that many languages (including python) promote the confusion by using + for a "put things together" operator, ie both mathematical addition and string concatenation. > > I believe the prefered method to flatten a list of lists is this: > > > > shallow = [] > > for i in deep: > > shallow.extend(i) > > > > Yes, it's three lines. It's also very easy to read. reduce() and > > sum() are not. > > I'd like to squeeze in the listcomp version, not because it is one line > shorter, but because I, and maybe others prefer short listcomps such as > the folowing: > > shallow = [] > [shallow.extend(i) for i in deep] I'm sure this has been mentioned before, but listcomps are for when you want to store the list and use it for further things, not for when you want a side effect. TOOWTDI. And of course, if saving a line was the reason: shallow = [] for i in deep: shallow.extend(i) From fredrik at pythonware.com Tue Aug 22 02:16:37 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Aug 2006 08:16:37 +0200 Subject: how do you get the name of a dictionary? In-Reply-To: <1156204770.339106.151110@m73g2000cwd.googlegroups.com> References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <pan.2006.08.21.03.33.27.84160@REMOVEME.cybersource.com.au> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> Message-ID: <ece7ga$p2o$1@sea.gmane.org> jojoba wrote: > im quite surprised at the arrogance laid out by some of the above > posters: > > However, does it not seem reasonable to ask python: > > Given a dicitionary, Banana = {} > return one or more strings, > where each string is the name(s) of the reference(s) to Banana. > > why is this not sane?!?! > what am i missing here? Python's object model. an object has a value, a type, and an identity, but no name. required reading: http://tinyurl.com/gxrdr (relevant faq entry) http://effbot.org/zone/python-objects.htm http://www.python.net/crew/mwh/hacks/objectthink.html </F> From python.list at tim.thechases.com Tue Aug 1 11:54:32 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 01 Aug 2006 10:54:32 -0500 Subject: Finding the name of a class In-Reply-To: <44cf7538$0$29435$626a54ce@news.free.fr> References: <q684q3xmd11.ln2@news.conpoint.com> <44cf7538$0$29435$626a54ce@news.free.fr> Message-ID: <44CF7938.9070206@tim.thechases.com> >>>> class Foo(object): > ... pass > ... >>>> b = Foo >>>> b.__name__ > 'Foo' While this is surely true, would somebody explain why I had such trouble finding this? >>>> help(dir) > Help on built-in function dir in module __builtin__: continuing from your example... >>> dir(b) ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__'] >>> '__name__' in dir(b) False '__name__' *really is* a method of b as shown by your example lines, and can be successfully called. However, it *doesn't* show up when asked for via dir(b). Grumble. Is there a dir_and_i_really_mean_everything() function? I suppose problems (mostly with expectations) can ensue when you've got dynamic attributes, but this seems like something that dir() should be finding. -a puzzled tkc From percivall at gmail.com Sun Aug 20 12:45:46 2006 From: percivall at gmail.com (Simon Percivall) Date: 20 Aug 2006 09:45:46 -0700 Subject: Help in using introspection to simplify repetitive code References: <1156090845.875872.41220@75g2000cwc.googlegroups.com> Message-ID: <1156092346.194990.166550@i3g2000cwc.googlegroups.com> jsceballos at gmail.com wrote: > Hello. > I'm writing a proxy class, i.e: a class whose methods mostly delegate > their functionality to other class object. Most of the methods (which > are quite a lot) defined in the class would end up being: > > def thisIsTheMethodName(self): > self._handlerClass.thisIsTheMethodName() > > The handler object is the same in all methods. > > I was wondering if there is a way to simplify this proxy class, maybe > using some pythonic technique like metaclasses, introspection... any > suggestion is appreciated. > > Thanks, > > Javier Sanz http://docs.python.org/ref/attribute-access.html#l2h-206 From a at tempinbox.com Wed Aug 9 06:17:18 2006 From: a at tempinbox.com (a) Date: 9 Aug 2006 03:17:18 -0700 Subject: Best way to construct an email - attach a html file and send Message-ID: <1155118638.773107.214710@m79g2000cwm.googlegroups.com> What is the best way to construct an email in python and also attach a html file the html file to be attached is not on disk, but should be dynamically constructed in the python script I want to attach the django debug error to an email and mail it to myself whenever there is an error in the application thanks a lot py From hancock at anansispaceworks.com Wed Aug 30 16:07:40 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 30 Aug 2006 15:07:40 -0500 Subject: audio with graphics In-Reply-To: <20060830.100147.10554.687309@webmail18.nyc.untd.com> References: <20060830.100147.10554.687309@webmail18.nyc.untd.com> Message-ID: <44F5F00C.1080700@anansispaceworks.com> squall_leonheart7 at netzero.net wrote: > How do I make audio play when the graphics window is opened and then > loop so it repeats until the graphics window is closed? I'm not even > sure how to make ANY audio file play in using Python. This only makes sense in the context of some kind of multimedia library (like PyGame, for example). The platform you are running on may matter too (Windows, Mac, Linux, etc). Cheers, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From gelists at gmail.com Thu Aug 3 10:25:10 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Thu, 3 Aug 2006 11:25:10 -0300 Subject: How to force a thread to stop References: <mailman.8475.1153762034.27775.python-list@python.org>mailman.8528.1153845034.27775.python-list@python.org><1153880729.687711.227570@h48g2000cwc.googlegroups.com><mailman.8572.1153932090.27775.python-list@python.org><1153942270.301732.99880@h48g2000cwc.googlegroups.com><mailman.8585.1153946003.27775.python-list@python.org><7xslkoum88.fsf@ruckus.brouhaha.com> <44C7E7EC.4020301@mvista.com><1lwn8bs8qhg4c.dlg@gelists.gmail.com><mailman.8597.1153960691.27775.python-list@python.org><fangc2hg3d6rmcusjqqpk8ct8v3m8eqbd8@4ax.com><mailman.8615.1154004533.27775.python-list@python.org><3sphc25or7ir5keeithpvb1k3vog39botu@4ax.com><mailman.8644.1154070822.27775.python-list@python.org><7xwt9y8916.fsf@ruckus.brouhaha.com><mailman.8655.1154092222.27775.python-list@python.org><7xvephg7yq.fsf@ruckus.brouhaha.com><mailman.8693.1154164578.27775.python-list@python.org> <1hjgrs7.w01xtjt192o1N%aleax@mac.com> <00ae01c6b6e5$9996ca00$03000080@hendrik> Message-ID: <zmj78svvh7nl.dlg@gelists.gmail.com> On 2006-08-03 06:07:31, H J van Rooyen wrote: > Thanks - will check it out - seems a lot of money for 555 functionality > though.... > > Especially if like I, you have to pay for it with Rand - I have started > to call the local currency Runt... Depending on what you're up to, you can make such a thing yourself relatively easily. There are various possibilities, both for the reset/restart part and for the kick-the-watchdog part. Since you're talking about a "555" you know at least /some/ electronics :) Two 555s (or similar): - One wired as a retriggerable monostable and hooked up to a control line of a serial port. It needs to be triggered regularly in order to not trigger the second timer. - The other wired as a monostable and hooked up to a relay that gets activated for a certain time when it gets triggered. That relay controls the computer power line (if you want to stay outside the case) or the reset switch (if you want to build it into your computer). I don't do such things with 555s... I'm more a digital guy. There are many options to do that, and all a lot cheaper than those boards, if you have more time than money :) Gerhard From rbonvall at cern.ch Thu Aug 24 11:41:39 2006 From: rbonvall at cern.ch (Roberto Bonvallet) Date: 24 Aug 2006 15:41:39 GMT Subject: Taking data from a text file to parse html page References: <1156378275.662140.214650@h48g2000cwc.googlegroups.com> <mailman.9767.1156402497.27775.python-list@python.org> <1156431516.121577.282890@b28g2000cwb.googlegroups.com> Message-ID: <eckhbj$nan$1@sunnews.cern.ch> DH wrote: >> > I'm trying to strip the html and other useless junk from a html page.. >> > Id like to create something like an automated text editor, where it >> > takes the keywords from a txt file and removes them from the html page >> > (replace the words in the html page with blank space) [...] > I've looked into using BeatifulSoup but came to the conculsion that my > idea would work better in the end. You could use BeautifulSoup anyway for the junk-removal part and then do your magic. Even if it is not exactly what you want, it is a good idea to try to reuse modules that are good at what they do. -- Roberto Bonvallet From fuzzyman at gmail.com Tue Aug 29 19:13:25 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 29 Aug 2006 16:13:25 -0700 Subject: python for flash drives In-Reply-To: <1156876019.177142.101730@e3g2000cwe.googlegroups.com> References: <1156876019.177142.101730@e3g2000cwe.googlegroups.com> Message-ID: <1156893205.822150.266840@i3g2000cwc.googlegroups.com> Putty wrote: > Is there such a thing as a special version of python that I can run > more efficiently from a flash drive? I'll be at college for hours > every day with hours of free time for the next few months, but the only > computers at my disposal are windows PCs that use GoBack to auto-revert > every reboot. So I'm kinda stuck. I don't want to have to reinstall > python AND wxPython AND PIL every stinking time I log on. However, > using it from my flash drive is painfully slow taking up to a minute > just to execute some scripts. And it's not doing me any favors with > I/O to the flash disk either. > > So I was wondering if anybody knew of some flash drive implementations > of python that might exist out there somewhere? Use Movable Python, which comes with wxPython and PIL. It's never been that slow for me off a USB flash drive, but you could just copy the distribution onto the PC each time you use it. http://www.voidspace.org.uk/python/movpy/ Fuzzyman From jeremit0 at gmail.com Fri Aug 4 14:51:14 2006 From: jeremit0 at gmail.com (jeremito) Date: 4 Aug 2006 11:51:14 -0700 Subject: Extending/Embedding Confusion Message-ID: <1154717474.528297.285240@i42g2000cwa.googlegroups.com> I am trying to learn how to extend and/or embed Python. I have looked at the document "Extending and Embedding the Python Interpreter" and also "Python/C API Reference Manual. In the examples shown in "Extending..." there are some things I ma not familiar with so I turn to the index in the Reference Manual, but they are not listed. For example, PyEval_CallObject and PyDict_GetAttrString. My question is this: Is the documentation out of date or is the index not complete? Where can I get information about these things? Secondly, I am really struggling with understanding how to Extend/Embed Python. The examples given in the documentation are not as helpful as I would hope. Does anyone know of additional examples on the web that will shed some light on this issue? I have tried Google, but haven't yet been successful in finding additional examples that help. Thanks, Jeremy From dasn at bluebottle.com Mon Aug 21 21:39:07 2006 From: dasn at bluebottle.com (Dasn) Date: Mon, 21 Aug 2006 20:39:07 -0500 Subject: Problem of function calls from map() In-Reply-To: <200608211350.k7LDoBJb032411@fe12.bluebottle.com> References: <200608211350.k7LDoBJb032411@fe12.bluebottle.com> Message-ID: <200608220139.k7M1d7ue015431@fe10.bluebottle.com> Thanks for your reply. Well, please drop a glance at my current profile report: #------------------------ test.py --------------------- import os, sys, profile print os.uname() print sys.version # size of 'dict.txt' is about 3.6M, 154563 lines f = open('dict.txt', 'r') print "Reading lines..." lines = f.readlines() print "Done." def splitUsing(chars): def tmp(s): return s.split(chars) return tmp def sp0(lines): """====> sp0() -- Normal 'for' loop""" l = [] for line in lines: l.append(line.split('\t')) return l def sp1(lines): """====> sp1() -- List-comprehension""" return [s.split('\t') for s in lines] def sp2(lines): """====> sp2() -- Map with lambda function""" return map(lambda s: s.split('\t'), lines) def sp3(lines): """====> sp3() -- Map with splitUsing() function""" return map(splitUsing('\t'), lines) def sp4(lines): """====> sp4() -- Not correct, but very fast""" return map(str.split, lines) for num in xrange(5): fname = 'sp%(num)s' % locals() print eval(fname).__doc__ profile.run(fname+'(lines)') #---------------------------End of test.py ---------------- $ python test.py ('OpenBSD', 'Compaq', '3.9', 'kernel#1', 'i386') 2.4.2 (#1, Mar 2 2006, 14:17:22) [GCC 3.3.5 (propolice)] Reading lines... Done. ====> sp0() -- Normal 'for' loop 309130 function calls in 20.510 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 154563 4.160 0.000 4.160 0.000 :0(append) 1 0.010 0.010 0.010 0.010 :0(setprofile) 154563 6.490 0.000 6.490 0.000 :0(split) 1 0.380 0.380 20.500 20.500 <string>:1(?) 0 0.000 0.000 profile:0(profiler) 1 0.000 0.000 20.510 20.510 profile:0(sp0(lines)) 1 9.470 9.470 20.120 20.120 test.py:20(sp0) ====> sp1() -- List-comprehension 154567 function calls in 12.240 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 :0(setprofile) 154563 6.740 0.000 6.740 0.000 :0(split) 1 0.380 0.380 12.240 12.240 <string>:1(?) 0 0.000 0.000 profile:0(profiler) 1 0.000 0.000 12.240 12.240 profile:0(sp1(lines)) 1 5.120 5.120 11.860 11.860 test.py:27(sp1) ====> sp2() -- Map with lambda function 309131 function calls in 20.480 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 4.600 4.600 20.100 20.100 :0(map) 1 0.000 0.000 0.000 0.000 :0(setprofile) 154563 7.320 0.000 7.320 0.000 :0(split) 1 0.370 0.370 20.470 20.470 <string>:1(?) 0 0.000 0.000 profile:0(profiler) 1 0.010 0.010 20.480 20.480 profile:0(sp2(lines)) 1 0.000 0.000 20.100 20.100 test.py:31(sp2) 154563 8.180 0.000 15.500 0.000 test.py:33(<lambda>) ====> sp3() -- Map with splitUsing() function 309132 function calls in 21.900 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 5.540 5.540 21.520 21.520 :0(map) 1 0.000 0.000 0.000 0.000 :0(setprofile) 154563 7.100 0.000 7.100 0.000 :0(split) 1 0.380 0.380 21.900 21.900 <string>:1(?) 0 0.000 0.000 profile:0(profiler) 1 0.000 0.000 21.900 21.900 profile:0(sp3(lines)) 1 0.000 0.000 0.000 0.000 test.py:14(splitUsing) 154563 8.880 0.000 15.980 0.000 test.py:15(tmp) 1 0.000 0.000 21.520 21.520 test.py:35(sp3) ====> sp4() -- Not correct, but very fast 5 function calls in 3.090 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 2.660 2.660 2.660 2.660 :0(map) 1 0.000 0.000 0.000 0.000 :0(setprofile) 1 0.430 0.430 3.090 3.090 <string>:1(?) 0 0.000 0.000 profile:0(profiler) 1 0.000 0.000 3.090 3.090 profile:0(sp4(lines)) 1 0.000 0.000 2.660 2.660 test.py:39(sp4) The problem is the default behavior of str.split should be more complex than str.split('\t'). If we could use the str.split('\t') in map(), the result would be witty. What do u guys think? From onurb at xiludom.gro Wed Aug 30 04:35:16 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 30 Aug 2006 10:35:16 +0200 Subject: Variables in nested functions In-Reply-To: <1156899313.019757.285060@b28g2000cwb.googlegroups.com> References: <1156899313.019757.285060@b28g2000cwb.googlegroups.com> Message-ID: <44f54dc5$0$22211$626a54ce@news.free.fr> zero.maximum at gmail.com wrote: > Is it possible to change the value of a variable in the outer function > if you are in a nested inner function? Depends on what you mean by "changing the value". If you mean mutating a mutable object, yes, it's possible. If you mean rebinding the name to a different object, no, it isn't possible actually. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From bj_666 at gmx.net Fri Aug 11 14:03:42 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 11 Aug 2006 20:03:42 +0200 Subject: Read a file with open command References: <1155288288.954142.293000@i3g2000cwc.googlegroups.com> <1155288697.170018.61160@m79g2000cwm.googlegroups.com> <1155314363.231911.74170@75g2000cwc.googlegroups.com> Message-ID: <pan.2006.08.11.18.03.40.880533@gmx.net> In <1155314363.231911.74170 at 75g2000cwc.googlegroups.com>, jean-jeanot wrote: > Sorry, but the access mode is not binary with XP Windows. But ods files are binary so you better open them as binary files. Windows does a "magical" translation of line ending bytes and stops processing a file if it hits a \x26 byte if the file was opened in the default text mode. > Finally for reading the file it is necessary to use a slash or a double > backslash. If the file is a simple textfile, using a backslash is > perhaps not recommended but it is functionning. The slashes don't have anything to do with the content of the file. For both, binary and text files, you have to escape backslashes in literal strings or sooner or later you will be bitten by a backslash + character combination that's a valid escape sequence in literal strings. > >>> file_obj= open ("D:/Mes documents/ADB Anna.ods",'r') > >>> s = file_obj > >>> s.readlines() This doesn't make much sense as `ods` files don't contain text lines but are binary. A ZIP archive containing XML files to be more precise. If you want to read the raw binary data into memory it's better to use:: file_obj = open('D:/Mes documents/ADB Anna.ods', 'rb') data = file_obj.read() file_obj.close() Ciao, Marc 'BlackJack' Rintsch From tjreedy at udel.edu Sat Aug 5 12:30:49 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 5 Aug 2006 12:30:49 -0400 Subject: the perens in lisp dilects is there for a reson... macros. References: <1154760130.279122.148460@75g2000cwc.googlegroups.com> Message-ID: <eb2h3p$me0$1@sea.gmane.org> <atbusbook at aol.com> wrote in message I presume you accidentally misdirected this to the wrong newsgroup. Otherwise, it would be off-topic spam. In any case, you should learn how to spell or use a spell-checker. From johan2sson at gmail.com Sun Aug 13 15:23:36 2006 From: johan2sson at gmail.com (johan2sson at gmail.com) Date: 13 Aug 2006 12:23:36 -0700 Subject: Subtyping a non-builtin type in C/C++ In-Reply-To: <1154992267.851573.276120@n13g2000cwa.googlegroups.com> References: <1154822507.152920.182940@i3g2000cwc.googlegroups.com> <44D72E96.6090703@v.loewis.de> <1154992267.851573.276120@n13g2000cwa.googlegroups.com> Message-ID: <1155497016.842872.287660@m79g2000cwm.googlegroups.com> johan2sson at gmail.com wrote: > > > I am trying to create a subclass of a python class, defined in python, > > > in C++, but I am having some problems. Note to future news group archeologists: I have since learned that that's because it "can't be done", in the sense that there's no defined way that is supposed to work. Of course it could probably be done by reverse engineering what is done by the interpreter and then applying the same steps manually, but it would be a real hack. From seyeRMReyes at gmail.com Fri Aug 18 08:40:00 2006 From: seyeRMReyes at gmail.com (seyeRMReyes at gmail.com) Date: 18 Aug 2006 05:40:00 -0700 Subject: Text to MP3 using pyTTS - Non-programmer question Message-ID: <1155904799.935486.105460@i3g2000cwc.googlegroups.com> I'm not a programmer, but I'd like to make a program that will open and read a txt file and output to a mp3 file. I don't need to ever hear the voice, but I'd like the program to direct I've been google'ing around and have found a few tutorials about converting pdfs to mp3 and converting typed text (in the source file) to wave, but I'm looking for the ability to directly convert from txt to mp3/ogg/wma. Currently I'm running on WinXP, but I also have access to a Linux box. Any help would be appreciated. From fredrik at pythonware.com Fri Aug 25 18:30:43 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 26 Aug 2006 00:30:43 +0200 Subject: Consistency in Python In-Reply-To: <CD19F2D3-C840-404E-AAD9-ED92BF730C63@carnegielearning.com> References: <mailman.35854.1156516502.27774.python-list@python.org> <CD19F2D3-C840-404E-AAD9-ED92BF730C63@carnegielearning.com> Message-ID: <ecntmi$8ov$1@sea.gmane.org> Brendon Towle wrote: > My third response is that it's *always* possible to shoot yourself in > the foot. Protecting a naive user from one particular metatarsal > projectile insertion at the expense of letting the power-user write more > concise code seems a bad tradeoff to me -- but, I'm not involved with > Python design, which brings me back to my original question above. Anyone? what makes you think Python was designed for ex-LISP:ers who think that they are more important than others ? </F> From ptmcg at austin.rr._bogus_.com Sat Aug 26 08:26:58 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sat, 26 Aug 2006 12:26:58 GMT Subject: mechanize, how send forms? References: <1156586954.498802.143960@m73g2000cwd.googlegroups.com> Message-ID: <m6XHg.1614$dl.243@tornado.texas.rr.com> "Kowalski" <kowadam at gmail.com> wrote in message news:1156586954.498802.143960 at m73g2000cwd.googlegroups.com... > from mechanize import Browser > > br = Browser() > br.open("http://www.google.com") #example > > for form in br.forms(): > print form > > br.select_form(name="f") > br["q"] = "Blah" > > #??? > #response1=br.submit() > #??? > Check out twill, it puts a wrapper around mechanize to make this kind of thing pretty easy. -- Paul From f.braennstroem at gmx.de Thu Aug 24 07:34:10 2006 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Thu, 24 Aug 2006 13:34:10 +0200 Subject: radio buttons in curses References: <ecaadb$ojt$1@sea.gmane.org> <ecfm93$v6q$1@sea.gmane.org> <eck0g5$n7k$1@sea.gmane.org> Message-ID: <eck2ri$t92$2@sea.gmane.org> Hi Fredrik, * Fredrik Lundh <fredrik at pythonware.com> wrote: > Fabian Braennstroem wrote: > >> Does nobody have an idea or is it to stupid? > > have you looked at: > > http://excess.org/urwid/ Thanks! I found this too and it seems to be helpful... Greetings! Fabian From borique at gmail.com Wed Aug 23 09:39:46 2006 From: borique at gmail.com (peter) Date: 23 Aug 2006 06:39:46 -0700 Subject: find, replace and save string in ascii file In-Reply-To: <mailman.9699.1156339689.27775.python-list@python.org> References: <1156337317.644501.120480@m73g2000cwd.googlegroups.com> <mailman.9699.1156339689.27775.python-list@python.org> Message-ID: <1156340386.790775.147590@m73g2000cwd.googlegroups.com> Thank you for your advice. I'm not so good in python yet, so could you be so kind and write me a piece of code for the part If you want the output to be written to same file just 'move' this temperory file to the input file once you are done. Because that's what I don't know how to do it. How to replace a string in the middle of the file and than save this file. Thanks a lot. Amit Khemka wrote: > On 23 Aug 2006 05:48:37 -0700, peter <borique at gmail.com> wrote: > > Hello all, > > > > I'm looking for an advice. > > > > Example (one block in ascii file): > > $------------------------ > > NAME='ALFA' > > CODE='x' > > $------------------------ > > > > There are many similar blocks in the file with different NAMEs and > > different CODEs. What I'm looking for is a script that searchs through > > whole file and finds all strings with name ALFA and based on what CODE > > is after each ALFA (can be x, y or z) the ALFA name is replaced by > > BETAx,BETAy or BETAz and so changed file saves. > > > > What I did is that I can find all strings which I need, next I change > > these strings based on CODE, but what I can't is to replace old string > > with new one, on the same position in the file. It always writes new > > string at the end of the file. Here is my code.... > > A simpler way can be: > > 1. Read a 'block' from the input file, ( you can simply read a line > starting with 'NAME' and keep on reading till you find a line with > starting 'CODE') > 2. Once you have read a 'block', make whatever you want changes to the > NAME and then write the 'block' to a temperory file. > > If you want the output to be written to same file just 'move' this > temperory file to the input file once you are done. > > Note: if there is other stuff in the input file, apart from such > 'blocks' that you want to preserve, a small modification in step 1 > would take care of it. > > hth, > amit. > > -- > ---- > Amit Khemka -- onyomo.com > Home Page: www.cse.iitd.ernet.in/~csd00377 > Endless the world's turn, endless the sun's Spinning, Endless the quest; > I turn again, back to my own beginning, And here, find rest. From grante at visi.com Wed Aug 30 10:46:03 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 30 Aug 2006 14:46:03 -0000 Subject: Python for Windows References: <1156889674.296093.5390@74g2000cwt.googlegroups.com> Message-ID: <12fb95ba4q18i53@corp.supernews.com> On 2006-08-29, mistral <polychrom at softhome.net> wrote: > I need compile code written in Python. I use Windows 98SE. > Should I download Python for Windows installer? > http://www.python.org/ftp/python/2.4.3/python-2.4.3.msi I like the active state windows installs. They contain a few pretty nice extras: http://www.activestate.com/Products/ActivePython/ > Will the msi installer modify registry or other system files? > Does it possible install Python not touching registry and > system files? Dunno. -- Grant Edwards grante Yow! I know th'MAMBO!! I at have a TWO-TONE CHEMISTRY visi.com SET!! From bignose+hates-spam at benfinney.id.au Wed Aug 23 01:31:04 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 23 Aug 2006 15:31:04 +1000 Subject: Can I do this with list comprehension? References: <1156306056.165984.37820@h48g2000cwc.googlegroups.com> Message-ID: <87ac5wxbl3.fsf@benfinney.id.au> barberomarcelo at gmail.com writes: > Let's say I have two lists: > > a = [0, 1, 0, 1, 1, 0] > b = [2, 4, 6, 8, 10, 12] > > I want a list comprehension that has the elements in b where a[element] > == 1. > > That's to say, in the example above, the result must be: [4, 8, 10] > > Any hints? What have you already tried, and how is it insufficient? -- \ "Unix is an operating system, OS/2 is half an operating system, | `\ Windows is a shell, and DOS is a boot partition virus." -- | _o__) Peter H. Coffin | Ben Finney From nicolas at pontoizeau.org Tue Aug 22 09:13:07 2006 From: nicolas at pontoizeau.org (Nicolas Pontoizeau) Date: Tue, 22 Aug 2006 15:13:07 +0200 Subject: unicode "table of character" implementation in python Message-ID: <c11342e60608220613o6b7ad07gb2aa42208b813de4@mail.gmail.com> Hi, I am handling a mixed languages text file encoded in UTF-8. Theres is mainly French, English and Asian languages. I need to detect every asian characters in order to enclose it by a special tag for latex. Does anybody know if there is a unicode "table of character" implementation in python? I mean, I give a character and python replys me with the language in which the character occurs. Thanks in advance -- http://www.nicolas.pontoizeau.org/ Nicolas Pontoizeau - Promotion EFREI 2005 From duncan.booth at invalid.invalid Fri Aug 18 13:38:43 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 Aug 2006 17:38:43 GMT Subject: Type conversion? References: <1155915139.622448.178160@m73g2000cwd.googlegroups.com> <1155915914.141274.99020@m79g2000cwm.googlegroups.com> <1155921295.608755.269970@i3g2000cwc.googlegroups.com> Message-ID: <Xns9823BDA9DDEC4duncanbooth@127.0.0.1> KraftDiner wrote: > In C++ you can cast one class type to another if you override the > operator= > Then you can convert one class type to another... > In Python it would appear that the left hand side of the assignment > operator > is not used to determine if a cast is necessary. > So how would I do this in python? > > a = classA() > b = classB() > b = a > > In the end b would end up just being a refrence to a (You aren't quite correct there: the name 'b' would refer to the same object as is referred to by the name 'a'. However there is nothing associating the two names 'b' and 'a', so no reference from 'b' to 'a'.) > no conversion would have been done. You just have to call the appropriate constructor: b = classB(a) So long as the constructor for classB knows how to create an instance from a classA instance this will have the desired effect. So: aStr = str(anInt) aFloat = float(anInt) ...and so on... From saint.infidel at gmail.com Wed Aug 2 17:03:02 2006 From: saint.infidel at gmail.com (infidel) Date: 2 Aug 2006 14:03:02 -0700 Subject: Programming newbie coming from Ruby: a few Python questions In-Reply-To: <1154549436.073418.202840@s13g2000cwa.googlegroups.com> References: <mailman.8824.1154472963.27775.python-list@python.org> <1154494954.082706.283750@b28g2000cwb.googlegroups.com> <44d06f9f$0$19127$626a54ce@news.free.fr> <1154539223.873418.286830@i42g2000cwa.googlegroups.com> <1154539652.256975.155200@i3g2000cwc.googlegroups.com> <1154549436.073418.202840@s13g2000cwa.googlegroups.com> Message-ID: <1154552582.223865.87130@75g2000cwc.googlegroups.com> > The time to crush our enemies has come. > This is the Jihad! Death to the infidels!!!! Whoa, dude, let's not get carried away now, 'k? Looking-over-his-shoulder-ly y'rs, infidel From quncao at gmail.com Tue Aug 8 05:28:31 2006 From: quncao at gmail.com (Qun Cao) Date: 8 Aug 2006 02:28:31 -0700 Subject: beginner questions on embedding/extending python with C++ Message-ID: <1155029311.885266.131980@m73g2000cwd.googlegroups.com> Hi Everyone, I am a beginner on cross language development. My problem at hand is to build a python interface for a C++ application built on top of a 3D game engine. The purpose of this python interface is providing a convenient scripting toolkit for the application. One example is that a user can write a python script like: player = Player() game.loadPlayer(player) player.moveTo(location) To configure the game environment. I am trying to figure out how to make this happen. I only have the vague idea that this concerns embedding/extending python with C++, but after reading Python Doc, SWIG, BOOST.Python, I am still not sure how to architecture it. Since the main program is still going to be the C++ application, I guess we need to embedding the python scripts in the C++ code. So at initialization stage, the python script needs to be loaded into the C++ code. And this code can be simple, like player = Player() game.loadPlayer(player) But for this to work, the python code needs to know the Player class, is it right? Does that mean I need to build a python wrapper class for Player and "import Player" in the python code? But because this application is built on top of a game engine, Player class inherits many classes from there, I cannot possibly wrapping them all, right? Also, some global objects are probably needed in this code of adding players, how can the python code access them? I know I probably don't have a grasp of basics here, please kindly enlighten me! Btw, if you can point me to any source code of non-trivial projects utilizing SWIG/Boost.Python, that would be very helpful. I found the examples on the tutorials are far too simple. Thank you very much, Qun From mervyn11 at gmail.com Tue Aug 15 09:16:33 2006 From: mervyn11 at gmail.com (M_M) Date: Tue, 15 Aug 2006 23:16:33 +1000 Subject: Beginner Textbook In-Reply-To: <mailman.9369.1155646386.27775.python-list@python.org> References: <12e3gkdhjngum6a@corp.supernews.com> <mailman.9369.1155646386.27775.python-list@python.org> Message-ID: <12e3i9gr0edeb74@corp.supernews.com> Michiel Sikma wrote: > Introducing 13 year olds to a programming language? You're gonna have a > hard time finding good literature for that. Even if you do, it's going > to cost a lot of time to guide them. > > "Beginning Python: From Novice to Professional" by Magnus Lee Hetland > might be a good choice. ISBN: 159059519X. > > Michiel > > Op 15-aug-2006, om 14:48 heeft M_M het volgende geschreven: > >> Hi, >> >> I am looking for a simple text book to introduce 13 to 18 year olds to >> python programming. Suggestion? >> >> New to python. >> --http://mail.python.org/mailman/listinfo/python-list > Thanks - a very bright lot of 13 year olds- need the challenge! From mail at microcorp.co.za Mon Aug 21 08:48:40 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 21 Aug 2006 14:48:40 +0200 Subject: Small Troll on notation of variables over time References: <mailman.9535.1155985480.27775.python-list@python.org> <m23bbql5s1.fsf@ordesa.lan> Message-ID: <00e901c6c524$7aebb500$03000080@hendrik> "Piet van Oostrum" <piet at cs.uu.nl> Wrote: | You are about 7 months early. | -- Am I? - Early for what - a seven months premature baby is small indeed... - Hendrik From levub137 at wi.rr.com Sat Aug 19 12:21:40 2006 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Sat, 19 Aug 2006 16:21:40 GMT Subject: [ANN] ratfun-2.3 Polynomials and Rational Functions Message-ID: <oUGFg.16988$zg.13628@tornado.rdc-kc.rr.com> The ratfun module provides classes for defining polynomial and rational function (ratio of two polynomials) objects. These objects can be used in arithmetic expressions and evaluated at a particular point. Home page: http://calcrpnpy.sourceforge.net/ratfun.html Note: If you are using rpncalc-1.2 or later, this module is already included. This release is for folks who don't want rpncalc. Changes in 2.3 * Update the included clnum package. * Improved the formatting of the string representation of a polynomial. * Polynomial and rational function evaluation now works with array inputs. From you at cogeco.ca Mon Aug 14 16:58:06 2006 From: you at cogeco.ca (AlbaClause) Date: Mon, 14 Aug 2006 16:58:06 -0400 Subject: Mega Newbie Questions: Probably FAQs References: <E64Eg.103891$hp.90053@read2.cgocable.net> Message-ID: <Wp5Eg.4$dB.0@read2.cgocable.net> Zeph wrote: > 4) There are a lot of books and tutorials out there, but they are of the > proof-of-concept type. Specifically, a tutorial might teach me Hello > World, but not really care about the framework, because it's a very > simple item, and the point is simply to get me coding. I'd like to start > off with an established, tested and reputable system whose habits I can > ingrain from day one, rather than figure it out later. Can someone > recommend a good book, or your favourite tutorials? Perhaps even one > that assumes MVC as the framework? There is no "tutorial" that will teach you good coding habits. You pretty much have to develop them on your own. Looking at other people's source is a good way to learn "accepted" coding habits. Python, in and of itself, is a good language for learning good programming habits, as the interpreter forces you to use certain conventions that are widely regarded as good coding structure. One of the things that many Python detractors harp about, is that Python forces you to use a considerable amount of whitespace. i.e. consistent indentation of code blocks. However, good and consistent indentation is generally considered to assist in making the source more readable and thus, easier to debug. All in all, these conventions help you to develop some good habits by producing runtime errors when you fail to observe them. -- -- There are several things that I will never be: * I will never be attracted to females. * I will never enjoy the company of others. Exactly how these realities bode for my enemy, is not of my concern. From khp257 at verizon.net Tue Aug 15 11:43:40 2006 From: khp257 at verizon.net (Keith Perkins) Date: Tue, 15 Aug 2006 15:43:40 GMT Subject: Best IDE for Python In-Reply-To: <1155652422.017843.182790@m79g2000cwm.googlegroups.com> References: <1155541849.350392.31190@h48g2000cwc.googlegroups.com> <1155652422.017843.182790@m79g2000cwm.googlegroups.com> Message-ID: <MYlEg.14316$X77.13608@trndny08> yogamatt1970 at gmail.com wrote: > stylecomputers at gmail.com wrote: >> Hi All, What do you find the best IDE for creating web applications in >> Python is? Preferably FOS IDE. >> >> Cheers > > I like ActiveState's Komodo. It's heavyweight and not free ($30 for > the personal edition) but it also supports Perl, Ruby, PHP and TCL. I > started using it mostly on Windows but I've used it on Linux more > recently (and it runs on Solaris and OSX now too). > It has all the bells and whistles and probably won't appeal too much to > hardcore emacs/vim people because it is so GUI oriented and nowhere > near as fast. Also, it's text editor is similar to the ones you get > with other popular IDE's like MS DevStudio and Eclipse i.e. not very > powerful. > I've used it extensively with Python and it handles whitespace > indentation beautifully. I like that it also supports Perl because I > use Perl quite a bit too. > That being said, I'm going to give Wing IDE a try at some point soon. > Have you tried SPE (Stani's Python Editor) http://stani.be/python/spe/ Free, and available for Linux, Mac, and Windows. From martin at v.loewis.de Mon Aug 28 12:39:07 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 28 Aug 2006 18:39:07 +0200 Subject: libcurses.so & installing Python 2.4.3 In-Reply-To: <1156434123.526207.28500@74g2000cwt.googlegroups.com> References: <1156434123.526207.28500@74g2000cwt.googlegroups.com> Message-ID: <44F31C2B.103@v.loewis.de> dmulcahy schrieb: > I am trying to build the binaries for Python 2.4.3 on a Sun E6900 > running SPARC Solaris 9 and using gcc 3.4.2. > > When the makefile tries to build the _curses extension it fails with a > symbol referencing error on "mvwgetnstr", which it appears should exist > in libcurses.so. For some reason it seems this function does not exist > in the version of libcurses.so shipped with Solaris 9. > > Will I find it in some other library on Solaris or do I need to > download a different version of libcurses.so? Neither, nor. You will need to port the curses module to Solaris 9 (if you really need it). I believe in the subversion trunk of Python (and in Python 2.5), this problem is fixed. Regards, Martin From skip at pobox.com Tue Aug 1 11:22:41 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 1 Aug 2006 10:22:41 -0500 Subject: Python-list Digest, Vol 35, Issue 10 In-Reply-To: <TKJzg.28997$rp4.28066@tornado.texas.rr.com> References: <mailman.8787.1154426764.27775.python-list@python.org> <TKJzg.28997$rp4.28066@tornado.texas.rr.com> Message-ID: <17615.29121.733895.50692@montanaro.dyndns.org> Paul> Can someone PLEASE remove support at mathworks.co.uk from the Paul> subscriber list??? BTDT. Skip From gelists at gmail.com Wed Aug 2 09:54:11 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Wed, 2 Aug 2006 10:54:11 -0300 Subject: Windows vs. Linux References: <1154301694.445639.99580@m79g2000cwm.googlegroups.com> <44cddfb3$0$7761$7a628cd7@news.club-internet.fr> <e%szg.3$gY6.1@newssvr11.news.prodigy.com> <slrnecustl.dsk.sybrenUSE@schuimige.stuvel.eu> <mailman.8814.1154454507.27775.python-list@python.org> <slrnecvati.eia.sybrenUSE@schuimige.stuvel.eu> <mailman.8825.1154473236.27775.python-list@python.org> <slrned0lr7.f6d.sybrenUSE@schuimige.stuvel.eu> Message-ID: <1mn0lql0i2xv4$.dlg@gelists.gmail.com> On 2006-08-02 04:42:31, Sybren Stuvel wrote: > I never said "I would have known it better". I just said that IMO it > was a bad design choice ;-) Well, and I question your qualification to judge that. In order to say that, you would have to know the reasoning, would have to put it in the historical context and would have to be able to explain why that reasoning was wrong at the time. A design choice is not necessarily a bad choice just because it turns out that some 30 years later there is a similar common product whose creators made a different choice, and now programmers have to cater to both. With the same reasoning one could say that the Unix creators should have used the VMS (or any other existing) form. Gerhard From petdragon69-weather at yahoo.co.uk Sun Aug 27 11:55:39 2006 From: petdragon69-weather at yahoo.co.uk (Fraggle69) Date: Sun, 27 Aug 2006 16:55:39 +0100 Subject: Firewire comms using Python? Message-ID: <4b6dnSo0jtHhXWzZnZ2dnUVZ8tadnZ2d@bt.com> Hi, Does anyone have any idea of how I can use Python to get images from my firewire camera?? I am using python under winXP pro.... Cheers Fraggle From fredrik at pythonware.com Fri Aug 25 18:46:16 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 26 Aug 2006 00:46:16 +0200 Subject: prevent unauthorized call to script In-Reply-To: <87749a050608250324v51f301cdh67d486d54e319129@mail.gmail.com> References: <87749a050608250324v51f301cdh67d486d54e319129@mail.gmail.com> Message-ID: <ecnujm$as2$1@sea.gmane.org> kudincendol at gmail.com wrote: > I have copy-paste a script called "form.py" from somewhere else. sounds a bit dangerous. > This script is called from " form.html". Both are running in my Apache > server. How do I prevent other html files from other server to call my > "form.py" script ? usual approaches include checking the referrer field, using server- generated tokens in hidden fields, etc. this won't keep the determined hacker to issue requests to your server, but at least it makes it a bit harder to just post a HTML form somewhere else and point that to your server. it's probably best if you look for a form script that already supports things like this. </F> From Iljya.Kalai at gmail.com Wed Aug 16 14:55:39 2006 From: Iljya.Kalai at gmail.com (Iljya) Date: 16 Aug 2006 11:55:39 -0700 Subject: Error with: pickle.dumps(numpy.float32) In-Reply-To: <1155749127.210339.50580@h48g2000cwc.googlegroups.com> References: <1155670034.655485.214360@i3g2000cwc.googlegroups.com> <1155741080.438315.192040@b28g2000cwb.googlegroups.com> <1155749127.210339.50580@h48g2000cwc.googlegroups.com> Message-ID: <1155754539.157818.147730@75g2000cwc.googlegroups.com> Thanks, Ziga I have submitted the bug to http://projects.scipy.org/scipy/numpy I am using the following workaround for now: >>> import numpy >>> import pickle >>> import __builtin__ >>> __builtin__.float32_arrtype = numpy.float32 >>> pickle.dumps(numpy.float32) 'c__builtin__\nfloat32_arrtype\np0\n.' The name binding must also be present when unpickling. Iljya Kalai Ziga Seilnacht wrote: > Iljya wrote: > > I have reproduced the error with Numpy 1.0b1 > > > > The output with v.1.0b1 reads: > > PicklingError: Can't pickle <type 'float32scalar'>: it's not found as > > __builtin__.float32scalar > > > > Has anyone else encountered this? > > > > Thanks, > > > > Iljya > > > > Iljya wrote: > > > Hello, > > > > > > I need to pickle the type numpy.float32 but encounter an error when I > > > try to do so. I am able to pickle the array itself, it is specifically > > > the type that I cannot pickle. > > > > > > I am using: > > > Numpy version: 0.9.4 > > > Python version: 2.4.3 > > > Windows XP > > > > > > Here is the code that reproduces the error: > > > ______________________________________ > > > import numpy > > > import pickle > > > > > > pickle.dumps(numpy.float32) > > > > > > Output: > > > PicklingError: Can't pickle <type 'float32_arrtype'>: it's not found as > > > __builtin__.float32_arrtype > > > ______________________________________ > > > > > > Any suggestions would be much appreciated. > > > > > > Thanks, > > > > > > Iljya Kalai > > This looks like a numpy bug. It seems that float32_arrtype's name is > incomplete. Its tp_name field should start with a module name, but > since it doesn't, Python assumes that it is a builtin type: > > >>> import numpy > >>> numpy.float32.__module__ > '__builtin__' > > You should report this bug either to the numpy list: > https://lists.sourceforge.net/lists/listinfo/numpy-discussion > > or to their bug tracker: > http://projects.scipy.org/scipy/numpy > > Ziga From johnjsal at NOSPAMgmail.com Tue Aug 8 16:00:33 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 08 Aug 2006 20:00:33 GMT Subject: #!/usr/bin/python or #!/usr/bin/env python? In-Reply-To: <mailman.9110.1155066093.27775.python-list@python.org> References: <fj5Cg.2658$No6.51984@news.tufts.edu> <mailman.9110.1155066093.27775.python-list@python.org> Message-ID: <B36Cg.2659$No6.51783@news.tufts.edu> skip at pobox.com wrote: > On most systems /usr/bin/python will be > the system-provided one (e.g. the one that came with your Linux > distribution). You might prefer a Python of more recent vintage though. > That's commonly installed in /usr/local/bin/python and /usr/local/bin is > generally ahead of /usr/bin in PATH. Ah, that answered my next question too! I guess I'll stick with the env method, since I like the more general, abstract stuff over the absolute anyway. From bearophileHUGS at lycos.com Sun Aug 6 10:23:29 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 6 Aug 2006 07:23:29 -0700 Subject: string.translate with unicode In-Reply-To: <1154869518.223041.112410@b28g2000cwb.googlegroups.com> References: <1154869518.223041.112410@b28g2000cwb.googlegroups.com> Message-ID: <1154874209.861638.248640@h48g2000cwc.googlegroups.com> peterbe at gmail.com: It's not a bug, but such incompatibility problem will probably be solved with Python 3.0, when most strings will managed as unicode. The documentation says: >it returns a copy of the s where all characters have been mapped through the given translation table which must be a mapping of Unicode ordinals to Unicode ordinals, Unicode strings or None. Unmapped characters are left untouched. Characters mapped to None are deleted.< An example: def maketransU(s1, s2, todel=""): trans_tab = dict( zip( map(ord, s1), map(ord, s2) ) ) trans_tab.update( (ord(c),None) for c in todel ) return trans_tab trans_tab_u = maketransU('_', ' ', "?&!;<=>*#[]{}") print u"Peter!_*fine*".translate(trans_tab_u) Bye, bearophile From harshad.sharma at gmail.com Fri Aug 25 15:16:02 2006 From: harshad.sharma at gmail.com (Harshad) Date: 25 Aug 2006 12:16:02 -0700 Subject: Drag and Drop with PyQt4 Message-ID: <1156533361.933690.221260@b28g2000cwb.googlegroups.com> Hi, I'm writing a program using Python 2.4 and PyQt4. The aim is to implement drag and drop from filesystem and display a list of files dragged on to the listWidget. This function will later become part of a software for workflow management. When I run the program, DragEnterEvent works as expected, but the DropEvent does not seem to be working. I'm not an experienced Python hacker, and am unable to trace out any problems with the source code. Any and all help will be appreciated! Cheers! Harshad. P.S.: The source code for the two files is given below: ------------------------------------------- zaraa.py ------------------------------------------- from PyQt4 import QtCore, QtGui from zaraamain import Ui_Dialog import sys from PyQt4 import * class Zaraa(QtGui.QDialog, Ui_Dialog): def __init__(self): QtGui.QDialog.__init__(self) # Set up the user interface from Designer. self.setupUi(self) # Enable Drag and Drop self.listWidget.setAcceptDrops(True) # Set up the handlers for the listWidget self.listWidget.__class__.dragEnterEvent = self.lwDragEnterEvent self.listWidget.__class__.dropEvent = self.lwDropEvent # Drag Enter Event handler def lwDragEnterEvent(self, event): print "DragEnter" event.acceptProposedAction() # ------------------------ BEGIN ------------------------ # The following event is not fired, or at least is not # handled by this function - as is expected... # Drag Drop Event Handler def lwDropEvent(self, event): print "DragDrop" event.acceptProposedAction() # we want to append only URLs to the list... if event.mimeData().hasUrls() == True: urllist = event.mimeData().urls() for url in urllist: self.listWidget.addItem(url.toLocalFile()) # ------------------------ END ------------------------ # Set up the application and execute it. app = QtGui.QApplication(sys.argv) window = Zaraa() window.show() sys.exit(app.exec_()) ------------------------------------------- /zaraa.py ------------------------------------------- ------------------------------------------- zaraamain.py ------------------------------------------- # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'zaraamain.ui' # # Created: Sat Aug 26 00:00:10 2006 # by: PyQt4 UI code generator 4.0.1 # # WARNING! All changes made in this file will be lost! import sys from PyQt4 import QtCore, QtGui class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(QtCore.QSize(QtCore.QRect(0,0,249,300).size()).expandedTo(Dialog.minimumSizeHint())) self.vboxlayout = QtGui.QVBoxLayout(Dialog) self.vboxlayout.setMargin(9) self.vboxlayout.setSpacing(6) self.vboxlayout.setObjectName("vboxlayout") self.listWidget = QtGui.QListWidget(Dialog) self.listWidget.setObjectName("listWidget") self.vboxlayout.addWidget(self.listWidget) self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Zaraa", None, QtGui.QApplication.UnicodeUTF8)) ------------------------------------------- /zaraamain.py ------------------------------------------- From levub137 at wi.rr.com Sat Aug 19 12:16:52 2006 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Sat, 19 Aug 2006 16:16:52 GMT Subject: [ANN] clnum-1.3 Class Library For Numbers Python Binding Message-ID: <UPGFg.16952$zg.2711@tornado.rdc-kc.rr.com> The clnum package adds rational numbers and arbitrary precision floating point numbers in real and complex form to Python. Also provides arbitrary precision floating point replacements for the functions in the math and cmath standard library modules. Home page: http://calcrpnpy.sourceforge.net/clnum.html Changes in 1.3 * Added combinatorial functions. * Improved the performance of converting very large Python longs. From paolopantaleo at gmail.com Sun Aug 27 05:22:35 2006 From: paolopantaleo at gmail.com (Paolo Pantaleo) Date: Sun, 27 Aug 2006 11:22:35 +0200 Subject: avoiding file corruption In-Reply-To: <1156664673.325201.271140@i42g2000cwa.googlegroups.com> References: <1156664673.325201.271140@i42g2000cwa.googlegroups.com> Message-ID: <83e8215e0608270222n4cca35d1p66e2c3f3879c7393@mail.gmail.com> 27 Aug 2006 00:44:33 -0700, Amir Michail <amichail at gmail.com>: > Hi, > > Trying to open a file for writing that is already open for writing > should result in an exception. > > It's all too easy to accidentally open a shelve for writing twice and > this can lead to hard to track down database corruption errors. > > Amir > > -- > http://mail.python.org/mailman/listinfo/python-list > Even if it could be strange, the OS usually allow you to open a file twice, that's up to the programmer to ensure the consistency of the operations. PAolo -- if you have a minute to spend please visit my photogrphy site: http://mypic.co.nr From geli at tasmail.com Sun Aug 20 20:00:42 2006 From: geli at tasmail.com (gel) Date: 20 Aug 2006 17:00:42 -0700 Subject: What would be the best way to run python client in the background In-Reply-To: <1155717093_49711@sp6iad.superfeed.net> References: <1155625271.858914.175780@m73g2000cwd.googlegroups.com> <1155717093_49711@sp6iad.superfeed.net> Message-ID: <1156118441.944732.87340@p79g2000cwp.googlegroups.com> Roger Upole wrote: > You can use the Task Scheduler to run a script at login. > It's not as robust as creating a service, but it's much less > work. > > Roger > OK thanks Roger I will have a bit a look at that option. It is fairly important for the solution to be robust, but this maybe enough. Cheers > "gel" <geli at tasmail.com> wrote in message news:1155625271.858914.175780 at m73g2000cwd.googlegroups.com... > > Hi > > I have written a python client server app that keeps an eye on > > processes starting and ending on a client and makes decision on what to > > do based on information from the server end. I want to run the client > > end of the app more or less invisibly (no console) on the XP clients > > when ever a users logs on. What would be the best way to get this > > done? A bit more info on the purpose of the app... it is to act as a > > licence server, where we have a limited number of licences for software > > and the software installed on all PCs. The app will only allow a pre > > defined number of clients to run the software at any one time. > > From grante at visi.com Mon Aug 14 23:37:02 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 15 Aug 2006 03:37:02 -0000 Subject: How to fill a form References: <20060815034051.89ef7e18.sulsa@gazeta.pl> <mailman.9336.1155608567.27775.python-list@python.org> <20060815050733.10e14112.sulsa@gazeta.pl> Message-ID: <12e2gau4jouhmcf@corp.supernews.com> On 2006-08-15, Sulsa <sulsa at gazeta.pl> wrote: > I want to fill only one smiple form so i would like not to use > any non standard libraries. Then just send the HTTP "POST" request containing the fields and data you want to submit. -- Grant Edwards grante Yow! LBJ, LBJ, how many at JOKES did you tell today??! visi.com From gene.tani at gmail.com Tue Aug 1 19:19:20 2006 From: gene.tani at gmail.com (gene tani) Date: 1 Aug 2006 16:19:20 -0700 Subject: Programming newbie coming from Ruby: a few Python questions In-Reply-To: <1154458926.738922.156910@h48g2000cwc.googlegroups.com> References: <1154458926.738922.156910@h48g2000cwc.googlegroups.com> Message-ID: <1154474360.188457.158850@b28g2000cwb.googlegroups.com> simonharrison at fastmail.co.uk wrote: > Hi all. I've been try to learn ruby for a few months but I'm about > ready to give up. The available books either assume a programming > background, or are out of date. Anyway, http://www.awaretek.com/book.html From zxo102 at gmail.com Thu Aug 10 11:12:13 2006 From: zxo102 at gmail.com (zxo102) Date: 10 Aug 2006 08:12:13 -0700 Subject: draw an image in wx.BufferedDC onto the page created by AddPage of wx.Notebook Message-ID: <1155222733.322056.40090@75g2000cwc.googlegroups.com> Hi everyone, I have tried two days to figure out how to draw the image in wx.BufferedDC on the page created by AddPage of wx.Notebook but still got no clue. The attached example works fine. If I click the menu "Draw" --> "New Drawing". The image with wx.BufferedDC/wx.BufferedPaintDC can move around on the frame. But If I uncomment those three commented lines in "class TestFrame" to add a new page (from wx.Notebook) with a tag and modify the last line like self.Window = DrawWindow(form2) I can not see the image from wx.BufferedDC anywhere and don't know what is going on. I need your help. Thanks a lot. The attached example is based on the example on the site: http://wiki.wxpython.org/index.cgi/DoubleBufferedDrawing ouyang import wx import random import os,time USE_BUFFERED_DC = 1 def opj(path): """Convert paths to the platform-specific separator""" str = apply(os.path.join, tuple(path.split('/'))) # HACK: on Linux, a leading / gets lost... if path.startswith('/'): str = '/' + str return str class BufferedWindow(wx.Window): def __init__(self, parent, id, pos = wx.DefaultPosition, size = wx.DefaultSize, style=wx.NO_FULL_REPAINT_ON_RESIZE): wx.Window.__init__(self, parent, id, pos, size, style) self.Bind(wx.EVT_PAINT, self.OnPaint) self.Bind(wx.EVT_SIZE, self.OnSize) self.bmp0 = wx.Image(opj('image.bmp'), wx.BITMAP_TYPE_BMP) self.bmp0.SetMask(True) self.bmp = self.bmp0.Rotate(1.1215, (50,10), True,None) self.bmp = self.bmp.ConvertToBitmap() self.x = 100 self.y = 100 self.angle = 0.0 self.OnSize(None) def Draw(self,dc): pass def OnPaint(self, event): if USE_BUFFERED_DC: dc = wx.BufferedPaintDC(self, self._Buffer) else: dc = wx.PaintDC(self) dc.DrawBitmap(self._Buffer,0,0) def OnSize(self,event): self.Width, self.Height = self.GetClientSizeTuple() self._Buffer = wx.EmptyBitmap(self.Width, self.Height) self.UpdateDrawing() def SaveToFile(self,FileName,FileType): self._Buffer.SaveFile(FileName,FileType) def UpdateDrawing(self): if USE_BUFFERED_DC: dc = wx.BufferedDC(wx.ClientDC(self), self._Buffer) self.Draw(dc) else: # update the buffer dc = wx.MemoryDC() dc.SelectObject(self._Buffer) self.Draw(dc) # update the screen wx.ClientDC(self).Blit(0, 0, self.Width, self.Height, dc, 0, 0) class DrawWindow(BufferedWindow): def __init__(self, parent, id = -1): BufferedWindow.__init__(self, parent, id) def Draw(self, dc): dc.BeginDrawing() dc.SetBackground( wx.Brush("White") ) dc.Clear() # make sure you clear the bitmap! bmp = self.bmp0.Rotate(self.angle, (self.x,self.y), True,None) bmp = bmp.ConvertToBitmap() dc.DrawBitmap(bmp, self.x,self.y, True) dc.EndDrawing() class TestFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, "Double Buffered Test", wx.DefaultPosition, size=(500,500), style=wx.DEFAULT_FRAME_STYLE | wx.NO_FULL_REPAINT_ON_RESIZE) MenuBar = wx.MenuBar() file_menu = wx.Menu() ID_EXIT_MENU = wx.NewId() file_menu.Append(ID_EXIT_MENU, "E&xit","Terminate the program") self.Bind(wx.EVT_MENU, self.OnQuit, id=ID_EXIT_MENU) MenuBar.Append(file_menu, "&File") draw_menu = wx.Menu() ID_DRAW_MENU = wx.NewId() draw_menu.Append(ID_DRAW_MENU, "&New Drawing","Update the Drawing Data") self.Bind(wx.EVT_MENU, self.NewDrawing, id=ID_DRAW_MENU) BMP_ID = wx.NewId() draw_menu.Append(BMP_ID,'&Save Drawing\tAlt-I','') self.Bind(wx.EVT_MENU, self.SaveToFile, id=BMP_ID) MenuBar.Append(draw_menu, "&Draw") self.SetMenuBar(MenuBar) #nb = wx.Notebook(self, -1) #form2 = Form2(nb, -1) #nb.AddPage(form2, "Sizers") self.Window = DrawWindow(self) def OnQuit(self,event): self.Close(True) def NewDrawing(self,event): if event==None: self.Window.UpdateDrawing() else: self.Window.y = 100 for i in range(10): time.sleep(1) self.Window.y = self.Window.y + 5 self.Window.angle = self.Window.angle+0.1*1 self.Window.UpdateDrawing() def SaveToFile(self,event): dlg = wx.FileDialog(self, "Choose a file name to save the image as a PNG to", defaultDir = "", defaultFile = "", wildcard = "*.png", style=wx.SAVE) if dlg.ShowModal() == wx.ID_OK: self.Window.SaveToFile(dlg.GetPath(),wx.BITMAP_TYPE_PNG) dlg.Destroy() class Form2(wx.Panel): def __init__(self, parent, id): wx.Panel.__init__(self, parent, -1) class DemoApp(wx.App): def OnInit(self): wx.InitAllImageHandlers() # called so a PNG can be saved frame = TestFrame() frame.Show(True) frame.NewDrawing(None) self.SetTopWindow(frame) return True if __name__ == "__main__": app = DemoApp(0) app.MainLoop() From steve at holdenweb.com Thu Aug 17 00:35:05 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 17 Aug 2006 05:35:05 +0100 Subject: Newbie needs Help In-Reply-To: <1155783551.689026.273260@m73g2000cwd.googlegroups.com> References: <1155783551.689026.273260@m73g2000cwd.googlegroups.com> Message-ID: <ec0rl2$s3s$1@sea.gmane.org> len wrote: > Hi all > > I am writing a python program that inserts records into a database on > XP using mxODBC. > > I need to write a section of code which will create the following SQL > command as an example; > > INSERT INTO statecode (state, name) VALUES ('IL', 'Illinois') > > This statement will be built up using the following code; > > import mx.ODBC > import mx.ODBC.Windows > def insertFromDict(table, dict): > """Take dictionary object dict and produce sql for > inserting it into the named table""" > sql = 'INSERT INTO ' + table > sql += ' (' > sql += ', '.join(dict) > sql += ') VALUES (' > sql += ', '.join(map(dictValuePad, dict)) # ??? this code does > NOT format correctly > sql += ')' > return sql > > def dictValuePad(key): # ??? this code > does Not format correctly > return "'" + str(key) + "'" > > db = mx.ODBC.Windows.DriverConnect('dsn=UICPS Test') > c = db.cursor() > insert_dict = {'state':'IL', 'name':'Illinois'} > sql = insertFromDict("statecode", insert_dict) > print sql > c.execute(sql) > > I copied this code off of ASP and I sure it worked for his particular > circumstance but I need to format up the VALUE clause just a bit > different. > ASP code frequently makes the mistake of bulding SQL statements that way. I suspect this is because the ASP ADO model makes it difficult to produce paramtereized queries. In Python, however, the position is very different, and you should always try to separate the data from the fieldnames. > I will be working from a dictionary which will be continualy update in > another part of the program and this code is working. > Well, assuming you would rather be free of SQL inhection errors you would be much better advised to do something like this: >>> def insertFromDict(table, d): vector ... """Return SQL statement and data vector for insertion into table.""" ... fields = d.keys() ... sql = 'INSERT INTO %s (%s) VALUES(%s)' % ( ... table, ", ... ".join(fields), ... ", ".join("?" for f in fields)) ... return sql, d.values() ... >>> sql, data = insertFromDict("statecode", ... {"state": "IL", "name": "Illinois"}) >>> sql 'INSERT INTO statecode (state, name) VALUES(?, ?)' >>> data ['IL', 'Illinois'] >>> Then you make the insertion into the database using c.execute(sql, data) The other principal advantage of this technique is that you don't need to discriminate between numeric and string fields, since they are both handled the same way. You also get better efficiency if you run with the same fields many times, as the DBMS will (if it's sufficiently advanced) use the already-prepared version of the statement rather than recompiling it repeatedly. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From steve at holdenweb.com Mon Aug 28 04:15:20 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 28 Aug 2006 09:15:20 +0100 Subject: dictionaries vs. objects In-Reply-To: <7008329d0608241906t551f39efif0afeb666d9df0fc@mail.gmail.com> References: <7008329d0608241906t551f39efif0afeb666d9df0fc@mail.gmail.com> Message-ID: <ecu8ls$kq2$1@sea.gmane.org> Andre Meyer wrote: > Hi all > > I have the following question: I need a representation of a physically > inspired environment. The environment contains a large number of objects > with varying attributes. There may be classes of objects, but there is > not necessarily a strictly defined hierarchy among them. Object access > should be fast, because there a many objects that change often ( e.g., > moving objects). > > My approach is to use a dictionary for the environment model and store > each object as a slot, which contains either a dictionary or an object. > Now, which is better? What is the performance of Python to look up > attributes as either slots of a dictionary or attributes of an object? > What feels more logical? What is more pythonic and performs better? > Which is constructed and modified easier and quicker? Are there effects > that I am not yet aware of? > I'd suggest using objects: quite apart from the fact that name lookup in a namespace is pretty much equivalent to a dictionary lookup (namespaces use an internal optimised dictionary-style object) remember that objects can have methods, and that the names are given as attributes rather than as strings. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From jackson at hotmail.com Mon Aug 14 14:04:33 2006 From: jackson at hotmail.com (Jackson) Date: Mon, 14 Aug 2006 11:04:33 -0700 Subject: selecting base class from user input In-Reply-To: <1155545101.710338.129160@m79g2000cwm.googlegroups.com> References: <ebo1v5$jos$1@skeeter.ucdavis.edu> <1155523781.860117.203140@h48g2000cwc.googlegroups.com> <ebp90n$sh6$1@skeeter.ucdavis.edu> <1155545101.710338.129160@m79g2000cwm.googlegroups.com> Message-ID: <ebqdvh$6bc$1@skeeter.ucdavis.edu> John Machin wrote the following on 2006-08-14 01:45: > Here are a couple of thoughts that *might* help: > > (1) mix-in i.e. a class can have multiple base classes: > > class AntWorker(Animal, Worker): > > (2) you can create classes on the fly using the 3-argument form of the > built-in type() function: > > new_cls = type(name_of_class, base_classes_tuple, dict_of_methods_etc) > This seems like it should work. The only problem I have with it is that there are a _lot_ of classes to define (and remember). For 256 different animals, we'd have to create 256 more animal-worker classes. Obviously this works, but it seems not to be in the spirit of classes and subclasses in that it doesn't (in some central way) highlight that there is just one occupation: a worker. As another example, suppose we had Shakespeare's Romeo and Juliet. What I mean is that we have the "idea" (the storyline, themes, etc) of Romeo and Juliet. Further, suppose that we have various ways of expressing the piece: poem, book, movie, broadway. It is true, we could do: a = RaJPoem() a = RaJBook() a = RaJMovie() a = RaJBroadway() but it would be nice if we could do something like this: a = RaJ(Poem) a = RaJ(Book) a = RaJ(Movie) a = RaJ(Broadway) And then a method call to RaJ might do something different for each media. For example, a.get_opening() should fetch the opening of each media(first stanza, first chapter, first scene, etc). Thus, Poem, Book, Movie, and Broadway should probably have a get_opening() method, and the RaJ class should pass this call onto the respective class. Notice, get_opening() is not exclusive to RaJ. Maric's method works nicely for this. Additionally, I might want some methods which are exclusive to RaJ. For example, a.get_love() would fetch elements of love from each type of media. Clearly this method depends on the type of media. And there is not one method that each media class could call. For a poem, the RaJ class might look for a specific way that love can be expressed (specific to RaJ). Studpid example, look for the word 'love' at the end of each line. For a movie, we might look for any scenes where the couple kisses. The point is that there are methods for which the set of calls will differ depending on the media type (poem, book, movie, etc). This seems like a fun idea to me, and I'd like to think that things like this are done frequently. Thanks. From http Thu Aug 10 20:40:37 2006 From: http (Paul Rubin) Date: 10 Aug 2006 17:40:37 -0700 Subject: Password authentication systems References: <1155218165.193546.136090@h48g2000cwc.googlegroups.com> <7xk65g3cis.fsf@ruckus.brouhaha.com> <1155221184.665002.95160@i42g2000cwa.googlegroups.com> <7xr6zo5fre.fsf@ruckus.brouhaha.com> <1155256125.796796.289000@i42g2000cwa.googlegroups.com> Message-ID: <7xk65gxfy2.fsf@ruckus.brouhaha.com> neokosmos at gmail.com writes: > My goal is to keep user passwords as safe as possible, assuming someone > did decide to steal the password files. How often will new accounts be added? I have an idea I might try to code up. From hale at tulane.edu Sun Aug 27 17:28:36 2006 From: hale at tulane.edu (Bill Hale) Date: Sun, 27 Aug 2006 16:28:36 -0500 Subject: IDLE on Mac OS X References: <MbnIg.65514$fV1.23660@fe1.news.blueyonder.co.uk> Message-ID: <hale-CE2DA6.16283627082006@news.east.cox.net> In article <MbnIg.65514$fV1.23660 at fe1.news.blueyonder.co.uk>, Furbybrain <furbybrain at blueyonder.co.uk> wrote: > I'm running 10.3.9 and I've just installed Python 2.4. IDLE won't start- > it bounces in the dock once or twice then goes away. > I'm new to Python, and I'm trying to learn. Thanks. You might want to open the console window by running the application "Console" found in the Applications/Utilities folder. An error message may be there indicating what the problem is. -- Bill Hael From dimitri.pater at gmail.com Sat Aug 19 18:59:13 2006 From: dimitri.pater at gmail.com (dimitri pater) Date: Sun, 20 Aug 2006 00:59:13 +0200 Subject: Python complaining about CherryPY? In-Reply-To: <59236.87.127.37.129.1156017419.squirrel@ineed2.co.uk> References: <59236.87.127.37.129.1156017419.squirrel@ineed2.co.uk> Message-ID: <e75321bd0608191559q7344fc35k567c7bf1935678e8@mail.gmail.com> Hi Thomas, try the CP mailinglist: http://www.cherrypy.org/wiki/CherryPyMailingLists , they can probably answer your question. cheers, Dimitri On 8/19/06, Thomas McLean <tam at ineed2.co.uk> wrote: > > Hi all, > > First post to the list, so first off, I'm new to Python and everything > surrounding it so if you can please ignore my ignorance. > > I setup a cherryPY server so that I could use sabnzbd but once, I have > installed/configured what I was told by the tutorials and everything else. > I run ubuntu x86 dapper FYI. > > The error messages I get from the logs are as follows (which don't really > mean to muchto me): > > 19/Aug/2006:20:55:33 HTTP INFO Traceback (most recent call last): > File "/usr/lib/python2.4/site-packages/cherrypy/_cphttptools.py", line > 110, in _run > applyFilters('before_finalize') > File "/usr/lib/python2.4/site-packages/cherrypy/filters/__init__.py", > line 151, in applyFilters > method() > File > > "/home/tam/www/sites/domain1/htdocs/SABnzbd/sabnzbd/utils/multiauth/filter.py", > line 59, in beforeFinalize > cherrypy.response.body = rsrc.callable(rsrc.instance, > File "/home/tam/www/sites/domain1/htdocs/SABnzbd/sabnzbd/interface.py", > line 116, in index > info, pnfo_list, bytespersec = build_header() > File "/home/tam/www/sites/domain1/htdocs/SABnzbd/sabnzbd/interface.py", > line 933, in build_header > header = { 'version':sabnzbd.__version__, 'paused':sabnzbd.paused(), > File "/home/tam/www/sites/domain1/htdocs/SABnzbd/sabnzbd/__init__.py", > line 753, in paused > return DOWNLOADER.paused > AttributeError: 'NoneType' object has no attribute 'paused' > > 127.0.0.1 - - [19/Aug/2006:20:55:33] "POST /sabnzbd/ HTTP/1.1" 500 791 > "http://localhost:8080/sabnzbd/" "Mozilla/5.0 (X11; U; Linux i686; en-US; > rv:1.8.0.4) Gecko/20060608 Ubuntu/dapper-security Firefox/1.5.0.4" > > > So if anyone can shed some light on this I would be very greatful. > > Thanks for your time. > > Tam. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- --- You can't have everything. Where would you put it? -- Steven Wright --- please visit www.serpia.org -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060820/8629fb23/attachment.html> From guotie.9 at gmail.com Thu Aug 17 23:14:35 2006 From: guotie.9 at gmail.com (=?utf-8?B?5Y+u5Y+u5b2T5b2T?=) Date: 17 Aug 2006 20:14:35 -0700 Subject: python and poplib Message-ID: <1155870875.084567.312820@75g2000cwc.googlegroups.com> Hi, all. i have two question with poplib: 1. How to judge if a mail is or not a new mail ? 2. How Can i get the send-mailbox's mail? thanks . From gene.tani at gmail.com Fri Aug 4 23:45:04 2006 From: gene.tani at gmail.com (gene tani) Date: 4 Aug 2006 20:45:04 -0700 Subject: Design Patterns in Python In-Reply-To: <mailman.9004.1154746181.27775.python-list@python.org> References: <mailman.9004.1154746181.27775.python-list@python.org> Message-ID: <1154749504.292590.238350@p79g2000cwp.googlegroups.com> Gabriel Genellina wrote: > Hello > > Most authors talk about Java/C++, and describe patterns used as a > workaround to their static class model; the dynamic nature of Python > allows for trivial implementations in some cases. > I've seen some design patterns examples on the ActiveState site, and > some discussions some time ago on this list. > But does anyone know of a complete discussion/analysis of patterns in http://www.strakt.com/docs/ep04_pydp.pdf http://www.aleax.it/5ep.html http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html http://www.pasteur.fr/formation/infobio/python/ch18s06.html http://www.sauria.com/~twl/conferences/pycon2005/20050323/Design%20Patterns%20and%20Python%20OOP%20-%20Objects%20By%20Design.html http://norvig.com/design-patterns/ppframe.htm From python-url at phaseit.net Tue Aug 1 22:02:37 2006 From: python-url at phaseit.net (Cameron Laird) Date: Wed, 2 Aug 2006 02:02:37 +0000 (UTC) Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Aug 2) Message-ID: <eap13t$hgb$1@lairds.us> QOTW: "[U]sing Python is not programming, it IS a fun!" - Tolga "The reason for making complex a builtin is _not_ to ease a single program, but to create a convention allowing different modules which operate on complex numbers to communicate." -Scott David Daniels Komodo 4.0 debuted at last week's OSCON: http://www.activestate.com/komodo/beta Python2.5final is under two weeks away. Watch for it. 'Want to *really* learn Python? http://home.earthlink.net/~python-training/public.html Quest for the Holy Grail is as Pythonic as it gets: http://www.cosc.canterbury.ac.nz/greg.ewing/grailquest/index.html John Henry asks a sober question which Simon Brunning can't refrain from soiling with his perverse algorithmic imagination: http://groups.google.com/group/comp.lang.python/msg/bb47da1c1c346954 C has static locals. Python has classes, closures, and defaulted keyword parameters: http://groups.google.com/group/comp.lang.python/browse_thread/t hread/9799c58168e0615b/ Python range()s the way Dijkstra preaches: http://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to <Python-URL at phaseit.net> should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask <claird at phaseit.net> to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From bignose+hates-spam at benfinney.id.au Wed Aug 30 19:15:35 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 31 Aug 2006 09:15:35 +1000 Subject: What make a great community References: <1156949259.255949.323150@i42g2000cwa.googlegroups.com> Message-ID: <871wqxke7c.fsf@benfinney.id.au> "flit" <superflit at gmail.com> writes: > Results: > > No response from microsoft, and always 3 responses for posts on this > lists. > I just want to say thank you for all. > And notice that this is a great community.. Great people make a great community, of course. However, the dynamics of free software mean that great people can find more satisfaction helping others: there are very few restrictions on doing so compared to non-free software. Thanks for telling us. Remember to tell others of the great community and support you get in free software. -- \ "Read not to contradict and confute, nor to believe and take | `\ for granted ... but to weigh and consider." -- Francis Bacon | _o__) | Ben Finney From mail at microcorp.co.za Fri Aug 4 03:18:41 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Fri, 4 Aug 2006 09:18:41 +0200 Subject: Is there an obvious way to do this in python? References: <mailman.8853.1154537129.27775.python-list@python.org><1154541495.486057.316740@i3g2000cwc.googlegroups.com><eaqug3$99s$1@news-int.gatech.edu><mailman.8883.1154590372.27775.python-list@python.org> <gf84d29ss5uf9ljqt7mlrormuhksb3ndi2@4ax.com> Message-ID: <00d701c6b79d$fc871ee0$03000080@hendrik> "Dennis Lee Bieber" <wlfraed at ix.netcom.com> wrote: | On Thu, 3 Aug 2006 09:17:41 +0200, "H J van Rooyen" | <mail at microcorp.co.za> declaimed the following in comp.lang.python: | | > Can I not use the ssl module for encrypting the connections? - Please also | > understand that the system is aimed at small to medium companies, in ouse - | > >From my perspective the only valid reason to use a database would be for the | > ease of reporting - the files are not large - and the speed of a dict lookup in | > python is hard to beat for normal transaction processing... | > | You might want to read the "Kode Vicious" column in a recent issue | of Queue (probably last months issue -- it's been in my carry-bag for a | few weeks). | | For an "in house" effort, encrypting the LAN traffic is probably not | the most meaningful focus. Securing the data /storage/ is more important | -- why secure the LAN traffic if someone can walk off with a backup of | unsecured database. And who'd want to even spend time with a LAN sniffer | on unencrypted traffic if that same backup is available for filching. | > This makes sense - message is - lock your server room... | > NO! the last thing on my mind - want a dynamic process similar to banking | > terminals - see my response to Simon please | > | ? ATMs? Or internal clerk consoles? Semantics - sorry - neither - thinking of credit card terminals - in which area I have dabbled in a bit... These things have horrendously complex terminal management systems and elaborate mechanisms to download all manner of parameters to change their behaviour... - most have their internal state controlled by the server, sometimes formally, sometimes just via param download... | Pretty much everything is already in the terminal software -- what | the operator has access to, and sees, is dependent upon the privileges | defined for their "account". No "dynamic" loading of code (for security, | I'd not even permit remote updates -- I'd require a floppy or CD from | inside the secure box to change operating software; as soon as you | permit updates to be pushed from outside you expose the risk of a | cracker pushing a customized code set). | I was not aiming for this paranoid level of security - when I said "secure" or "reliable" I was just looking for something that would work and that I could trust not to fall over all the time... On the small boxes, the loading of software mechanism varies from manufacturer to manufacturer - some allow, others disallow the download and activation of new apps - likewise for the update of existing ones - but most banks don't use these mechanisms, even if they are available - they all tend to bring the device in to a trusted facility. I don't know one of them that actually use the mechanism on a per transaction basis, because it would be, amongst other things, too slow - but most of the systems can force the terminal into a reload of at least its set of parameters the next time it logs in - and this mechanism is used by for instance AMEX to vary the messages displayed on their terminals - not quite "code" update - but the user can't tell the difference. I used the example because this sort of facility is the kind of thing I want to find out if Python could do, in a more dynamic way than what the terminals that can use it, actually use it - little thinking that I was sowing confusion - sorry... If you are familiar with the sort of Terminal Management Systems I am talking about, that control the behaviour of the remote box via parameter download - then what I want find out is how to do that in Python, but with the added proviso that I must also be able to download "pieces" of the application - where "download" in this sense is just to a PC in the next office on the local LAN - So far the Pyro package that Bruno has steered me towards sounds the most promising way of doing this - but I still haven't been able to "research" it ... Thanks for the input and sorry about the confusion. - Hendrik From aries.shuaib at gmail.com Wed Aug 16 17:45:01 2006 From: aries.shuaib at gmail.com (Shuaib) Date: 16 Aug 2006 14:45:01 -0700 Subject: Calling a python script, and getting the returned result in C Message-ID: <1155764701.509056.207140@h48g2000cwc.googlegroups.com> Hi! I have a python script which returns an Integer value. How do I call this script from a C programe, and use the result returned? Thanks for your time. From sjmachin at lexicon.net Wed Aug 9 05:20:32 2006 From: sjmachin at lexicon.net (John Machin) Date: 9 Aug 2006 02:20:32 -0700 Subject: Unicode/utf-8 data in SQL Server References: <1155055758.835957.326440@i3g2000cwc.googlegroups.com> <1155083249.333622.40590@p79g2000cwp.googlegroups.com> <ebc3cv$f8b$1@upsn250.cri.u-psud.fr> Message-ID: <1155115232.064265.174230@b28g2000cwb.googlegroups.com> Laurent Pointal wrote: > John Machin a ?crit : > > The customer should be very happy if you do > > text.decode('utf-8').encode('cp1252') -- not only should the file > > import into Excel OK, he should be able to view it in > > Word/Notepad/whatever. > > + > text.decode('utf-8').encode('cp1252',errors='replace') > > As cp1252 may not cover all utf8 chars. In that case, the OP may well want to use 'xmlcharrefreplace' or 'backslashreplace' as they stand out more than '?' *and* the original Unicode is recoverable if necessary e.g.: #>>> msg = u'\u0124\u0114\u0139\u013B\u0150' >>> print msg HELLO #>>> msg.encode('cp1252', 'replace') '?????' #>>> msg.encode('cp1252', 'xmlcharrefreplace') 'ĤĔĹĻŐ' #>>> msg.encode('cp1252', 'backslashreplace') '\\u0124\\u0114\\u0139\\u013b\\u0150' #>>> Cheers, John From paul at boddie.org.uk Fri Aug 25 05:20:51 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 25 Aug 2006 02:20:51 -0700 Subject: Consistency in Python References: <mailman.9855.1156495956.27775.python-list@python.org> Message-ID: <1156497650.974905.196140@74g2000cwt.googlegroups.com> Hendrik van Rooyen wrote: > > There seems to be no common methods such as- > "prepend" - for adding something to the beginning > "append" - for adding something to the end > "insert[j]" - for adding something somewhere in the middle > > Or have I missed something ? [...] > BTW - I understand that some things are immutable - but that is an > implementation detail, not a language issue. - the fact that you get the name S > bound to a new object is irrelevant to a discussion about how you tell the > interpreter to do something... You haven't missed one of the principal reasons exactly, but you underestimate its importance. There aren't such methods as append or insert on strings or tuples precisely because those objects are immutable, whilst such methods on lists and other mutable objects change the contents of such objects. Moreover, append and insert return no result because the change occurs within an existing object - if you were to return a reference to the changed object, it would be the same reference as the one you already had. # Append on lists: l.append(something) # returns nothing (you'll get None) Now, you could argue that insert and append should always return a reference to some object, and that for lists (and other mutable objects) it should return the same reference (to the changed object), whereas for strings (and other immutable objects) it should return a different reference (to an object which has the changed contents of the original object). # Fictional append on strings: s2 = s.append(sometext) # s would be the same, s2 different # Fictional append variant on lists: l2 = l.append(something) # l and l2 would be the same However, there's a sort of unwritten guarantee - although it could be in the documentation - that the append and insert methods specifically mutate objects and that they therefore have no place in immutable objects. Certainly, the behaviour illustrated above could be surprising in some kinds of programs because the append method on strings would be more like a factory or a copy constructor rather than a "mutator". Now, you could argue that the name involved could be hacked in some magical way, thus preserving the illusions that strings are mutable, but what happens when a name is not involved? s.append(sometext) # s gets replaced (text + moretext).append(sometext) # what gets replaced? Mutability is more than a mere implementation detail: in imperative languages, it's probably one of the most underrated mechanisms influencing the correct behaviour of programs. Paul From gandalf at designaproduct.biz Thu Aug 24 16:26:01 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Thu, 24 Aug 2006 22:26:01 +0200 Subject: Python & chess In-Reply-To: <44edea60$0$8925$88260bb3@free.teranews.com> References: <83e8215e0608240358l4126bb83la93a4c61e4aa4499@mail.gmail.com> <mailman.9806.1156442412.27775.python-list@python.org> <44edea60$0$8925$88260bb3@free.teranews.com> Message-ID: <44EE0B59.3080403@designaproduct.biz> tobiah ?rta: > Paolo Pantaleo wrote: > >> Well Python is not a good language for writing a chess engine >> > > I'm curious; how does python fall short here, and what are the > features that make some other language more suitable for the > task? > Hmmm. I think that if you need to write a very clever chess game, then you need to use very fast routines, written in C or even assembly. I have heard that the best chess programs use a database. That database contains hundreds of thousands of games played previously by famous chess players. Usually they play the first few steps by using this database (and not using any AI). Do you plan to beat "Chessmaster"? :-) If you only want to try your AI abilities, then Python is ideal for the task. At least this is my opinion. Laszlo From iainking at gmail.com Thu Aug 17 11:19:03 2006 From: iainking at gmail.com (Iain King) Date: 17 Aug 2006 08:19:03 -0700 Subject: The Semicolon Wars as a software industry and human condition In-Reply-To: <1155822175.534005.100490@75g2000cwc.googlegroups.com> References: <1155822175.534005.100490@75g2000cwc.googlegroups.com> Message-ID: <1155827943.041208.51220@i3g2000cwc.googlegroups.com> Xah Lee wrote: > Of interest: > > ? The Semicolon Wars, by Brian Hayes. 2006. > http://www.americanscientist.org/template/AssetDetail/assetid/51982 > > in conjunction to this article, i recommend: > > ? Software Needs Philosophers, by Steve Yegge, 2006 > http://xahlee.org/Periodic_dosage_dir/_p/software_phil.html > > ? What Languages to Hate, Xah Lee, 2002 > http://xahlee.org/UnixResource_dir/writ/language_to_hate.html > > Xah > xah at xahlee.org > ? http://xahlee.org/ I'm confused - I thought Xah Lee loved Perl? Now he's bashing it? Huh? Iain From sjdevnull at yahoo.com Wed Aug 30 11:43:05 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 30 Aug 2006 08:43:05 -0700 Subject: How ahead are you guys in the (Python) real world? In-Reply-To: <XGgJg.2715$No6.53253@news.tufts.edu> References: <1156821234.820929.299740@p79g2000cwp.googlegroups.com> <XGgJg.2715$No6.53253@news.tufts.edu> Message-ID: <1156952585.686270.265300@m73g2000cwd.googlegroups.com> John Salerno wrote: > Interesting question. Just as a curious follow-up (not being someone who > works in the programming world), why does it take so long to move to the > latest version, especially when there aren't (I don't think) any changes > that would break existing code, such as moving to Python 2.4 from 2.2 or > 2.3? Well, let's see. We have about 5 live servers that would need to be upgraded. They're running an old enough version of the OS that 2.2 is the last supported release. Fine, building a new python release ourself is not a huge deal--but it means that we're no longer on the vendor's automatic update system for python and related packages. And, of course, we use mod_python. That needs to be rebuilt against the new python version. We also have a number of 3rd-party packages installed; each of those needs to be re-installed for the new python version, and possibly rebuilt first if it has any C extension modules. The real question in most production environments isn't "why not upgrade?", it's "why upgrade?". Until a new release has features that are going to be valuable enough to your project to offset the cost of upgrading, why would you bother? From steve at holdenweb.com Tue Aug 15 20:50:05 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 16 Aug 2006 01:50:05 +0100 Subject: proc A def/calls proc B: variable scoping rules. In-Reply-To: <1155685233.002415.184150@74g2000cwt.googlegroups.com> References: <1155685233.002415.184150@74g2000cwt.googlegroups.com> Message-ID: <ebtq37$u9f$1@sea.gmane.org> NevilleDNZ wrote: > Can anyone explain why "begin B: 123" prints, but 456 doesn't? > > $ /usr/bin/python2.3 x1x2.py > begin A: > Pre B: 123 456 > begin B: 123 > Traceback (most recent call last): > File "x1x2.py", line 13, in ? > A() > File "x1x2.py", line 11, in A > B() > File "x1x2.py", line 7, in B > print "begin B:",x1,x2 > UnboundLocalError: local variable 'x2' referenced before assignment > > > $ cat x1x2.py > #!/usr/bin/env python > def A(): > print "begin A:" > x1=123; > x2=456; > def B(): > print "begin B:",x1,x2 > x2 = x2 - 1; # comment out this line and script x1x2 magically > works!! Hardly surprising. This statement is an assignment to x2, which therefore becomes local to the function. Since no previous value has been assigned to this local, the exception occurs. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From tundra at tundraware.com Thu Aug 17 05:22:52 2006 From: tundra at tundraware.com (Tim Daneliuk) Date: Thu, 17 Aug 2006 04:22:52 -0500 Subject: Looking For mp3 ID Tag Module Message-ID: <f4pdr3-0rh.ln1@eskimo.tundraware.com> I have DAGS and generally nosed around the net but cannot quite find what I need. I am looking for a platform-independent Python module that would permit me to write mp3 ID tags conformant to the latest spects. I am currently calling 'mp3info' from my Python script, but that program is limited to the older ID tags that are severely limited in length and thus truncate the description strings I am providing. Ideas anyone? -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From dasn at bluebottle.com Mon Aug 28 03:38:04 2006 From: dasn at bluebottle.com (Dasn) Date: Mon, 28 Aug 2006 02:38:04 -0500 Subject: A problem from a Vim user In-Reply-To: <200608271210.k7RCA6Ck029114@fe10.bluebottle.com> References: <1154973541.450774.50090@75g2000cwc.googlegroups.com> <200608271210.k7RCA6Ck029114@fe10.bluebottle.com> Message-ID: <200608280738.k7S7borC007213@fe10.bluebottle.com> On Sun, Aug 27, 2006 at 07:10:06AM -0500, Dasn wrote: > vim.command('let vim_str=input("Please type something.\n")') > py_str = vim.eval('vim_str') py_str = vim.eval('input("Please type something.\n")') may be better. From cliff at develix.com Tue Aug 1 00:12:37 2006 From: cliff at develix.com (Cliff Wells) Date: Mon, 31 Jul 2006 21:12:37 -0700 Subject: Using Python for my web site In-Reply-To: <k291j3damhnf$.dlg@gelists.gmail.com> References: <1154361480.915174.262720@b28g2000cwb.googlegroups.com> <44ce3a5c$0$18952$626a54ce@news.free.fr> <1154367359.931684.106650@m73g2000cwd.googlegroups.com> <44ce4530$0$28242$626a54ce@news.free.fr> <1pbgluuxgrgbf$.dlg@gelists.gmail.com> <1154377680.20290.37.camel@devilbox> <1insadcgifsbv.dlg@gelists.gmail.com> <1154380997.20290.64.camel@devilbox> <k291j3damhnf$.dlg@gelists.gmail.com> Message-ID: <1154405557.20290.127.camel@devilbox> On Mon, 2006-07-31 at 21:57 -0300, Gerhard Fiedler wrote: > On 2006-07-31 18:23:17, Cliff Wells wrote: > > > My point is to stop FUD right at that comment. I don't doubt your > > research from "a few years ago", but ancient research is entirely > > irrelevant for making a decision *today*. > > That's exactly the reason why I added this information. It might not be for > you, but it is interesting for me (and might be for someone else) to see > that I get a different feedback now than I got a few years ago. It tells > something about the dynamic of the process that the mere status of today > doesn't tell. Well, perhaps I misunderstood your intent. Sorry if I was short. > Besides, "claimed to have" and "seemed to have" are not really FUD inducing > terms :) Taken in a vacuum, they can certainly add to an overall negative impression. PostgreSQL, in the past, has certainly had some hurdles that made it a suboptimal choice for many people: performance and difficulty in installation and management, among other things (I've personally not had stability issues), lack of a native Win32 version, etc, have made it the runner up in deployment to MySQL. Today, that's all changed. PostgreSQL is comparable in performance to MySQL (although I expect each outperforms the other in certain areas), *easier* to install and maintain than MySQL, and its stability is outstanding. Release 8 also saw a native Windows version. For many reasons, MySQL seems to be on the reverse track, sacrificing performance, stability and ease of use in an attempt to catch up to PostgreSQL in features. Nevertheless, there remains rumors and myths that stem from those old days that cause many people to fear deploying PostgreSQL. This is part of the reason I'm always quick to jump on statements such as yours. I feel it's a disservice to the community to let those myths continue and perhaps dissuade others from discovering what is today *the* premier FOSS relational database. > Anyway, I appreciate you sharing your experience (which in that area > certainly is more than mine). I'm glad I was able to add to the pool of knowledge (or at least the mud puddle of anecdote). Cliff -- From mgalves at gmail.com Wed Aug 16 08:29:03 2006 From: mgalves at gmail.com (Miguel Galves) Date: Wed, 16 Aug 2006 09:29:03 -0300 Subject: Current module reference Message-ID: <52655700608160529g31327e73na9474fe039aadeec@mail.gmail.com> Hi How do I get a reference for the current module I'm in ? I have a package called services with a __init__.py that need to use getattr() to fill out a hash whith my package attributes. But to use getattr, I need a object that references my package (kind of this this reference in Java). How can I do it ? the only way I found to o this is to call get attr from another module that imports the services package. But I suppose it's not the only way.... Thanks for your help Miguel -- Miguel Galves - Engenheiro de Computa??o J? leu meus blogs hoje? Para geeks http://log4dev.blogspot.com Pra pessoas normais http://miguelgalves.blogspot.com "N?o sabendo que era imposs?vel, ele foi l? e fez..." -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060816/6e9796bc/attachment.html> From jyoti.chhabra at gmail.com Tue Aug 29 03:24:27 2006 From: jyoti.chhabra at gmail.com (JyotiC) Date: 29 Aug 2006 00:24:27 -0700 Subject: prob with tkinter Message-ID: <1156836267.924197.289170@p79g2000cwp.googlegroups.com> hi, i am making a GUI using tkinter i need to get lot of data from user, it's in form of a excel sheets(many rows n columns) what i am using is grid for foramating, frame is from Toplevel, data collected from Entry widget I can't see most of the columns. I am not able to add scroll bar, i want it to be added horizontally and vertically. thanx Jyoti From p.barbierdereuille at free.fr Wed Aug 9 08:47:03 2006 From: p.barbierdereuille at free.fr (Pierre Barbier de Reuille) Date: Wed, 09 Aug 2006 13:47:03 +0100 Subject: do people really complain about significant whitespace? In-Reply-To: <1155077965.100108.232790@m79g2000cwm.googlegroups.com> References: <1154986984.740638.241130@m79g2000cwm.googlegroups.com> <87bqqwyumq.fsf@benfinney.id.au> <mailman.9084.1155026444.27775.python-list@python.org> <1155077965.100108.232790@m79g2000cwm.googlegroups.com> Message-ID: <44d9d949$0$14310$626a54ce@news.free.fr> Carl Banks wrote: > Michiel Sikma wrote: >> Op 8-aug-2006, om 1:49 heeft Ben Finney het volgende geschreven: >> >>> As others have pointed out, these people really do exist, and they >>> each believe their preconception -- that significant whitespace is >>> intrinsically wrong -- is valid, and automatically makes Python a >>> lesser language. >> Well, I most certainly disagree with that, of course, but you gotta >> admit that there's something really charming about running an auto- >> formatting script on a large piece of C code, turning it from an >> unreadable mess into a beautifully indented and organized document. > > The only time I get that satisfaction is when I run the formatter to > format some C code I'm asked to debug. Quite often the problem was > something that could have been easily spotted if the coder had used > good indentation in the first place. Though they probably wouldn't > have seen it anyways, considering the poor programming skills of most > engineers (the classical definition, not computer engineers). > > The very fact the code formatters exist should tell you that grouping > by indentation is superior. > > > Carl Banks > Problem being : grouping by indentation do *not* imply good indentation. For example, I had to read a piece of (almost working) code which looked like that : if cond1 : stmt1 stmt2 stmt3 if cond2: stmt4 stmt5 elif cond3: stmt6 stmt7 else: stmt8 stmt9 stmt10 stmt11 So you can tell what you want, but this code is valid but impossible to read and impossible to reindent correctly. So although I personnaly like Python, I still don't think meaningful indentation is good. Pierre From jack at psynchronous.com Sat Aug 19 12:43:33 2006 From: jack at psynchronous.com (Jack Diederich) Date: Sat, 19 Aug 2006 12:43:33 -0400 Subject: PyThreadState_Swap(NULL) In-Reply-To: <ec7cts$svs$1@sea.gmane.org> References: <ec5b3m$puo$1@sea.gmane.org> <20060819145056.GL5772@performancedrivers.com> <ec7cts$svs$1@sea.gmane.org> Message-ID: <20060819164333.GN5772@performancedrivers.com> On Sat, Aug 19, 2006 at 09:08:21AM -0700, Bryan wrote: > Jack Diederich wrote: > > On Fri, Aug 18, 2006 at 02:21:40PM -0700, Bryan wrote: > >> i've written a program that uses python c api code that lives in a > >> shared library that is loaded by a custom apache module (mod_xxx). this > >> python c api code all works correctly under our test server and under > >> apache but only if mod_python isn't loaded. when apache loads > >> mod_python as shown in the http.conf snippet below, > >> PyThreadState_Swap(NULL) in mod_xxx returns NULL. when the snippet of > >> code in http.conf is commented out, it works again. what do i have to > >> do to have mod_xxx code work correctly when apache loads mod_python? > >> > >> > >> failure case when apache loads mod_python: > >> Py_Initialize() succeeded > >> PyThreadState_Swap(NULL) failed > >> > >> > >> sucess case when apache doesn't load mod_python: > >> Py_Initialize() succeeded > >> PyThreadState_Swap(NULL) succeeded > >> > > > > Running multiple python interpreters in the same process isn't supported. > > It works OK for most things but some low-level guts are shared between > > interpreters so it is possible to run into trouble. > > > > You aren't running multiple interpreters in the same process. You and > > mod_python both think you are in charge and end up nuking each other's > > states. Py_Initialize() resets the global state and shouldn't be called > > more than once. You can create more than one sub-interpreter (check out > > the mod_python source for how, the source is small and readable). > > > > The best thing to do would be to load your module last and conitionally > > call Py_Initialize() if someone else hasn't already. > > > > -Jack > > > thanks for replying jack. i tested what you suggested. > > i put our module after mod_python, commented out Py_Initialize(), and > Py_IsInitialized() returned True, but PyThreadState_Swap() failed. > > i put our module before mod_python, called Py_Initialize(), and > Py_IsInitialized() returned True, but PyThreadState_Swap() failed. > > i removed mod_python and our module succeeded. > > i even tested combinations of calling and PyEval_InitThreads() but didn't work > either. I'm out of my depth here, I only know that this kind of thing is tricky. I think you need to explicitly spawn a new sub-interpreter or at least a new thread state from the existing interpreter. Your best bet is to ask on the mod_python mailing list. Those guys actually do this kind of thing so if you are going to get good advice it will be from them. -Jack From claudio.grondi at freenet.de Sat Aug 26 19:55:25 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Sun, 27 Aug 2006 01:55:25 +0200 Subject: random writing access to a file in Python In-Reply-To: <7xbqq7f6q7.fsf@ruckus.brouhaha.com> References: <ecn00i$t2o$1@newsreader2.netcologne.de> <mailman.9872.1156515341.27775.python-list@python.org> <ecn22h$3o5$1@newsreader2.netcologne.de> <5a9ue2lrjh214ecmme09fsodhm3ico1ntm@4ax.com> <ecno4v$h11$1@newsreader2.netcologne.de> <7xhczzqoi3.fsf@ruckus.brouhaha.com> <ecqhd2$17u$1@newsreader2.netcologne.de> <7xbqq7f6q7.fsf@ruckus.brouhaha.com> Message-ID: <ecqn1d$8ui$1@newsreader2.netcologne.de> Paul Rubin wrote: > Claudio Grondi <claudio.grondi at freenet.de> writes: > >>>Try the standard Unix/Linux sort utility. Use the --buffer-size=SIZE >>>to tell it how much memory to use. >> >>I am on Windows and it seems, that Windows XP SP2 'sort' can work with >>the file, but not without a temporary file and space for the resulting >>file, so triple of space of the file to sort must be provided. > > > Oh, sorry, I didn't see the earlier parts of the thread. Anyway, > depending on the application, it's probably not worth the hassle of > coding something yourself, instead of just throwing more disk space at > the Unix utility. But especially if the fields are fixed size, you > could just mmap the file and then do quicksort on disk. Simplest > would be to just let the OS paging system take care of caching stuff > if you wanted to get fancy, you could sort in memory once the sorting > regions got below a certain size. > > A huge amount of stuff has been written (e.g. about half of Knuth vol > 3) about how to sort. Remember too, that traditionally large-scale > sorting was done on serial media like tape drives, so random access > isn't that vital. Does it mean, that in case of very large files: the size of available memory for the sorting operation (making it possible to work on larger chunks of data in memory) has less impact on the actual sorting speed than the speed of the data transfer from/to storage device(s) ? So, that the most effective measure towards shortening the time required for sorting very large files were to use faster hard drives (e.g. 10.000 rpm instead of 7.600 rpm) and faster interfaces for the data transfer (e.g. E-IDE or S-ATA instead of USB), right? Claudio Grondi From david_wahler at bic.ky Tue Aug 15 02:15:42 2006 From: david_wahler at bic.ky (david_wahler at bic.ky) Date: 15 Aug 2006 01:15:42 -0500 Subject: =?utf-8?Q?Re:_ANN:_Crunchy_version_0.7_is_here=21?= Message-ID: <20060815061542.6473.qmail@BICSRV1011.bic.ky> I'll be out of the office until approximately August 20th. If you have any questions, please email support at bic.ky. -- David Wahler From steve at REMOVEME.cybersource.com.au Wed Aug 23 03:30:59 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 23 Aug 2006 17:30:59 +1000 Subject: how do you get the name of a dictionary? References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <pan.2006.08.21.03.33.27.84160@REMOVEME.cybersource.com.au> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> <mailman.9631.1156227418.27775.python-list@python.org> <1156264475.968894.221710@p79g2000cwp.googlegroups.com> <1156266720.205126.284050@i3g2000cwc.googlegroups.com> <pan.2006.08.23.00.36.23.369082@REMOVEME.cybersource.com.au> <mailman.9687.1156316236.27775.python-list@python.org> Message-ID: <pan.2006.08.23.07.30.58.840683@REMOVEME.cybersource.com.au> On Wed, 23 Aug 2006 08:56:54 +0200, Fredrik Lundh wrote: > Steven D'Aprano wrote: > >> But an upside is that it would enable more useful error messages, at least >> sometimes. Here's some trivial pseudo-code: >> >> def foo(a): >> assert len(a) > 10, "%s is too short" % a.__name__ >> >> y = "hello" >> foo(y) >> >> would display "AssertionError: y is too short". > > why not "a is too short" ? > > or for that matter, "x is to short" ? These are all valid responses too. But consider that when you get an exception that says "a is too short", you often have to mentally change gears and think about where a came from and what it is called in the enclosing scope. After all, if the value of a is invalid, and the value of a is set in the enclosing scope, it makes sense to refer to "the object known locally as a" by the name it was known as when it was set. Of course, this leads to greater complexity, it still doesn't deal well with objects known by multiple names, or no name at all, and it would require a lot of overhead for something which is only of value occasionally. In other words, the downside outweighs the upside significantly. -- Steven D'Aprano From bearophileHUGS at lycos.com Fri Aug 25 18:19:42 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 25 Aug 2006 15:19:42 -0700 Subject: Python and STL efficiency In-Reply-To: <1156543134.839425.254040@75g2000cwc.googlegroups.com> References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <1156533768.283454.48570@m73g2000cwd.googlegroups.com> <1156540873.326734.15600@i42g2000cwa.googlegroups.com> <1156543134.839425.254040@75g2000cwc.googlegroups.com> Message-ID: <1156544382.789534.202680@p79g2000cwp.googlegroups.com> Pebblestone: >I heard that python's list is implemented as adjustable array. Correct, an array geometrically adjustable on the right. >Here's my lisp implementation:< What's the memory size of a before computing b? You can compare it with Python, that may need less memory (because the array contains pointers). >BTW, I couldn't install psyco on my system (ubuntu), gcc just prompt to me thousands of lines of errors and warnings.< Find a Win box ;-) It's already compiled for it (for Py 2.3, 2.4). >Your python's example (use direct index array index) of my corresponding lisp code works slower than the version which use 'append'.< For me (a slow PC) it's almost twice faster, computer life is usually complex. For me using the esplicit allocation + Psyco makes that program about 4 times faster (from 8 to 2 seconds). >This let me think how python's list is implemented.< You also have to think how the * allocation is implemented and many other things :-) The list implementation is rather readable, Python sources are online too. >Anyway, python's list is surprisingly efficient.< But its access isn't that fast :-) Psyco helps. Bye, bearophile From forum at anton.e4ward.com Sat Aug 12 12:36:32 2006 From: forum at anton.e4ward.com (Anton81) Date: Sat, 12 Aug 2006 18:36:32 +0200 Subject: self=pickle.load(file)? (Object loads itself) Message-ID: <ebl02g$3dv$1@gwdu112.gwdg.de> Hi! it seems that class Obj: def __init__(self): f=file("obj.dat") self=pickle.load(f) ... doesn't work. Can an object load itself with pickle from a file somehow? What's an easy solution? Anton From nicolasg at gmail.com Sat Aug 26 12:12:50 2006 From: nicolasg at gmail.com (NicolasG) Date: 26 Aug 2006 09:12:50 -0700 Subject: Python web service ... References: <1156590455.555359.247410@h48g2000cwc.googlegroups.com> <mailman.9921.1156605379.27775.python-list@python.org> Message-ID: <1156608770.864092.169920@i3g2000cwc.googlegroups.com> > For a one-shot thing, plain old CGI might be enough. You can have a > static HTML page with the form for the upload, have python do the > image part, and generate the return HTML with the image with a python > script. If you plan to do this a lot, or want fairly sophisticated > stuff, or DB access underneath, authentication, etc, then you might > want to look at any of the web framewoks. If you don't have the web > server part already taken care of (e.g., you already have Apache up > and running) then the web server framework can be more attractive. > > As for web frameworks there is a long list in the Python web site. > Which framework fits you best might depend on what you want to > accomplish now and in the future. You can try something simple and > minimalist (and with docs that you can read in less than an afternoon) > such as Karrigell, or try something more complex, such as Django, > TurboGears, Pylons, CherryPy, etc. > > And then, you might try the CGI approach to begin with, and as your > needs become more complex, move to a framework. (This has been our own > path: we've used plain CGI for over a year for the web-based > bioinformatics applications we've developed, that use R and Python for > computations, and are now moving to framework). > > Good luck! > > R. > > -- > Ramon Diaz-Uriarte At this time right now I prefer to do something that works the quickest possible... I never had any experience with CGI, do I need to set up a web server for that ? can you point me some usefull reading material so I can get a start ? I will post for a comment at Zope , I had installed once and it was very easy. Don't know if it will be easy too to get my job done... Gracias Ramon. From rosedb0 at gmail.com Tue Aug 8 16:55:12 2006 From: rosedb0 at gmail.com (hiaips) Date: 8 Aug 2006 13:55:12 -0700 Subject: newb question: file searching In-Reply-To: <1155069065.129575.10650@i42g2000cwa.googlegroups.com> References: <1155067111.892386.130610@n13g2000cwa.googlegroups.com> <1155068505.141479.5210@m79g2000cwm.googlegroups.com> <1155069065.129575.10650@i42g2000cwa.googlegroups.com> Message-ID: <1155070512.182518.189560@m79g2000cwm.googlegroups.com> > I'm thinking os.walk() could definitely be a big part of my solution, > but I need a little for info. If I'm reading this correctly, os.walk() > just goes file by file and serves it up for your script to decide what > to do with each one. Is that right? So, for each file it found, I'd > have to decide if it met the criteria of the filetype I'm searching for > and then add that info to whatever datatype I want to make a little > list for myself? Am I being coherent? > > Something like: > > for files in os.walk(top, topdown=False): > for name in files: > (do whatever to decide if criteria is met, etc.) > > Does this look correct? IIRC, repeated calls to os.walk would implement a depth-first search on your current directory. Each call returns a list: [<directory name relative to where you started>, <list of files and directories in that directory>] --dave From rzantow at gmail.com Wed Aug 2 11:09:46 2006 From: rzantow at gmail.com (Rick Zantow) Date: Wed, 02 Aug 2006 11:09:46 -0400 Subject: Class definition within function References: <Su0Ag.121$fe3.114@read3.inet.fi> <Xns9813882C9C0FDduncanbooth@127.0.0.1> Message-ID: <Xns9813719115C60rzed@208.49.80.253> Duncan Booth <duncan.booth at invalid.invalid> wrote in news:Xns9813882C9C0FDduncanbooth at 127.0.0.1: >> >>> def f(): >> class C(object): >> def __init__(self): >> self.a = 'a' >> return C() >> >> >>> x = f() >> >>> x.a >> 'a' >> >>> y=f.C() >> > Of course there's this: >>> def f(): ... class C(object): ... def __init__(self): ... self.a = 'a' ... return C() ... >>> x = f() >>> x.a 'a' >>> y=x.__class__() >>> y.a 'a' >>> type(y) == type(x) True From avelldiroll at yahoo.fr Wed Aug 2 04:24:57 2006 From: avelldiroll at yahoo.fr (Avell Diroll) Date: Wed, 02 Aug 2006 10:24:57 +0200 Subject: Reinstalling Python Problem (Newbie) In-Reply-To: <44CF9ADE.4080008@python.org> References: <mailman.8802.1154445784.27775.python-list@python.org> <eanuit$mbk$1@news.u-bordeaux1.fr> <44CF9ADE.4080008@python.org> Message-ID: <44D06159.2070706@yahoo.fr> beno wrote: > I intend to do that. However, I think this is the RIGHT list to ask > questions pertinent to python... I didn't intend to be abrupt, ... I was just in an hurry, sorry for that. Anyway I still see this problem more as a program not compiling correctly on Freebsd than python not compiling correctly on a platform ... everybody has his own point of view :-) Anyway I don't have any freebsd box around any more, so there is no way for me to reproduce your problem (hence my remark about the place to post). Another thing, if you just want to use zope, it seems to be included in freebsd ports ... so you should not need to compile anything to _run_ zope on your system, but maybe you need specific options not included in the ports (this is only fully supported on freebsd-stable and freebsd-current which are AFAIK respectively 6.1 and 7.). Ref.: http://www.freebsd.org/ports/zope.html http://www.freebsd.org/ports/lang.html#python-2.4.3 Zope is not supported in 5.5 anymore but it is present in the ports archive. ftp://ftp.freebsd.org/pub/FreeBSD/releases/i386/5.5-RELEASE/ports/ To get back to your specific problem : > 2 tests failed: > test_mimetools test_urllib2 > 48 tests skipped: > test_aepack test_al test_applesingle test_asynchat test_bsddb > test_bsddb3 test_cd test_cl test_codecmaps_cn test_codecmaps_hk > test_codecmaps_jp test_codecmaps_kr test_codecmaps_tw test_curses > test_doctest test_fork1 test_gdbm test_gl test_imgfile test_imp > test_linuxaudiodev test_logging test_macfs test_macostools > test_nis test_normalization test_ossaudiodev test_pep277 > test_plistlib test_queue test_scriptpackages test_socket > test_socket_ssl test_socketserver test_sunaudiodev test_tcl > test_thread test_threaded_import test_threadedtempfile > test_threading test_threading_local test_threadsignals > test_timeout test_unicode_file test_urllib2net test_urllibnet > test_winreg test_winsound > 13 skips unexpected on freebsd5: > test_threadedtempfile test_imp test_threaded_import test_fork1 > test_threading test_threadsignals test_socket test_thread > test_queue test_asynchat test_doctest test_threading_local > test_logging > *** Error code 1 > > What do I do about the problems with mimetools and urllib2? This is the last report of the 'make test' command and there should be a few lines before that stating each test one by one and printing problems has they appear, and sometime pointing at a possible source for the specific problem. Have you got such a report for test_urllib2 ? > What is meant by pointing to this folder thus (as the installation > instructions instruct): > ./configure --prefix=/usr/python The autotools (configure/make/make install) default installation directory is /usr/local by using the prefix option, you are indicating that you want to install all the python files in /usr/python when you will execute the command 'make install' (instead of /usr/local). I don't know which installation instructions you are following, but FWIK this is not a standard place for python to be installed (although it is recommended in the README for the AtheOS platform ...). > BTW, the modpython site is down! It was up when I sent my first mail, and it is up as I send this one. http://www.modpython.org/ > TIA, > beno > As I stated before I don't have any freebsd box to play with ... HTH Regards Avell From rogue_pedro at yahoo.com Mon Aug 14 16:47:35 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 14 Aug 2006 13:47:35 -0700 Subject: Memory problem In-Reply-To: <mailman.9325.1155587201.27775.python-list@python.org> References: <mailman.9320.1155580347.27775.python-list@python.org> <85mdnb4jzcpTRH3ZnZ2dnUVZ_t6dnZ2d@comcast.com> <mailman.9325.1155587201.27775.python-list@python.org> Message-ID: <1155588455.120237.246600@75g2000cwc.googlegroups.com> Yi Xing wrote: > On a related question: how do I initialize a list or an array with a > pre-specified number of elements, something like > int p[100] in C? I can do append() for 100 times but this looks silly... > > Thanks. > > Yi Xing You seldom need to do that in python, but it's easy enough: new_list = [0 for notused in xrange(100)] or if you already have a list: my_list.extend(0 for notused in xrange(100)) HTH, ~Simon From crowell at mit.edu Sun Aug 6 22:04:00 2006 From: crowell at mit.edu (crowell at mit.edu) Date: 6 Aug 2006 19:04:00 -0700 Subject: Nice unicode -> ascii translation? Message-ID: <1154916240.860577.35860@p79g2000cwp.googlegroups.com> I'm using the ID3 tag of an mp3 file to query musicbrainz to get their sort-name for the artist. A simple example is "The Beatles" -> MusicBrainz -> "Beatles, The". I then want to rename the mp3 file using this information. However, I would like the filename to contain only ascii characters, while musicbrainz gives unicode back. So far, I've got something like: >>> artist = u'B\xe9la Fleck' >>> artist.encode('ascii', 'ignore') 'Bla Fleck' However, I'd like to see the more sensible "Bela Fleck" instead of dropping '\xe9' entirely. I believe this sort of translation can be done using: >>> artist.translate(XXXX) The trick is finding the right XXXX. Has someone attempted this before, or am I stuck writing my own solution? From duncan.booth at invalid.invalid Tue Aug 29 08:50:49 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 29 Aug 2006 12:50:49 GMT Subject: Extending the dict class References: <1156852916.254032.172390@b28g2000cwb.googlegroups.com> <44f4313e$0$26985$626a54ce@news.free.fr> <1156854958.228815.107090@m73g2000cwd.googlegroups.com> Message-ID: <Xns982E8CDD96042duncanbooth@127.0.0.1> chosechu wrote: > SOAPpy cannot know in advance the argument names since > they are server-dependent and SOAPpy is generic, so retrieving > named arguments with **k seems like the sensible thing to do. > Unfortunately this gets converted to a dict so looses all ordering > when being received. Extending the base dict class to support ordering > was one possible idea. If the order of the argument names matters, then it seems to me that should be handled by the SOAP library, not pushed onto the end user whoch should just be calling the function with the named arguments in the most convenient order. Shouldn't SOAPpy be able to get this information out of the WSDL? From rosedb0 at gmail.com Tue Aug 15 19:23:10 2006 From: rosedb0 at gmail.com (hiaips) Date: 15 Aug 2006 16:23:10 -0700 Subject: MySQLdb installation error In-Reply-To: <mailman.9393.1155683139.27775.python-list@python.org> References: <mailman.9393.1155683139.27775.python-list@python.org> Message-ID: <1155684189.787556.322970@p79g2000cwp.googlegroups.com> Yi Xing wrote: > Hi, > > I met the following error when I tried to install MySQLdb. I had no > problem installing numarray, Numeric, Rpy, etc. Does anyone know > what's the problem? Thanks! > > running install > running build > running build_py > creating build > creating build/lib.darwin-7.9.0-Power_Macintosh-2.4 > copying _mysql_exceptions.py -> > build/lib.darwin-7.9.0-Power_Macintosh-2.4 > creating build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb > copying MySQLdb/__init__.py -> > build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb > copying MySQLdb/converters.py -> > build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb > copying MySQLdb/connections.py -> > build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb > copying MySQLdb/cursors.py -> > build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb > copying MySQLdb/release.py -> > build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb > copying MySQLdb/times.py -> > build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb > creating build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb/constants > copying MySQLdb/constants/__init__.py -> > build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb/constants > copying MySQLdb/constants/CR.py -> > build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb/constants > copying MySQLdb/constants/FIELD_TYPE.py -> > build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb/constants > copying MySQLdb/constants/ER.py -> > build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb/constants > copying MySQLdb/constants/FLAG.py -> > build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb/constants > copying MySQLdb/constants/REFRESH.py -> > build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb/constants > copying MySQLdb/constants/CLIENT.py -> > build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb/constants > running build_ext > building '_mysql' extension > creating build/temp.darwin-7.9.0-Power_Macintosh-2.4 > gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp > -mno-fused-madd -fno-common -dynamic -DNDEBUG -g -O3 -Wall > -Wstrict-prototypes -I/usr/include/mysql > -I/Library/Frameworks/Python.framework/Versions/2.4/include/python2.4 > -c _mysql.c -o build/temp.darwin-7.9.0-Power_Macintosh-2.4/_mysql.o > -fno-omit-frame-pointer -arch i386 -arch ppc -pipe > -Dversion_info="(1,2,1,'final',2)" -D__version__="1.2.1_p2" > gcc: cannot read specs file for arch `i386' > error: command 'gcc' failed with exit status 1 What version of OSX are you running? From paul.johnston at manchester.ac.uk Fri Aug 25 03:19:49 2006 From: paul.johnston at manchester.ac.uk (Paul Johnston) Date: Fri, 25 Aug 2006 08:19:49 +0100 Subject: Newbie question about numpy References: <e4hre29hpv4ef1spfbqsu2hq0ee4apgdpv@4ax.com> <evnre2pnag425vese4qiculn80lhfu3rag@4ax.com> Message-ID: <5p8te2tf2fit1c0lpcrvvjt8ovv9t4j6je@4ax.com> On Thu, 24 Aug 2006 17:23:49 GMT, Dennis Lee Bieber <wlfraed at ix.netcom.com> wrote: >On Thu, 24 Aug 2006 16:38:45 +0100, Paul Johnston ><paul.johnston at manchester.ac.uk> declaimed the following in >comp.lang.python: > >> I know its a long time since my degree but that's not matrix >> multiplication is it ? > > Define "matrix multiplication"... > > What you see appears to be multiplication of corresponding elements. > > Were you expecting a dot product, or a cross product, or something >else? > That as explained in http://people.hofstra.edu/faculty/stefan_Waner/RealWorld/tutorialsf1/frames3_2.html As I say its been a long time :-) Thanks to everyone for the help. Paul From deets at nospam.web.de Mon Aug 28 11:49:41 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Aug 2006 17:49:41 +0200 Subject: Truly platform-independent DB access in Python? References: <1156748466.739709.117850@h48g2000cwc.googlegroups.com> <mailman.9974.1156775518.27775.python-list@python.org> <1156779665.977489.300090@74g2000cwt.googlegroups.com> Message-ID: <4lghklF1pfufU1@uni-berlin.de> > > Yes, you excactly got my point. The thing is that I can't rely on > Python 2.5 to be installed soon. > So the only solution for me at this moment is to use jython and from > there use Java JDBC API (sorry :-) But it would be great if the Python > DB API compliant-modules would become parts of core python quickly. > Python DB API itself is a great thing. They won't be. The reason that sqlite is is because it is self-contained. But your average DB itself you need to install using a platform-specific build. And building the the extensions even requires proprietary libraries installed (think of oracle) - so without having installed a dozen or more DBs, no one could build python! So - no chance that this will ever happen. The only thing you could do is to try and convince the DB-vendors to provide pure python DB drivers - as they do it for java. Diez From cliff at develix.com Thu Aug 24 14:07:48 2006 From: cliff at develix.com (Cliff Wells) Date: Thu, 24 Aug 2006 11:07:48 -0700 Subject: What do you want in a new web framework? In-Reply-To: <1156418930.810044.29440@75g2000cwc.googlegroups.com> References: <1156100331.329889.216340@p79g2000cwp.googlegroups.com> <pan.2006.08.20.19.48.34.996227@gmx.net> <1156156636.515678.118210@75g2000cwc.googlegroups.com> <4jele2pe011di99c5dnq4olclglrkieggc@4ax.com> <mailman.9667.1156282843.27775.python-list@python.org> <1156325280.062278.244990@m79g2000cwm.googlegroups.com> <mailman.9741.1156369630.27775.python-list@python.org> <s09qe2l6j51j47cqhs2c3dgukhrf5nsfbh@4ax.com> <mailman.9764.1156397772.27775.python-list@python.org> <1156418930.810044.29440@75g2000cwc.googlegroups.com> Message-ID: <1156442868.13191.112.camel@devilbox> On Thu, 2006-08-24 at 04:28 -0700, Paul Boddie wrote: > Cliff Wells wrote: > > On Thu, 2006-08-24 at 04:04 +0000, Tim Roberts wrote: > > > Cliff Wells <cliff at develix.com> wrote: > > > > > > > >But there are interesting things in Ruby (and Ruby 2 should take care of > > > >lots of warts Ruby 1.8 has) that Python could learn from. All-in-all, > > > >Ruby is mostly as good as Python in most ways and better than Python in > > > >a couple key ways. > > The big difference between Ruby and Python is the lifecycle phase that > the languages/systems are in: Ruby arguably has room for a lot of basic > improvements in the architecture of the virtual machine and presumably > has a list of "must add" features that cover gaping holes with respect > to certain audiences [1], whereas Python has been around for ages and > has covered most of the critical gaps in the feature list (although we > can always suggest things which bother our own part of the community). > Whereas the Ruby people merely have to agree on how critical their > missing features are and to move in one widely agreed direction, the > Python people face a tougher choice as to what should be done next; > strategies include a tidying-up exercise to make the language more > coherent, a complete reimplementation, deep modifications to the > runtime, the introduction of radical new semantics. All true, but there's a more fundamental difference that's going to show more as a larger number of people become used to Ruby's semantics: any Ruby statement can be used as an expression. This is firmly from the Lisp family of languages whereas Python's statement-based syntax is firmly in the Fortran branch. With the exception of Lisp itself, no language has seen the popularity of this style of programming until Ruby. I think this represents a real danger to Python's mindshare. Once people have tried expression-based languages, they tend to be loathe to return to statement-based languages. To date, expression-based languages have been mostly of interest in academia or to a small group of elitists and so weren't practical to use for day-to-day work. Ruby has changed that and I think we're just starting to see the fallout. Rails may have brought them there, but Ruby itself is keeping them there. My fear is that the expression-based family of languages is the Homo Sapiens to our statement-based Neanderthals and we can either evolve or disappear. Python is unique in many ways and I'd hate to see those unique features lost because we're stuck on the wrong evolutionary branch. > The fewer obvious issues that a language has, the less energy there is > in the community to deal with those issues thoroughly, I think. I guess > the Perl community chose a bold new direction in line with the > observation that a big vision can inspire much more in people than lots > of incremental changes to an existing vision, but the energy required > to follow through on such a vision can be immense. In addition to all > this, a large existing community is more likely to want larger benefits > for smaller levels of disruption because of the amount of existing > code. Thus, the available energy for change is less in a mature project > than in a growing project because people have to constantly monitor the > breakage in their existing investments in the language. > > > > ...but you can't READ Ruby code. > > > > Yeah, that's one of the big reasons I haven't seriously considered > > trying it. It's expressive, got interesting features... and appears > > unreadable to me. I'm usually pretty good at deciphering most > > languages, even if I haven't used them before, but Ruby is one of the > > exceptions. > > My feeling is that I'd rather learn more about Lisp or Scheme than Ruby > - the benefits are greater and for me Lisp and Scheme increasingly have > the edge on readability. Perhaps I'm just not "tuned in" to > Smalltalk-style syntaxes. I'm in the same camp. As I mentioned earlier, it's been mostly inertia and the wealth of the Python community that's kept me with Python. That's why I was so excited when I found Logix. Lisp-like features with Python's syntax that generates Python bytecode. Actually Logix is perhaps too far the other direction as it supports Lisp-style macros and the creation of arbitrary syntax, which perhaps would justify some of the fears people have of Lisp-like languages. The part I found appealing was having Python-like syntax in an expression-based language, with the capability to integrate completely with Python libraries. Absolutely the best of both worlds. I've been trying to contact the author of Logix to find out what the status of the project is or if he's abandoned it. If you haven't looked at it you really ought to. http://livelogix.net/logix/ > > This brings us back around to the web framework debates. For many > > people Ruby "fits" their brains and for others Python does. I think > > frameworks are similar. I tried Django and while I thought it was a > > great product, it simply didn't "fit" how I think about that problem > > domain. > > I thought that the most interesting thing about Django was the URL > mapping strategy it employs, although you have to be fond of regular > expressions to really appreciate it, I think. Django's dispatch mechanism is flexible, but what I disliked about it was the extra steps required upfront just to get a single page online. I prefered CherryPy's object-publishing scheme for its sheer simplicity. I think that simple mechanism, coupled with Routes for more complicated stuff is the sweet spot in this area. > The template and > persistence mechanisms used have the principal advantage of just being > there in the same package when compared with other solutions, and I > don't think they'd have many fans if they were just some random > projects available from the Python Package Index. Perhaps, but I find the ORM and templates from Django inferior to other projects, namely SQLAlchemy and Stan. These two aspects of frameworks seem to be the ones that generate the most passionate debate, probably because they touch the spot the framework user spends most of his time working in. The bottom line is that if you don't like the ORM or the template engine, you probably won't like the framework, even though they are logically separate entities. Also, I think TurboGears has demonstrated that it's quite possible to paste together a lot of subprojects into a single uberproject and have it succeed. Not only has TurboGears succeeded, it's increased interest in the various subprojects that it's composed of. One project I'm keeping my eye on is Clever Harold which is taking the most loosely-coupled approach to date, using WSGI to paste together all the layers so you could conceivably replace every component in the framework. I haven't tried it yet, but it sounds interesting. http://www.cleverharold.org/ > > TurboGears on the other hand did, and really, it helped clarify > > a few things I had vague notions about. I think we'll do better not > > trying to shoehorn people into one or the other. > > The goal is to provide appropriate solutions for particular problem > cases, especially common cases like database-backed Web sites, rather > than choosing something which only does a particular flavour of > database-backed site and then claiming that it's a silver bullet. > I've written a number of Web applications for my own use, and many such > applications either don't use a relational database or use it in a way > that is completely orthogonal to some relatively simple > object-relational scheme. Some of these applications are admittedly > simple, but having to create various tables in relational databases as > an offering to some framework deity is pure unnecessary overhead that > should suggest, at least to the more objective among us, that any > solution requiring such baggage is perhaps not always the most optimal. I don't think any of the frameworks really require a database. There was some discussion of this exact topic on the TurboGears list a while back, but I don't recall the outcome, but yes, I think there's a place for all sorts of web frameworks, ranging from simple to Zope ;-) Regards, Cliff -- From rschroev_nospam_ml at fastmail.fm Fri Aug 4 10:06:10 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 04 Aug 2006 14:06:10 GMT Subject: Problem reading/writing files In-Reply-To: <1154692797.329732.73290@75g2000cwc.googlegroups.com> References: <1154661460.803694.241220@s13g2000cwa.googlegroups.com> <1154663988.871166.112930@s13g2000cwa.googlegroups.com> <1154692797.329732.73290@75g2000cwc.googlegroups.com> Message-ID: <mvIAg.2906$I92.177295@phobos.telenet-ops.be> smeenehan at hmc.edu schreef: > f = open('evil2.gfx','rb') > i1 = open('img1.jpg','wb') > i2 = open('img2.png','wb') > i3 = open('img3.gif','wb') > i4 = open('img4.png','wb') > i5 = open('img5.jpg','wb') > > > for i in range(0,67575,5): > i1.write(f.read(1)) > i2.write(f.read(1)) > i3.write(f.read(1)) > i4.write(f.read(1)) > i5.write(f.read(1)) > > f.close() > i1.close() > i2.close() > i3.close() > i4.close() > i5.close() > > I first noticed the problem by looking at the original file and > img1.jpg side by side with a hex editor. Since img1 contains every 5th > byte from the original file, I was able to find many places where \x00 > should have been copied to img1.jpg, but instead a \x20 was copied. > What caused me to suspect the read method was the following: > >>>> f = open('evil2.gfx','rb') >>>> s = f.read() > print repr(s[19:22]) > '\xe0 \r' > > Now, I have checked many times with a hex editor that the 21st byte of > the file is \x00, yet above you can see that it is reading it as a > space. I've repeated this with several different nulls in the original > file and the result is always the same. > > As I said in my original post, when I try simply writing a null to my > own file and reading it (as someone mentioned earlier) everything is > fine. It seems to be only this file which is causing issue. Very weird. I tried your code on my system (Python 2.4, Windows XP) (but using a copy of evil2.gfx I still had on my system), with no problems. Are you sure that you don't have 2 copies of that file around, and that your program is using the wrong one? Or is it possible that some module imported with 'from blabla import *' clashes with the builtin open()? -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From gmt at sdf-eu.org Fri Aug 18 18:00:57 2006 From: gmt at sdf-eu.org (Max Yuzhakov) Date: Fri, 18 Aug 2006 22:00:57 +0000 (UTC) Subject: It is __del__ calling twice for some instances? References: <ebvnod$mp7$1@pandora.alkar.net> <Xns9821CFF0D1C70duncanbooth@127.0.0.1> <ec2qif$12qo$1@pandora.alkar.net> <Xns98235A0264C70duncanbooth@127.0.0.1> <Xns982364A2FDD33duncanbooth@127.0.0.1> Message-ID: <ec5dap$2tu7$1@pandora.alkar.net> Duncan Booth wrote: DB> I figured out what is going on in the code to deallocate an old-style class DB> instance: DB> DB> The reference count is temporarily incremented. DB> DB> If the class has a __del__ method then a descriptor is created for the DB> method and called. When the call returns, the descriptor is released. DB> DB> Then the object itself is released using special code to avoid a recursive DB> call to the deallocator. DB> DB> However, if the trashcan mechanism is invoked by the attempt to release the DB> descriptor, it actually queues the descriptor in the trashcan. Since the DB> descriptor contains a reference to the object it has effectively DB> resurrected it. This means the special code to avoid the recursive call DB> simply decrements the reference count but does not release anything (the DB> object has been resurrected by the descriptor). When the descriptor is DB> later released the __del__ method is triggered a second time. Thank You for so detailed explanation! -- GMT More Then ... From rogue_pedro at yahoo.com Wed Aug 23 16:56:52 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 23 Aug 2006 13:56:52 -0700 Subject: setting a breakpoint in the module In-Reply-To: <mailman.9734.1156362020.27775.python-list@python.org> References: <mailman.9734.1156362020.27775.python-list@python.org> Message-ID: <1156366612.827337.256610@74g2000cwt.googlegroups.com> Jason Jiang wrote: > Hi, > > I have two modules: a.py and b.py. In a.py, I have a function called > aFunc(). I'm calling aFunc() from b.py (of course I import module a first). > The question is how to directly set a breakpoint in aFunc(). > > The way I'm doing now is to set a breakpoint in b.py at the line to call > aFunc(), 'c' to it, then 's' to step in, then set the breakpoint inside > aFunc() by 'b lineNumber'. It's too cumbersome. > > Thanks. > Jason What debugger are you using? From bignose+hates-spam at benfinney.id.au Thu Aug 31 09:52:31 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 31 Aug 2006 23:52:31 +1000 Subject: Coding style and else statements References: <44f355d6$0$8812$88260bb3@free.teranews.com> <1156898310.795476.187030@i3g2000cwc.googlegroups.com> <mailman.10091.1156921386.27775.python-list@python.org> <1156965902.621615.314160@h48g2000cwc.googlegroups.com> <mailman.10141.1156980023.27775.python-list@python.org> <d5ahmf77.fsf@wgmail2.gatwick.eur.slb.com> Message-ID: <87k64phv1c.fsf@benfinney.id.au> Pete Forman <pete.forman at westerngeco.com> writes: > Ben Finney <bignose+hates-spam at benfinney.id.au> writes: > > > Why not ensure that there is one return point from the function, > > so the reader doesn't have to remind themselves to look for hidden > > return points? > > There will always be more potential return points in languages that > support exceptions. I was specifically referring to 'return' points, i.e. points in the function where a 'return' statement appears. In the example to which I responded, the function had multiple 'return' statements, and an 'assert' to aid in finding out when none of the return statements was hit. I'm making the point that if that effort is being taken anyway, it's more readable to allow the reader to see only *one* explicit return at the end, and not write any more in the first place. -- \ "Ours is a world where people don't know what they want and are | `\ willing to go through hell to get it." -- Donald Robert Perry | _o__) Marquis | Ben Finney From rbonvall at cern.ch Wed Aug 23 12:26:44 2006 From: rbonvall at cern.ch (Roberto Bonvallet) Date: 23 Aug 2006 16:26:44 GMT Subject: find, replace and save string in ascii file References: <1156337317.644501.120480@m73g2000cwd.googlegroups.com> Message-ID: <echvk4$80s$1@sunnews.cern.ch> peter wrote: > Example (one block in ascii file): > $------------------------ > NAME='ALFA' > CODE='x' > $------------------------ > > There are many similar blocks in the file with different NAMEs and > different CODEs. What I'm looking for is a script that searchs through > whole file and finds all strings with name ALFA and based on what CODE > is after each ALFA (can be x, y or z) the ALFA name is replaced by > BETAx,BETAy or BETAz and so changed file saves. name = "myfile" lines = file(name).readlines() for i, line in enumerate(lines): if "ALFA" in line: code = lines[i + 1].split("=")[1].strip("' \n") lines[i] = line.replace("ALFA", "BETA%s" % code) file(name).writelines(lines) -- Roberto Bonvallet From alf at merlin.fayauffre.org Fri Aug 4 04:20:35 2006 From: alf at merlin.fayauffre.org (Alexandre Fayolle) Date: Fri, 4 Aug 2006 08:20:35 +0000 (UTC) Subject: Are there any AOP project in python community? References: <1154562487.677431.274440@i3g2000cwc.googlegroups.com> Message-ID: <slrned60qi.789.alf@merlin.fayauffre.org> Le 02-08-2006, steve <hxianping at gmail.com> nous disait: > I mean Aspect-Oriented Programming. > If any please give me some of links. > Thanks a lot. You may want to look at http://www.logilab.org/projects/aspects -- Alexandre Fayolle LOGILAB, Paris (France) Formations Python, Zope, Plone, Debian: http://www.logilab.fr/formations D?veloppement logiciel sur mesure: http://www.logilab.fr/services Python et calcul scientifique: http://www.logilab.fr/science From gene.tani at gmail.com Wed Aug 9 15:15:20 2006 From: gene.tani at gmail.com (gene tani) Date: 9 Aug 2006 12:15:20 -0700 Subject: Eval (was Re: Question about using python as a scripting language) In-Reply-To: <mailman.9159.1155141228.27775.python-list@python.org> References: <73BFFFC6-760D-4794-9B5C-AA749287B78A@carnegielearning.com> <20060809150432.GA15121@kateandchris.net> <B8AFCCDC-64A0-4674-B335-DAAD7E8DEDE3@carnegielearning.com> <mailman.9159.1155141228.27775.python-list@python.org> Message-ID: <1155150919.947507.3830@75g2000cwc.googlegroups.com> Chris Lambacher wrote: > On Wed, Aug 09, 2006 at 11:51:19AM -0400, Brendon Towle wrote: > I don't disagree with you. The problem is that the obvious way to do it > (eval) is a big security hole. In this case you are trusting that no one > inserts themselves between you and the website providing you with code to > EXECUTE. I have heard of people attempting to use the parser provided with > python and examining the AST to do this, but I think that approach is even > more complicated. here's some things about sandboxing python: http://svn.python.org/view/python/branches/bcannon-sandboxing/securing_python.txt?rev=50717&view=log http://sayspy.blogspot.com/2006/07/still-working-on-security.html From sile_brennan at hotmail.com Mon Aug 28 09:31:35 2006 From: sile_brennan at hotmail.com (Sile) Date: 28 Aug 2006 06:31:35 -0700 Subject: f2py on windows XP - "Unknown Switch"?? References: <1156177095.867153.327380@h48g2000cwc.googlegroups.com> <1156629368.463878.138620@h48g2000cwc.googlegroups.com> <1156754647.169794.272430@m79g2000cwm.googlegroups.com> <44F2B70A.3080209@lexicon.net> <1156765622.807252.235140@i3g2000cwc.googlegroups.com> <44F2E836.8000801@lexicon.net> Message-ID: <1156771895.583406.90510@m79g2000cwm.googlegroups.com> Thanks John, Your help is very much appreciated - my f2py finally recognises my fortran compiler - I'm very relieved! > > That won't match the guff your f95 puts out. The "!)" appears *after* > the version number. See below. > > |>>> import re > |>>> guff = 'G95 (GCC 4.0.3 (g95 0.90!) Aug 22 2006) etc etc' > |>>> vp1 = r'G95.*\(GCC 4.0.3 \(g95!\) (?P<version>.*)\).*' > |>>> vp2 = r'G95.*\(GCC 4.0.3 \(g95 (?P<version>.*)!\).*' I changed my g95 file so that version_pattern was correct. > > > THE LINE ABOVE WAS ORIGINALLY: > > version_pattern = r'G95.*\(experimental \(g95!\) > > (?P<version.*)\).*' > > No it wasn't. It would have had a ">" after "version" :-) oops! Many thanks again, Sile From fredrik at pythonware.com Fri Aug 25 09:03:24 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Aug 2006 15:03:24 +0200 Subject: performance of dictionary lookup vs. object attributes References: <mailman.9853.1156495094.27775.python-list@python.org> <ecmrhf$do8$01$1@news.t-online.com> Message-ID: <ecmses$o9l$1@sea.gmane.org> Peter Otten wrote: > $ python -m timeit -s'class A(object): pass' -s 'a = A(); a.alpha = 42' > 'a.__getattribute__("alpha")' > 1000000 loops, best of 3: 0.674 usec per loop also: timeit -s "class A(object): pass" -s "a = A(); a.alpha = 42" "a.__getattribute__('alpha')" 1000000 loops, best of 3: 0.592 usec per loop timeit -s "class A(object): pass" -s "a = A(); a.alpha = 42" "getattr(a, 'alpha')" 1000000 loops, best of 3: 0.403 usec per loop which is better, but nowhere close to timeit -s"class A(object): pass" -s "a = A(); a.alpha = 42" "a.alpha" 10000000 loops, best of 3: 0.158 usec per loop timeit -s"class A(object): pass" -s "a = A(); a.alpha = 42; d=vars(a)" "d['alpha']" 10000000 loops, best of 3: 0.126 usec per loop on the other hand, when we're talking about sub-microsecond operations, you'll see "massive slowdowns" as soon as you're actually trying to do something with the data you just fetched... </F> From Tim.Gallagher at gd-ais.com Tue Aug 22 13:44:55 2006 From: Tim.Gallagher at gd-ais.com (Gallagher, Tim (NE)) Date: Tue, 22 Aug 2006 13:44:55 -0400 Subject: Unicode Error Message-ID: <794CB73454A59D488ED061055AA282073CBBE9@miaa01-mail01.ad.gd-ais.com> Hey all I am learning Python and having a fun time doing so. I have a question for y'all, it has to do with active directory. I want to get the last login for a computer from Active Directory. I am using the active_directory module and here is my code. [START] import active_directory computer = active_directory.root() for cpu in computer.search ("cn='Computer_Name'"): print cpu.samAccountName ?--- Works find print cpu.operatingSystem ?--- Works find print cpu.lastLogon ?--- Getting Error [END] I get an error that I am not sure what to do with, the error is TypeError: coercing to Unicode: need string or buffer, instance found in my line Do I have to change the output to meet Unicode formation? Thanks, -T -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060822/590fe259/attachment.html> From arenium at gmail.com Tue Aug 8 18:42:51 2006 From: arenium at gmail.com (Kevin M) Date: 8 Aug 2006 15:42:51 -0700 Subject: Class data being zapped by method References: <1155065906.910642.77320@75g2000cwc.googlegroups.com> <mailman.9111.1155066643.27775.python-list@python.org> Message-ID: <1155076971.519157.92540@i42g2000cwa.googlegroups.com> Figures. I'll try to complicate it sufficiently ;) [edit] I was going to try to sum up what goes on, but I realized that I was retyping what I already programmed in an effort to better illustrate exactly what I'm doing. Pastebin it is. Don't fear, it's only around 200 lines total. Class file -- http://pastebin.4programmers.net/640 Main file -- http://pastebin.4programmers.net/639 PLEASE don't worry about any file parsing stuff. That's all working well. The problem is that I'm getting IndexError exceptions in my _a_count and _b_count methods when they're called from analyze(). I added some code to increase verbosity, and it turns that the count methods within the Test class are operating on EMPTY lists ( [] ), so naturally they can't index anything. This is the core of the problem, especially considering that line 98 in main.py works as expected. Once again, thank you VERY VERY much for addressing this situation, everyone Gary Herron wrote: > arenium at gmail.com wrote: > > Hi, > > > > I'll cut to the chase. > > > > I have a class named Foo(). I create an instance of this class named > > bar, and I set bar.data to a large list of tuples. > > > > Within Foo() there is a method which operates on self.data. I need to > > call this method after I set self.data from the "outside" (bar.data), > > which isn't a problem. However, I have found through simple debugging > > procedures that while bar.data exists fine before the said method is > > called, self.data within the class method is EMPTY. In my class > > constructor I do declare self.data to be an empty list ([]), but > > shouldn't self.data contain the populated list? > > > > Basically... > > > > -------------------------------------------------------------------------- > > class Foo(): > > __init__(self): > > self.data = [] > > a_count(self): > > .... > > print self.data > > .... > > > > bar = Foo() > > bar.data = [(-74.0015, 1), (123.451, 18), ...] > > print bar.data # Get what I expect > > bar.a_count() # [] > > -------------------------------------------------------------------------- > > > Well, ... you have not told us the whole story here. This code works as > expected. > > >>> class Foo(): > ... def __init__(self): > ... self.data = [] > ... def a_count(self): > ... print self.data > ... > >>> bar = Foo() > >>> bar.data = [(-74.0015, 1), (123.451, 18)] > >>> print bar.data > [(-74.001499999999993, 1), (123.45099999999999, 18)] > >>> bar.a_count() > [(-74.001499999999993, 1), (123.45099999999999, 18)] > >>> > > > You effort to reduce your real code to a simple demonstration of the > problem is appreciated, but I don't think it worked in this case. > > Want to try again? > > > Gary Herron From nospan at nothanks.org Tue Aug 1 22:37:56 2006 From: nospan at nothanks.org (Conrad) Date: Wed, 02 Aug 2006 02:37:56 GMT Subject: wxPython - Event processing order arbitrary across platforms? Message-ID: <pan.2006.08.02.02.38.09.148905@nothanks.org> Greetings, For user actions on a wxWidget that trigger multiple events for that wxWidget, is the order those events are processed in undefined, and therefore arbitrary from one platform (ie Windows) to the next (ie Linux)? Specifically, I have a convience aggregate class that combines a wxStaticText with a wxComboBox, as I often need those two at the same time. The aggregate catches events from the wxComboBox and stores them in it's own class. The calling parent then catches the event, uses the stored values and set's any variables and does any processing it needs. But I had a slight bug, which I didn't catch until a recent upgrade. Suddenly, this technique still worked under windows - and didn't under Linux. The bug? the wxComboBox and the parents were catching two different events - oops. (I was catching the EVT_COMBOBOX in the child widget - and EVT_TEXT in the parent methods - thanks to cut'n'paste an error I managed to propagate through most of my code. Duh) The reason the Windows version works, is because apparently the EVT_COMBOBOX is processed first. By the time the parent catches the EVT_TEXT evt, the aggregate widget has already caught the EVT_COMBOBOX and set its local values. Under Linux, however, it appears that the EVT_TEXT is processed first - before the aggregate catches the EVT_COMBOBOX and has had a chance to set it's values - boom. Hence the above question. I know that the event propagation for any single event is pretty well defined, crawling up through the superclasses, and for wxCommand- derived events, up through the container heirarchy. But I really haven't found any docs that guarantee which events are processed first when a user action fires multiple events. My bug is fixed - but curiosity and coding go hand in hand. Cheers, Conrad From fredrik at pythonware.com Wed Aug 23 06:03:35 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Aug 2006 12:03:35 +0200 Subject: Finding the type of indexing supported by an object? References: <slrneeo9ac.p1u.dpeschel@eskimo.com> Message-ID: <ech95n$a44$1@sea.gmane.org> Derek Peschel wrote: > I've thought about looking for keys(), looking for the special method names > that allow you to override indexing behavior, and looking at the class or > type of the object. I could be wrong, but I don't think any of those > strategies will work with all arguments. the behaviour of obj[arg] is determined by the __getitem__ method, and that method can do whatever it wants. </F> From timr at probo.com Sat Aug 12 00:50:40 2006 From: timr at probo.com (Tim Roberts) Date: Sat, 12 Aug 2006 04:50:40 GMT Subject: Regd:Video Converter Programming References: <1155092497.011057.219180@m79g2000cwm.googlegroups.com> <1155098914.953285.48410@i42g2000cwa.googlegroups.com> <12djo0melsc5icb@corp.supernews.com> <1155164376.036405.231040@n13g2000cwa.googlegroups.com> <1155187700.869574.18460@75g2000cwc.googlegroups.com> Message-ID: <v9nqd2timjn8jdkaljbg5ep83unibv4idv@4ax.com> "Ch3ru5" <muppadivya at gmail.com> wrote: > > Thanks all for replies . I am sorry for a confusion of the question . >But what i wanted to know is in general in any programming language , >how you go about writing a video converter . The problem is that converting between video formats requires LOTS of manipulation of bitfields: pull 3 bits from here, pull 6 bits from here, insert 9 bits there. That kind of manipulation is easier in some languages than in others. For example, it makes sense in C and C++. It can be done in Python, although not as efficiently. It would be difficult in PHP. >The basic flow of code . that's it . I will look into the resources in >a particular language of my choice later . The basic flow depends on what formats you are converting between. To to MPEG-to-AVI, for instance, you would normally go through the whole MPEG decompression process to get to a series of bitmaps, then go through the whole AVI compression process to get a movie. If you are on Windows, you almost certainly want to use DirectShow to do this job. There is a DirectShow interface for Python. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From steve at REMOVEME.cybersource.com.au Thu Aug 10 20:21:07 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Fri, 11 Aug 2006 10:21:07 +1000 Subject: hide python code ! References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155253821.570487.165400@b28g2000cwb.googlegroups.com> <1155254631.617208.299550@m73g2000cwd.googlegroups.com> Message-ID: <pan.2006.08.11.00.21.06.658272@REMOVEME.cybersource.com.au> On Thu, 10 Aug 2006 17:03:51 -0700, Bayazee wrote: > hi > in compiled languages when we compile a code to an executable file it > convert to a machine code so now we cant access to source ... There are disassemblers for machine code. If somebody really wants to see how your code works, they can do it. > but in python we easily open the program executable(ascii) file and read > source .... Yes. That is by design. > i meen than any way to protect my code or convert it to executable witch > can not be decompiled (python code).... In your first email, you wrote: "First Iranian Open Source Community : www.python.ir" Hiding source code is incompatible with Open Source software. You can hide code, or be Open Source, but not both. What makes you think that your code is so special that it is worth stealing? Do you have incredible secret algorithms that nobody has ever seen before? Or are you just so ashamed of it that you don't want people to see it? Or maybe you've copied other people's code, and you don't want them to see that? What are you hiding? Whatever your reasons for hiding the source code, there are things which you can do to obfuscate Python code which will make it difficult for people to get to the source code. Google for "python obfuscate" for links. But I'm guessing that, if you hide your source code, most people will wonder what you are hiding and avoid your program. If you really want something which compiles to machine code, then Python is not the language for you. Use another language. -- Steven D'Aprano From donn at u.washington.edu Mon Aug 7 11:51:36 2006 From: donn at u.washington.edu (Donn Cave) Date: Mon, 07 Aug 2006 08:51:36 -0700 Subject: Python open a named pipe == hanging? References: <op.tdp5i6tsh12lye@cadet.mshome.net> <donn-37DEFC.08500404082006@gnus01.u.washington.edu> <1hjk7cf.iswobo130hqzxN%aleax@mac.com> Message-ID: <donn-F34134.08513607082006@gnus01.u.washington.edu> In article <1hjk7cf.iswobo130hqzxN%aleax at mac.com>, aleax at mac.com (Alex Martelli) wrote: > Donn Cave <donn at u.washington.edu> wrote: > > > In article <op.tdp5i6tsh12lye at cadet.mshome.net>, > > Rochester <rochester1976 at gmail.com> wrote: > > > > > I just found out that the general open file mechanism doesn't work > > > for named pipes (fifo). Say I wrote something like this and it > > > simply hangs python: > > > > > > #!/usr/bin/python > > > > > > import os > > > > > > os.mkfifo('my fifo') > > > > > > open('my fifo', 'r+').write('some strings.') > > > x = os.popen('cat my fifo').read() > > > > > > print x > > > > I believe your problem is that, by the time you open the > > pipe for read, it has already been closed by its writer. > > Hmmm, no: the problem is, he never opens the pipe for write, because the > open blocks (will not proceed until somebody opens the fifo for reading, > which in turn won't happen here because the open blocks). > > Try: > > a = open('my_fifo', 'w') > b = os.popen('cat my_fifo') > a.write ... > a.close() > c = b.read() > > this STILL doesn't work, since the very first statement blocks. (I've > also removed the 'r+' mode in favor of 'w', since opening a FIFO for > reading AND writing produces undefined behavior, at least in all Unix > versions and variants I'm familiar with). But it does work. I edited that excerpt only to complete missing parts, and ran it on MacOS X and GNU Linux. import os f = '/tmp/r' try: os.unlink(f) except: pass a = open(f, 'w') b = os.popen('cat %s' % f) a.write('chunks\n') a.close() c = b.read() print repr(c) > > it. (You can't read "all" the data, though - since you still > > have the file open, it has no end of file - so you can't > > solve the problem exactly as stated above.) > > Actually, in CPython (1.5.2 to 2.5 included, at least), _IF_ open worked > normally then the file WOULD be closed by the statement > > open('my fifo', 'r+').write('some strings.') Sure, but now we're back to closing the pipe before the reader gets to it. That doesn't work. Donn Cave, donn at u.washington.edu From fredrik at pythonware.com Mon Aug 14 08:14:58 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 14 Aug 2006 14:14:58 +0200 Subject: proxy for xmlrpc calls References: <eblta8$6sv$1@mailhub227.itcs.purdue.edu> Message-ID: <ebppfp$nr7$1@sea.gmane.org> Xavier wrote: > I'm attempting to write a proxy for xmlrpc calls. why not use the one in the standard library? > I want to expand this to do something like; > > >>a=MagicObject() > >>x = a.b.c.d > > Then on the last __getattr__ send a call over xmlrpc. > How do I determine when the last __getattr__ will be? you can't determine that. (and XML-RPC doesn't support attribute access either, so this sounds like a rather pointless exercise) > I thought about getting the source code from the correct frame, but > I don't think thats a good solution. getting the source won't help, unless you're willing to violate Python's execution model. > Any ideas? stick to the standard. </F> From m.sloyko at gmail.com Wed Aug 30 03:15:27 2006 From: m.sloyko at gmail.com (Maxim Sloyko) Date: 30 Aug 2006 00:15:27 -0700 Subject: psycopg2 features Message-ID: <1156922127.882417.137920@i42g2000cwa.googlegroups.com> Hello, clp and all people reading it! Recently I was porting my (small) app from psycopg to psycopg2 (they got me with this "2"). I read, that psycopg2 supports all features of psycopg and plus many more, however, when I started to port, I discovered, that psycopg2 lacks serialized connections and "commit on cursor" completely. Did I miss something or psycopg2 just isn't mature enough yet? BTW, is there any postgresql engine, that can fake nested transactions via savepoints feature? From brown at esteem.com Wed Aug 2 19:02:25 2006 From: brown at esteem.com (Tom Brown) Date: Wed, 2 Aug 2006 16:02:25 -0700 Subject: serial ports, threads and windows Message-ID: <200608021602.25413.brown@esteem.com> Hey people, I've written a python app that r/w eight serial ports to control eight devices using eight threads. This all works very nicely in Linux. I even put a GUI on it using PyQt4. Still works nicely. Then I put the app on on a virtual Windows machine running inside of vmware on the same Linux box. Vmware only lets me have four serial ports so I run the app against four serial ports using four threads. The app did not respond quick enough to data from the serial ports and eventually hung. So, I tried one serial port and the app still did not respond quick enough to the single serial port. It eventually hangs. When the app hung, in each case, it was not hogging the cpu nor reading any data off the serial ports. The task manager didn't show it was doing anything at all. When it runs on Windows, could it be: 1) Just struggling to run inside of VMware? 2) Using threads with Qt on Windows is a problem? 3) Threads in python on Windows is a problem? Any ideas? Thanks, Tom From luismgz at gmail.com Wed Aug 2 01:02:34 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 1 Aug 2006 22:02:34 -0700 Subject: Programming newbie coming from Ruby: a few Python questions In-Reply-To: <mailman.8824.1154472963.27775.python-list@python.org> References: <mailman.8824.1154472963.27775.python-list@python.org> Message-ID: <1154494954.082706.283750@b28g2000cwb.googlegroups.com> Delaney, Timothy (Tim) wrote: > Edmond Dantes wrote: > > > Of course, it's all what you really mean by "clever". To me, being > > "clever" partly means writing code without bugs in the first place, > > so there is nothing that needs debugging!!!!!!!! > > "Clever" in this context generally means using a trick/hack that is > non-obvious (often even after you understand it). "Cleverness" often > leads to difficult-to-understand code, which is contrary to the "python > philosophy". > > There are occasionally times when cleverness is useful, but in those > cases it should always be commented explaining exactly what it is doing, > and why a non-clever solution was not used. Most of the time there's > still a better non-clever way to do it, but the coder is not clever > enough to find it ;) > > Tim Delaney Is this kind of cleverness what is usually known as "magic"? I suspect that this has something to do with it, but not completely sure... Luis From aahz at pythoncraft.com Wed Aug 30 23:01:02 2006 From: aahz at pythoncraft.com (Aahz) Date: 30 Aug 2006 20:01:02 -0700 Subject: How ahead are you guys in the (Python) real world? References: <1156821234.820929.299740@p79g2000cwp.googlegroups.com> <ed4jjl$e6t$1@panix1.panix.com> <vMrJg.484475$Mn5.394204@pd7tw3no> Message-ID: <ed5jde$lu3$1@panix3.panix.com> In article <vMrJg.484475$Mn5.394204 at pd7tw3no>, Neil Schemenauer <nas at arctrix.com> wrote: >Aahz <aahz at pythoncraft.com> wrote: >> >> My company uses 2.2 and 2.3; we hope to drop 2.2 Real Soon Now. > >This has been an interesting thread. There has been some discussion >on python-dev about doing another 2.3 bugfix release. Based on the >number of people still using 2.3, it looks to me like there would be >interest. Yes; the real question is whether there is enough labor available to make it happen. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ I support the RKAB From python at hope.cz Tue Aug 22 02:47:19 2006 From: python at hope.cz (Lad) Date: 21 Aug 2006 23:47:19 -0700 Subject: How to decode a string In-Reply-To: <pan.2006.08.21.17.10.16.104915@gmx.net> References: <1156170296.076521.174180@i3g2000cwc.googlegroups.com> <mailman.9610.1156171864.27775.python-list@python.org> <1156175385.580508.302330@m73g2000cwd.googlegroups.com> <pan.2006.08.21.17.10.16.104915@gmx.net> Message-ID: <1156229239.418473.248090@i3g2000cwc.googlegroups.com> Marc 'BlackJack' Rintsch wrote: > In <1156175385.580508.302330 at m73g2000cwd.googlegroups.com>, Lad wrote: > > > The text is from Mysql table field that uses utf8_czech_ci collation, > > but when I try > > `RealName`.decode('utf8'),where RealName is that field of MySQL > > > > I will get: > > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 3: > > ordinal > > not in range(128) > > > > Can you please suggest the solution? > > Do you get this from converting the value from the database or from trying > to print the unicode string? Can you give us the output of > > print repr(RealName) > > Ciao, Marc 'BlackJack' Rintsch for print repr(RealName) command I will get P?ibylov\xe1 Ludmila where instead of ? should be also a character Thank you for help L. From thattommyhall at gmail.com Fri Aug 18 16:12:12 2006 From: thattommyhall at gmail.com (thattommyhallll@gmail.com) Date: 18 Aug 2006 13:12:12 -0700 Subject: efficient memoize decorator? Message-ID: <1155931932.349283.27700@h48g2000cwc.googlegroups.com> im plugging away at the problems at http://www.mathschallenge.net/index.php?section=project im trying to use them as a motivator to get into advanced topics in python. one thing that Structure And Interpretation Of Computer Programs teaches is that memoisation is good. all of the memoize decorators at the python cookbook seem to make my code slower. is using a decorator a lazy and inefficient way of doing memoization? can anyone point me to where would explain how to do it quickly. or is my function at fault? the code in question is as follows """ from memoize import memoize,memoize2 @memoize def col(n, count): if n == 1: return count elif n % 2 == 0: return col(n/2, count+1) else: return col((3*n+1)/2, count+2) import psyco psyco.full() start = time() maxlength = 0 best = 0 for i in range(1, 1000001): length = col(i,1) if length > maxlength: maxlength = length best = i print maxlength, best end = time() print 'took', end-start From fredrik at pythonware.com Mon Aug 28 05:48:14 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 28 Aug 2006 11:48:14 +0200 Subject: Starting up the server References: <1156757061.162827.301260@h48g2000cwc.googlegroups.com> Message-ID: <ecue4u$610$1@sea.gmane.org> "john Perry" wrote: > how to solve these error > > Traceback (most recent call last): > File "mrsm-start.py", line 2, in <module> > import pkg_resources > ImportError: No module named pkg_resources > > please help me thanks what server? what software are you using? </F> From marcel.vandendungen at gmail.com Mon Aug 14 10:08:24 2006 From: marcel.vandendungen at gmail.com (Marcel) Date: 14 Aug 2006 07:08:24 -0700 Subject: Looking for a text file based wiki system written in Python In-Reply-To: <RpKdneu1J9f6ckDZnZ2dnUVZ_qKdnZ2d@comcast.com> References: <RpKdneu1J9f6ckDZnZ2dnUVZ_qKdnZ2d@comcast.com> Message-ID: <1155564504.693321.117600@i3g2000cwc.googlegroups.com> Jack wrote: > I'd like to set up a wiki system for a project I'm working on. > Since I'm not good at databases, and there's really not much > stuff to put into the wiki, I hope it is text file-based. > I used DokuWiki before, which is very nice but it's written > in PHP. Is there a similar system that's written in Python? > I found pwyky but it's functionality is a bit too simple. A TiddlyWiki with a python backend. http://www.cs.utexas.edu/~joeraii/pytw/ -- Marcel From fredrik at pythonware.com Sun Aug 20 04:58:19 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Aug 2006 10:58:19 +0200 Subject: How to get the ascii code of Chinese characters? In-Reply-To: <1156039938.770189.200070@b28g2000cwb.googlegroups.com> References: <1155986298.643983.157460@i3g2000cwc.googlegroups.com> <1155990488.395220.178810@74g2000cwt.googlegroups.com> <1155999554.486951.303480@i42g2000cwa.googlegroups.com> <1156021926.365938.220900@75g2000cwc.googlegroups.com> <1156039938.770189.200070@b28g2000cwb.googlegroups.com> Message-ID: <ec987b$356$2@sea.gmane.org> many_years_after wrote: > Well, people may input from keyboard. They input some Chinese > characters, then, I want to create a number. The same number will be > created if they input the same Chinese characters. assuming you mean "code point" rather than "ASCII code" (ASCII is a specific encoding that *doesn't* include Chinese characters), "ord" is what you want: char = read_from_some_input_device() code = ord(char) see: http://pyref.infogami.com/ord </F> From bj_666 at gmx.net Mon Aug 21 03:48:27 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 21 Aug 2006 09:48:27 +0200 Subject: Python and STL efficiency References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> Message-ID: <pan.2006.08.21.07.48.24.455806@gmx.net> In <1156143136.020647.294290 at i42g2000cwa.googlegroups.com>, Licheng Fang wrote: > Hi, I'm learning STL and I wrote some simple code to compare the > efficiency of python and STL. > > //C++ > #include <iostream> > #include <string> > #include <vector> > #include <set> > #include <algorithm> > using namespace std; > > int main(){ > vector<string> a; > for (long int i=0; i<10000 ; ++i){ > a.push_back("What do you know?"); > a.push_back("so long..."); > a.push_back("chicken crosses road"); > a.push_back("fool"); > } > set<string> b(a.begin(), a.end()); > unique_copy(b.begin(), b.end(), ostream_iterator<string>(cout, "\n")); > } Why are you using `unique_copy` here? > #python > def f(): > a = [] > for i in range(10000): > a.append('What do you know') > a.append('so long...') > a.append('chicken crosses road') > a.append('fool') > b = set(a) > for s in b: > print s > > I was using VC++.net and IDLE, respectively. I had expected C++ to be > way faster. However, while the python code gave the result almost > instantly, the C++ code took several seconds to run! Can somebody > explain this to me? Or is there something wrong with my code? There's a difference in data structures at least. The Python `set` type is implemented with a hash algorithm, so the equivalent STL type would be `hash_set`. `set` in Python does not store its contents sorted. Ciao, Marc 'BlackJack' Rintsch From Andreas.Ames at comergo.com Thu Aug 24 07:08:57 2006 From: Andreas.Ames at comergo.com (Ames Andreas) Date: Thu, 24 Aug 2006 13:08:57 +0200 Subject: Python and STL efficiency Message-ID: <552B6B925278EF478EA8887D7F9E5AC301171374@tndefr-ws00024.tenovis.corp.lan> > -----Original Message----- > From: python-list-bounces+andreas.ames=comergo.com at python.org > [mailto:python-list-bounces+andreas.ames=comergo.com at python.or > g] On Behalf Of Ray > Sent: Wednesday, August 23, 2006 4:28 PM > Subject: Re: Python and STL efficiency > > > Tim N. van der Leeuw wrote: > > With the nr of loops corrected, Python on my laptop > performs worse than > > C++ under all circumstances, by a factor of about 2: > > *Phew* > > Great to know that my model of how the world works is still correct! > (at least in relation to Python and C++!) :) If you're really eager to see python succeed with this 'test' or 'benchmark', if you will, you can look at the results with VC7.1. It clearly shows that much depends on the STL implementation, you use. I use the implementations posted by Maric Michaud in http://mail.python.org/pipermail/python-list/2006-August/357593.html. The tests, for which I appended 'with hash', use a hash_set instead of a plain set. 1) vc71 with dinkumware STL (which is vc's default STL): print_occurence_of_strings What do you know? chicken crosses road fool so long... print_occurence_of_unique_strings What do you know? chicken crosses road fool so long... print_occurence_of_unique_strings_compared_by_address What do you know? chicken crosses road fool so long... print_occurence_of_strings_with_hash What do you know? chicken crosses road fool so long... print_occurence_of_unique_strings_with_hash What do you know? chicken crosses road fool so long... strings : 10.921 <---- Oops ... unique strings : 1.047 compared by address : 0.328 strings with hash : 11.484 <---- Oooops ... unique strings with hash : 1.016 2) vc7.1 with STLport 5.02: print_occurence_of_strings What do you know? chicken crosses road fool so long... print_occurence_of_unique_strings What do you know? chicken crosses road fool so long... print_occurence_of_unique_strings_compared_by_address What do you know? chicken crosses road fool so long... print_occurence_of_strings_with_hash <--- reorders fool What do you know? chicken crosses road so long... print_occurence_of_unique_strings_with_hash <--- reorders so long... What do you know? chicken crosses road fool strings : 2.156 unique strings : 0.953 compared by address : 0.187 strings with hash : 2.078 unique strings with hash : 0.922 This seems to substantiate this post http://sourceforge.net/mailarchive/forum.php?thread_id=30201462&forum_id=46178. 3) python 4.2 (python test.py; interestingly this is faster than with -OO) so long... What do you know fool chicken crosses road Elapsed: 2.278332 seconds It seems the unification of the strings via hash is not significantly better (compared to memcpy or whatever is used). The results for the dinkumware STL are dominated by the sheer number of calls to HeapAlloc/HeapFree and to EnterCriticalSection/LeaveCriticalSection (I compiled with multithreading and linked statically). The python version won't be concerned with the latter, I guess (although just by importing 'threading' performance gets about 3.5% worse). STLport uses for example InterlockedExchange (obviously in the default allocator) and several orders of magnitude fewer calls to the heap allocation API. It all boils down to the fact that I can write C++ or even assembler programs that perform worse (by any degree I want) than a functionally equivalent python program. That's a trivial insight and it certainly doesn't provide evidence that python 'is faster' than c++/assembler. Even if that's just because it *isn't* and can't be. I always wonder where this rage comes from to prove oneself or whomever that python is the best programming language in any regard as if it hadn't enough other advantages. It is certainly not the fastest/most memory efficient tool out there. One of the biggest advantages of python to me is that, even if I run into a hotspot, the transition from python to C/C++ is so easy. That means that in spite of its warts (GIL, memory efficiency ...) I don't easily come to a dead end using python. This fact lets me use python's great strengths (like programmer efficiency etc.) without tossing and turning sleeplessly in my bed. cheers, aa -- Andreas Ames | Programmer | Comergo GmbH | Voice: +49 69 7505 3213 | ames AT avaya DOT com From jojoba12 at hotmail.com Tue Aug 22 12:34:36 2006 From: jojoba12 at hotmail.com (jojoba) Date: 22 Aug 2006 09:34:36 -0700 Subject: how do you get the name of a dictionary? References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <pan.2006.08.21.03.33.27.84160@REMOVEME.cybersource.com.au> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> <mailman.9631.1156227418.27775.python-list@python.org> Message-ID: <1156264475.968894.221710@p79g2000cwp.googlegroups.com> Hello again, Fredrick said: > Python's object model. an object has a value, a type, and an identity, > but no name. I say: Thank you Fredrick for the reply! However, although python's object model does not currently support what i am asking for, how difficult would it be to assign a string name(s) to an object upon creation (and upon referencing)? please note: i don't want to do anything sophisticated with this, i am really only looking for a TITLE for my dictionary when i throw it in a tree editor that i have built. And i do realize that its not possible now. I am just pressing a point here. Sorry to ruffle everyone's feathers, but this is a fairly curious problem. Thanks to all, jojoba From mensanator at aol.com Sun Aug 20 12:50:41 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 20 Aug 2006 09:50:41 -0700 Subject: convert a long string in binary References: <mailman.9568.1156073739.27775.python-list@python.org> Message-ID: <1156092641.685571.88090@74g2000cwt.googlegroups.com> bussiere maillist wrote: > i've got a very long string > and i wanted to convert it in binary > like > > string = """Monty Python, or The Pythons, is the collective name of > the creators of Monty Python's Flying Circus, a British television > comedy sketch show that first aired on the BBC on October 5, 1969. A > total of 45 episodes were made over four series. However, the Python > phenomenon was much greater, spawning stage tours, a musical, four > films, numerous albums, and several books, as well as launching the > members to individual stardom. > > The television series, broadcast by the BBC from 1969 to 1974, was > conceived, written and performed by Graham Chapman, John Cleese > (1969-1973), Terry Gilliam, Eric Idle, Terry Jones and Michael Palin. > Loosely structured as a sketch show, but with a highly innovative > stream-of-consciousness approach (aided by Terry Gilliam's > animations), it pushed the boundaries of what was then considered > acceptable, both in terms of style and content. > """ > > string = binary(string) > print string > // 01010101010101 > > > i 'am searching for something like the binary function (taht doesn't > exist) to convert my string directly in binary. The gmpy module can convert numbers to binary strings: import gmpy s = """ Yes, well, of course that's just the sort of blinkered philistine pig ignorance I've come to expect from you non-creative garbage. """ ss = '' for c in s: sb = gmpy.digits(ord(c),2) #convert to binary string sb = '0'*(8-len(sb)) + sb #add leading 0's ss += sb print ss 000010100101100101100101011100110010110000100000011101110110010101101100011011000010110000100000011011110110011000100000011000110110111101110101011100100111001101100101001000000111010001101000011000010111010000100111011100110010000001101010011101010111001101110100001000000111010001101000011001010010000001110011011011110111001001110100001000000110111101100110000010100110001001101100011010010110111001101011011001010111001001100101011001000010000001110000011010000110100101101100011010010111001101110100011010010110111001100101001000000111000001101001011001110010000001101001011001110110111001101111011100100110000101101110011000110110010100100000010010010010011101110110011001010010000001100011011011110110110101100101000010100111010001101111001000000110010101111000011100000110010101100011011101000010000001100110011100100110111101101101001000000111100101101111011101010010000001101110011011110110111000101101011000110111001001100101011000010111010001101001011101100110010100100000011001110110000101110010011000100110000101100111011001010010111000001010 > Regards > Bussiere From bearophileHUGS at lycos.com Wed Aug 23 12:30:01 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 23 Aug 2006 09:30:01 -0700 Subject: Python-like C++ library In-Reply-To: <1156342782.435869.250350@75g2000cwc.googlegroups.com> References: <1156342782.435869.250350@75g2000cwc.googlegroups.com> Message-ID: <1156350601.733047.198620@i42g2000cwa.googlegroups.com> Will McGugan: > I was wondering if there was a C++ library that > implemented the fundamental objects of Python as close as possible, > perhaps using STL underneath the hood. > Too clarify, Im not looking to interface C++ with Python in any way, > just to emulate the strings / containers / slicing etc. Maybe you can use the ShedSkin libraries, it maps Python to C++: http://shedskin.sourceforge.net/ EasySTL is unrelated to Python, but you may find it useful: http://userpages.umbc.edu/~bcorfm1/software.html Bye, bearophile From vedran500 at net.hr Sun Aug 13 15:24:39 2006 From: vedran500 at net.hr (2Good4You-Veki(Cro)) Date: 13 Aug 2006 12:24:39 -0700 Subject: NNTPLIB STRANGE ERROR Message-ID: <1155497079.234800.234260@p79g2000cwp.googlegroups.com> HI, when I want use python nntplib: >>> import nntplib >>> s=nntplib.NNTP('news.t-com.hr') >>> s.group('hr.mag.bug') THEN ERROR IS: Traceback (most recent call last): File "<pyshell#2>", line 1, in -toplevel- s.group('hr.mag.bug') File "C:\Python24\lib\nntplib.py", line 346, in group resp = self.shortcmd('GROUP ' + name) File "C:\Python24\lib\nntplib.py", line 260, in shortcmd return self.getresp() File "C:\Python24\lib\nntplib.py", line 215, in getresp resp = self.getline() File "C:\Python24\lib\nntplib.py", line 204, in getline line = self.file.readline() File "C:\Python24\lib\socket.py", line 340, in readline data = self._sock.recv(self._rbufsize) error: (10053, 'Software caused connection abort') From jojoba12 at hotmail.com Wed Aug 23 12:39:05 2006 From: jojoba12 at hotmail.com (jojoba) Date: 23 Aug 2006 09:39:05 -0700 Subject: how do you get the name of a dictionary? In-Reply-To: <1156350580.363393.256730@74g2000cwt.googlegroups.com> References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <pan.2006.08.21.03.33.27.84160@REMOVEME.cybersource.com.au> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> <mailman.9631.1156227418.27775.python-list@python.org> <1156264475.968894.221710@p79g2000cwp.googlegroups.com> <1156266720.205126.284050@i3g2000cwc.googlegroups.com> <1156268752.574983.123520@75g2000cwc.googlegroups.com> <pan.2006.08.22.20.05.58.528777@gmx.net> <1156281268.865624.302070@b28g2000cwb.googlegroups.com> <mailman.9666.1156281679.27775.python-list@python.org> <1156283135.985893.186500@m73g2000cwd.googlegroups.com> <mailman.9668.1156283600.27775.python-list@python.org> <1156284812.469380.274370@b28g2000cwb.googlegroups.com> <mailman.9686.1156315895.27775.python-list@python.org> <1156350580.363393.256730@74g2000cwt.googlegroups.com> Message-ID: <1156351145.331923.73190@m79g2000cwm.googlegroups.com> > And what im saying is that isnt it silly that we need pass an entire > namespace, when a much simpler notion would be to have each object know > its own name(s) (even if that name doesnt exist). please note: in my above comment, i was completely disregarding any notions of added costs that would be incurred to have such a feature, and that in fact, such costs might actually nullify any other benefits from having such a feature. Purely a what-if idea from a nascent python programmer. jojoba From bruce+usenet at cenderis.demon.co.uk Fri Aug 25 18:20:41 2006 From: bruce+usenet at cenderis.demon.co.uk (Bruce Stephens) Date: Fri, 25 Aug 2006 23:20:41 +0100 Subject: ASN.1 encoder & decoder References: <a8que25donq0epints24mkq0g83505d0ug@4ax.com> Message-ID: <87odu8e9ty.fsf@cenderis.demon.co.uk> Doug Stell <celiadoug at mchsi.com> writes: > Can anyone provide guidance on building an ASN.1 decoder and encoder > in Python? <http://sourceforge.net/projects/pyasn1/>? From chppatel at gmail.com Thu Aug 17 13:28:59 2006 From: chppatel at gmail.com (chppatel at gmail.com) Date: 17 Aug 2006 10:28:59 -0700 Subject: where can i get older version of python? Message-ID: <1155835739.694566.177080@75g2000cwc.googlegroups.com> does any one know where can I get older version of python for windows? I am looking for versions between 2.0 and 2.2. thanks for your help From simon at brunningonline.net Wed Aug 16 16:00:06 2006 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 16 Aug 2006 21:00:06 +0100 Subject: trouble understanding inheritance... In-Reply-To: <1155757992.706040.288890@74g2000cwt.googlegroups.com> References: <1155753183.207393.116940@m79g2000cwm.googlegroups.com> <mailman.9435.1155753894.27775.python-list@python.org> <1155754767.694480.256200@h48g2000cwc.googlegroups.com> <1155756282.851876.46470@b28g2000cwb.googlegroups.com> <1155757992.706040.288890@74g2000cwt.googlegroups.com> Message-ID: <8c7f10c60608161300j6fc61eddtd4278843205add75@mail.gmail.com> On 16 Aug 2006 12:53:12 -0700, KraftDiner <bobrien18 at yahoo.com> wrote: > I can see that this might work... > c = [a, b] > for c in [a,b]: > c.getName() > > but when does baseClass ever get used? > Why did i even have to define it? Well, quite. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From vbgunz at gmail.com Wed Aug 23 22:43:25 2006 From: vbgunz at gmail.com (vbgunz) Date: 23 Aug 2006 19:43:25 -0700 Subject: Regex help...pretty please? In-Reply-To: <1156358822.649578.126990@74g2000cwt.googlegroups.com> References: <1156358822.649578.126990@74g2000cwt.googlegroups.com> Message-ID: <1156387405.590301.289570@p79g2000cwp.googlegroups.com> MooMaster Wrote: > I'm trying to develop a little script that does some string > manipulation. I have some few hundred strings that currently look like > this: > cond(a,b,c) > and I want them to look like this: > cond(c,a,b) I zoned out on your question and created a very simple flipper. Although it will not solve your problem maybe someone looking for a simpler version may find it useful as a starting point. I hope it proves useful. I'll post my simple flipper here: s = 'cond(1,savv(grave(3,2,1),y,x),maxx(c,b,a),0)' def argFlipper(s): ''' take a string of arguments and reverse'em e.g. >>> cond(1,savv(grave(3,2,1),y,x),maxx(c,b,a),0) -> cond(0,maxx(a,b,c),savv(x,y,grave(1,2,3)),1) ''' count = 0 keyholder = {} while 1: if s.find('(') > 0: count += 1 value = '%sph' + '%d' % count tempstring = [x for x in s] startindex = s.rfind('(') limitindex = s.find(')', startindex) argtarget = s[startindex + 1:limitindex].split(',') argreversed = ','.join(reversed(argtarget)) keyholder[value] = '(' + argreversed + ')' tempstring[startindex:limitindex + 1] = value s = ''.join(tempstring) else: while count and keyholder: s = s.replace(value, keyholder[value]) count -= 1 value = '%sph' + '%d' % count return s print argFlipper(s) From martin.witte at gmail.com Tue Aug 15 12:13:06 2006 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 15 Aug 2006 09:13:06 -0700 Subject: Beginner Textbook In-Reply-To: <12e3gkdhjngum6a@corp.supernews.com> References: <12e3gkdhjngum6a@corp.supernews.com> Message-ID: <1155658386.778845.119600@75g2000cwc.googlegroups.com> M_M wrote: > Hi, > > I am looking for a simple text book to introduce 13 to 18 year olds to > python programming. Suggestion? > > New to python. On the Python site is a list of tutorials on this page: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers, towards the end of the page you'll find a few entries for younger students. Good luck! From sjdevnull at yahoo.com Tue Aug 29 13:10:08 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 29 Aug 2006 10:10:08 -0700 Subject: How ahead are you guys in the (Python) real world? In-Reply-To: <1156821234.820929.299740@p79g2000cwp.googlegroups.com> References: <1156821234.820929.299740@p79g2000cwp.googlegroups.com> Message-ID: <1156871408.186573.185990@75g2000cwc.googlegroups.com> Ray wrote: > Since I haven't used Python at work, I am using Python 2.5 right now. > However I wonder, how fast are you guys moving from version to version > at work? As an illustration my ex-company just moved to Java 5, which > was released around... what, 2-3 years ago? (While I am running Java 6 > at home) We are using 2.2 most places, with 2.3 on a few dev boxes. We're planning an update to 2.4 in the next couple of months. From riko at despammed.com Tue Aug 22 06:55:36 2006 From: riko at despammed.com (Mc Osten) Date: Tue, 22 Aug 2006 12:55:36 +0200 Subject: Python and STL efficiency References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <mailman.9595.1156153010.27775.python-list@python.org> <1156162237.274636.17850@i3g2000cwc.googlegroups.com> <1156165101.702758.148420@74g2000cwt.googlegroups.com> <1156235875.990556.25990@74g2000cwt.googlegroups.com> <1156238765.761842.160090@b28g2000cwb.googlegroups.com> Message-ID: <1hkh2bb.1stxif340llmoN%riko@despammed.com> Tim N. van der Leeuw <tim.leeuwvander at nl.unisys.com> wrote: > I'm curious though, if on the OP's machine the slowed-down Python > version is still faster than the C++ version. I tested both on my machine (my other post in the thread) -- blog: http://www.akropolix.net/rik0/blogs | Uccidete i filosofi, site: http://www.akropolix.net/rik0/ | tenetevi riso e forum: http://www.akropolix.net/forum/ | bacchette per voi. From bborcic at gmail.com Wed Aug 23 09:09:31 2006 From: bborcic at gmail.com (Boris Borcic) Date: Wed, 23 Aug 2006 15:09:31 +0200 Subject: swapping numeric items in a list In-Reply-To: <mailman.9675.1156291509.27775.python-list@python.org> References: <mailman.9675.1156291509.27775.python-list@python.org> Message-ID: <44ec53b4_3@news.bluewin.ch> Jiang Nutao wrote: > Hi, > > I simplify my problem like below > > To convert list > aa = [0x12, 0x34, 0x56, 0x78] > into > [0x34, 0x12, 0x78, 0x56] > > How to do it fast? My real list is huge. Mark Rintsch's suggestion appears best if applicable, but just to cite yet other ways to do it : list(aa[j+(-1)**j] for j in range(len(aa))) or sum(reversed(zip(*[reversed(aa)]*2)),()) or (py 2.5) from itertools import izip ab = iter(aa) list((yield y) or x for x,y in izip(ab,ab)) From johnjsal at NOSPAMgmail.com Thu Aug 31 14:39:45 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 31 Aug 2006 18:39:45 GMT Subject: problem with appending to a list, possibly mysqldb related In-Reply-To: <U0GJg.2720$No6.53312@news.tufts.edu> References: <7DFJg.2719$No6.53311@news.tufts.edu> <mailman.10208.1157049030.27775.python-list@python.org> <U0GJg.2720$No6.53312@news.tufts.edu> Message-ID: <R1GJg.2721$No6.53312@news.tufts.edu> John Salerno wrote: > John Purser wrote: > >> I'd say you had a record with a null value for the namefirst field. >> The join method don't like that. > > Wow, you're right! I tried this: > > if x[0] and not x[0] == 'NULL': > > and sure enough it works after that. (Not sure if that's the best way to > test, though. Just testing for NULL still produced the error, so I > guessed that some namefirst fields were actually blank.) Just tried again with: if x[0]: and that worked, so I guess NULL isn't a string value. From johnjsal at NOSPAMgmail.com Thu Aug 31 14:38:44 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 31 Aug 2006 18:38:44 GMT Subject: problem with appending to a list, possibly mysqldb related In-Reply-To: <mailman.10208.1157049030.27775.python-list@python.org> References: <7DFJg.2719$No6.53311@news.tufts.edu> <mailman.10208.1157049030.27775.python-list@python.org> Message-ID: <U0GJg.2720$No6.53312@news.tufts.edu> John Purser wrote: > I'd say you had a record with a null value for the namefirst field. > The join method don't like that. Wow, you're right! I tried this: if x[0] and not x[0] == 'NULL': and sure enough it works after that. (Not sure if that's the best way to test, though. Just testing for NULL still produced the error, so I guessed that some namefirst fields were actually blank.) From jorge.vargas at gmail.com Mon Aug 28 18:00:41 2006 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Mon, 28 Aug 2006 18:00:41 -0400 Subject: Max OSX and Excel In-Reply-To: <C1189A84.F5%Johanna.Pfalz@telus.net> References: <C1189A84.F5%Johanna.Pfalz@telus.net> Message-ID: <32822fe60608281500l762b61ddqc6f3300ec1e296a6@mail.gmail.com> On 8/28/06, Johanna Pfalz <Johanna.Pfalz at telus.net> wrote: > Hi there, > > Does anyone have details on how to drive excel using python 2.4 on OSX? > I've searched the web and have not found anything specific to excel. drive? > > Thanks in advance, > > > Johanna Pfalz > Smithers, BC > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From rosedb0 at gmail.com Tue Aug 8 17:10:33 2006 From: rosedb0 at gmail.com (hiaips) Date: 8 Aug 2006 14:10:33 -0700 Subject: newb question: file searching In-Reply-To: <1155070517.448510.149380@b28g2000cwb.googlegroups.com> References: <1155067111.892386.130610@n13g2000cwa.googlegroups.com> <1155067720.211789.208560@i42g2000cwa.googlegroups.com> <1155068675.101390.299110@i3g2000cwc.googlegroups.com> <1155070517.448510.149380@b28g2000cwb.googlegroups.com> Message-ID: <1155071433.686040.276080@m79g2000cwm.googlegroups.com> jaysherby at gmail.com wrote: > Thanks, Dave. That's exactly what I was looking for, well, except for > a few small alterations I'll make to achieve the desired effect. I > must ask, in the interest of learning, what is > > [file for file in files if file.endswith(extension)] > > actually doing? I know that 'file' is a type, but what's with the set > up and the brackets and all? Can someone run down the syntax for me on > that? And also, I'm still not sure I know exactly how os.walk() works. > And, finally, the python docs all note that symbols like . and .. > don't work with these commands. How can I grab the directory that my > script is residing in? [file for file in files if file.endswith(extension)] is called a list comprehension. Functionally, it is equivalent to something like this: files_with_ext = [] for file in files: if file.endswith(extension): files_with_ext.append(file) However, list comprehensions provide a much more terse, declarative syntax without sacrificing readability. To get your current working directory (i.e., the directory in which your script is residing): cwd = os.getcwd() As far as os.walk... This is actually a generator (effectively, a function that eventually produces a sequence, but rather than returning the entire sequence, it "yields" one value at a time). You might use it as follows: for x in os.walk(mydirectory): for file in x[1]: <whatever tests or code you need to run> You might want to read up on the os and os.path modules - these probably have many of the utilities you're looking for. Good luck, dave From sjmachin at lexicon.net Fri Aug 4 01:00:37 2006 From: sjmachin at lexicon.net (John Machin) Date: 3 Aug 2006 22:00:37 -0700 Subject: looking for a regular expression References: <4POChV$9OC@bbs.wretch.cc> <5fg5d2t5c5j4s665bgut58s0diea3794u5@4ax.com> Message-ID: <1154667637.105633.42890@i42g2000cwa.googlegroups.com> Tim Roberts wrote: > What is your signature supposed to be? It looks like you are trying to > inject ANSI terminal escape sequences. The vast majority of Usenet > participants are now reading these articles through GUI newsreaders or > web-based readers which show this as 5 lines of unrecognizable line noise. Tim, Next time you have a problem like this, and indications of origin like the ".tw" at the end don't clue you in, try "view source" (or similar) in your news reader, and look for a Content-Type like this: Content-Type: text/plain; charset="big5" You should then be able to adjust the encoding config in your news reader. HTH, John From pmartin at snakecard.com Sat Aug 19 07:35:56 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Sat, 19 Aug 2006 06:35:56 -0500 Subject: text editor suggestion? References: <44e66724$0$2363$c3e8da3@news.astraweb.com> Message-ID: <1UCFg.85161$LF4.1811@dukeread05> John Salerno wrote: > Ok, I know it's been asked a million times, but I have a more specific > question so hopefully this won't be just the same old post. I've tried a > few different editors, and I really like UltraEdit, but it's > Windows-only and I'm working more on Linux nowadays. > > Here are my criteria: > > 1. syntax highlighting (highly customizable) > 2. auto/smart indenting > 3. ability to run script > 4. light-weight text editor, not an IDE > 5. cross-platform (not really necessary, but nice) > > That's pretty much all I need. It's nice when you can customize a bunch > of other stuff too, but those are the most important. > > I've tried vim, but I really don't feel like taking the time to learn > how to use it, given that I just like to casually program (not to > mention that I prefer to use the mouse when navigating a document > sometimes). > > I also just started using Scite, and I really like it, except I find its > syntax highlighting to be very inflexible. You aren't able to define > your own groups of words -- you have to use what's given, basically. One > thing I like about UltraEdit is that you simply define as many groups of > keywords as you want and then assign a style to each one. Scite has a > very strange and rigid method of highlighting. > > So hopefully some of you might have some suggestions. My requirements > are minimal, but I'm still not happy with the syntax highlighting I'm > seeing in a lot of editors out there. Emacs would be my choice. Philippe From uche.ogbuji at gmail.com Mon Aug 28 10:49:54 2006 From: uche.ogbuji at gmail.com (uche.ogbuji at gmail.com) Date: 28 Aug 2006 07:49:54 -0700 Subject: XML parsing and writing In-Reply-To: <1154374561.173011.45590@i3g2000cwc.googlegroups.com> References: <1154111594.276996.161800@b28g2000cwb.googlegroups.com> <44cdc907$0$18516$9b4e6d93@newsread2.arcor-online.net> <1154374561.173011.45590@i3g2000cwc.googlegroups.com> Message-ID: <1156776593.955852.29260@h48g2000cwc.googlegroups.com> c00i90wn wrote: > Nice package ElementTree is but sadly it doesn't have a pretty print, > well, guess I'll have to do it myself, if you have one already can you > please give it to me? thanks :) FWIW Amara and plain old 4Suite both support pretty-print, canonical XML print and more such options. http://uche.ogbuji.net/tech/4suite/amara/ http://4Suite.org -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://fourthought.com http://copia.ogbuji.net http://4Suite.org Articles: http://uche.ogbuji.net/tech/publications/ From g.brandl-nospam at gmx.net Mon Aug 28 16:12:53 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Mon, 28 Aug 2006 22:12:53 +0200 Subject: Misleading error message when opening a file (on Windows XP SP 2) In-Reply-To: <ecuh7n$kk2$1@newsreader2.netcologne.de> References: <ecu65e$12o$1@newsreader2.netcologne.de> <mailman.9968.1156757977.27775.python-list@python.org> <ecuh7n$kk2$1@newsreader2.netcologne.de> Message-ID: <ecvio6$4dq$3@news.albasani.net> Claudio Grondi wrote: > Tim Peters wrote: >> [Claudio Grondi] >> >>> Here an example of what I mean >>> (Python 2.4.2, IDLE 1.1.2, Windows XP SP2, NTFS file system, 80 GByte >>> large file): >>> >>> >>> f = file('veryBigFile.dat','r') >>> >>> f = file('veryBigFile.dat','r+') >>> >>> Traceback (most recent call last): >>> File "<pyshell#1>", line 1, in -toplevel- >>> f = file('veryBigFile.dat','r+') >>> IOError: [Errno 2] No such file or directory: 'veryBigFile.dat' >>> >>> Is it a BUG or a FEATURE? >> >> >> Assuming the file exists and isn't read-only, I bet it's a Windows >> bug, and that if you open in binary mode ("r+b") instead I bet it goes >> away (this wouldn't be the first large-file text-mode Windows bug). > > I knew already that 'r+b' fixes it. Yes, you have won the bet :) . > > I suppose, like you do, that because there is a difference between text > and binary files on Windows and the text files are e.g. opened being > buffered using a 32-bit buffer pointer, this fails on too large NTFS files. > > I could also imagine that Python tries to buffer the text file and fails > because it uses the wrong pointer size when asking Windows for the > content. I have not yet looked into the C-code of Python - any hint > which file I should take a closer look at? That would be Objects/fileobject.c. And no, on just open()ing the file, Python does nothing more than fopen() (or some Windows equivalent). Georg From kylotan at gmail.com Fri Aug 11 12:18:12 2006 From: kylotan at gmail.com (Ben Sizer) Date: 11 Aug 2006 09:18:12 -0700 Subject: hide python code ! In-Reply-To: <1155309563.898182.195950@p79g2000cwp.googlegroups.com> References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155300852.497741.73230@74g2000cwt.googlegroups.com> <1155301468.870340.82920@b28g2000cwb.googlegroups.com> <1155307415.855555.124760@i3g2000cwc.googlegroups.com> <1155309563.898182.195950@p79g2000cwp.googlegroups.com> Message-ID: <1155313092.743230.33950@m73g2000cwd.googlegroups.com> Paul Boddie wrote: > Ben Sizer wrote: > > > > It's worth remembering that there is a massive amount of software that > > has nothing to do with 'infrastructure', that won't need to be > > maintained, or upgraded. Examples include most retail software for the > > home or small office, and most entertainment software. Developers of > > such software often have understandable reasons for making it > > inconvenient to examine the algorithms at a high level. > > Sure, developers of such software may not want their competitors to > find out how their products work - certain companies also like to file > patents for that added anticompetitive edge, should their competitors > even consider figuring out the not-so-magic formula - but as end-users > of software ourselves, we don't have to share such an understanding of > their motivations, especially when such motivations directly conflict > with our own: with respect to the above evidence, our own motivations > are to have a reasonable level of control over the tools to manage our > own data. I think you're possibly being a bit idealistic here. I use and endorse open source and open formats wherever possible but I don't believe we would have the same degree of diversity of software available if everything was open. Imagine if you were the single-person developer of a small application that did something quite innovative, and charged a small fee for your product. Now imagine you were practically forced to make your algorithm obvious - a couple of months later, Microsoft bring out a freeware version and destroy your business in an instant. Sure, they and others can (and have) done that with closed-source products, but you increase your chances of survival 10-fold if the key algorithms are not obvious. The only other way to protect against that would be a software patent, and I disagree with their existence on the grounds that it punishes those who discover the techniques independently. > It may not matter if some console game or other doesn't work after 20 > years... Certainly; yet this is a valid example of software that requires a degree of protection since some of the algorithms employed truly are 'worth stealing'. They can usually be replicated in time, but that may be months and allows the original company to have a deserved commercial advantage. > ...although I think it's actually something of a shame given that > such artifacts, no matter how apparently trivial they are, are actually > part of our culture and shouldn't be so readily discarded and > forgotten... Thankfully we have emulators for most platforms, and hopefully litigation won't kill those off. > ...but when your own data is not easily accessible within a > much shorter timeframe, the scandal is (at least to me) so much more > obvious. I think it's quite possible to have a closed binary but an open document format, thus allowing the user to migrate away at any point while still preserving any 'secrets' in the implementation. -- Ben Sizer From claudio.grondi at freenet.de Sun Aug 27 03:44:30 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Sun, 27 Aug 2006 09:44:30 +0200 Subject: random writing access to a file in Python In-Reply-To: <7xd5anf23u.fsf@ruckus.brouhaha.com> References: <ecn00i$t2o$1@newsreader2.netcologne.de> <mailman.9872.1156515341.27775.python-list@python.org> <ecn22h$3o5$1@newsreader2.netcologne.de> <5a9ue2lrjh214ecmme09fsodhm3ico1ntm@4ax.com> <ecno4v$h11$1@newsreader2.netcologne.de> <7xhczzqoi3.fsf@ruckus.brouhaha.com> <ecqhd2$17u$1@newsreader2.netcologne.de> <7xbqq7f6q7.fsf@ruckus.brouhaha.com> <ecqn1d$8ui$1@newsreader2.netcologne.de> <7xd5anf23u.fsf@ruckus.brouhaha.com> Message-ID: <ecrigu$g5v$1@newsreader2.netcologne.de> Paul Rubin wrote: > Claudio Grondi <claudio.grondi at freenet.de> writes: > >>Does it mean, that in case of very large files: >> the size of available memory for the sorting operation (making it >>possible to work on larger chunks of data in memory) has less impact >>on the actual sorting speed than >> the speed of the data transfer from/to storage device(s) > > > Transfer speed and parallelism matters most, if the cpu can keep up. > Parallelism means you want multiple drives that you can do i/o to > simultaneously without having to seek. Random access helps simulate > this, but only somewhat. Large database installations always want > lots of parallel disks for similar reasons to this. > > The basic method of sorting large files has traditionally been: > > 1) Read the file in pieces p(1),p(2),...,p(n) where each piece is as > big as will fit in memory. Sort each piece with your favorite > in-memory sort, and write out sorted pieces that we'll designate > r(1,1),...r(1,n). The r(a,b)'s are called "runs". Use multiple > output devices (tape or disk drives) to write out the runs, i.e. each > output tape will contain its own bunch of runs. > > 2) Read back a bunch of the runs in parallel, i.e. say you have > written r(1,1),r(1,2),...,r(1,5) to five separate tape drives. Read > them back simultaneously and merge them (requires very little external > memory) into a new "second level" run called r(2,1). Similarly merge > r(1,6),...,r(1,10) to the second level run r(2,2), and so forth. > > 3) Merge the second level runs into third level runs, and so forth > recursively until there's only one giant run. That is the sorted > output. > > The amount of memory determines the size of the initial "first level" > runs, which determines how many recursive merges are needed, so more > memory helps. > > The number of levels of recursion also depends on the "merge order", > i.e. the number of runs merged at each merge step. You really want > each merge to read from M physical input devices that are separate > from the output device(s). > > There are obviously a lot of optimizations that the above description > is missing, and there's a lot of strategy about how to organize the > merges, e.g. if you have 8 drives, do you use 4 for input and 4 for > output, or 5 in and 3 out, or what? The Windows XP SP 2 '/> sort' (sorting of four Gigs of 20 byte records took 12 CPU and 18 usual hours) has, from what I could observe on the task manager, done the job in only two runs of 'copying' : 1. first to a temporary file, 2. then to the final file. In the second run the size of processed chunks between reading/writing was in the order of up to tenths of Megabytes, where in the first run in order of up to hundreds Megabytes. I suppose that the procedure behind it was as follows: 1. decision about the size of chunks to split the file into and choosing the size of required memory 2. processing the chunks with in-memory sorting them and writing to the temporary file 3. decision about the size of buffers for merge sorting the chunks into the final file, so that they all fit into the 300 MByte of used memory 4. opening as many 'pipes' as there were chunks filling all of the pipe buffers up when one of them runs out of data 5. continuously switching between reading and writing to the hard disk, writing the results of the merge sorting to the final file always when one of the buffers run out of data and then filling up all of the buffers for the next cycle (concluded from observed scattered reading, smooth writing) > > Is this some kind of production deployment problem you're working on, > or do you just have a big pile of data you need to sort once? The latter. One of the intermediate reasons behind doing it, is an attempt to get more and better intuitive understanding what are the hardware and software limits of brute force based approaches to solving problems in the area of AI, language processing and data compression. > If you > need to deploy across multiple machines (i.e. you can't just buy a > giant machine if you need to do this sorting frequently), then I'd > suggest reading up on the subject, starting with Knuth vol 3. Thank you much for your detailed response. Claudio Grondi From sinor1 at REMOVElycos.com Sun Aug 13 11:12:34 2006 From: sinor1 at REMOVElycos.com (Rich) Date: Sun, 13 Aug 2006 17:12:34 +0200 Subject: Installed correctly References: <i87ud25fkbif2rk2daul8t1rc5nmv7msj1@4ax.com> <1155476706.812107.276950@b28g2000cwb.googlegroups.com> Message-ID: <8mfud29jq75g9mnvkm54iosdsonnnflcnj@4ax.com> (sorry, I accidentally hit "send" before I was finished) Well thanks for all your replies. I've now uninstalled Python, and reinstalled it using the default path (C:\python24), to avoid any complications. But command line still said "unrecognized command", when typing "python". So apparently you have to do that manually (at least in some cases). In any case I added the path according to your instructions, and now it seems to work. Perhaps the page refered to systems that comes with Python pre-installed (they mention that some HP machines do). Obviously, the pre-iinstallation would have to include setting the path. Again, thanks for your help! :) From slawomir.nowaczyk.847 at student.lu.se Fri Aug 11 06:48:31 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Fri, 11 Aug 2006 12:48:31 +0200 Subject: hide python code ! In-Reply-To: <1155256527.061808.135200@74g2000cwt.googlegroups.com> References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155256527.061808.135200@74g2000cwt.googlegroups.com> Message-ID: <20060811101230.EFB8.SLAWOMIR.NOWACZYK.847@student.lu.se> On Thu, 10 Aug 2006 17:35:27 -0700 enigmadude <enigmadude at rock.com> wrote: #> 2. I've never done this, but you might be able to encrypt or otherwise #> turn you modules into binary form, and then use a clever import #> hook. Please observe that whatever the "clever import hook" is, it actually needs to know the way to *decrypt* the module (secret key or whatever). It means that if somebody decompiles the importing code, he can just as well decompile the "hidden" one. -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) Children are natural mimics, who act like their parents despite every effort to teach them good manners. From haraldarminmassa at gmail.com Thu Aug 3 08:21:45 2006 From: haraldarminmassa at gmail.com (GHUM) Date: 3 Aug 2006 05:21:45 -0700 Subject: need help of regular expression genius In-Reply-To: <W6kAg.42283$rp4.38054@tornado.texas.rr.com> References: <1154532421.096157.289570@i42g2000cwa.googlegroups.com> <QDdAg.40847$rp4.22091@tornado.texas.rr.com> <1154590996.372956.113320@s13g2000cwa.googlegroups.com> <W6kAg.42283$rp4.38054@tornado.texas.rr.com> Message-ID: <1154607705.403691.134000@m73g2000cwd.googlegroups.com> Paul, > Pyparsing ships with JPG and PNG files containing class diagrams, plus an > htmldoc directory containing epydoc-generated help files. > There are also about 20 example programs included (also accessible in the > wiki). Yes. That's what I have been missing. Maybe you could add: "please also download the .zip file if you use the windows installer to find the documentation" :))) >You could also look into using scanString instead of transformString thats what I found: from pyparsing import SkipTo,Literal,replaceWith ign1 = "$$" + SkipTo("$$") + "$$" ign2 = "$_$" + SkipTo("$_$") + "$_$" semi = Literal(";") von=0 befehle=[] for row in (ign1 | ign2 | semi).scanString(txt): if row[0][0]==";": token, bis, von2=row befehle.append(txt[von: von2]) von=von2 I knew that for this common kind of problem there MUST be better solution then my homebrewn tokenizer (skimming through text char by char and remembering the switch to escape mode ... brrrrrr, looked like perl) Thanks for the reminder of pyparsing, maybe I should put in a reminder in my calender ... something along the lines "if you think of using a RE, you propably have forgotton pyparsing" every 3 months :))))) Best wishes and thank you very much for pyparsing and the hint Harald From sj.vanwerkhoven at wxs.nl Thu Aug 3 05:34:08 2006 From: sj.vanwerkhoven at wxs.nl (sj.vanwerkhoven at wxs.nl) Date: Thu, 03 Aug 2006 05:34:08 -0400 Subject: using globals Message-ID: <d17e144d1804b0.d1804b0d17e144@planet.nl> Hi, I have got a problem with importing global variables. For instance I have got two files: # t1.py #t2.py counter = 1 def counter_adder(filenr): def show_adder(): global counter import t1 counter+= 1 print("adder is %d" % t1.counter) if filenr == 1: show_adder() else: import t2 t2.show_adder() def show_adder(): print("adder is %d" % counter) >>counter_adder(1) adder is 2 >>counter_adder(2) adder is 1 When I look at the outcome of two function calls I expected no differences but much to my surprise it goes wrong when the global variable is imported. It doesn't give the updated value but the value it get when instantiated. Who come? What should I do to get the updated value greetings, Sjaak van Werkhoven From michiel at thingmajig.org Thu Aug 24 07:41:34 2006 From: michiel at thingmajig.org (Michiel Sikma) Date: Thu, 24 Aug 2006 13:41:34 +0200 Subject: Best Editor In-Reply-To: <44ed8db6$0$75034$14726298@news.sunsite.dk> References: <44ed8db6$0$75034$14726298@news.sunsite.dk> Message-ID: <717DECFF-DB1A-4200-B09D-41108B015B00@thingmajig.org> I personally use Eclipse with PyDev. It is a cross-platform solution because Eclipse is made with Java. http://www.eclipse.org/ http://pydev.sourceforge.net/ Michiel Op 24-aug-2006, om 13:29 heeft JAG CHAN het volgende geschreven: > Friends, I am trying to learn Python. > It will be of great help to me if you let me know which one would > be best > editor for learning Python. > Plese note that I would like to have multiplatform editor which > will be > useful for both LInux and Windows XP. > Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list From fphsml at gmail.com Fri Aug 11 01:43:27 2006 From: fphsml at gmail.com (James) Date: 10 Aug 2006 22:43:27 -0700 Subject: ALLAH In-Reply-To: <1155266738.533763.229330@p79g2000cwp.googlegroups.com> References: <1155117922.061942.100370@n13g2000cwa.googlegroups.com> <1155266738.533763.229330@p79g2000cwp.googlegroups.com> Message-ID: <1155275006.941624.69540@74g2000cwt.googlegroups.com> > I dont know why post a subject like this here! Anyway, the post is in > Turkish and talks about Islam, with the format, sub-heading (which is a > main topic in Islamic belief) and then a story relating to the > sub-heading, which is used to explain the topic. He is an Internet Looney. According to Google groups, he has posted 639 messages in the last 2 months to Usenet under this identity, everyone of them to a very large number of unrelated newsgroups. Effectively this is spam. I reported abuse in Google groups (if that works at all) and will try to contact his ISP. From fredrik at pythonware.com Wed Aug 30 14:04:16 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 30 Aug 2006 20:04:16 +0200 Subject: py2exe for programs with excel COM objects In-Reply-To: <1156957480.182219.165010@h48g2000cwc.googlegroups.com> References: <1156957480.182219.165010@h48g2000cwc.googlegroups.com> Message-ID: <ed4jv1$8e7$1@sea.gmane.org> marijuanated at gmail.com wrote: > Is it possible to create a executable of a python program that refers > to Excel COM objects with the help of py2exe. the py2exe site is full of nice howto articles; this one might help in your case: http://www.py2exe.org/index.cgi/IncludingTypelibs </F> From aries.shuaib at gmail.com Sat Aug 19 15:47:40 2006 From: aries.shuaib at gmail.com (Shuaib) Date: 19 Aug 2006 12:47:40 -0700 Subject: Embedding python: GCC gives errors of "undefined reference" to Py_* functions. In-Reply-To: <1156014074.961189.147070@m73g2000cwd.googlegroups.com> References: <1156014074.961189.147070@m73g2000cwd.googlegroups.com> Message-ID: <1156016860.331602.271420@i42g2000cwa.googlegroups.com> OK, I am not ashamed to admit that I am ashamed as I didn't search the group for my problem before posting it yet again. The solution was right there. I have link in my libpython2.4.so while compiling. $gcc -I/usr/include/python2.4/ -lpython2.4 -o foo foo.c Shuaib wrote: > Hey! > > I am trying to embedd python into a C programe of mine. But when I try > to compile the C code, gcc gives errors like "undefined reference to > `Py_Finalize'" and the same kind for all the other functions. I have > incuded "Python.h". > > Any idea what might be wrong? > > Thanks. From fredrik at pythonware.com Sun Aug 27 06:08:37 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 27 Aug 2006 12:08:37 +0200 Subject: marshal and unmarshal In-Reply-To: <7W%Hg.3545$k%3.270@newsfe12.lga> References: <7W%Hg.3545$k%3.270@newsfe12.lga> Message-ID: <ecrqv4$jg0$1@sea.gmane.org> leo wrote: > 'c\x00\x00\x00\x00\x01\x00... > ---------------------------------------------------- > <code object ? at 0x81690c0, file "<strng>", line 2> > > Question: > 1. why unmarshal data is > <code object ? at 0x81690c0, file "<strng>", line 2> because that's what compile returns, of course. marshal.dumps takes a Python object and turns it into a string; marshal.loads takes such a string and turns it into a Python object. > 2. how safe is the compiled and serialize data. define "safe". </F> From johnjsal at NOSPAMgmail.com Tue Aug 8 13:03:21 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 08 Aug 2006 17:03:21 GMT Subject: using python at the bash shell? In-Reply-To: <1155054162.683298.21760@m73g2000cwd.googlegroups.com> References: <44d7e364$0$24980$c3e8da3@news.astraweb.com> <mailman.9071.1155002101.27775.python-list@python.org> <R31Cg.2645$No6.51906@news.tufts.edu> <1155054162.683298.21760@m73g2000cwd.googlegroups.com> Message-ID: <tt3Cg.2656$No6.51953@news.tufts.edu> Simon Forman wrote: > "normal bash things"? :-) forgive my ignorance, i just installed linux on saturday! :) From danielwong at berkeley.edu Mon Aug 14 17:40:06 2006 From: danielwong at berkeley.edu (danielx) Date: 14 Aug 2006 14:40:06 -0700 Subject: selecting base class from user input In-Reply-To: <ebqcdf$61i$1@skeeter.ucdavis.edu> References: <ebo1v5$jos$1@skeeter.ucdavis.edu> <1155523781.860117.203140@h48g2000cwc.googlegroups.com> <ebp90n$sh6$1@skeeter.ucdavis.edu> <mailman.9295.1155543976.27775.python-list@python.org> <ebqcdf$61i$1@skeeter.ucdavis.edu> Message-ID: <1155591606.459214.150650@i42g2000cwa.googlegroups.com> Jackson wrote: > Maric Michaud wrote the following on 2006-08-14 01:26: > > In [28]: class Animal(object) : > > ....: _types = {} > > ....: > > ....: > > > > In [29]: class Worker(object) : > > ....: def work(self) : print 'hard' > > ....: > > ....: > > > [snip] > > What you are trying to achieve is more commonly done by agregation and > > delegation : > > > > In [47]: class Lion(Animal) : > > ....: def __init__(self, *classes) : > > ....: self._objects = tuple(c() for c in classes) > > ....: def isA(self, class_) : > > ....: return class_ in (type(o) for o in self._objects) > > ....: def __getattr__(self, name) : > > ....: for obj in self._objects : > > ....: try: return getattr(obj, name) > > ....: except: pass > > ....: raise AttributeError('not defined or found in objects "%s"' % > > name) > > ....: > > ....: > > > > In [48]: Lion().work() > > --------------------------------------------------------------------------- > > exceptions.AttributeError Traceback (most recent > > call last) > > > > /home/maric/<ipython console> > > > > /home/maric/<ipython console> in __getattr__(self, name) > > > > AttributeError: not defined or found in objects "work" > > > > In [49]: Lion().isA(Worker) > > Out[49]: False > > > > In [50]: Lion(Worker).isA(Worker) > > Out[50]: True > > > > In [51]: Lion(Worker).work() > > hard > > > > This is exactly what I am looking for. However, I am not sure how to > implement different Worker methods. For example, a Lion might work > differently than an Bee. In my example, the Lion would take a cat-nap > while the Bee might do a dance. > > It seems that I would need to what kind of class called the work() > method. Is there a way to do that? If all of your animals are supposed to be workers, maybe you should declare your animal classes like this: class Lion(Animal, Worker): def work(self): pass Your Worker class might not have a work method (or it might have one which does no work, pun intended), even though the methods it does have depend on an instance being able to respond to a work call. Then, the Worker class is like an "abstract" class in Java (cross yourselves). This is an example of "delegation" which someone here has already mentioned. In that case, users will most likely never instantiate Worker, but none of the Worker code needs to be replicated, because Lion (or whatever) is a subclass of Worker. This is one of the "benefits" of OOP :P. > > Even if I could do that, it seems these various definitions of work > should probably go into the class of the animal---so that Lion actions > are all within the Lion class. Thus, the Lion class should have its own > work method, and the Bee class should have its own work method as well. > The problem with this is that every Lion can use the work method, when > I really only work Workers to use the work method. > > I can picture another way of achieving this...have a list of > occupations...which are booleans for each instance of the class. Then > the work() method will call only if the Worker boolean is True. This > should be sufficient...and the differing work methods would be in their > respective classes. However, now the actual method names are not > uniform---that is, it becomes a bookkeeping exercise to remember that > when Worker is True, then the method to create is work(), that when > Student is True, then the method to create is study(). So this > procedure has its own problems too. It seems like I am trading off > hardships now. > > So here is what I am looking for: > > A single Worker class with a standardized set of method names. The In Java (cross-ing ritual), you would create an interface, which requires a work method. But this is Python :P. We just don't do that. Search the following page for "easier to ask for forgiveness" and "look before you leap" on this page (the glossary of Guido's Python tutorial): http://docs.python.org/tut/node18.html > methods in the Worker class are dependent on the "superclass" (via > aggregation and delegation, as shown above) of the worker. That is, a > Bee performs different actions when working than a Lion or a Human. And > finally, the occupations such that "not every Bee is a worker" and > "there are some Workers which are Bees". > > Thanks! From fredrik at pythonware.com Thu Aug 31 03:02:40 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 31 Aug 2006 09:02:40 +0200 Subject: Possible problem in compiler/transformer.py of Python2.4... In-Reply-To: <1157001516.911682.207060@p79g2000cwp.googlegroups.com> References: <1157001516.911682.207060@p79g2000cwp.googlegroups.com> Message-ID: <ed61ig$9el$1@sea.gmane.org> venkatbo at yahoo.com wrote: > What is surprising is I checkd the entire py2.4 distribution and I > can't see a symbol.py (or a module with symbol defined) where > transformer.py could import the symbol module form. All I can see > is: > ...../lib/python2.4/compiler/symbols.py > in the same directory as that of transformer.py (in compiler). > > Has anyone seen this error, or have any pointers to solve the problem. looks like your installation is botched. > dir \python24\lib\compiler\symbols.py 2005-10-28 20:15 15 059 symbols.py $ cd /usr/local/lib/python2.4/compiler $ ls -l symbols.py -rw-r--r-- 1 root root 14591 Aug 11 2005 symbols.py (the former is 2.4.3 on windows, the latter 2.4.1 on unix) </F> From bj_666 at gmx.net Thu Aug 24 16:08:59 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 24 Aug 2006 22:08:59 +0200 Subject: Is this a good idea or a waste of time? References: <1156449402.022781.292840@p79g2000cwp.googlegroups.com> Message-ID: <pan.2006.08.24.20.08.58.321086@gmx.net> In <1156449402.022781.292840 at p79g2000cwp.googlegroups.com>, asincero wrote: > def foo(a, b, c, d): > assert type(a) == str > assert type(b) == str > assert type(c) == int > assert type(d) == bool > # rest of function follows > > This is something I miss from working with more stricter languages like > C++, where the compiler will tell you if a parameter is the wrong type. > If anything, I think it goes a long way towards the code being more > self documenting. Or is this a waste of time and not really "the > Python way"? Not really the Python way I'd say. What if `c` is of type `long` for instance? Your code would stop with an assertion error for a value that should work. Strict type checking prevents "duck typing" which is a quite fundamental concept in Python. Ciao, Marc 'BlackJack' Rintsch From rogue_pedro at yahoo.com Sun Aug 13 11:51:41 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 13 Aug 2006 08:51:41 -0700 Subject: reading from sockets In-Reply-To: <1155479587.521795.307670@m73g2000cwd.googlegroups.com> References: <1155227695.625250.17920@m73g2000cwd.googlegroups.com> <TFQCg.103113$hp.69833@read2.cgocable.net> <1155387684.513673.130770@75g2000cwc.googlegroups.com> <1155404471.418202.252850@75g2000cwc.googlegroups.com> <1155479587.521795.307670@m73g2000cwd.googlegroups.com> Message-ID: <1155484301.249872.300450@b28g2000cwb.googlegroups.com> AndrewTK wrote: > Simon Forman wrote: > > So I'm guessing it's something wrong in your java server. > > Thanks then. I'll keep testing then... Although I don't seem to have > netcat on my unit... > > I'm using a uni computer so I can't install stuff... but I'm guessing > what I wrote is something like a basic-basic thingy that does what > netcat is designed to do.....? First link from googling netcat: http://netcat.sourceforge.net/ Online man page for netcat (a.k.a. nc) http://www.openbsd.org/cgi-bin/man.cgi?query=nc (Note, it's the openbsd man page. YMMV) If you can compile C on your university computer then you should be able to download, compile, and "install" it to a dir in your homedir. I've done it, so I know it's possible. :-) (I was working on a remote machine that I didn't have root on, and I needed to test a tcp server I was writing.) Netcat's a truly awesome and surprisingly useful little tool. Any effort you spend to learn it will be well repaid. Peace, ~Simon From mturillo at gmail.com Mon Aug 21 11:03:29 2006 From: mturillo at gmail.com (Perseo) Date: 21 Aug 2006 08:03:29 -0700 Subject: Create a Multilanguage PDF in Python In-Reply-To: <1156143575.547217.237270@p79g2000cwp.googlegroups.com> References: <1156073383.983914.149180@i3g2000cwc.googlegroups.com> <87mz9z4f8h.fsf@smsnet.pl> <1156108451.762961.70140@h48g2000cwc.googlegroups.com> <1156143575.547217.237270@p79g2000cwp.googlegroups.com> Message-ID: <1156172609.125230.218190@i42g2000cwa.googlegroups.com> I can't upload in the PYTHONPATH but in a normal folder of our site. Exist another way to do it? Thanks Rob Wolfe wrote: > Perseo wrote: > > Hi again, > > > > WORKS!!! I download all I need as python + reportlab. Only 2 questions: > > > > 1. I need all of this package? because it is 6Mb! > > I'm afraid you need all of it. > BTW My reportlab package is only 3MB... hmm strange. > > > 2. How can I connect my software with MySql. In my Hosting is present > > the Python support but I don't thing that the MySQLdb is present. How > > can I solve this little problem? > > You can install MySQLdb wherever you want. You need only to make > sure the module is in your PYTHONPATH. > > HTH, > Rob From originalbrownster at gmail.com Sat Aug 19 17:30:13 2006 From: originalbrownster at gmail.com (OriginalBrownster) Date: 19 Aug 2006 14:30:13 -0700 Subject: trouble using "\" as a string Message-ID: <1156023013.462640.165970@i42g2000cwa.googlegroups.com> Hi there... I'm still pretty new to turbogears. but i have gotten pretty familiar with it i'm just trying to clear something up, i'm having a difficult time using \ when declaring a string expression such as tempname="\"..it says that the line is single qouted. i want this because using python I am pulling in filenames from a mac..thus they are "/" in the pathways..and i want to .split it at the "/" to obtain the filename at the end...but its proving diffucult with this obstacle in the way. Why is this happening?? From python.list at tim.thechases.com Thu Aug 10 15:05:14 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 10 Aug 2006 14:05:14 -0500 Subject: easy string formating question In-Reply-To: <1155235180.871436.22480@75g2000cwc.googlegroups.com> References: <1155235180.871436.22480@75g2000cwc.googlegroups.com> Message-ID: <44DB836A.3020002@tim.thechases.com> > I have kind of an interesting string, it looks like a couple hundred > letters bunched together with no spaces. Anyway, i'm trying to put a > "?" and a (\n) newline after every 100th character of the string and > then write that string to a file. How would I go about doing that? Any > help would be much appreciated. >>> s = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' >>> size = 10 >>> print '?\n'.join([s[i:i+size] for i in xrange(0, len(s)+1, size)]) 1234567890? abcdefghij? klmnopqrst? uvwxyzABCD? EFGHIJKLMN? OPQRSTUVWX? YZ Just adjust "size" to 100 rather than 10. It may be a bit brute-force-ish, and there may be other more elegant ways that I don't know, but that list comprehension extracts pieces of "s" of size "size" and creates a list where each piece doesn't excede "size" characters. The join() then just smashes them all together, joined with your requested "quotation-mark followed by newline" And for the regexp-junkies in the crowd, you can use >>> import re >>> r = re.compile("(.{%i})" % size) >>> print r.sub(r"\1?\n", s) 1234567890? abcdefghij? klmnopqrst? uvwxyzABCD? EFGHIJKLMN? OPQRSTUVWX? YZ I'm sure there are plenty of other ways to do it. :) -tkc From ajaksu at gmail.com Thu Aug 17 08:45:39 2006 From: ajaksu at gmail.com (ajaksu) Date: 17 Aug 2006 05:45:39 -0700 Subject: Compiling wxPython app for Windows; Single EXE References: <g21vd2ps3nedou94o7fbgdv52t5k4l9pb6@4ax.com> <1155573542.310208.43190@i3g2000cwc.googlegroups.com> <1155649590.275349.245200@p79g2000cwp.googlegroups.com> Message-ID: <1155818739.177510.145310@h48g2000cwc.googlegroups.com> GHUM wrote: > and with py2exe: > Changes in 0.6.1: > > * py2exe can now bundle binary extensions and dlls into the > library-archive or the executable itself. This allows to > finally build real single-file executables. > > The bundled dlls and pyds are loaded at runtime by some special > code that emulates the Windows LoadLibrary function - they are > never unpacked to the file system. > > this "they are never unpacked to the file system" is the USP of py2exe > to me at the moment. Thank you very much, Harald, this is very important. As I mentioned, PyInstaller single file has a bad start up time... your information is enough for me to dive in py2exe for good :) Biased or not, you may have performed one more conversion ;) Daniel From pobrien at orbtech.com Tue Aug 15 10:10:27 2006 From: pobrien at orbtech.com (Pat) Date: 15 Aug 2006 07:10:27 -0700 Subject: pycrust xmlrpclib problem References: <gAvBg.319$dQ4.201@bignews1.bellsouth.net> Message-ID: <1155651027.382659.33480@75g2000cwc.googlegroups.com> Timothy Gee wrote: > Have do a lot of lab work making use of xmlrpclib and am quite > dependent on it. I just started working with pycrust under Linux RH9, > and wanted to use it as my standard python environment, however, when I > import xmlrpclib, I get a segmentation fault. Command line still works > fine however. Details for pycrust are: > PyCrust 0.9.5 > > Yet another Python shell, only flakier. > > Half-baked by Patrick K. O'Brien, > the other half is still in the oven. > > Shell Revision: 1.9.2.10 > Interpreter Revision: 1.6.2.1 > > Platform: linux2 > Python Version: 2.4.1 > wxPython Version: 2.6.3.3 > (wxGTK, unicode, gtk2, wx-assertions-on, SWIG-1.3.27) > Linux Info: > Linux rtphostb06 2.4.20-18.9 #1 Thu May 29 07:08:16 EDT 2003 i686 i686 > i386 GNU/Linux > > Anyone had a similar problem? Any workarounds? > -Tim- It works fine for me on Windows XP with wxPython 2.6.2.1, so you may want to report this on the wxPython mailing list and see if anyone else has the same problem. Unless you've already done that. I haven't been actively involved with wxPython in some time. -- Patrick K. O'Brien Orbtech http://www.orbtech.com Schevo http://www.schevo.org Louie http://www.pylouie.org From bill.pursell at gmail.com Sat Aug 5 05:55:03 2006 From: bill.pursell at gmail.com (Bill Pursell) Date: 5 Aug 2006 02:55:03 -0700 Subject: Nested function scope problem References: <mailman.8523.1153834254.27775.python-list@python.org> <44c6444c$0$30849$626a54ce@news.free.fr> <1153965046.805129.44350@75g2000cwc.googlegroups.com> <44c8b4a9$0$6740$636a55ce@news.free.fr> <slrnechicn.iu.apardon@rcpc42.vub.ac.be> <44c8d59a$0$31797$626a54ce@news.free.fr> <slrnechoqg.qq.apardon@rcpc42.vub.ac.be> <44c8eb5e$0$21632$626a54ce@news.free.fr> <slrneci0b1.14s.apardon@rcpc42.vub.ac.be> <mq4jc2topbu781vcdtaeog4it914r8hr57@4ax.com> <slrnecklc4.5a7.apardon@rcpc42.vub.ac.be> <mailman.8675.1154112875.27775.python-list@python.org> <slrnecn499.98c.apardon@rcpc42.vub.ac.be> <mailman.8703.1154198214.27775.python-list@python.org> <slrnecpavl.c6f.apardon@rcpc42.vub.ac.be> <mailman.8711.1154269113.27775.python-list@python.org> <1154400727.472816.243290@b28g2000cwb.googlegroups.com> <mailman.8800.1154441595.27775.python-list@python.org> Message-ID: <1154771703.272988.211290@m79g2000cwm.googlegroups.com> Gerhard Fiedler wrote: >There's no Python equivalent to "int*p=345; *p++;". Sure there is: os.kill(os.getpid(), signal.SIGSEGV) :) From rob at digital-crocus.com Thu Aug 10 06:07:12 2006 From: rob at digital-crocus.com (Robin Haswell) Date: Thu, 10 Aug 2006 11:07:12 +0100 Subject: why does getpass() show the input? References: <KMrCg.2664$No6.52070@news.tufts.edu> <pan.2006.08.10.09.24.21.415086@digital-crocus.com> <1155202742.056728.191680@q16g2000cwq.googlegroups.com> Message-ID: <pan.2006.08.10.10.07.12.895741@digital-crocus.com> > Please look again at the OP's post. Here is the relevant part, with my > annotations: You're right, my bad. It's still first thing in the morning here :'( -Rob From meyer at acm.org Sat Aug 26 11:49:13 2006 From: meyer at acm.org (Andre Meyer) Date: Sat, 26 Aug 2006 17:49:13 +0200 Subject: Learning Python In-Reply-To: <44f03c80$0$75042$14726298@news.sunsite.dk> References: <44f03c80$0$75042$14726298@news.sunsite.dk> Message-ID: <7008329d0608260849k1656cb6au68e3a22182325795@mail.gmail.com> http://www.python.org/download/releases/2.4/bugs/ - IDLE now executes code in a separate process. To communicate between the main process and executing processes, IDLE opens a socket to 127.0.0.1 (the local machine). Some firewalls running on Windows machines interfere with this and can cause either silent failures or erroneous popup windows from the firewall. This problem only occurs if you run a firewall on the same machine as IDLE. hth Andre -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060826/229170f0/attachment.html> From rxrx at yamama.com Tue Aug 29 23:46:58 2006 From: rxrx at yamama.com (Butternut Squash) Date: Wed, 30 Aug 2006 03:46:58 GMT Subject: block a network port References: <1156879445.723089.126630@m73g2000cwd.googlegroups.com> <JvWdneceyYX4KGnZnZ2dnUVZ_tednZ2d@comcast.com> <1156907536.509187.32300@m73g2000cwd.googlegroups.com> Message-ID: <SS7Jg.7581$5i3.333@bgtnsc04-news.ops.worldnet.att.net> abcd wrote: > Larry Bates wrote: >> This is not really a Python question. Blocking ports is a function >> of your firewall solution. >> > > > ok, no of any python solutions? or command-line firewalls? So now you're question is how to write a firewall in python? You can probably bind to all the ports and not open up any connections. That would keep something else from using the port. Simple but effective. Firewall software is a much better solution, though Good luck. From steve at holdenweb.com Wed Aug 16 09:08:37 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 16 Aug 2006 14:08:37 +0100 Subject: Current module reference In-Reply-To: <52655700608160529g31327e73na9474fe039aadeec@mail.gmail.com> References: <52655700608160529g31327e73na9474fe039aadeec@mail.gmail.com> Message-ID: <ebv5bt$jvl$1@sea.gmane.org> Miguel Galves wrote: > Hi > > How do I get a reference for the current module I'm in ? > I have a package called services with a __init__.py > that need to use getattr() to fill out a hash whith > my package attributes. But to use getattr, I need > a object that references my package (kind of this this reference in Java). > How can I do it ? > > the only way I found to o this is to call get attr from another > module that imports the services package. But I suppose > it's not the only way.... > sys.modules[__name__] ? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From gmt at sdf-eu.org Wed Aug 16 17:14:36 2006 From: gmt at sdf-eu.org (Max Yuzhakov) Date: Wed, 16 Aug 2006 21:14:36 +0000 (UTC) Subject: It is __del__ calling twice for some instances? References: <ebvnod$mp7$1@pandora.alkar.net> <Xns9821CFF0D1C70duncanbooth@127.0.0.1> Message-ID: <ec01rs$2bus$1@pandora.alkar.net> Duncan Booth ?????: DB> Not with the code which you gave as an example, but in the general case DB> yes, the only guarantee that Python gives about the __del__ method on an DB> instance is that it will be called zero, one or more than one times during DB> the run of the program. In practice there are various situations where DB> __del__ will not be called, but it is only called multiple times if you DB> resurrect the object during a call to __del__. No, only presented code in __del__ do increment of global variable del_cnt. DB> The output from your stat function could, of course, also be generated by DB> creating and destroying lots of foo objects in another thread. If a foo was DB> both created and destroyed between the first two print statements, and DB> another one was created and destroyed in the middle of the evaluation of DB> the last print statement then you could see the output you described DB> without any multiple __del__ calls in the same object. No, it's a single-threaded code. DB> You should post a working code sample which generates your output if you DB> want a more useful answer. I'm sorry for mess with a code. I have forgotten to write, that is only fragments for demonstration of essence of a question. Real code in this module has 880 lines and I shall not abuse your time. I shall try to solve a problem by debuger. And thank for Your answer! -- GMT More Then ... From mturillo at gmail.com Sun Aug 20 16:19:25 2006 From: mturillo at gmail.com (Perseo) Date: 20 Aug 2006 13:19:25 -0700 Subject: Create a Multilanguage PDF in Python In-Reply-To: <87mz9z4f8h.fsf@smsnet.pl> References: <1156073383.983914.149180@i3g2000cwc.googlegroups.com> <87mz9z4f8h.fsf@smsnet.pl> Message-ID: <1156105165.657363.110170@h48g2000cwc.googlegroups.com> Hi Rob, thank you for your answer, but I'm a newbie in Web application written in Python. Now I try your suggestion ... Thanks Perseo Rob Wolfe wrote: > "Perseo" <mturillo at gmail.com> writes: > > > Hi guys, > > > > I'm disprate with the Pdf Unicode. I try to create a class using ufpdf > > but some chars are not correct and now I would like try Python because > > a friend tolds me that it's very powerful. > > I need a simple script in Python that grab all Records from a MySql > > table and print in the pdf file. > > > > The languages stored in my db are about 25 and they are: > > Greek English French Hungarian Italian Lithuanian Dutch Portuguese > > Albanian > > Czech Danish German Spanish Estonian Finnish Irish Latvian Maltese > > Polish Romanian > > Russian Slovene Slovak Swedish > > You can give reportlab [1] a try. It has support for TrueType fonts > and unicode translation using UTF-8. I used to use it for pdf files > with polish chars. > > Some example code: > > <code> > from reportlab.pdfbase import pdfmetrics > from reportlab.pdfbase.ttfonts import TTFont > from reportlab.pdfgen import canvas > > pdfmetrics.registerFont(TTFont('Verdana', 'Verdana.ttf')) > c = canvas.Canvas("pl.pdf") > c.setFont("Verdana", 12) > c.drawString(100, 600, "Witaj, ?wiecie!".decode("iso-8859-2").encode("utf-8")) > c.showPage() > c.save() > </code> > > > [1] http://www.reportlab.org/ > > -- > HTH, > Rob From duncan.booth at invalid.invalid Thu Aug 31 03:20:13 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 31 Aug 2006 07:20:13 GMT Subject: Possible problem in compiler/transformer.py of Python2.4... References: <1157001516.911682.207060@p79g2000cwp.googlegroups.com> <mailman.10148.1157007786.27775.python-list@python.org> Message-ID: <Xns983054CC59DDEduncanbooth@127.0.0.1> Fredrik Lundh wrote: > venkatbo at yahoo.com wrote: > >> What is surprising is I checkd the entire py2.4 distribution and I >> can't see a symbol.py (or a module with symbol defined) where >> transformer.py could import the symbol module form. All I can see >> is: >> ...../lib/python2.4/compiler/symbols.py >> in the same directory as that of transformer.py (in compiler). >> >> Has anyone seen this error, or have any pointers to solve the problem. > > looks like your installation is botched. > > > dir \python24\lib\compiler\symbols.py > > 2005-10-28 20:15 15 059 symbols.py > > $ cd /usr/local/lib/python2.4/compiler > $ ls -l symbols.py > -rw-r--r-- 1 root root 14591 Aug 11 2005 symbols.py > > (the former is 2.4.3 on windows, the latter 2.4.1 on unix) > What has listing symbols.py got to do with this? He said he has symbols.py. What is missing is symbol.py which should be in the main lib folder, not the compiler package. e.g. Directory of C:\Python24\Lib 02/09/2004 11:54 2,043 symbol.py 1 File(s) 2,043 bytes But yes, the conclusion is that his installation is botched. From john106henry at hotmail.com Fri Aug 11 14:35:08 2006 From: john106henry at hotmail.com (John Henry) Date: 11 Aug 2006 11:35:08 -0700 Subject: What's the cleanest way to compare 2 dictionary? In-Reply-To: <pan.2006.08.11.17.51.01.818223@gmx.net> References: <1155147450.628625.20270@m79g2000cwm.googlegroups.com> <1155165349.766502.314760@n13g2000cwa.googlegroups.com> <1155240726.922672.279230@i3g2000cwc.googlegroups.com> <1155247703.127047.57670@m79g2000cwm.googlegroups.com> <1155318148.342951.12590@h48g2000cwc.googlegroups.com> <pan.2006.08.11.17.51.01.818223@gmx.net> Message-ID: <1155321308.036163.17920@m79g2000cwm.googlegroups.com> Thank you. That works. Marc 'BlackJack' Rintsch wrote: > In <1155318148.342951.12590 at h48g2000cwc.googlegroups.com>, John Henry > wrote: > > > When I do it under 2.3, I get: > > > > common_eq = set(k for k in _common if a[k] == b[k]) > > ^ > > SyntaxError: invalid syntax > > > > Don't know why that is. > > There are no generator expressions in 2.3. Turn it into a list > comprehension:: > > common_eq = set([k for k in _common if a[k] == b[k]]) > > Ciao, > Marc 'BlackJack' Rintsch From fredrik at pythonware.com Tue Aug 29 04:47:52 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 29 Aug 2006 10:47:52 +0200 Subject: unit test for a printing method References: <1156780399.289589.58750@m73g2000cwd.googlegroups.com><44f330ce$1@nntp0.pdx.net><mailman.9992.1156793468.27775.python-list@python.org> <1156831448.829576.140240@h48g2000cwc.googlegroups.com> Message-ID: <ed0uvo$uoe$1@sea.gmane.org> Marco Wahl wrote: > Fredrik Lundh <fredrik at pythonware.com> writes: >> >> Scott David Daniels wrote: >> >>> For silly module myprog.py: >>> def A(s): >>> print '---'+s+'---' >>> in test_myprog.py: >>> import unittest >>> from cStringIO import StringIO # or from StringIO ... >> >> why are you trying to reinvent doctest ? > > The OP asked for unit test. This could be read that > the OP wants to use module unittest. http://docs.python.org/lib/doctest-unittest-api.html </F> From tal.no.no.spam at gmail.com Mon Aug 28 06:33:54 2006 From: tal.no.no.spam at gmail.com (Tal Einat) Date: 28 Aug 2006 03:33:54 -0700 Subject: Learning Python - Have Question. In-Reply-To: <AumIg.3983$ED.295@read2.cgocable.net> References: <8l2Ig.3933$ED.894@read2.cgocable.net> <1156626744.641752.281500@p79g2000cwp.googlegroups.com> <1156662608.080319.281310@74g2000cwt.googlegroups.com> <AumIg.3983$ED.295@read2.cgocable.net> Message-ID: <1156761234.776837.47990@h48g2000cwc.googlegroups.com> > Thank you for this. The most daunting task in learning Python, is learning > all of the modules and functions that are available. And there's a tonne > of them. :-) > Actually, much of this file-system related stuff really is badly spread out between many different modules (os, os.path, glob, fnmatch, shutil, stat), mostly for historical reasons. Consulting the docs often and viewing working code examples are a good way to learn how to effectively do these things with Python's current stdlib. Some discussion has been going on for several years now about joining all such functionality into one "path" module, by creating a standard Path object, and having all of this nicely Object-Oriented. Currently there is a PEP about this (see PEP 355), but with the release of Python 2.5 nearing this has been further delayed by the development community. PEP 355: http://www.python.org/dev/peps/pep-0355/ - Tal From skip at pobox.com Mon Aug 21 15:14:47 2006 From: skip at pobox.com (skip at pobox.com) Date: Mon, 21 Aug 2006 14:14:47 -0500 Subject: Mailman - Sendmail problem In-Reply-To: <1156185577.165019.305040@74g2000cwt.googlegroups.com> References: <1156185577.165019.305040@74g2000cwt.googlegroups.com> Message-ID: <17642.1575.165568.537830@montanaro.dyndns.org> >> I am trying to get Mailman to work on this server and so far, no luck. ... >> assert 0, 'Use of the Sendmail.py delivery module is highly >> discouraged' >> AssertionError: Use of the Sendmail.py delivery module is highly >> discouraged >> *** At the python level, assert 0 is going to fail. You can either hack the source to 'assert 1, ...' or, better yet, dig around and see if there's another delivery module that works with sendmail better than Sendmail.py. >> Thanks for any help you can give! One other thing... Have you posted your request to the mailman-users mailing list? <http://mail.python.org/mailman/listinfo/mailman-users> You're more likely to get a knowledgable Mailman-related answer from the folks who use Mailman daily. Skip From bearophileHUGS at lycos.com Thu Aug 10 07:32:24 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 10 Aug 2006 04:32:24 -0700 Subject: technique to enter text using a mobile phone keypad (T9 dictionary-based disambiguation) In-Reply-To: <ebe4f5$28b$1@news-int.gatech.edu> References: <mailman.9116.1155077147.27775.python-list@python.org> <1155095477.440347.149350@m79g2000cwm.googlegroups.com> <1155154447.409931.55750@p79g2000cwp.googlegroups.com> <1155156341.298792.188280@75g2000cwc.googlegroups.com> <1155164070.665244.193080@b28g2000cwb.googlegroups.com> <1155166420.058201.81630@n13g2000cwa.googlegroups.com> <1155167794.239636.202050@n13g2000cwa.googlegroups.com> <ebe4f5$28b$1@news-int.gatech.edu> Message-ID: <1155209544.783700.187100@i42g2000cwa.googlegroups.com> Yu-Xi Lim: Thank you for your comments, and sorry for my last cryptic answer. >I think Bearophile isn't refering to compression of the dictionary, but the predictive algorithms used by modern data compressors. However, I think he's over-complicating the issue. It is *not* a data compression problem, imho.< I agree that my solution is probably too much complex for most purposes (using a compressor simpler than PAQ is probably better for most of such purposes), but I think it is a data compression problem, because compressing data essentially means predicting the next bit, and this program has to predict what's the most probable letter that the user wanted to add. See Dasher too at the end of this post. >While predictive input is desired, the PAQ algorithm utilizes multiple "contexts" (the novel contribution of the paper mentioned below). This is intended for general purpose data compressors which work on a variety of data, such as uncompressed graphics and audio, text, or other binary data. There is however, only one context in this case.< PAQ8 manages many contexts. Some of them are fit for digital audio/images, or Jpeg, etc. Such contexts can be removed (disabled) from the PAQ source code, it's not difficult. But PAQ8 contains many (more than one) contexts just for textual data, and you can keep such contexts, because they improve text compression, so they improve the prediction. (Removing those contexts improves speed and even more it reduces memory used). For this program I think you can keep the following ones: Order n, Sparse, Text, Formatted text, Fixed record length, Context gap, Indirect. If you are short on memory you can probably remove some of them. If you use the keyboard to input specific kinds of data, you may add a context for them too. >A more advanced system (beyond regular T9 and comparable to Motorola's iTap) may consider the context of the word. So typing followed 2255#466 would make "call home" the most likely word.< A good compressor (a PPM can be okay too) can do this too, its contexts can be many chars long (but you need lot of memory, probably too much for a telephone of today). >https://www.cs.fit.edu/Projects/tech_reports/cs-2005-16.pdf Note that this document doesn't explain the new versions, that contain a new good idea. Code for the last version: http://cs.fit.edu/~mmahoney/compression/paq8h.zip You can be interested in a similar project, that uses a PPM: http://www.inference.phy.cam.ac.uk/djw30/dasher/ Using an instrumented PAQ this Dasher can be improved a little (speed of the algorithm isn't important, because you are compressing few bits/minute. The dictionaries created by the PAQ can be even frozen, in some cases, so they can be read from disk/flash at the start of the program. Bye, strong bear hugs, bearophile From ptmcg at austin.rr._bogus_.com Wed Aug 23 20:37:53 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 24 Aug 2006 00:37:53 GMT Subject: Regex help...pretty please? References: <1156358822.649578.126990@74g2000cwt.googlegroups.com> Message-ID: <Bx6Hg.27561$ph.25013@tornado.texas.rr.com> "MooMaster" <ntv1534 at gmail.com> wrote in message news:1156358822.649578.126990 at 74g2000cwt.googlegroups.com... > I'm trying to develop a little script that does some string > manipulation. I have some few hundred strings that currently look like > this: > > cond(a,b,c) > > and I want them to look like this: > > cond(c,a,b) <snip> Pyparsing makes this a fairly tractable problem. The hardest part is defining the valid contents of a relational and arithmetic expression, which may be found within the arguments of your cond(a,b,c) constructs. Not guaranteeing this 100%, but it did convert your pathologically nested example on the first try. -- Paul ---------- from pyparsing import * ident = ~Literal("cond") + Word(alphas) number = Combine(Optional("-") + Word(nums) + Optional("." + Word(nums))) arithExpr = Forward() funcCall = ident+"("+delimitedList(arithExpr)+")" operand = number | funcCall | ident binop = oneOf("+ - * /") arithExpr << ( ( operand + ZeroOrMore( binop + operand ) ) | ("(" + arithExpr + ")" ) ) relop = oneOf("< > == <= >= != <>") condDef = Forward() simpleCondExpr = arithExpr + ZeroOrMore( relop + arithExpr ) | condDef multCondExpr = simpleCondExpr + "*" + arithExpr condExpr = Forward() condExpr << ( simpleCondExpr | multCondExpr | "(" + condExpr + ")" ) def reorderArgs(t): return "cond(" + ",".join(["".join(t.arg3), "".join(t.arg1), "".join(t.arg2)]) + ")" condDef << ( Literal("cond") + "(" + Group(condExpr).setResultsName("arg1") + "," + Group(condExpr).setResultsName("arg2") + "," + Group(condExpr).setResultsName("arg3") + ")" ).setParseAction( reorderArgs ) tests = [ "cond(a,b,c)", "cond(1>2,b,c)", "cond(-1,1,f)*((float(e)*(2**4))+(float(d)*8)+(float(c)*4)+(float(b)*2)+floa t(a))", "cond(a,b,(abs(c) >= d))", "cond(0,cond(c,cond(e,cond(g,h,(a<f)),(a<d)),(a<b)),(a<1))", ] for t in tests: print t,"->",condExpr.transformString(t) ---------- Prints: cond(a,b,c) -> cond(c,a,b) cond(1>2,b,c) -> cond(c,1>2,b) cond(-1,1,f)*((float(e)*(2**4))+(float(d)*8)+(float(c)*4)+(float(b)*2)+float (a)) -> cond(f,-1,1)*((float(e)*(2**4))+(float(d)*8)+(float(c)*4)+(float(b)*2)+float (a)) cond(a,b,(abs(c) >= d)) -> cond((abs(c)>=d),a,b) cond(0,cond(c,cond(e,cond(g,h,(a<f)),(a<d)),(a<b)),(a<1)) -> cond((a<1),0,cond((a<b),c,cond((a<d),e,cond((a<f),g,h)))) From skip at pobox.com Wed Aug 30 10:08:23 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 30 Aug 2006 09:08:23 -0500 Subject: How ahead are you guys in the (Python) real world? In-Reply-To: <XGgJg.2715$No6.53253@news.tufts.edu> References: <1156821234.820929.299740@p79g2000cwp.googlegroups.com> <XGgJg.2715$No6.53253@news.tufts.edu> Message-ID: <17653.39895.25642.257929@montanaro.dyndns.org> John> Interesting question. Just as a curious follow-up (not being John> someone who works in the programming world), why does it take so John> long to move to the latest version, especially when there aren't John> (I don't think) any changes that would break existing code, such John> as moving to Python 2.4 from 2.2 or 2.3? There are often lots of binary interdependencies between the Python version and internal or external packages. For instance, all the database adaptors I'm aware of for SQL-based databases have extension modules written in C. Then consider GUI stuff (PyGtk, wxPython, etc), scientific (SciPy, Numeric, VTK, ...). The list can be nearly endless. At work we have lots of in-house C++ libraries, many of which have been exposed to Python programmers via SWIG or Boost.Python. All that stuff at minimum needs to be recompiled with the new version of Python's header files (which can and do change between versions). Then you have to test it. While it's true that there are generally no semantic or syntactic differences between versions and for the most part the developers try hard not to break things, differences do creep into the Python level and can be subtle to discover. In short, it takes a fair amount of work to move from one version to another. Skip From xi at gamma.dn.ua Tue Aug 1 08:22:51 2006 From: xi at gamma.dn.ua (Kirill Simonov) Date: Tue, 1 Aug 2006 15:22:51 +0300 Subject: [ANN] LibYAML-0.0.1: The initial release Message-ID: <20060801122251.GA2664@58sirius016.dc.ukrtel.net> I'd like to announce the initial release of LibYAML, a YAML parser and emitter library written in C. LibYAML homepage: http://pyyaml.org/wiki/LibYAML TAR.GZ package: http://pyyaml.org/download/libyaml/yaml-0.0.1.tar.gz SVN repository: http://svn.pyyaml.org/libyaml Bug tracker: http://pyyaml.org/newticket?component=libyaml The library is functionally complete, but the documentation is scarce and the API is subject to change. For more information, you may check the project homepage, the doxygen-generated documentation in the `doc` directory of the source distribution, and the examples `tests/example-reformatter.c` and `tests/example-deconstructor.c`. There are preliminary Python bindings for LibYAML in the PyYAML SVN repository. LibYAML is written by Kirill Simonov <xi at resolvent.net>. It is released under the MIT license. See the file LICENSE for more details. This project is developed for Python Software Foundation as a part of the Google Summer of Code program under the mentorship of Clark C. Evans. From Bulkan at gmail.com Sat Aug 12 09:29:31 2006 From: Bulkan at gmail.com (placid) Date: 12 Aug 2006 06:29:31 -0700 Subject: ANN: PyPsp 0.1 Message-ID: <1155389371.353294.7240@p79g2000cwp.googlegroups.com> First version of PyPsp is released. I have done limited testing as i have limited free time to devote to this project, but im doing my best. There are a three external modules that you need to download see the README file for additional information. Summary Playstation Portable(PSP) Video Manager written in Python. It will use ffmpeg to do the conversion of video files. So basically it is a framework around ffmpeg.It will provide better filename tracking on both the PSP and the hard drive for firmware<=2.71 Getting It: http://sourceforge.net/projects/pypsp Ideas, tips welcome! Cheers From squall_leonheart7 at netzero.net Wed Aug 30 12:57:53 2006 From: squall_leonheart7 at netzero.net (squall_leonheart7 at netzero.net) Date: Wed, 30 Aug 2006 16:57:53 GMT Subject: active python windows Message-ID: <20060830.095840.10554.687271@webmail18.nyc.untd.com> An embedded and charset-unspecified text was scrubbed... Name: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20060830/f959b920/attachment.ksh> From furbybrain at blueyonder.co.uk Mon Aug 28 14:44:00 2006 From: furbybrain at blueyonder.co.uk (Furbybrain) Date: Mon, 28 Aug 2006 18:44:00 GMT Subject: IDLE on Mac OS X In-Reply-To: <MbnIg.65514$fV1.23660@fe1.news.blueyonder.co.uk> References: <MbnIg.65514$fV1.23660@fe1.news.blueyonder.co.uk> Message-ID: <QPGIg.180454$9d4.7339@fe2.news.blueyonder.co.uk> Furbybrain wrote: > I'm running 10.3.9 and I've just installed Python 2.4. IDLE won't start- > it bounces in the dock once or twice then goes away. > I'm new to Python, and I'm trying to learn. Thanks. ** IDLE can't import Tkinter. Your Python may not be configured for Tk. ** I'm installing TK like Kevin said. Thanks! From stk at mevis.de Wed Aug 9 04:09:52 2006 From: stk at mevis.de (Stephan Kuhagen) Date: Wed, 09 Aug 2006 10:09:52 +0200 Subject: #!/usr/bin/python or #!/usr/bin/env python? References: <fj5Cg.2658$No6.51984@news.tufts.edu> <bL6dnTXbq9adbkXZnZ2dnUVZ_u2dnZ2d@speakeasy.net> <ebbtor$evr$1@kohl.informatik.uni-bremen.de> <mailman.9130.1155106885.27775.python-list@python.org> <ebc288$g8s$1@kohl.informatik.uni-bremen.de> <vsgCg.66818$zy5.1253926@twister1.libero.it> Message-ID: <ebc58g$h22$1@kohl.informatik.uni-bremen.de> ZeD wrote: > print "Hello, world" > $ file test.py > test.py: Bourne shell script text executable Yes, the same happens with all Tcl-Scripts. I like to see this as a bug in "file", not in the scripting... Stephan From bobrien18 at yahoo.com Tue Aug 22 14:49:56 2006 From: bobrien18 at yahoo.com (KraftDiner) Date: 22 Aug 2006 11:49:56 -0700 Subject: key not found in dictionary Message-ID: <1156272596.613723.219280@h48g2000cwc.googlegroups.com> I have a dictionary and sometime the lookup fails... it seems to raise an exception when this happens. What should I do to fix/catch this problem? desc = self.numericDict[k][2] KeyError: 589824 <---- This is the error that is being produced, because there is no key 589824. From rogue_pedro at yahoo.com Tue Aug 15 20:21:06 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 15 Aug 2006 17:21:06 -0700 Subject: yEnc In-Reply-To: <597dc$44e21e10$5497e66d$9926@nf4.news-service.com> References: <597dc$44e21e10$5497e66d$9926@nf4.news-service.com> Message-ID: <1155687666.852270.35080@h48g2000cwc.googlegroups.com> Kairo Matthias wrote: > How can i encode with yEnc? What's yEnc? :-) Seriously though, did you try googling for "yEnc python"? Peace, ~Simon From resnak at mail.com Sun Aug 20 13:25:00 2006 From: resnak at mail.com (resnak) Date: Sun, 20 Aug 2006 12:25:00 -0500 Subject: import References: <1156093283.529579.80600@i42g2000cwa.googlegroups.com> <1156093799.775420.51970@m73g2000cwd.googlegroups.com> <1156094307.576025.3430@i3g2000cwc.googlegroups.com> Message-ID: <part1of1.1.G6okm328plyBkg@ue.ph> Try putting it in C:\Python24\Lib\site-packages instead. figo_wei01 at 126.com wrote: >bugnthecode ????????? > >> How are you trying to import it? Is it in the same directory as your >> other script? If not is your python path set correctly? >> >> When importing a module that you have written you exlude the .py >> extension. You should be using: >> import hello >> >> Hope that helps, >> Will > >i am on a windows platform. i have written scrip named 123.py. it can >be run. ok i save it to C:\Python24 ,exactly the same dir where python >works. but " import 123" doesnt work. From hitesh287 at gmail.com Wed Aug 16 10:15:00 2006 From: hitesh287 at gmail.com (Hitesh) Date: 16 Aug 2006 07:15:00 -0700 Subject: Adding a char inside path string Message-ID: <1155737700.290268.248250@i42g2000cwa.googlegroups.com> Hi, I get path strings from a DB like: \\serverName\C:\FolderName1\FolderName2\example.exe I am writing a script that can give me access to that exe file. But problem is that string is not universal path, I need to add C$. Any idea how I can add $ char in that string. ServerName is not fixed length. It could be any chars length. Thank you, hj From aries.shuaib at gmail.com Sat Aug 19 16:34:08 2006 From: aries.shuaib at gmail.com (Shuaib) Date: 19 Aug 2006 13:34:08 -0700 Subject: Embedding python: Segmentation Fault Message-ID: <1156019648.777923.194830@i42g2000cwa.googlegroups.com> Hi! I am trying to embed python into a C programe of mine. When the execution reaches the following line pModule = PyImport_Import(pName); It causes a Segmentation Fault Error. pModule is of type PyObject *, so is pName. What could be the possible reasons for the error? Thanks for your time. From eternalsquire at comcast.net Sun Aug 6 16:50:22 2006 From: eternalsquire at comcast.net (The Eternal Squire) Date: 6 Aug 2006 13:50:22 -0700 Subject: where can I find Python acceptance test suite? Message-ID: <1154897422.081562.80780@n13g2000cwa.googlegroups.com> All, I've been doing some hacking of the Python engine, and I've been looking for where the comprehensive regression tests are kept so that I can determine where I've broken part of the engine. Thanks in advance, The Eternal Squire From zero.maximum at gmail.com Tue Aug 29 20:55:13 2006 From: zero.maximum at gmail.com (zero.maximum at gmail.com) Date: 29 Aug 2006 17:55:13 -0700 Subject: Variables in nested functions Message-ID: <1156899313.019757.285060@b28g2000cwb.googlegroups.com> Is it possible to change the value of a variable in the outer function if you are in a nested inner function? For example: def outer(): a = "outer" def inner(): print a a = "inner" # I'm trying to change the outer 'a' here, # but this statement causes Python to # produce an UnboundLocalError. return inner What I'm trying to do here is to get the following output from these lines of code? # Code: func = outer() func() func() func() # Output: outer inner inner From jon+usenet at unequivocal.co.uk Thu Aug 10 06:39:26 2006 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 10 Aug 2006 10:39:26 GMT Subject: IP address References: <1155194251.196501.277470@m79g2000cwm.googlegroups.com> <slrnedlran.n2b.sybrenUSE@schuimige.stuvel.eu> <1155206207.759038.38720@m79g2000cwm.googlegroups.com> Message-ID: <slrnedm36u.n99.jon+usenet@snowy.squish.net> In article <1155206207.759038.38720 at m79g2000cwm.googlegroups.com>, Lad wrote: > I have a website written in Python and I would like to login every > visitor's IP address. > In other words, if a visitor come to my Python application, this > application will record his IP. Depending on what CGI framework you're using, something like: os.environ["REMOTE_ADDR"] From pmartin at snakecard.com Sun Aug 6 13:51:47 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Sun, 06 Aug 2006 12:51:47 -0500 Subject: why did wxpython MakeActiveXclass stopped working?!?!!?!? References: <1154884250.224877.229650@p79g2000cwp.googlegroups.com> Message-ID: <o2qBg.12234$W93.8871@dukeread05> jojoba wrote: > HI > I wrote a little wxpython program with an embedded windows media > player. > It worked great. Recently, I reinstalled windows and then wxpython > (most likely a newer version than i had before). Now when i run the > exact same code, i get this error: > > File "C:\Documents and > Settings\jojoba.DEMO-019591FB22\Desktop\Projects\SrAsse > ts\sr.py", line 353, in __init__ > self.CreateActiveXplayer() > File "C:\Documents and > Settings\jojoba.DEMO-019591FB22\Desktop\Projects\SrAsse > ts\sr.py", line 363, in CreateActiveXplayer > self.Player = PlayerActiveXClass(self, -1) > File > "C:\Python24\Lib\site-packages\wx-2.6-msw-ansi\wx\lib\activexwrapper.py", > line 108, in axw__init__ > (0, 0, sz.width, sz.height), self._wnd, ID) > File "C:\Python24\Lib\site-packages\pythonwin\pywin\mfc\activex.py", > line 23, > in CreateControl > self.__dict__["_obj_"] = win32ui.CreateControl(clsid, windowTitle, > style, re > ct, parent, id, None, False, lic_string) > win32ui: The window can not be created as it has an invalid handle > > > Here is a snippet from my code: > > from wxPython.lib.activexwrapper import MakeActiveXClass > import win32com > from win32com import client > > class wxWMPlayer(wxPanel): > def __init__(self, parent): > wxPanel.__init__(self, parent, -1, > style=wxCLIP_CHILDREN|wxNO_FULL_REPAINT_ON_RESIZE) > self.MixMaster = parent > self.ID3data = {} > self.InitWindowProperties() > self.CreateActiveXplayer() > > def InitWindowProperties(self): > self.WindowsMediaPlayerTopSizer = wxBoxSizer(wxVERTICAL) > self.SetSizer(self.WindowsMediaPlayerTopSizer) > self.SetAutoLayout(1) > > def CreateActiveXplayer(self): > PlayerModule = > win32com.client.gencache.EnsureModule('{6BF52A50-394A-11D3-B153-00C04F79FAA6}', > 0,1,0) > PlayerActiveXClass = > MakeActiveXClass(PlayerModule.WindowsMediaPlayer, eventObj = self) > self.Player = PlayerActiveXClass(self, -1) > self.Player.isPlaying = 0 > self.Player.uiMode = 'full' > self.WindowsMediaPlayerTopSizer.Add(self.Player, 1, wxEXPAND) > > > Any ideas anyone...i have reinstalled wxpython to no avail....Please > help anyone.... > thanks, > jojoba Did you reinstall pywin32 ? Philippe From SPAMworFREEwor at bellsouth.net Mon Aug 14 13:29:02 2006 From: SPAMworFREEwor at bellsouth.net (Charles Russell) Date: Mon, 14 Aug 2006 17:29:02 GMT Subject: TypeError: 'module' object is not callable (newby question) Message-ID: <yp2Eg.1858$VQ.825@trndny05> Why does this work from the python prompt, but fail from a script? How does one make it work from a script? #! /usr/bin/python import glob # following line works from python prompt; why not in script? files=glob.glob('*.py') print files Traceback (most recent call last): File "./glob.py", line 2, in ? import glob File "/home/cdr/python/glob.py", line 5, in ? files=glob.glob('*.py') TypeError: 'module' object is not callable From duncan.booth at invalid.invalid Mon Aug 28 13:52:18 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Aug 2006 17:52:18 GMT Subject: class problem References: <1156786617.162744.128870@h48g2000cwc.googlegroups.com> Message-ID: <Xns982DBFD76BA73duncanbooth@127.0.0.1> fegge wrote: > when i declare a class, is there difference between the below: > class myClass(): > class myClass(threading.Thread) > Yes, the first one is a syntax error because you aren't allowed empty parentheses in a class statement but the second one is a syntax error because you don't have a colon. From cga2000 at optonline.net Tue Aug 15 16:34:09 2006 From: cga2000 at optonline.net (cga2000) Date: Tue, 15 Aug 2006 16:34:09 -0400 Subject: using python at the bash shell? In-Reply-To: <1155054162.683298.21760@m73g2000cwd.googlegroups.com> References: <44d7e364$0$24980$c3e8da3@news.astraweb.com> <mailman.9071.1155002101.27775.python-list@python.org> <R31Cg.2645$No6.51906@news.tufts.edu> <1155054162.683298.21760@m73g2000cwd.googlegroups.com> Message-ID: <20060815203409.GD12939@turki.gavron.org> On Tue, Aug 08, 2006 at 12:22:42PM EDT, Simon Forman wrote: > John Salerno wrote: > > skip at pobox.com wrote: > > > John> Aside from the normal commands you can use, I was wondering if > > > John> it's possible to use Python from the terminal instead of the > > > John> normal bash commands (e.g. print instead of echo). > > > > > > Take a look at ipython <http://ipython.scipy.org/>. It's not precisely what > > > you've asked for, but it provides some features that help integrate Python > > > with the shell environment. > > > > > > Skip > > > > Can you use IPython to do normal bash things, like installing, etc.? > > "normal bash things"? :-) Yes, most commands can be run by putting an > '!' before them. If you ever need to run something that for some > reason doesn't work with this, you can always run !bash and do it in > bash. :-) > Sorry, I'm late with my howmework .. but this is rather cool. Although .. prefixing all your "system commands" with the far-to-reach "!" would probably become a royal pain after a while. Why do you write "most commands" .. what type of command might not be run by "putting '!' before them?" In the linux world it would be rather interesting if a distro was available that uses nothing but python. The installer .. the startup scripts .. utilities .. etc. Maybe there is such a thing and I'm just not aware of it? Since it would be byt-code being executed it would be faster than regular shell stuff and a lot easier to customize/maintain. Don't know enough to figure out if such a thing is possible, though .. Thanks cga From info at wingware.com Tue Aug 29 15:59:23 2006 From: info at wingware.com (Wingware Announce) Date: Tue, 29 Aug 2006 15:59:23 -0400 (EDT) Subject: ANN: Wing IDE 2.1.2 released Message-ID: <Pine.LNX.4.64.0608291558180.8996@localhost.localdomain> Hi, We're happy to announce version 2.1.2 of Wing IDE, an advanced development environment for the Python programming language. This is a bugfix release that improves support for Python 2.5 (2.5c1 is required) and fixes a number of bugs. The release can be downloaded from: http://wingware.com/downloads A detailed list of changes is available here: http://wingware.com/pub/wingide/2.1.2/CHANGELOG.txt Wing IDE provides powerful debugging, editing, code intelligence, and search capabilities that reduce development and debugging time, cut down on coding errors, and make it easier to understand and navigate Python code. Highlights of Wing IDE 2.1: * Professional quality code editor * Visual Studio, VI/Vim, Emacs, and Brief key bindings * Auto-completion, call tips, and source browser * Graphical debugger for Python, Zope, and Plone * Subversion, CVS, and Perforce integration * Powerful search interface * User-extensible with Python scripts * Templates (code snippets), bookmarks, folding, macros, and more Some features are available in Wing IDE Pro only -- for details see http://wingware.com/wingide/features This release is available for Windows (2000+), Linux, and Mac OS X (10.3+ with X11 installed) and can be compiled from sources on *BSD, Solaris, and other Posix operating systems. For more information see: Product Info: http://wingware.com/products Sales: http://wingware.com/store/purchase Sincerely, The Wingware Team From apardon at forel.vub.ac.be Tue Aug 1 09:27:29 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 1 Aug 2006 13:27:29 GMT Subject: Nested function scope problem References: <9eabc2t5kj3o7bor1g10ioqbfo2o9drhgl@4ax.com> <ea4ftg$g4m$1@sea.gmane.org> <mailman.8523.1153834254.27775.python-list@python.org> <44c6444c$0$30849$626a54ce@news.free.fr> <1153965046.805129.44350@75g2000cwc.googlegroups.com> <44c8b4a9$0$6740$636a55ce@news.free.fr> <slrnechicn.iu.apardon@rcpc42.vub.ac.be> <44c8d59a$0$31797$626a54ce@news.free.fr> <slrnechoqg.qq.apardon@rcpc42.vub.ac.be> <44c8eb5e$0$21632$626a54ce@news.free.fr> <slrneci0b1.14s.apardon@rcpc42.vub.ac.be> <mq4jc2topbu781vcdtaeog4it914r8hr57@4ax.com> <slrnecklc4.5a7.apardon@rcpc42.vub.ac.be> <mailman.8675.1154112875.27775.python-list@python.org> <slrnecn499.98c.apardon@rcpc42.vub.ac.be> <mailman.8703.1154198214.27775.python-list@python.org> <slrnecpavl.c6f.apardon@rcpc42.vub.ac.be> <mailman.8711.1154269113.27775.python-list@python.org> <slrnecpl1e.cqh.apardon@rcpc42.vub.ac.be> <mailman.8712.1154288014.27775.python-list@python.org> <slrnecsgpj.h0l.apardon@rcpc42.vub.ac.be> <44ce4ac6$0$8239$626a54ce@news.free.fr> Message-ID: <slrneculm1.k84.apardon@rcpc42.vub.ac.be> On 2006-07-31, Bruno Desthuilliers <onurb at xiludom.gro> wrote: > Antoon Pardon wrote: > (snip) >> Sure it is usefull. It may be not 100% formally correct, but often >> things that are not 100% formally correct can be better in bringing >> an idea accross. > > hear hear... > > And yet you still fail to understand why I claimed Python didn't have > variables ? Talk about stubborness :( I don't think it is usefull to claim Python has no variables. Smalltalk variables behave essentially the same as python variables and AFAIK never has the term 'variable' been seen there as an obstacle for understanding how smalltalk works. Python objects/classes don't behave exactly the same as objects/classes in some other languages, are you going to claim that python has no objects/classes when you want to explain these difference? What other terminology are you prepared to throw away because things behave somewhat differently in Python than they do in some other languages? IMO you are the one who seem to want 100% formally correctness, because you wanted to throw away a term because the entity refered to by it, didn't behave exactly the same as it did in an other language. -- Antoon Pardon From haraldarminmassa at gmail.com Wed Aug 9 09:08:50 2006 From: haraldarminmassa at gmail.com (GHUM) Date: 9 Aug 2006 06:08:50 -0700 Subject: need hint for refactoring Message-ID: <1155128930.807498.179700@75g2000cwc.googlegroups.com> I have a bunch of function like: def p2neufrage(_): """ create new element""" anfrage,ergebnis=getanfrage() if ergebnis.get("status","ok") == "ok": wert=anfrage["feld"] # do something # unique here ergebnis["innerHTML"]=..... something .... # return simplejson.dumps(ergebnis, skipkeys=False, ensure_ascii=False, check_circular=True, allow_nan=True) so, everywhere there is the same beginning: anfrage,ergebnis=getanfrage() I analyze some transmitted jason-document; check for errors then I take the values out of the request, process it and fill the slots of a result ("ergebnis") dictionary, which is returned. So the beginning and the end of the function is allways repeated. It would be great to factor it out ... i startet with that ...getanfrage() call. Is there anything more possible? Thanks for any hint Harald From asincero at gmail.com Thu Aug 24 15:56:42 2006 From: asincero at gmail.com (asincero) Date: 24 Aug 2006 12:56:42 -0700 Subject: Is this a good idea or a waste of time? Message-ID: <1156449402.022781.292840@p79g2000cwp.googlegroups.com> Would it be considered good form to begin every method or function with a bunch of asserts checking to see if the parameters are of the correct type (in addition to seeing if they meet other kinds of precondition constraints)? Like: def foo(a, b, c, d): assert type(a) == str assert type(b) == str assert type(c) == int assert type(d) == bool # rest of function follows This is something I miss from working with more stricter languages like C++, where the compiler will tell you if a parameter is the wrong type. If anything, I think it goes a long way towards the code being more self documenting. Or is this a waste of time and not really "the Python way"? -- Arcadio From Eric_Dexter at msn.com Sun Aug 20 19:44:42 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 20 Aug 2006 16:44:42 -0700 Subject: looking for help with dex tracker Message-ID: <1156117482.785763.13240@p79g2000cwp.googlegroups.com> I have a project on sourceforge that is going to be a tracker for csound currently it is a text editor with some external programs attached. There is no complex thing to do to join just post to http://groups.google.com/group/dexrow-software-and-programming-group the software is available at https://sourceforge.net/projects/dex-tracker currently what I am trying to do is write reusable routines for text file conversion i.e. remove a representation of an instrument or add one. From pianomaestro at gmail.com Thu Aug 24 23:36:32 2006 From: pianomaestro at gmail.com (pianomaestro at gmail.com) Date: 24 Aug 2006 20:36:32 -0700 Subject: lazy arithmetic Message-ID: <1156476992.102203.304450@p79g2000cwp.googlegroups.com> # This is what I have in mind: class Item(object): def __add__(self, other): return Add(self, other) class Add(Item): def __init__(self, a, b): self.a = a self.b = b a = Item() b = Item() c = a+b # Now, I am going absolutely crazy with this idea # and using it in a big way. So I'm looking at # automating the process. As a first step, # I thought maybe this would work: class Item(object): pass class Add(Item): def __init__(self, a, b=None): print self, a, b self.a = a self.b = b Item.__add__ = Add x = Item() y = Item() print x, y c = x+y # This time, the Add constructor gets only the first two arguments: "self" and "y". # So, what happened to "x" ? Is this some kind of property voodoo going on ? # Simon. From jiangnutao at gmail.com Thu Aug 24 20:27:44 2006 From: jiangnutao at gmail.com (Jason Jiang) Date: Thu, 24 Aug 2006 17:27:44 -0700 Subject: Python editor References: <mailman.9834.1156459647.27775.python-list@python.org> <1156459965.478756.230230@b28g2000cwb.googlegroups.com> Message-ID: <eclg60$u44$1@sea.gmane.org> Thanks Simon. I finally picked SciTE. No time to do further investigation. Jason "Simon Forman" <rogue_pedro at yahoo.com> wrote in message news:1156459965.478756.230230 at b28g2000cwb.googlegroups.com... > Jason Jiang wrote: >> Hi, >> >> Could someone recommend a good Python editor? Thanks. >> >> Jason > > There have just been one or two long-ish threads on exactly this > question. Search the google groups version of this group for them. > > Peace, > ~Simon > > -- > http://mail.python.org/mailman/listinfo/python-list > From justask at acme.com Fri Aug 4 11:26:23 2006 From: justask at acme.com (Vincent Delporte) Date: Fri, 04 Aug 2006 17:26:23 +0200 Subject: [Linux] What toolkit for a good grid/spreadsheet widget? References: <6fo4d2h0lnq2qcgi8jknh0ddmphhdgaulj@4ax.com> <mailman.8938.1154639225.27775.python-list@python.org> <ma85d2lg1l260fmgg6k14kcqu6al2ift3c@4ax.com> <CLFAg.1917$W01.1915@dukeread08> Message-ID: <jop6d2lqckcmdrt8g371a0vbp2nem7v3ks@4ax.com> On Fri, 04 Aug 2006 10:58:42 GMT, Dave Cook <davecook at nowhere.net> wrote: >But both pyqt and wxpython also offer that. Try running the demos for each. Thx everyone! From justin.azoff at gmail.com Tue Aug 8 23:51:17 2006 From: justin.azoff at gmail.com (Justin Azoff) Date: 8 Aug 2006 20:51:17 -0700 Subject: technique to enter text using a mobile phone keypad (T9 dictionary-based disambiguation) References: <mailman.9116.1155077147.27775.python-list@python.org> Message-ID: <1155095477.440347.149350@m79g2000cwm.googlegroups.com> Petr Jake? wrote: > I have a standard 12-key mobile phone keypad connected to my Linux > machine as a I2C peripheral. I would like to write a code which allows > the text entry to the computer using this keypad (something like T9 on > the mobile phones) > > According to the http://www.yorku.ca/mack/uist01.html > dictionary-based disambiguation is coming in the mind. > > With dictionary-based disambiguation, each key is pressed only once. > For example, to enter the, the user enters 8-4-3-0. The 0 key, for > SPACE, delimits words and terminates disambiguation of the preceding > keys. The key sequence 8-4-3 has 3 ? 3 ? 3 = 27 possible renderings > (see Figure 1). The system compares the possibilities to a dictionary > of words to guess the intended word. > > I would like to ask some guru here to give me the direction which > technique (Python functionality) or which strategy to use to solve > this riddle. > > Thanks for your advices and comments > > Regards > > Petr Jakes I can think of 2 approaches to this, 1) Map the numbers to parts of a regular expression, and then use this to search through the dictiionary. 2) Pre-compute a copy of the dictionary converted to it's numerical equivalent, then just match the numbers. The basic structure you need for both of these is simple. For the first method you use keys = ['','abc','def','ghi',....'] then if you have s="123321" ''.join(['[%s]' % keys[int(l)] for l in s]) will give you a string like '[abc][def][ghi][def][abc]', which you can then use to match words... I think the second solution would end up being faster, as long as you have the memory - no regex work, plus, you can sort the wordlist. The following quickly written class seems to work nicely: import string import bisect letters = string.lowercase numbers = '2223334445556667777888999' letter_mapping = dict(zip(letters, numbers)) class phone: def __init__(self): self.read_dictionary() def word_as_numbers(self, word): nums='' for letter in word: if letter in letter_mapping: nums += letter_mapping[letter] return nums def read_dictionary(self): words = [] for line in file("/usr/share/dict/words"): word = line.strip().lower() nums = self.word_as_numbers(word) words.append((nums, word)) words.sort() self.dict = words def get_matching_words(self, number_str): tup = (number_str,) left = bisect.bisect_left(self.dict, tup) for num, word in self.dict[left:]: if num.startswith(number_str): yield word else: break It takes a second or two to read the list of words in, but matching is instant thanks to bisect: In [14]:%time p=phone.phone() CPU times: user 1.65 s, sys: 0.00 s, total: 1.65 s Wall time: 1.66 In [15]:%time list(p.get_matching_words('43556')) CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s Wall time: 0.01 Out[15]:['hello', 'hellman', "hellman's", "hello's", 'hellos'] It seems the ruby version just posted takes a similar approach, but uses an actual tree.. using the bisect module keeps it simple. -- - Justin From DustanGroups at gmail.com Sun Aug 13 20:38:49 2006 From: DustanGroups at gmail.com (Dustan) Date: 13 Aug 2006 17:38:49 -0700 Subject: Nested if and expected an indent block In-Reply-To: <1155514407.728107.196600@i42g2000cwa.googlegroups.com> References: <1155511725.874993.140020@b28g2000cwb.googlegroups.com> <1155512775.186869.69190@m79g2000cwm.googlegroups.com> <1155514407.728107.196600@i42g2000cwa.googlegroups.com> Message-ID: <1155515929.791561.5300@m79g2000cwm.googlegroups.com> > Thanks for the replies: > > I'm sorry, the colon is there in the original, I accidentally blew it > off when I added the comment. The only information I get from IDLE is a > dialog box that says: > > Syntax Error > There's an error in your program: > expected an indented block > > Keith To see the full traceback, assuming you're using windows, you need to run it on the Command prompt. From paolopantaleo at gmail.com Wed Aug 2 11:31:05 2006 From: paolopantaleo at gmail.com (Paolo Pantaleo) Date: Wed, 2 Aug 2006 17:31:05 +0200 Subject: Behavior on non definded name in Cheetah In-Reply-To: <eaq2pj$olc$01$1@news.t-online.com> References: <mailman.8838.1154512541.27775.python-list@python.org> <eapt2e$gbv$00$1@news.t-online.com> <mailman.8839.1154516764.27775.python-list@python.org> <eaq2pj$olc$01$1@news.t-online.com> Message-ID: <83e8215e0608020831n3bb71394ge51fa027b3a6999b@mail.gmail.com> 2006/8/2, Peter Otten <__peter__ at web.de>: > Paolo Pantaleo wrote: > > > 2006/8/2, Stephan Diehl <stephan.diehl at gmx.net>: > >> Paolo Pantaleo wrote: > >> > [I hope I am posting to the right place] > >> > > >> > I have a cheetah template something like this: > >> > > >> > x is: $x > >> > y is: $y > >> > z is: $z > >> > > >> > [Actually more complicated] > >> > > >> > If for example $y is not defined I get an exception and the parsing > >> > of the template stops. Is there any way to substitute $y with an emty > >> > string and making cheeta going on with parsing? > >> > > >> > Thnx > >> > PAolo > >> > > >> > >> > http://cheetahtemplate.org/docs/users_guide_html_multipage/language.namemapper.missing.html > >> -- > >> http://mail.python.org/mailman/listinfo/python-list > >> > > > > Actually I wanted to keep things simple for who writes the template, > > so I am using this workaround: I define a class > > > > class ClassMapper: > > def __init__(self,dict={}): > > self.__dict=dict > > def getValue(self,str): > > try: > > return self.__dict[str] > > except KeyError: > > return "" > > > > x=ClassMapper(dict) > > Template(definition, searchList=[{"info":x.getValue}]) > > > > > > > > so the user should do > > > > $info("name") > > > > Maybe I could define a class that implements a dictionary and doesn''t > > raise an exception for a key not present... but it seems to > > complicated. > > You mean something like > > from Cheetah.Template import Template > > class Dict(dict): > def __getitem__(self, key): > return self.get(key, "") > > template = """\ > x is $x > y is $y > z is $z > """ > print Template(template, searchList=[Dict(x="x", y="y")]) > > You can also make a debugging version: > > class Dict(dict): > def __getitem__(self, key): > return self.get(key, "#missing key: %r#" % key) > > Peter > > -- > http://mail.python.org/mailman/listinfo/python-list > Wonderful, thnx a lot. Well not so complicated if you know how to do :D PAolo From hitesh287 at gmail.com Wed Aug 16 15:45:48 2006 From: hitesh287 at gmail.com (Hitesh) Date: 16 Aug 2006 12:45:48 -0700 Subject: Adding a char inside path string In-Reply-To: <mph6e21upc0c07v5mk45fbn2nnuv7s9sp7@4ax.com> References: <1155737700.290268.248250@i42g2000cwa.googlegroups.com> <mailman.9419.1155738127.27775.python-list@python.org> <1155744057.573884.111850@m73g2000cwd.googlegroups.com> <mph6e21upc0c07v5mk45fbn2nnuv7s9sp7@4ax.com> Message-ID: <1155757548.080769.213490@p79g2000cwp.googlegroups.com> Hi, Everything is working fine and dandy but I ran across another issue here. Some of the path comes with some extra chars padded at the end. i.e. '\\serverName\C:\FolderName1\FolderName2\example.exe' -u ABC -g XYZ abcdef Now those padded chars are not constant all the time. It can be anything. Only common denometer in each string that comes with those padded chars is that it is after .exe and then there is space and then 99% of the time it is -u and then there can be anything, I meant its dynemic after that. so I am using string1.find(".exe") and could retrive the index but don't know how to get rid any garbase after index + 4 hj Dennis Lee Bieber wrote: > On 16 Aug 2006 09:00:57 -0700, "Hitesh" <hitesh287 at gmail.com> declaimed > the following in comp.lang.python: > > > > > Thank you Fredrik. That works for a string. > > But I am getting list of tuples from DB. > > > > rows = [('\\serverName\C:\FolderName1\FolderName2\example.exe',), > > ('\\serverName\C:\FolderName1\FolderName2\example2.exe',), > > ('\\serverName\C:\FolderName1\FolderName2\example3.exe',), > > ('\\serverName\C:\FolderName1\FolderName2\example4.exe',)] > > > > I tried this: > > for i in rows: > > row = str(i) > > path = row.replace("C:" , "c$") > > print path > > > > I am getting path something like > > > > ('\\serverName\c$:\FolderName1\FolderName2\example.exe',) > > > > How on the earth I can remove those paranthesis? > > > By accessing the contents of the tuple, not the tuple itself > > >>> rows = [('\\serverName\C:\FolderName1\FolderName2\example.exe',), > ... ('\\serverName\C:\FolderName1\FolderName2\example2.exe',), > ... ('\\serverName\C:\FolderName1\FolderName2\example3.exe',), > ... ('\\serverName\C:\FolderName1\FolderName2\example4.exe',)] > >>> rows > [('\\serverName\\C:\\FolderName1\\FolderName2\\example.exe',), > ('\\serverName\\C:\\FolderName1\\FolderName2\\example2.exe',), > ('\\serverName\\C:\\FolderName1\\FolderName2\\example3.exe',), > ('\\serverName\\C:\\FolderName1\\FolderName2\\example4.exe',)] > >>> modRows = [itm[0].replace("C:", "C$") for itm in rows] > >>> modRows > ['\\serverName\\C$\\FolderName1\\FolderName2\\example.exe', > '\\serverName\\C$\\FolderName1\\FolderName2\\example2.exe', > '\\serverName\\C$\\FolderName1\\FolderName2\\example3.exe', > '\\serverName\\C$\\FolderName1\\FolderName2\\example4.exe'] > >>> > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com wulfraed at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-asst at bestiaria.com) > HTTP://www.bestiaria.com/ From madeonamac at gmail.com Thu Aug 17 15:18:39 2006 From: madeonamac at gmail.com (Gabe) Date: 17 Aug 2006 12:18:39 -0700 Subject: New to python In-Reply-To: <mailman.9477.1155841371.27775.python-list@python.org> References: <mailman.9477.1155841371.27775.python-list@python.org> Message-ID: <1155842319.698739.169650@75g2000cwc.googlegroups.com> Gallagher, Tim (NE) wrote: > 1. Is there a repository that I can go to for modules? Perl has CPAN and > I was wondering what the Python equivalent was. You can try the CheeseShop. You can locate it here: http://cheeseshop.python.org/pypi. Also, you might want to look into the new .egg format for downloading modules (it's like 'gem' from ruby, if you're familiar with that.) Good Luck, Gabe From anthra.norell at tiscalinet.ch Sun Aug 13 05:42:19 2006 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Sun, 13 Aug 2006 11:42:19 +0200 Subject: trouble with replace References: <1155401390.926925.252000@m79g2000cwm.googlegroups.com> Message-ID: <014e01c6bebc$c575d240$0201a8c0@mcuf7> This might well take the trouble out ot the OP's replace: http://cheeseshop.python.org/pypi/SE/2.2%20beta Regards Frederic ---------------------------------------------------------------------------------- And here is how it works: >>> text = '''defgefabcdefyuuuu effwerbyuuuterrfr''' >>> import SE >>> String_Editor = SE.SE ( 'abcdef=highway defgef=news effwer=monitor') >>> print String_Editor (text) newshighwayyuuuu monitorbyuuuterrfr ---------------------------------------------------------------------------------- ----- Original Message ----- From: "f pemberton" <fpemberton133 at yahoo.com> Newsgroups: comp.lang.python To: <python-list at python.org> Sent: Saturday, August 12, 2006 6:49 PM Subject: trouble with replace > I have a string (xdata) and theres a newline after every 17 characters > of the string. I was wondering how I can replace multiple substrings > multiple times within a string? To put it another way, this is what i > want to do. > > Substring to find ("abcdef") replace it with ("highway") > search again, substring to find ("defgef") replace it with > ("news").Search again and find ("effwer") replace it with > ("monitor").Example string to search under is '''defgefabcdefyuuuu > > > effwerbyuuuterrfr''' > > I've tried using replace but its not working for me. > xdata.replace('abcdef', 'highway') > xdata.replace('defgef', 'news') > xdata.replace('effwer', 'monitor') > Basically I would want to get the output of "newshighwayyuuuu > > > monitorbyuuuterrfr" > > Thanks, any help would be appreciated. > > -- > http://mail.python.org/mailman/listinfo/python-list From belred at gmail.com Sat Aug 19 12:08:21 2006 From: belred at gmail.com (Bryan) Date: Sat, 19 Aug 2006 09:08:21 -0700 Subject: PyThreadState_Swap(NULL) In-Reply-To: <20060819145056.GL5772@performancedrivers.com> References: <ec5b3m$puo$1@sea.gmane.org> <20060819145056.GL5772@performancedrivers.com> Message-ID: <ec7cts$svs$1@sea.gmane.org> Jack Diederich wrote: > On Fri, Aug 18, 2006 at 02:21:40PM -0700, Bryan wrote: >> i've written a program that uses python c api code that lives in a >> shared library that is loaded by a custom apache module (mod_xxx). this >> python c api code all works correctly under our test server and under >> apache but only if mod_python isn't loaded. when apache loads >> mod_python as shown in the http.conf snippet below, >> PyThreadState_Swap(NULL) in mod_xxx returns NULL. when the snippet of >> code in http.conf is commented out, it works again. what do i have to >> do to have mod_xxx code work correctly when apache loads mod_python? >> >> >> failure case when apache loads mod_python: >> Py_Initialize() succeeded >> PyThreadState_Swap(NULL) failed >> >> >> sucess case when apache doesn't load mod_python: >> Py_Initialize() succeeded >> PyThreadState_Swap(NULL) succeeded >> > > Running multiple python interpreters in the same process isn't supported. > It works OK for most things but some low-level guts are shared between > interpreters so it is possible to run into trouble. > > You aren't running multiple interpreters in the same process. You and > mod_python both think you are in charge and end up nuking each other's > states. Py_Initialize() resets the global state and shouldn't be called > more than once. You can create more than one sub-interpreter (check out > the mod_python source for how, the source is small and readable). > > The best thing to do would be to load your module last and conitionally > call Py_Initialize() if someone else hasn't already. > > -Jack thanks for replying jack. i tested what you suggested. i put our module after mod_python, commented out Py_Initialize(), and Py_IsInitialized() returned True, but PyThreadState_Swap() failed. i put our module before mod_python, called Py_Initialize(), and Py_IsInitialized() returned True, but PyThreadState_Swap() failed. i removed mod_python and our module succeeded. i even tested combinations of calling and PyEval_InitThreads() but didn't work either. bryan From richardjones at optushome.com.au Tue Aug 22 21:10:33 2006 From: richardjones at optushome.com.au (Richard Jones) Date: Wed, 23 Aug 2006 11:10:33 +1000 Subject: What are decorated functions? References: <af5sr3-658.ln1@darkstargames.dnsalias.net> <mailman.9676.1156292683.27775.python-list@python.org> Message-ID: <44ebab09$0$11972$afc38c87@news.optusnet.com.au> Gabriel Genellina wrote: > At Tuesday 22/8/2006 17:19, Wolfgang Draxinger wrote: >> I'm just reading the python language reference and came around >> the term "decorated functions", but I have no idea, for what >> they could be used. > > A decorator takes a function/method/callable, "decorates" (modifies) > it in a certain way, and returns it. It's important to note here that decorators, using the @decorate syntax[1], *can only decorate methods and functions*. That is, they must be followed by either another @decorator or a "def" statement. Anything else will result in a SyntaxError. For example: >>> def test(callable): return callable ... >>> @test ... def foo(): pass ... >>> @test ... @test ... @test ... def foo(): pass ... >>> @test ... class bar: File "<stdin>", line 2 class bar: ^ SyntaxError: invalid syntax >>> @test ... file File "<stdin>", line 2 file ^ SyntaxError: invalid syntax >>> So you can't decorate classes (the original PEP proposed it, but it was dropped - see the discussion about this on python-dev[2]). You *can* decorate a class' __init__ method, but that's not quite the same as eg. implementing @singleton (mind you, we already have a bazillion ways to implement the singleton pattern, so I don't think we're poorer for this limitation <wink>) Richard [1] of course, you can "anything = decorate(anything)" [2] http://mail.python.org/pipermail/python-dev/2005-March/052369.html From hale at tulane.edu Thu Aug 10 21:05:26 2006 From: hale at tulane.edu (Bill Hale) Date: Thu, 10 Aug 2006 20:05:26 -0500 Subject: Packages Message-ID: <hale-7963E1.20052610082006@news.east.cox.net> I have a question on packages. Suppose I have a package P with modules A.py, B.py, and C.py. Suppose that C.py defines a class X. Assume that the package __init__.py file contains the statement "from C import X". If I write an external Python program H.py, then I can refer to the class X by doing: import P myX = P.X() My question is that I would like to use the same method for consistentcy sake for the modules A and B in the package. That is, if A needs to use the class X from C, I would like to do the following in the file A.py: import P aX = P.X() I tried this and it works. But, is there a problem with recursion here since C might refer to A, or B might refer to A and C refer to B? Is this even a good idea? Is there another way to achieve the consistency whether referring to class X from an external Python program or referring to class X from a sibling Python program in the package? Of course, the normal way to refer to class X in program A.py is to do the following: from C import X aX = X() Bill Hale From steven.bethard at gmail.com Fri Aug 4 12:09:38 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 04 Aug 2006 10:09:38 -0600 Subject: What is the best way to print the usage string ? In-Reply-To: <mailman.8951.1154672221.27775.python-list@python.org> References: <2ccb22540608030918o1670c2bbxe21012f97ba34d67@mail.gmail.com> <mailman.8951.1154672221.27775.python-list@python.org> Message-ID: <keednTZapefc7E7ZnZ2dnUVZ_oSdnZ2d@comcast.com> Ben Finney wrote: > "Leonel Gayard" <leonel.gayard at gmail.com> writes: > >> import sys >> args = sys.argv[1:] >> if args == []: >> print """Concat: concatenates the arguments with a colon (:) between them >> Usage: concat arg1 [arg2...] >> Example: concat a b c prints \"a.jar:b.jar:c/\"""" >> sys.exit(1) >> print reduce(lambda x, y: x + ':' + y, sys.argv[1:]) >> [snip] > > For this particular use case, you may also want to investigate the > standard library 'optparse' module, which provides a way of defining > options as objects that contain everything the parser needs to know, > including a help message for each option which it then uses to > automatically construct a program usage message. > > <URL:http://docs.python.org/lib/module-optparse> FWIW, here's what the optparse code might look like: parser = optparse.OptionParser( usage='%prog arg1 [arg2...]', description='concatenates the arguments with a colon (:) ' 'between them') options, args = parser.parse_args() if not args: parser.error('wrong number of arguments') print ':'.join(args) The optparse module doesn't do anything for positional arguments, so you have to check them afterwards and issue an error as necessary. It also doesn't know how to construct your usage message, so you have to write this by hand. To handle these two things automatically, see my other post on the argparse module[1]. STeVe [1] http://mail.python.org/pipermail/python-list/2006-August/354792.html From mail at microcorp.co.za Sat Aug 26 04:10:40 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 26 Aug 2006 10:10:40 +0200 Subject: Consistency in Python References: <mailman.9855.1156495956.27775.python-list@python.org> <1156497650.974905.196140@74g2000cwt.googlegroups.com> Message-ID: <01d601c6c8ed$03a09de0$03000080@hendrik> "Paul Boddie" <paul at boddie.org.uk> Wrote: | Hendrik van Rooyen wrote: | > | > There seems to be no common methods such as- | > "prepend" - for adding something to the beginning | > "append" - for adding something to the end | > "insert[j]" - for adding something somewhere in the middle | > | > Or have I missed something ? | | [...] | | > BTW - I understand that some things are immutable - but that is an | > implementation detail, not a language issue. - the fact that you get the name S | > bound to a new object is irrelevant to a discussion about how you tell the | > interpreter to do something... | | You haven't missed one of the principal reasons exactly, but you | underestimate its importance. There aren't such methods as append or | insert on strings or tuples precisely because those objects are | immutable, whilst such methods on lists and other mutable objects | change the contents of such objects. Moreover, append and insert return | no result because the change occurs within an existing object - if you | were to return a reference to the changed object, it would be the same | reference as the one you already had. | | # Append on lists: | l.append(something) # returns nothing (you'll get None) | | Now, you could argue that insert and append should always return a | reference to some object, and that for lists (and other mutable | objects) it should return the same reference (to the changed object), | whereas for strings (and other immutable objects) it should return a | different reference (to an object which has the changed contents of the | original object). | | # Fictional append on strings: | s2 = s.append(sometext) # s would be the same, s2 different | # Fictional append variant on lists: | l2 = l.append(something) # l and l2 would be the same Lovely - this is exactly what I am thinking about... | | However, there's a sort of unwritten guarantee - although it could be | in the documentation - that the append and insert methods specifically | mutate objects and that they therefore have no place in immutable | objects. Certainly, the behaviour illustrated above could be surprising | in some kinds of programs because the append method on strings would be | more like a factory or a copy constructor rather than a "mutator". | | Now, you could argue that the name involved could be hacked in some | magical way, thus preserving the illusions that strings are mutable, | but what happens when a name is not involved? | | s.append(sometext) # s gets replaced | (text + moretext).append(sometext) # what gets replaced? nothing really - this thing standing on its own is kind of "outside" the language - If I do not have a name for you, I can't order you about - and the same is true here - the result is just a string that is used wherever its needed, as a literal would be : "this is a string" + " Here is some more" ("is" being used in the sense of "should be" - we are talking hypothetics here and not how stuff actually "is") | | Mutability is more than a mere implementation detail: in imperative | languages, it's probably one of the most underrated mechanisms | influencing the correct behaviour of programs. | | Paul This could be true - its just that, as an assembler type person - the notion that some parts of memory is "cast in concrete" is kind of strange to me... I understand that when you do something like giving a dict a key and tie a value to the key - its dangerous to change the key - it would be a very smart implementation indeed that can track the changes to such a key - but I can see no value in solving the problem by making the key "Immutable" - it is a natural consequence (at least in my mind) that when you store something in one way, you have to use exactly the same way to retrieve it - but I don't think it should be a language rule to try to protect a programmer from his own stupidity in such cases - so if I do something like: PaulsName = "Paul Buddie" and I use that as a key in my telephone directory, and then I see the error, and I do PaulsName = "Paul Boddie" and I try to get at the information I have stored earlier, using the same symbolic name - it aint gonna work... And I accept this - its not what I am on about - I still think it would be nicer if there were these commands to do the prepend insert append job, instead of doing it laboriously using slicing. (Aside: note that in the above the "value" tied to the symbolic name "PaulsName" has actually changed - so what is immutable about it from this perspective? if I can do this - why bother with immutability? ) Think for instance of the hoops you have to jump through to calculate the checksum on an Intel hex, or Motorola s file, and to make a string that you can write to a file or send to a serial port... Thanks for the reasoned reply, btw - I appreciate it! - Hendrik From felipe.lessa at gmail.com Wed Aug 30 07:02:40 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Wed, 30 Aug 2006 08:02:40 -0300 Subject: What do you want in a new web framework? In-Reply-To: <87u03uu0yt.fsf@benfinney.id.au> References: <1156100331.329889.216340@p79g2000cwp.googlegroups.com> <pan.2006.08.20.19.48.34.996227@gmx.net> <1156156636.515678.118210@75g2000cwc.googlegroups.com> <4jele2pe011di99c5dnq4olclglrkieggc@4ax.com> <1hkgnbt.ebn4o1111ftp0N%aleax@mac.com> <ecicsj$91v$1@online.de> <1156369723.13191.35.camel@devilbox> <740c3aec0608300017h37a97300lcb0670b1dea2116a@mail.gmail.com> <87u03uu0yt.fsf@benfinney.id.au> Message-ID: <c2701f5c0608300402p52e01d9by16ba065adc2cf108@mail.gmail.com> 2006/8/30, Ben Finney <bignose+hates-spam at benfinney.id.au>: > re > struct > unicodedata > decimal > random > logging > Queue > urlparse > email operator cStringIO math cmath sets (merged to the language) itertools os + stat time tempfile glob Not that I use them all the time, but they are really useful and usually fulfill my needs. -- Felipe. From wuwei23 at gmail.com Tue Aug 29 05:30:11 2006 From: wuwei23 at gmail.com (alex23) Date: 29 Aug 2006 02:30:11 -0700 Subject: Starting up the server In-Reply-To: <1156757061.162827.301260@h48g2000cwc.googlegroups.com> References: <1156757061.162827.301260@h48g2000cwc.googlegroups.com> Message-ID: <1156843811.297185.268450@74g2000cwt.googlegroups.com> john Perry wrote: > how to solve these error > ImportError: No module named pkg_resources Hey John, There's a TurboGears group that will be better suited to answering TG-related questions: http://groups.google.com/group/turbogears It looks like this issue has come up before: http://groups.google.com/group/turbogears/search?group=turbogears&q=%22No+module+named+pkg_resources%22&qt_g=1&searchnow=Search+this+group In at least one case, the answer was: "install setuptools". Hope this helps. -alex23 From st at tobiah.org Thu Aug 24 14:58:37 2006 From: st at tobiah.org (tobiah) Date: Thu, 24 Aug 2006 11:58:37 -0700 Subject: all ip addresses of machines in the local network In-Reply-To: <Xns98293000DF07castleamber@130.133.1.4> References: <1156387621.568779.191420@m73g2000cwd.googlegroups.com> <1156393371.550249.138930@75g2000cwc.googlegroups.com> <1156394781.155152.313080@i3g2000cwc.googlegroups.com> <Xns98293000DF07castleamber@130.133.1.4> Message-ID: <44ede9b8$0$8925$88260bb3@free.teranews.com> I am a member of another list that has at least one member who has lost his vision, and reads his news with a speech generator. It is terribly inconvenient for him to follow a thread full of 'bottom postings', as he is then forced to sit through the previous message contents again and again in search of the new content. > Google for top posting, and read why it's generally considered bad. > -- Posted via a free Usenet account from http://www.teranews.com From codecraig at gmail.com Tue Aug 29 23:12:16 2006 From: codecraig at gmail.com (abcd) Date: 29 Aug 2006 20:12:16 -0700 Subject: block a network port In-Reply-To: <JvWdneceyYX4KGnZnZ2dnUVZ_tednZ2d@comcast.com> References: <1156879445.723089.126630@m73g2000cwd.googlegroups.com> <JvWdneceyYX4KGnZnZ2dnUVZ_tednZ2d@comcast.com> Message-ID: <1156907536.509187.32300@m73g2000cwd.googlegroups.com> Larry Bates wrote: > This is not really a Python question. Blocking ports is a function > of your firewall solution. > ok, no of any python solutions? or command-line firewalls? From vojta.d at gmail.com Wed Aug 16 12:29:40 2006 From: vojta.d at gmail.com (Vojta Drbohlav) Date: Wed, 16 Aug 2006 18:29:40 +0200 Subject: QListView and text Message-ID: <200608161829.40715.vojta.d@gmail.com> Oh, sorry. I explained it bad. I use PyQt3 and I need text from all rows. From marijuanated at gmail.com Wed Aug 30 13:04:40 2006 From: marijuanated at gmail.com (marijuanated at gmail.com) Date: 30 Aug 2006 10:04:40 -0700 Subject: py2exe for programs with excel COM objects Message-ID: <1156957480.182219.165010@h48g2000cwc.googlegroups.com> Is it possible to create a executable of a python program that refers to Excel COM objects with the help of py2exe. From sjmachin at lexicon.net Mon Aug 14 04:45:01 2006 From: sjmachin at lexicon.net (John Machin) Date: 14 Aug 2006 01:45:01 -0700 Subject: selecting base class from user input References: <ebo1v5$jos$1@skeeter.ucdavis.edu> <1155523781.860117.203140@h48g2000cwc.googlegroups.com> <ebp90n$sh6$1@skeeter.ucdavis.edu> Message-ID: <1155545101.710338.129160@m79g2000cwm.googlegroups.com> Jackson wrote: > I have 4 classes: > > Lion(Animal): > Ant(Animal): > Bee(Animal): > Human(Animal): > > which are all subclasses of some superclass called Animal. Now I want > to define an occupation. For example, Worker. A worker can exist as any > of the 4 classes above. Their constructors are different and I might > want to add certain features. > > My first thought was to create a class called "Worker" and have the base > class determined by a variable which is passed into the constructor. > Most of the method calls will come from the Animal superclass anyway, > but some method calls might come from the Lion class, for example. > Here are a couple of thoughts that *might* help: (1) mix-in i.e. a class can have multiple base classes: class AntWorker(Animal, Worker): (2) you can create classes on the fly using the 3-argument form of the built-in type() function: new_cls = type(name_of_class, base_classes_tuple, dict_of_methods_etc) so you can have just one base class (i.e. object) and populate the dict with methods and/or you can have pre-packaged base-classes each already containing relevant methods ... so when the order for a new tailored class comes in you just rush about your virtual warehouse throwing packaged base-classes into a tuple and extra methods into a dict, attach a name tag and then type() gift-wraps it for you. You need to read up on "method resolution order" aka "mro" before planning what methods go in what mixin classes and what methods are optional add-ons and what order you specify the classes in the tuple. HTH, John From claudio.grondi at freenet.de Mon Aug 28 03:00:19 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Mon, 28 Aug 2006 09:00:19 +0200 Subject: random writing access to a file in Python In-Reply-To: <nei4f25gg876vl3sibgrsbbin2t9fdol78@4ax.com> References: <ecn22h$3o5$1@newsreader2.netcologne.de> <5a9ue2lrjh214ecmme09fsodhm3ico1ntm@4ax.com> <ecno4v$h11$1@newsreader2.netcologne.de> <7xhczzqoi3.fsf@ruckus.brouhaha.com> <ecqhd2$17u$1@newsreader2.netcologne.de> <7xbqq7f6q7.fsf@ruckus.brouhaha.com> <ecqn1d$8ui$1@newsreader2.netcologne.de> <7xd5anf23u.fsf@ruckus.brouhaha.com> <ecrigu$g5v$1@newsreader2.netcologne.de> <7xr6z2dpt0.fsf@ruckus.brouhaha.com> <ecsvgk$61u$1@newsreader2.netcologne.de> <7xpselvnow.fsf@ruckus.brouhaha.com> <nei4f25gg876vl3sibgrsbbin2t9fdol78@4ax.com> Message-ID: <ecu4a2$re0$1@newsreader2.netcologne.de> Dennis Lee Bieber wrote: > On 27 Aug 2006 15:06:07 -0700, Paul Rubin <http://phr.cx at NOSPAM.invalid> > declaimed the following in comp.lang.python: > > > >>I think that's not so bad, though probably still not optimal. 85 GB >>divided by 18 hours is 1.3 MB/sec, which means if the program is >>reading the file 8 times, it's getting 10 MB/sec through the Windows >>file system, which is fairly reasonable throughput. >> > > Especially if, as implied, this was on a USB drive <G> Don't underestimate external USB drives (I have heard there are great differences between them depending on the used controller). If the file requested is not scattered over the drive due to defragmentation and appropriate reading procedure is used I have seen (e.g. just yesterday with the 80 Gig file) constant throughput of 28 MBytes/second what compared to the maximum I have seen on E-IDE of 40 MBytes/second is not that bad as your posting might suggest. Thanks to Paul Rubin for the hint on radix sorting (even if coming a bit too late). I had used already yesterday this kind of approach in another context on the file I was sorting and can therefore estimate the total time on my system for such sorting using this method quite well: it will take not more than 3 hours (what is a very big improvement compared to 18 hours). I suppose, that the problem with Windows XP 'sort' is that it can't take advantage of the constant record size as there is no option available which could be used to pass this hint to it. "But if you only had to do it once and it's finished now, why do you still care how long it took?" Because one of my usual goals going along with doing things like that, is to get some feeling for them gaining experience making me in similar future cases capable of improvement by _intuitive_ selection of the best known to me path to the solution (learning by doing). It is a big difference between _knowing_ that there are various different sorting algorithms and it is necessary to choose the right one to speed up sorting and actually _experiencing_ that you have to wait for your results 18 hours and the machine is so busy that it is hard to use it for other tasks at the same time. If the sorting took less than one hour I would probably never make the effort to give it some serious thoughts. Claudio Grondi From deets at nospam.web.de Mon Aug 7 09:50:44 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 07 Aug 2006 15:50:44 +0200 Subject: is it possible to dividing up a class in multiple files? References: <eb7ftn$t15$1@news.lrz-muenchen.de> Message-ID: <4jouimF8ue5nU1@uni-berlin.de> Martin H?fling wrote: > is it possible to put the methods of a class in different files? I just > want to order them and try to keep the files small. No, its not possible. What you can do is to create several classes and one that inherits from all of them. Better yet is to not write huge classes and getting rid of strange conventions or views that make the problem appear as such. To explain that: I've never felt the need to spread a class over several files - au contraire, I despise Java for forcing me to only have one top level class per file. Diez From webraviteja at gmail.com Fri Aug 18 16:35:20 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 18 Aug 2006 13:35:20 -0700 Subject: sqlite3 or mysqldb? In-Reply-To: <ec2k8a$qha$1@atlantis.news.tpi.pl> References: <uR%Eg.2697$No6.52598@news.tufts.edu> <ec2k8a$qha$1@atlantis.news.tpi.pl> Message-ID: <1155933320.647256.233270@74g2000cwt.googlegroups.com> > To learn SQL SQLite should be enough - it has all the basics, just as > MySQL, while it doesn't require any server/client configuration > (encoding configuration in MySQL is real PITA). But if you want any > "serious SQL", go with any freely available *real SQL server*, like > Firebird or PostgreSQL. I'd consider Firebird, as it's pretty lightweight. Firebird can be used as an embedded database just like SQLite as well. This gives a much more powerful database that can still be used without the administration overhead. Aside from flexibility, the reason I prefer FireBird is that it has much more sophisticated visual tools available. From onurb at xiludom.gro Tue Aug 29 08:21:17 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 29 Aug 2006 14:21:17 +0200 Subject: Extending the dict class In-Reply-To: <1156852916.254032.172390@b28g2000cwb.googlegroups.com> References: <1156852916.254032.172390@b28g2000cwb.googlegroups.com> Message-ID: <44f4313e$0$26985$626a54ce@news.free.fr> chosechu wrote: > Hello Pythoneers: > > I need to pass a list of named arguments to a function in a given > order, > and make sure these named arguments are retrieved using keys() in the > same order they were given. Example: > > keyargs={} > keyargs['one']=1 > keyargs['two']=2 > keyargs['three']=3 > > myfunc(**keyargs) > -> myfunc would retrieve key arguments with keys() in the same order > as they were set, i.e. keyargs.keys() == ['one', 'two', 'three'] I'm not sure to understand why you want to do so - perhaps you could tell more about your real use case ? Anyway, and since it's not directly possible, a possible workaround could be to pass a sequence of (key, value) tuples instead (possibly as *args). This of course requires that you can modify the implementation of myfunc(). -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From gagsl-py at yahoo.com.ar Fri Aug 11 20:32:32 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 11 Aug 2006 21:32:32 -0300 Subject: Learning Python In-Reply-To: <1155329631_4653@sp6iad.superfeed.net> References: <1155329631_4653@sp6iad.superfeed.net> Message-ID: <7.0.1.0.0.20060811210856.047f3f90@yahoo.com.ar> At Friday 11/8/2006 18:04, Dr. Pastor wrote: >Attempting to learn Python; I constructed the module >listed below. I would like to make it shorter, faster, >more "Python like". (Windows XP, Pro.) >Many thanks for any advice! >... > >#------------------------------------------------------------------------------- > # Name: SendMoreMoney.py > # Purpose: A solution to the SEND+MORE=MONEY puzzle. > # > # Author: Dr. Pastor > # > # Copyright: (c) Dr. Pastor 2006 > >#------------------------------------------------------------------------------- > #!/usr/bin/env python This line is not used on Windows, but if you want to include it, must be the very first line on the script. ># ># The solution for the puzzle of ># SEND ># +MORE ># ----- ># MONEY ># > >def perm(items, n=None): > if n is None: > n = len(items) > for i in range(len(items)): > v = items[i:i+1] I would use v = [items[i]] but that's a matter of taste... > if n == 1: > yield v > else: > rest = items[:i] + items[i+1:] > for p in perm(rest, n-1): > yield v + p > >def comb(items, n=None): > if n is None: > n = len(items) > for i in range(len(items)): > v = items[i:i+1] Same as above. > if n == 1: > yield v > else: > rest = items[i+1:] > for c in comb(rest, n-1): > yield v + c ># ># S E N D M O R Y ># ['0','1','2','3','4','5','6','7','8','9'] ># >print >print "Selections of 8 items from 10 then the permutation of them." >print >b=0 >for s in comb([0,1,2,3,4,5,6,7,8,9],8): > for a in perm(s,None): > if (a[4]*1000+a[5]*100+a[2]*10+a[1])*10+a[7] == \ > (a[0]+a[4])*1000+(a[1]+a[5])*100+(a[2]+a[6])*10+(a[3]+a[1]): Backslash as continuation is a bit problematic (add an empty space after it and it's broken...) so it's better to add an open parens; continuation is implicit until the last parens is closed: if (a[4]*10000+a[5]*1000+a[2]*100+a[1]*10+a[7] == (a[0]+a[4])*1000+(a[1]+a[5])*100+(a[2]+a[6])*10+(a[3]+a[1])): If speed is not the most important thing, you could assign names to the 8 items: S, E, N, D, M, O, R, Y = a if poly(10, M,O,N,E,Y) == poly(10, S,E,N,D) + poly(10, M,O,R,E): which is infinitely more legible (and a bit compact, too). (poly is left as an exercise: def poly(x, *args): ) And a,b,s are too short names... Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From gelists at gmail.com Thu Aug 10 14:59:03 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Thu, 10 Aug 2006 15:59:03 -0300 Subject: using python to edit a word file? References: <aJKCg.2673$No6.52073@news.tufts.edu> Message-ID: <adsnaf8w06gb.dlg@gelists.gmail.com> On 2006-08-10 15:15:34, John Salerno wrote: > I figured my first step is to install the win32 extension, which I did, > but I can't seem to find any documentation for it. A couple of the links > on Mark Hammond's site don't seem to work. > > Anyway, all I need to do is search in the Word document for certain > strings and either delete them or replace them. Easy enough, if only I > knew which function, etc. to use. > > Hope someone can push me in the right direction. When Word is installed, you have a few COM interfaces to Word. I'm not sure how to access these with Python (but documentation about using COM with Python should help you here), and I'm not sure whether what you want is available (but the Word COM documentation should help you with that). Gerhard From fredrik at pythonware.com Tue Aug 29 04:03:46 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 29 Aug 2006 10:03:46 +0200 Subject: How ahead are you guys in the (Python) real world? References: <1156821234.820929.299740@p79g2000cwp.googlegroups.com> <32822fe60608282026y83009cx8f9bc3ae81107889@mail.gmail.com> Message-ID: <ed0sd2$mn5$1@sea.gmane.org> Jorge Vargas wrote: > for ones 2.5 is not consider production code yet so noone should be > running anything on it. same with 1.6. that's completely ignoring how Python's developed, though. if you know what you're doing, using stable (*) betas or release candidates can be an excellent idea. </F> *) where "stable" means "works well in your test environment". From st at tobiah.org Tue Aug 15 19:46:28 2006 From: st at tobiah.org (tobiah) Date: Tue, 15 Aug 2006 16:46:28 -0700 Subject: Clean way to not get object back from instantiation attempt gone bad In-Reply-To: <44e245c0$0$20991$88260bb3@free.teranews.com> References: <44e245c0$0$20991$88260bb3@free.teranews.com> Message-ID: <44E25CD4.40103@tobiah.org> I should have made it more clear that Foo is a class: class Foo: def __init__(self, *args): for arg in args: if is_fruit(arg): del(self) tobiah wrote: > Suppose I do: > > > myfoo = Foo('grapes', 'oranges') > > And in the __init__() of Foo, there is > a real problem with the consumption of fruit. > Is there a clean way to ensure that myfoo > will be None after the call? Would the > __init__() just do del(self), or is there > a better way to think about this? > > Thanks, > > Toby > -- Posted via a free Usenet account from http://www.teranews.com From akameswaran at gmail.com Tue Aug 8 17:23:55 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 8 Aug 2006 14:23:55 -0700 Subject: threading.Event usage causing intermitent exception Message-ID: <1155072235.904227.303090@m73g2000cwd.googlegroups.com> Admittedly this problem causes no actual functional issues aside from an occasional error message when the program exits. The error is: Unhandled exception in thread started by Error in sys.excepthook: Original exception was: Yes all that info is blank. The application is a console application that is waiting for some condition on the machine to happen. However, I leave open the possiblitiy to cancel by a single key press at which point the program terminates. Suffice it to say, I cannot perform both checks without invoking threads as the key press gets "missed" sometimes. Below is a simplification of the code canceled = False myEvent = threading.Event() def watchForCancel() global canceled # turn of terminal buffering and capture key presses here canceled = True myEvent.set() def watchForCondition() # do a bunch of stuff checking the system myEvent.set() cancelThread = threading.Thread(target = watchForCancel) cancelThread.setDaemon(True) # so I can exit the program when I want to cancelThread.start() conditionThread = threading.Thread(target = watchForCondition) conditionThread.setDaemon(True) conditionThread.start() myEvent.wait() if cancelled: sys.exit(2) # do more stuff if the condition returned instead of cancel and then I'm done I've left out most of the active code, just cuz I think it muddies the water. Now about 9 out of 10 times this works just fine. However, every once in a while I get the exceptions mentioned above, but only when I cancel out of the operation. I think the conditionThread is in the process of shutting down and gets hosed up somehow and spits out an exception, but the interpreter no longer has access to the info since it is shutting down. I know that the condition is not being met in these situations, since the condition is based on a network client sending a certain set of data, and in my tests I know that no client has sent said data. I haven't worried about this too much, as it doesn't cause any functional problems, but it really irritates me. I suppose I could make the threads aware of each other, but that just seems stupid. Any suggestions on how to eliminate this intermittent error? Thanks From jgodoy at gmail.com Sat Aug 19 16:14:48 2006 From: jgodoy at gmail.com (Jorge Godoy) Date: Sat, 19 Aug 2006 17:14:48 -0300 Subject: install patch on windows References: <1156014103.715131.143360@i3g2000cwc.googlegroups.com> <1156017314.249545.296940@h48g2000cwc.googlegroups.com> <1156017655.849634.95240@p79g2000cwp.googlegroups.com> Message-ID: <87y7tka3ev.fsf@gmail.com> "djoefish" <djoefish at gmail.com> writes: > Tim Golden wrote: >> djoefish wrote: >> > Does anyone know how to install a patch on Winodws? For example, I want >> > to install the patch 'ocmalloc-free-arenas.diff' in Python 2.3. >> >> You can get patch (and quite a lot besides) for win32 from >> the UnxUtils project: >> >> http://sourceforge.net/projects/unxutils >> >> TJG > > Thanks, but that project seems to be dead.... The files there didn't work? -- Jorge Godoy <jgodoy at gmail.com> From nemesian at gmail.com Fri Aug 18 21:56:15 2006 From: nemesian at gmail.com (nemesian at gmail.com) Date: 18 Aug 2006 18:56:15 -0700 Subject: text editor suggestion? In-Reply-To: <44e66724$0$2363$c3e8da3@news.astraweb.com> References: <44e66724$0$2363$c3e8da3@news.astraweb.com> Message-ID: <1155952575.636380.318300@m73g2000cwd.googlegroups.com> Have you tried Notepad++? It's a neat text-editor. From jo at durchholz.org Tue Aug 29 15:55:57 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Tue, 29 Aug 2006 21:55:57 +0200 Subject: A Sort Optimization Technique: decorate-sort-dedecorate In-Reply-To: <1f7befae0608291225o12985c18u95137d9b6ba928e2@mail.gmail.com> References: <1156719092.603277.57390@b28g2000cwb.googlegroups.com> <1156723602.192984.49610@m79g2000cwm.googlegroups.com> <pan.2006.08.28.08.53.08.647908@gmx.net> <280820061150081729%jgibson@mail.arc.nasa.gov> <ed1682$l41$1@online.de> <7.0.1.0.0.20060829132302.05c9e758@yahoo.com.ar> <44F480EF.9080202@durchholz.org> <1f7befae0608291225o12985c18u95137d9b6ba928e2@mail.gmail.com> Message-ID: <44F49BCD.6000903@durchholz.org> Tim Peters schrieb: > [Joachim Durchholz] >>>> Wikipedia says it's going from 2NlogN to N. If a sort is massively >>>> dominated by the comparison, that could give a speedup of up to 100% >>>> (approximately - dropping the logN factor is almost irrelevant, what >>>> counts is losing that factor of 2). > > [Gabriel Genellina] >>> In fact it's the other way - losing a factor of 2 is irrelevant, >>> O(2N)=O(N). The logN factor is crucial here. > > [Joachim Durchholz] >> That's just a question of what you're interested in. >> >> If it's asymptotic behavior, then the O(logN) factor is a difference. >> >> If it's practical speed, a constant factor of 2 is far more relevant >> than any O(logN) factor. > > Nope. Even if you're thinking of base 10 logarithms, log(N, 10) > 2 > for every N > 100. Base 2 logarithms are actually most appropriate > here, and log(N, 2) > 2 for every N > 4. So even if the "2" made > sense here (it doesn't -- see next paragraph), the log(N) term > dominates it for even relatively tiny values of N. Whether this argument is relevant depends on the constant factors associated with each term. Roughly speaking, if the constant factor on the O(N) term is 100 and the constant factor on the O(logN) term is 1, then it's still irrelevant. My point actually is this: big-Oh measures are fine for comparing algorithms in general, but when it comes to optimizing concrete implementations, its value greatly diminishes: you still have to investigate the constant factors and all the details that the big-Oh notation abstracts away. From that point of view, it's irrelevant whether some part of the algorithm contributes an O(1) or an O(logN) factor: the decision where to optimize is almost entirely dominated by the constant factors. Regards, Jo From python.list at tim.thechases.com Wed Aug 23 15:22:42 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 23 Aug 2006 14:22:42 -0500 Subject: Regex help...pretty please? In-Reply-To: <1156358822.649578.126990@74g2000cwt.googlegroups.com> References: <1156358822.649578.126990@74g2000cwt.googlegroups.com> Message-ID: <44ECAB02.1050404@tim.thechases.com> > cond(a,b,c) > > and I want them to look like this: > > cond(c,a,b) > > but it gets a little more complicated because the conds themselves may > have conds within, like the following: > > cond(0,cond(c,cond(e,cond(g,h,(a<f)),(a<d)),(a<b)),(a<1)) Regexps are *really* *REALLY* *bad* at arbitrarily nested structures. really. Sounds more like you want something like a lex/yacc sort of solution. IIUC, pyparsing may do the trick for you. I'm not a pyparsing wonk, but I can hold my own when it comes to crazy regexps, and can tell you from experience that regexps are *not* a good path to try and go down for this problem. Many times, a regexp can be hammered into solving problems superior solutions than employing regexps. This case is not even one of those. If you know the maximum depth of nesting you'll encounter, you can do some hackish stunts to shoehorn regexps to solve the problem. But if they are truely of arbitrary nesting-depth, *good* *luck*! :) -tkc From robin at reportlab.com Fri Aug 18 13:02:19 2006 From: robin at reportlab.com (Robin Becker) Date: Fri, 18 Aug 2006 18:02:19 +0100 Subject: amd64 Message-ID: <44E5F29B.5050601@chamonix.reportlab.co.uk> Does anyone know if it's possible to run python as a 32 bit app on AMD64's? One of our host providers AMD Athlon 64 3000+ and we are currently using a celeron which is real slow. The problem is that this machine would be a backup for another which is 32 pentium 4. If I have to recompile/debug all the extensions etc etc for another architecture it might not seem so attractive. -not ready for 64bitly yrs- Robin Becker From btowle at carnegielearning.com Thu Aug 10 11:09:44 2006 From: btowle at carnegielearning.com (Brendon Towle) Date: Thu, 10 Aug 2006 11:09:44 -0400 Subject: Eval (was Re: Question about the use of python as a scripting language) In-Reply-To: <17627.18125.510532.334070@montanaro.dyndns.org> References: <mailman.33888.1155215103.27774.python-list@python.org> <CC0D63AF-2F0C-4B84-A8BA-BFE5BBE1036B@carnegielearning.com> <17627.14233.684281.17915@montanaro.dyndns.org> <16E7238C-8601-4A9D-B244-E9D8668966DE@carnegielearning.com> <17627.18125.510532.334070@montanaro.dyndns.org> Message-ID: <17D29C4E-1481-4E52-B522-E881357376E2@carnegielearning.com> On 10 Aug 2006, at 10:46 AM, skip at pobox.com wrote: > > Brendon> A shortcut occurs to me; maybe someone can tell me > what's wrong > Brendon> with my reasoning here. It seems that any string that > is unsafe > Brendon> to pass to eval() must involve a function call, and > thus must > Brendon> contain an opening paren. Given that I know that the > data I > Brendon> expect contains no parens, would people expect this > code to be > Brendon> safe: > > Unfortunately, no. If I define a class which has properties, > attribute > assignment can involve arbitrary numbers of function calls. > Oh yeah -- forgot about that. Thanks. But, how could you get that class into my eval() call? Unless I'm missing something (entirely possible -- as we've seen above, I already did), it seems that you have only two options: 1. Get the code containing the class on my local machine, and import the class -- in this case, I'm screwed long before I call eval(). 2. Include it in the page I downloaded -- in this case, the function calls will be part of the string, and the data.pos('(') call will find them. Am I missing a third option? B. -- Brendon Towle, PhD Cognitive Scientist +1-412-690-2442x127 Carnegie Learning, Inc. The Cognitive Tutor Company ? Helping over 375,000 students in 1000 school districts succeed in math. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060810/cf3fb00f/attachment.html> From paolopantaleo at gmail.com Thu Aug 3 05:14:06 2006 From: paolopantaleo at gmail.com (Paolo Pantaleo) Date: Thu, 3 Aug 2006 11:14:06 +0200 Subject: Grammar parsing Message-ID: <83e8215e0608030214y3ac1cc1fs352199cad5f18b10@mail.gmail.com> Hi, How can I write a pareser for a certain gramamr? I found PyPy that does it, is thare any other tool? Maybe something built-in the python interpreter? Thnx PAolo -- if you have a minute to spend please visit my photogrphy site: http://mypic.co.nr From jjl at pobox.com Thu Aug 10 18:15:19 2006 From: jjl at pobox.com (John J. Lee) Date: Thu, 10 Aug 2006 22:15:19 GMT Subject: ANN: xtopdf: PDF creation / conversion toolkit: alpha release of v1.3 References: <mailman.9127.1155102352.27775.python-list@python.org> Message-ID: <87y7twnsp3.fsf@pobox.com> david_wahler at bic.ky writes: > I'll be out of the office until approximately August 20th. If you have any questions, please email support at bic.ky. I'm sure all c.l.py readers eagerly await your return ;-) John From claudio.grondi at freenet.de Fri Aug 18 13:11:06 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Fri, 18 Aug 2006 19:11:06 +0200 Subject: How to draw line on Image? In-Reply-To: <FSlFg.11687$3l.10458@tornado.texas.rr.com> References: <1155912952.668195.266340@b28g2000cwb.googlegroups.com> <3CkFg.855$uV.546@trnddc08> <FSlFg.11687$3l.10458@tornado.texas.rr.com> Message-ID: <ec4sba$ddt$1@newsreader2.netcologne.de> Paul McGuire wrote: > "David Isaac" <aisaac0 at verizon.net> wrote in message > news:3CkFg.855$uV.546 at trnddc08... > >>"Daniel Mark" <danielmarkhot at gmail.com> wrote in message >>news:1155912952.668195.266340 at b28g2000cwb.googlegroups.com... >> >>>I want to draw some shapes, such as lines, circles on an image. >> >> >>http://www.pythonware.com/library/pil/handbook/psdraw.htm >> >>hth, >>Alan Isaac >> >> > > > ImageDraw (http://www.pythonware.com/library/pil/handbook/imagedraw.htm) > might be more generally helpful than PSDraw. > > -- Paul > > And if the quality of the result is important maybe (maybe, because I haven't used it yet myself) aggdraw an add-on to the PIL library that supports anti-aliased drawing http://effbot.org/zone/draw-agg.htm Claudio Grondi From jarausch at skynet.be Mon Aug 7 08:46:06 2006 From: jarausch at skynet.be (Helmut Jarausch) Date: Mon, 07 Aug 2006 14:46:06 +0200 Subject: NNTPlib::xover problem In-Reply-To: <mailman.9048.1154948263.27775.python-list@python.org> References: <4jok7iF726biU1@news.dfncis.de> <mailman.9048.1154948263.27775.python-list@python.org> Message-ID: <44d7360e$0$1218$ba620e4c@news.skynet.be> Michiel Sikma wrote: > Hi Helmut, > > I guess it simply raises an exception in case there are no articles; > this may not be what you expected, but it would seem that this is the > way it operates. You should try catching the exception to plan out a > course of action in case no articles are present. Thanks, though the name of the exception 'nntplib.NNTPTemporaryError' sound 'temporary' Helmut. > Op 7-aug-2006, om 12:50 heeft Helmut Jarausch het volgende geschreven: > >> Hi >> >> I try to regularly extract recent news from some newsgroups. >> If News is an NNTP object I try >> (Response,Articles)= News.xover(str(int(Last)+1),'10000000') >> where 'Last' is the (previously saved) number of the last >> article read. >> If there are no new articles I get an Exception >> >> Traceback (most recent call last): >> File "/home/jarausch/Python_My/News", line 36, in -toplevel- >> (Response,Articles)= News.xover(str(int(Last)+1),'10000000') >> File "/usr/local/lib/python2.4/nntplib.py", line 479, in xover >> resp, lines = self.longcmd('XOVER ' + start + '-' + end, file) >> File "/usr/local/lib/python2.4/nntplib.py", line 265, in longcmd >> return self.getlongresp(file) >> File "/usr/local/lib/python2.4/nntplib.py", line 236, in getlongresp >> resp = self.getresp() >> File "/usr/local/lib/python2.4/nntplib.py", line 219, in getresp >> raise NNTPTemporaryError(resp) >> NNTPTemporaryError: 420 No such article >> >> >> I would have expected to get an empty 'Response' or the value None >> for 'Articles'. >> >> What am I missing? >> >> (This is Python 2.4.3) >> >> Many thanks for a hint, >> >> Helmut Jarausch >> >> Lehrstuhl fuer Numerische Mathematik >> RWTH - Aachen University >> D 52056 Aachen, Germany >> --http://mail.python.org/mailman/listinfo/python-list > -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From steve at holdenweb.com Mon Aug 28 12:17:15 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 28 Aug 2006 17:17:15 +0100 Subject: Truly platform-independent DB access in Python? In-Reply-To: <44f310e3$0$26022$636a55ce@news.free.fr> References: <1156748466.739709.117850@h48g2000cwc.googlegroups.com> <44f2bade$0$13039$626a54ce@news.free.fr> <1156778705.807852.140510@75g2000cwc.googlegroups.com> <44f310e3$0$26022$636a55ce@news.free.fr> Message-ID: <ecv4ta$plm$1@sea.gmane.org> Bruno Desthuilliers wrote: > Boris Du?ek wrote: > >>Bruno Desthuilliers wrote: >> >>>bobrik wrote: >>> >>>>Hello, >>>> >>>>I am using the Python DB API for access to MySQL. But it is not >>>>platform-independent >>> >>>It is. You don't have to change your Python code according to the OS or >>>CPU. >>> >> >>What I mean is that wiht platform-independent access, I should be able >>to not care on which operating system is the web server accessing my >>scripts where I use MySQLdb > > > When it comes to *using* MySQLdb, you don't care about the OS, CPU and > whatnot. > > >>which I have to install (and therfore >>platform-dependently) compile myself. > > > This is a very distinct problem. > > >>The important point is that >>MySQLdb is installed as an extra module. So you have to compile it >>manually, > > > Usually, cd <src-dir> && python setup.py install do the job. > > >>but what if the OS with server accessing the site that is on >>shared area changes? > > > And what if Python is not installed on it ?-) > > Seriously, do you think that hosting companies swap OS very often ? > Well, GoDaddy just switched enough domains from Linux to Windows to make a significant difference to the Internet hosting statistics, and were allegedly paid handsomely by Microsoft to do it, but those were parked domains. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From cliff at develix.com Thu Aug 31 19:47:38 2006 From: cliff at develix.com (Cliff Wells) Date: Thu, 31 Aug 2006 16:47:38 -0700 Subject: Pros/Cons of Turbogears/Rails? In-Reply-To: <1157040293.903010.152250@m79g2000cwm.googlegroups.com> References: <WXmIg.20772$gY6.18513@newssvr11.news.prodigy.com> <1156726071.579429.44650@b28g2000cwb.googlegroups.com> <1156740469.645955.52080@i3g2000cwc.googlegroups.com> <1156768355.275370.129680@h48g2000cwc.googlegroups.com> <1157038022.237121.127780@m73g2000cwd.googlegroups.com> <1157040293.903010.152250@m79g2000cwm.googlegroups.com> Message-ID: <1157068058.31869.69.camel@devilbox> On Thu, 2006-08-31 at 09:04 -0700, Paul Boddie wrote: > SkunkWeb (3.4.0), Zope (2.9.4 and 3.2.1), Plone (2.5), Karrigell (2.3), > CherryPy (2.2.1), Spyce (2.1), QP (1.8), Cymbeline (1.3.1), Django > (0.95), Webware (0.9.1), Pylons (0.9.1), TurboGears (0.8.9), PyLucid > (v0.7.0RC4), Paste (0.4.1), web.py (.138) And ironically, the one with the *lowest* version number (web.py) is used to power some fairly large (and ambitious) public projects: https://www.youos.com/ ( see http://blog.youos.com/?p=49 ) http://reddit.com/ I'd like to claim that in OSS, version numbers mean little, but I still recall Windows NT 1.0 (er, I mean 3.1), so I guess they don't mean much anywhere. Version numbers are *picked* by project leads for varying reasons, so comparing version numbers from different projects is pretty pointless. Is Windows 2000 more stable than Linux 2.6? It ought to be since it's 769 times more mature, right? Even if you called it Windows NT 5.0, I'd have to wonder if it's even twice as stable (I'm being intentionally generous here, so bear with me). Personally I tend to look at what the users (especially former users) say about a project and what's been or being done with that project. If it seems promising, I try it. I can't think of any other reasonable way of making that decision. Regards, Cliff -- From http Wed Aug 30 03:47:57 2006 From: http (Paul Rubin) Date: 30 Aug 2006 00:47:57 -0700 Subject: Allowing ref counting to close file items bad style? References: <9U6Jg.951$Xw6.283@trndny02> <7x4pvvylrh.fsf@ruckus.brouhaha.com> <1156910432.917443.259720@p79g2000cwp.googlegroups.com> <7xmz9mkgnv.fsf@ruckus.brouhaha.com> <1156921226.069647.233550@p79g2000cwp.googlegroups.com> Message-ID: <7xodu2ekb6.fsf@ruckus.brouhaha.com> "sjdevnull at yahoo.com" <sjdevnull at yahoo.com> writes: > Sure. But most Java GCs are pretty reasonable and for typical code > will run periodically (what I call the not-horribly-distant future). If your system allows max 100 files open and you're using 98 of them, then "horribly distant future" can be awfully close by. > > > (And personally I think the benefits to programmers of guaranteeing > > > ref-counting semantics would outweigh the additional headaches for > > > Jython and other alternative implementations). Ref counting is a rather primitive GC technique and implementations shouldn't be stuck having to use it. > It's obvious to the reader that in code like: > > def myFunc(filename): > f = open(filename, 'r') > for line in f: > # do something not using f That's not obvious except by recognizing the idiom and knowing the special semantics of files. Otherwise, look at def myOtherFunc(x): a = SomeClass(x) # make an instance of some class b = a.foo() # do something with b One can't say for sure that 'a' can be destructed when the above function finishes. Maybe a.foo() saved a copy of its 'self' argument somewhere. It's the same thing with your file example: "for line in f" calls f's iter method and them repeatedly calls f's next method. Those methods could have side effects that save f somewhere. > Having f destructed at least when the function returns makes for more > readable code and fewer mistakes. CPython's refcounting behaves very > nicely in this regard, The ref counting only works if it applies to all the lower scopes and not just the local scope. That means you can't use any other type of GC. From kay.schluehr at gmx.net Wed Aug 2 08:10:36 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 2 Aug 2006 05:10:36 -0700 Subject: Class definition within function References: <Su0Ag.121$fe3.114@read3.inet.fi> Message-ID: <1154520636.055317.292700@b28g2000cwb.googlegroups.com> Tomi Lindberg wrote: > Hi, > > With the following function definition, is it possible to > create an instance of class C outside the function f (and if > it is, how)? def f(): class C(object): def __init__(self): self.a = 'a' f.C = C return C() >>> f.C <class '__main__.C'> > And yes, I think this is one of those times > when the real question is why :) Definitely ;) From jorge.vargas at gmail.com Mon Aug 28 18:16:29 2006 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Mon, 28 Aug 2006 18:16:29 -0400 Subject: Max OSX and Excel In-Reply-To: <C118B8AE.116%Johanna.Pfalz@telus.net> References: <32822fe60608281500l762b61ddqc6f3300ec1e296a6@mail.gmail.com> <C118B8AE.116%Johanna.Pfalz@telus.net> Message-ID: <32822fe60608281516m254c5feeqa0e5d40a99b244a6@mail.gmail.com> On 8/28/06, Johanna Pfalz <Johanna.Pfalz at telus.net> wrote: > To be more specific, I'm interested in reading in certain rows and columns > from an excel spreadsheet directly without converting the information to a > text file. I'd also like to be able to write directly to an excel > spreadsheet from python. ohh I found a nice tool for that a while ago but I haven't been able to test it. http://groups.google.com/group/comp.lang.python.announce/browse_thread/thread/5d0828d7762e3586 http://cheeseshop.python.org/pypi/xlrd http://www.lexicon.net/sjmachin/xlrd.htm I'll love to read some feedback from you on it :) > > > On 8/28/06 3:00 PM, "Jorge Vargas" <jorge.vargas at gmail.com> wrote: > > > On 8/28/06, Johanna Pfalz <Johanna.Pfalz at telus.net> wrote: > >> Hi there, > >> > >> Does anyone have details on how to drive excel using python 2.4 on OSX? > >> I've searched the web and have not found anything specific to excel. > > > > drive? > >> > >> Thanks in advance, > >> > >> > >> Johanna Pfalz > >> Smithers, BC > >> > >> > >> > >> -- > >> http://mail.python.org/mailman/listinfo/python-list > >> > > Johanna Pfalz > Eclipse GIS > Smithers, BC > Office: (250) 847-3822 > Cell: (250) 877-3925 > > > -- > http://mail.python.org/mailman/listinfo/python-list > From apardon at forel.vub.ac.be Sun Aug 6 16:34:07 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 6 Aug 2006 20:34:07 GMT Subject: Nested function scope problem References: <20060804094245.A9AF.SLAWOMIR.NOWACZYK.847@student.lu.se> <1okvniwl5zgqj.dlg@gelists.gmail.com> <20060804155855.EE80.SLAWOMIR.NOWACZYK.847@student.lu.se> <mailman.8997.1154711381.27775.python-list@python.org> <vs27d2ls81p6jhugp1et05qkpe11d0mebb@4ax.com> <mailman.9003.1154731508.27775.python-list@python.org> <slrned93s3.2k4.apardon@rcpc42.vub.ac.be> <mailman.9019.1154814867.27775.python-list@python.org> Message-ID: <slrnedckhv.7h5.apardon@rcpc42.vub.ac.be> On 2006-08-05, Gerhard Fiedler <gelists at gmail.com> wrote: > On 2006-08-05 09:30:59, Antoon Pardon wrote: > >>> But this means that C variables are not analog to Python variables, >>> [...] >> >> Yes they are. > > Nobody so far has been able to create a simple table with analog operations > Python vs C that operates on C /variables/ (not dereferenced pointers) and > makes any sense. (Similar to the one Dennis just posted.) Do you have a table between analog operations on mathematical variables and C variables of Python variables? > Just do it (I mean state a few operations on/with variables in either > language, and what the analog operation in the other language is), and I > may be a convert :) There is only one operation on variables in general and that is assignment. >>> [...] C dereferenced pointers are. >> >> No they are not. a = b in Python translates to: a = b in C. It doesn't >> translate to *a = *b in C. > > Hold this thought for a little while... > >> It is true that a = b + c in Python doesn't translate to a = b + c in >> C, but since this really is a shortcut of a = b.__add__(c) there >> is nothing wrong with tranlating it into something like: >> a = IntPlus(b, c) for C, where the IntPlus will provide a new pointer >> that points to the sum [...] > > Did you hold that thought? Now IntPlus() returns a "new pointer", which > means that c is a pointer variable, not a value variable. Didn't you write > above that it wasn't a pointer? Read again. What is written is that I deny it is a *dereferenced* pointer. >> or we could provide the necessary structures so that we could translate >> is as: a = b->__add__(c) > > Which of course again requires b to be a pointer. Yes but just a pointer, not a dereferenced pointer. >From the way you seem to view dereferenced pointers as something different as variables, the only thing that makes sense IMO is that you mean the piece of memory the pointer points to, when you use "dereferenced pointer" the alternative is that you don't want to recognize pointer variables as variables in C. > You seem not to be clear > whether you want to create a C analogy (to Python variables) of C variables > (as you stated above) or of C dereferenced pointers (as your code examples > show). What exactly do you mean with dereferenced pointers. I don't talk about *dereferenced* pointers. That is your addition. >> [...] then there is something in C deserving the term variable which >> behaves like variables do in Python. > > ?? There /is/ something in C called a variable. And there is something in > Python (at least commonly) called variable. But IMO they don't behave in a > similar way. (It is obviously possible to create something in C that > behaves like a Python variable, but that's then not a C variable. It's a > more complex C construct.) You are special pleading here. The variables don't behave differently, all C variables use the same rules, a C variable doesn't behave differently depending it's type. An identifier is not any less a variable because it is a pointer to a structure instead of just an int. Your statement that it is not a variable but a more complex construct is again showing your confusing between the variable and what it is attached to. The variable is the name/identifier/symbol, it is not the (memory) location/value/object that is somehow attached to that this name/identifier/symbol. -- Antoon Pardon From horpner at yahoo.com Fri Aug 25 10:50:10 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 25 Aug 2006 16:50:10 +0200 Subject: Python and STL efficiency References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <1156445446.280027.92160@b28g2000cwb.googlegroups.com> <slrnees08s.ho.horpner@FIAD06.norwich.edu> <1156500706.638854.59980@m73g2000cwd.googlegroups.com> Message-ID: <slrneeu3gk.1kc.horpner@FIAD06.norwich.edu> On 2006-08-25, Ben Sizer <kylotan at gmail.com> wrote: > Neil Cerutti wrote: >> On 2006-08-24, JSprenkle at gmail.com <JSprenkle at gmail.com> wrote: >> > It will run a lot faster if it doesn't have to keep resizing >> > the array. >> >> I don't see why it should run a lot faster that way. >> >> Appending elements to a vector with push_back takes amortized >> constant time. In the example above, preallocating 40000 >> strings saves (probably) math.log(40000, 2) reallocations of >> the vector's storage along with the consequent >> copy-construction and destruction of some fixed number of >> strings. Most of those reallocations take place while the >> vector is still proportionally quite small. > > Math.log(40000, 2) is not a small number when talking about a > relatively expensive operation such as memory allocation and > deallocation. And the superfluous copying amounts to probably > an extra 2^16 copies in this case - not exactly trivial. Actually, I misread the suggestion. I thought I saw: vector<string> v; v.reserve(40000); instead of: vector<string> v(40000); The latter actually *slows* the program, according to my tests. I think the poster meant to suggest the former, and that's what I was discussing. I increased the number of iterations from 10000 to 100000 for the tests I'm reporting. The best of five, with reserve, was 2363 clock ticks. Without reserve, it was 3244. The suggestion to use an initial size resulted in 3655 clocks. So it appears you were more right (using reserve sped up the program by 35%, just about as the numbers predict), although we were both wrong. ;) -- Neil Cerutti 8 new choir robes are currently needed, due to the addition of several new members and to the deterioration of some of the older ones. --Church Bulletin Blooper From sjmachin at lexicon.net Tue Aug 8 18:15:05 2006 From: sjmachin at lexicon.net (John Machin) Date: 8 Aug 2006 15:15:05 -0700 Subject: newb question: file searching References: <1155067111.892386.130610@n13g2000cwa.googlegroups.com> <1155067720.211789.208560@i42g2000cwa.googlegroups.com> <1155068675.101390.299110@i3g2000cwc.googlegroups.com> <1155070517.448510.149380@b28g2000cwb.googlegroups.com> Message-ID: <1155075305.221789.322400@m79g2000cwm.googlegroups.com> jaysherby at gmail.com wrote: > And, finally, the python docs all note that symbols like . and .. > don't work with these commands. Where did you read that? The docs for os.listdir do say that '.' and '..' are (sensibly) not returned as *results*. AFAIK there is nothing to stop you using '.' or '..' as a path *argument* where appropriate/useful. > How can I grab the directory that my > script is residing in? C:\junk>type scriptdir.py import sys, os.path scriptpath = sys.argv[0] # read the docs for sys.argv print "script is", scriptpath scriptdir = os.path.split(scriptpath)[0] # read the docs for os.path.split print "script lives in", scriptdir C:\junk>scriptdir.py script is C:\junk\scriptdir.py script lives in C:\junk C:\junk>move scriptdir.py \bin C:\junk>scriptdir.py script is c:\bin\scriptdir.py script lives in c:\bin [Curiosity: drive letter is upper-case in first example, lower in second] HTH, John From tedlandis at gmail.com Wed Aug 2 15:03:51 2006 From: tedlandis at gmail.com (Ted) Date: 2 Aug 2006 12:03:51 -0700 Subject: Programming newbie coming from Ruby: a few Python questions References: <1154458926.738922.156910@h48g2000cwc.googlegroups.com> Message-ID: <1154545431.898056.212840@i42g2000cwa.googlegroups.com> I have always liked this tutorial for beginners: http://www.ibiblio.org/obp/thinkCSpy/ Cheers, Ted From gagsl-py at yahoo.com.ar Fri Aug 18 23:32:06 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 19 Aug 2006 00:32:06 -0300 Subject: efficient memoize decorator? In-Reply-To: <1155932056.313643.81420@i3g2000cwc.googlegroups.com> References: <1155931932.349283.27700@h48g2000cwc.googlegroups.com> <1155932056.313643.81420@i3g2000cwc.googlegroups.com> Message-ID: <7.0.1.0.0.20060819000545.05ae6a98@yahoo.com.ar> At Friday 18/8/2006 17:14, thattommyhallll at gmail.com wrote: >sorry >memoize is >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496879 This implementation uses cPickle to generate a key from the supplied function arguments, which is very slow and defeats the purpose of memoizing. In your example -function with no keyword arguments- use the much simpler implementation from <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/325205> NOT the original recipe but the comment by Chris Spencer titled "A working example". Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From rup at invalid.com Sat Aug 26 08:20:17 2006 From: rup at invalid.com (JAG CHAN) Date: 26 Aug 2006 12:20:17 GMT Subject: Learning Python Message-ID: <44f03c80$0$75042$14726298@news.sunsite.dk> Friends, As I had written earlier, I am trying to learn Python. I chose IDLE as an editor to learn Python. Now I find that it is an online editor. It is not possible for me to be always on online while learning. Kindly suggest me a suitable editor (for Windows XP) which does not require me to be on online. Regards. From chosechu at gmail.com Tue Aug 29 09:28:03 2006 From: chosechu at gmail.com (chosechu) Date: 29 Aug 2006 06:28:03 -0700 Subject: Extending the dict class In-Reply-To: <Xns982E918CA9DC2duncanbooth@127.0.0.1> References: <1156852916.254032.172390@b28g2000cwb.googlegroups.com> <44f4313e$0$26985$626a54ce@news.free.fr> <1156854958.228815.107090@m73g2000cwd.googlegroups.com> <Xns982E8CDD96042duncanbooth@127.0.0.1> <1156856325.095181.303140@p79g2000cwp.googlegroups.com> <Xns982E918CA9DC2duncanbooth@127.0.0.1> Message-ID: <1156858083.338457.66590@b28g2000cwb.googlegroups.com> Duncan Booth wrote: > No, you weren't able to extend the builtin dict class nor touch any its > constructor. Yes, sorry. Forgot the negation. > All you did was to create a subclass with its own constructor and hide the > name for the builtin dictionary type. The original type was still unchanged > as you can see since anything which constructed a dictionary without using > the name you had overwritten still got the original type. > > If you had looked at type(dict()) and type({}) after your subclassing, you > would see that they are different types. ... which prompted my question. And prompts yet another one: seems like it is not possible with Python to modify behaviour for base classes without recompiling the interpreter. Forgive me for asking what must surely have been asked already, but are there plans to implement something like that, <teasing>like Ruby</teasing>? I would not feel too safe navigating in a source where base object behaviour might have been re-defined, but it sure is a powerful way of adding behaviour to third-party code which you may not have possibility to modify. From tim at zoominternet.net Thu Aug 24 03:17:16 2006 From: tim at zoominternet.net (Tim Scheidemantle) Date: Thu, 24 Aug 2006 03:17:16 -0400 Subject: Problem with tokenize module and indents In-Reply-To: <44ECC8A1.6020607@zoominternet.net> References: <44ECC8A1.6020607@zoominternet.net> Message-ID: <44ED527C.2040104@zoominternet.net> Tim wrote: > I ran into a problem with a script i was playing with to check code > indents and need some direction. It seems to depend on if tabsize is > set to 4 in editor and spaces and tabs indents are mixed on consecutive > lines. Works fine when editors tabsize was 8 regardless if indents are > mixed. > Nevermind, I asked a *duh* question The simple answer is it would never compile anyway lol It's been a long week with 2 days to go... From johan2sson at gmail.com Mon Aug 7 19:11:07 2006 From: johan2sson at gmail.com (johan2sson at gmail.com) Date: 7 Aug 2006 16:11:07 -0700 Subject: Subtyping a non-builtin type in C/C++ In-Reply-To: <44D72E96.6090703@v.loewis.de> References: <1154822507.152920.182940@i3g2000cwc.googlegroups.com> <44D72E96.6090703@v.loewis.de> Message-ID: <1154992267.851573.276120@n13g2000cwa.googlegroups.com> Martin v. L?wis wrote: > johan2sson at gmail.com schrieb: > > I am trying to create a subclass of a python class, defined in python, > > in C++, but I am having some problems. > > Is the base class a classic class or a new-style class? Depending on > the answer, the code you should write varies significantly. > > To create a new type, it might be easiest to do the same as the > interpreter. Take, for example, a look at the code that gets executed > for new.classobj("Foo", (), {}). I deleted my post once I realized that I had been setting tp_bases when I should have been setting tp_base. As it turns out, that's not the end of my problems. I have looked in classobject.c, which I hope is the code you are referring to, but that doesn't really solve my problem since it assumes you have the correct base pointers and if I did I would be having a different problem! Anyway, back to the current one: The class I am trying to subclass is code.InteractiveConsole. With tp_base set to the result of PyMapping_GetItemString(PyModule_GetDict(code_module), "InteractiveConsole"), PyType_Ready fails with an AttributeError with a "value" of "mro" and looking at the structure in a debugger just before the call to PyType_Ready makes me think it's corrupted somehow (nonprintable name and clearly uninitialized fields). I can however create an instance by calling PyObject_CallFunction on that object. If I do, it's type (ob_type->tp_name) will be "instance". Of course, I don't know the python type system that well, but I must confess I was expecting it to be "code.InteractiveConsole". What gives? If I then lookup the __class__ attribute of that instance I am back full circle at the object with the unprintable name and garbage fields. The head does seem to be valid and if it means anything to someone it's ob_type->tp_name is "classobj". For several hours I actually wondered why it wasn't "Type" but I guess it's just a ... subtype of Type. I guess I should just go to bed. Johan From rogue_pedro at yahoo.com Tue Aug 8 01:18:14 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 7 Aug 2006 22:18:14 -0700 Subject: Import module with non-standard file name References: <mailman.9069.1154999229.27775.python-list@python.org> Message-ID: <1155014294.593388.137550@n13g2000cwa.googlegroups.com> Ben Finney wrote: > Howdy all, > > Question: I have Python modules named without '.py' as the extension, > and I'd like to be able to import them. How can I do that? > > Background: > > On Unix, I write programs intended to be run as commands to a file > with no extension. This allows other programs to use the command as an > interface, and I can re-write the program in some other language > without obsoleting the commandline interface. > > e.g., I might write 'frobnicate-foo' as a shell program so that other > programs can 'frobnicate-foo --bar baz'. If I later decide to > re-implement 'frobnicate-foo' in Python, I'll save the top level > module to the same file name since it implements the same command-line > interface. > > Now that I've got it written as a Python module, I'd like to write > unit tests for that module, which of course will need to import the > program module to test it. The unit test can explicitly add the > directory where the program module lives to 'sys.path' for the purpose > of importing that module. > > However, the Python reference tells me that 'import' (specifically, > '__import__()') needs modules to live in files named a particular way: > with a '.py' suffix. But my module is in a file called > 'frobnicate-foo', with no suffix, and that's part of the definition of > the program interface. > > I don't want symbolic links, or anything else that presents two > filenames for the same module, because there's no need for that except > for Python's apparent insistence on a particular naming > convention. Also, avoiding symbolic links inside the source code tree > makes version control smoother. > > > What are my options to import a module from a file whose name can't > change? > > -- > \ "[W]e are still the first generation of users, and for all that | > `\ we may have invented the net, we still don't really get it." | > _o__) -- Douglas Adams | > Ben Finney Leave your python module with the .py extension and create a small python script without the .py extension to import and run your code from the command line. For example, on my [linux] system /usr/local/bin/idle contains this: #!/usr/bin/python from idlelib.PyShell import main if __name__ == '__main__': main() You also get a modest performance boost because the interpreter will only process the text of this small script but will use the precompiled byte-code .pyc files (when available) of your main module, rather than re-parsing its text. HTH, ~Simon From stevebread at yahoo.com Mon Aug 21 06:38:44 2006 From: stevebread at yahoo.com (stevebread at yahoo.com) Date: 21 Aug 2006 03:38:44 -0700 Subject: Regular Expression question References: <1156153916.849933.178790@75g2000cwc.googlegroups.com> <1156154876.874272.283160@i3g2000cwc.googlegroups.com> Message-ID: <1156156724.165790.208880@b28g2000cwb.googlegroups.com> Thanks, i just tried it but I got the same result. I've been thinking about it for a few hours now and the problem with this approach is that the .*? before the (?=tag2) may have matched a tag1 and i don't know how to detect it. And even if I could, how would I make the search reset its start position to the second tag1 it found? From rpdooling at gmail.com Mon Aug 7 17:32:52 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 7 Aug 2006 14:32:52 -0700 Subject: format a number for output In-Reply-To: <7xwt9kth6m.fsf@ruckus.brouhaha.com> References: <1154962511.485221.229830@i3g2000cwc.googlegroups.com> <7xwt9kth6m.fsf@ruckus.brouhaha.com> Message-ID: <1154986372.482494.240410@75g2000cwc.googlegroups.com> Paul Rubin wrote: > "To iterate is human; to recurse, divine": > > def commafy(n): > if n < 0: return '-' + commafy(-n) > if n >= 1000: return '%s,%03d' % (commafy(n//1000), n % 1000) > return '%s'% n > > I don't like the locale solution because of how messy locales are. That's a keeper! Thanks! rd From jon+usenet at unequivocal.co.uk Mon Aug 7 12:46:34 2006 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 7 Aug 2006 16:46:34 GMT Subject: need an alternative to getattr() References: <1154961041.067164.199520@i42g2000cwa.googlegroups.com> Message-ID: <slrnederj9.31r.jon+usenet@snowy.squish.net> In article <1154961041.067164.199520 at i42g2000cwa.googlegroups.com>, pranav.choudhary at gmail.com wrote: > import heading1 > import heading2 > While True: > heading = get_next_heading(file_ptr) # This func will return > "heading1", then "heading2"(on next call) > if heading = "": > break > getattr(heading, "process")(file_ptr) # The problem, as you would > have noticed, is that the first > # argument to getattr is a string!! > > Is there an alternatice to getattr() that will solve my problem, or is > there another way to do it. globals()[heading].process(file_ptr) or sys.modules[heading].process(file_ptr) but note that, unless you are checking 'heading' against a 'known good configuration keywords' list beforehand, you are trusting the author of the configuration file. From bytter at gmail.com Fri Aug 11 07:23:14 2006 From: bytter at gmail.com (Bytter) Date: 11 Aug 2006 04:23:14 -0700 Subject: Rendering Vector Graphics In-Reply-To: <1155294149.767533.215190@m79g2000cwm.googlegroups.com> References: <1155293639.748785.316170@m73g2000cwd.googlegroups.com> <1155294149.767533.215190@m79g2000cwm.googlegroups.com> Message-ID: <1155295394.357278.168200@m73g2000cwd.googlegroups.com> Hi! h112211 at gmail.com wrote: > > I need to render high-quality vector graphics with Python. I was > > thinking of something like 'cairo', though I need to run under win32 > > and can't find a pycairo package for it. Suggestions? > > I've had good experiences doing simple 3d vector stuff with Pygame. > It's wraps SDL so it has pretty nice capabilities. What about 2D? I won't be doing any 3d stuff, though I need high-quality 2D, and complex stuff like defining clipping regions with bezier curves and filling with gradients. Thanks! Hugo Ferreira From fakeaddress at nowhere.org Sun Aug 13 20:57:26 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Mon, 14 Aug 2006 00:57:26 GMT Subject: NNTPLIB STRANGE ERROR In-Reply-To: <1155497079.234800.234260@p79g2000cwp.googlegroups.com> References: <1155497079.234800.234260@p79g2000cwp.googlegroups.com> Message-ID: <WTPDg.8017$kO3.6116@newssvr12.news.prodigy.com> 2Good4You-Veki(Cro) wrote: > when I want use python nntplib: [...] > error: (10053, 'Software caused connection abort') That's not such a strange error; various network problems can cause it. It means something went wrong with the TCP connection, so your system aborted it. Does it happen consistently at that point? -- --Bryan From bedouglas at earthlink.net Thu Aug 10 20:54:16 2006 From: bedouglas at earthlink.net (bruce) Date: Thu, 10 Aug 2006 17:54:16 -0700 Subject: seaching a list... In-Reply-To: <XcudnSMOqtVWXUbZnZ2dnUVZ_qqdnZ2d@comcast.com> Message-ID: <278501c6bce0$ae5d3cc0$0301a8c0@Mesa.com> hi larry... thanks for the reply... the issue i'm having is that i'm going to have to compare multiple rows of information to the information in the db. so essentially i'd have to do a hit to the db, for each row of information i want to compare if i did it your way... (which was what i had thought about) the issue of doing the string/list compare/search is that i can get everything from the db with one call... i can then iterate through memory for each of my row information that i'm searching to see if it exists in the db... memory searches should be faster than the network overhead, and the associated multiple db calls... -bruce -----Original Message----- From: python-list-bounces+bedouglas=earthlink.net at python.org [mailto:python-list-bounces+bedouglas=earthlink.net at python.org]On Behalf Of Larry Bates Sent: Thursday, August 10, 2006 4:28 PM To: python-list at python.org Subject: Re: seaching a list... bruce wrote: > hi... > > i'm playing with a test sample. i have somethhing like: > dog = mysql_get(.....) > . > . > . > > such that 'dog' will be an 'AxB' array of data from the tbls > > furher in the test app, i'm going to have a list, foo: > foo = 'a','b','c','d' > > i'm trying to determine what's the fastest way of searching through the > 'dog' array/list of information for the 'foo' list. > > should i essentially make dog into A lists, where each list is B elements, > or should it somehow combine all the elements/items in 'dog' into one large > list, and then search through that for the 'foo' list... > > also, in searching through google, i haven't come across the list.search > function.. so just how do i search a list to see if it contains a sublist... > > my real problem involves figuring out how to reduce the number of hits to > the db/tbl... > > thanks > > ps. if this is confusing, i could provide psuedo-code to make it easier to > see... > > > > You should use the database for what it is good at storing and searching through data. Don't read all the data from a table and search through it. Rather, create indexes on the table so that you can locate the data quickly in the database by passing in something you are looking for and let the database do the searching. I can promise you this will almost always be faster and more flexible. Something like: Assume the columns are called rownumber, c1, c2, c3, c4 and the table is indexed on c1, c2, c3, and c4. This will happen almost instantly no matter how many rows you are searching for. select rownumber from database_table where c1="a" and c2="b" and c3="c" and c5="d" It takes one "hit" to the db/table to return the rowindex that matches. -Larry Bates -- http://mail.python.org/mailman/listinfo/python-list From gherron at islandtraining.com Thu Aug 3 03:22:06 2006 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 03 Aug 2006 00:22:06 -0700 Subject: can this b done In-Reply-To: <1154588403.626530.72450@b28g2000cwb.googlegroups.com> References: <1154588403.626530.72450@b28g2000cwb.googlegroups.com> Message-ID: <44D1A41E.5040501@islandtraining.com> JyotiC wrote: > hi, > > i hv a var of type IntVar, ca i get the name of this variable > > eg:- > class someclass: > def somefun(...): > self.var=IntVar() > .... > > def someotherfun(...): > in this fun can i get the name of var. > as in, can i get name var as a string 'var' > > Thanx > > Perhaps this will do what you want: An instance of a class maintains a dictionary of all it's local variables. One of those will be self.var, but any other local variables will also be in the dictionary -- I have no idea how you plan to specify *which* local variable you want the name of. Anyway, the dictionary is: self.__dict__ and the list of variable names is the dictionary's keys: self.__dict__.keys() and one of the elements in that list will be the string: 'var' Hope that helps: Gary Herron From michiel at thingmajig.org Tue Aug 8 04:40:37 2006 From: michiel at thingmajig.org (Michiel Sikma) Date: Tue, 8 Aug 2006 10:40:37 +0200 Subject: do people really complain about significant whitespace? In-Reply-To: <87bqqwyumq.fsf@benfinney.id.au> References: <1154986984.740638.241130@m79g2000cwm.googlegroups.com> <87bqqwyumq.fsf@benfinney.id.au> Message-ID: <A1CBD12F-3A33-454A-A923-19F2BF82E9A2@thingmajig.org> Op 8-aug-2006, om 1:49 heeft Ben Finney het volgende geschreven: > As others have pointed out, these people really do exist, and they > each believe their preconception -- that significant whitespace is > intrinsically wrong -- is valid, and automatically makes Python a > lesser language. Well, I most certainly disagree with that, of course, but you gotta admit that there's something really charming about running an auto- formatting script on a large piece of C code, turning it from an unreadable mess into a beautifully indented and organized document. I actually sometimes intentionally programmed ugly code so that I could do that. I kind of miss it. :) Michiel From johnjsal at NOSPAMgmail.com Sun Aug 13 00:44:25 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 13 Aug 2006 00:44:25 -0400 Subject: [OT] John Salerno In-Reply-To: <slrnedt7ad.1bs.i3x9mdw@b29x3m.invalid> References: <44dd3a65$0$2381$c3e8da3@news.astraweb.com> <slrnedqpef.18n.i3x9mdw@b29x3m.invalid> <44de73c3$0$12587$c3e8da3@news.astraweb.com> <slrnedt7ad.1bs.i3x9mdw@b29x3m.invalid> Message-ID: <44deaecb$0$12581$c3e8da3@news.astraweb.com> Alan Connor wrote: > So. You post using three different newsservers, which no one who > posts under the same alias all the time does. > > And there are virtually no Linux groups in your posting history > for the last year. Wow, you need some help. I post at work on one server, and then also at home on another (and sometimes two), on both Windows and Linux, which I just installed last Saturday and am currently exploring for the first time. If that isn't enough to convince you, then *you* are the troll. From cliff at develix.com Sat Aug 26 16:03:54 2006 From: cliff at develix.com (Cliff Wells) Date: Sat, 26 Aug 2006 13:03:54 -0700 Subject: Out-dated compiled modules (*.pyc)? In-Reply-To: <bg41f2p2b5ri1nivoglue0kto6k826ma23@4ax.com> References: <mailman.9923.1156607371.27775.python-list@python.org> <bg41f2p2b5ri1nivoglue0kto6k826ma23@4ax.com> Message-ID: <1156622634.13625.1.camel@devilbox> On Sat, 2006-08-26 at 18:54 +0000, Dennis Lee Bieber wrote: > Normally, Python compares the date stamps of the files (and maybe > some internal magic values) and only rebuilds the .pyc if the .py is > newer. Perhaps the OP should check both the system date on his PC and the timestamp on the pyc files in question. Cliff From vedran_dekovic at yahoo.com Thu Aug 31 08:41:43 2006 From: vedran_dekovic at yahoo.com (vedran_dekovic at yahoo.com) Date: 31 Aug 2006 05:41:43 -0700 Subject: Tkinter listbox question Message-ID: <1157028103.075184.149250@i3g2000cwc.googlegroups.com> Hi, I need help about Tkinter listbox widget.I want,when somebody click on any item(file) in Listbox,then in new Label widget text must be selected item from server. my program (wrong example): import ftputil import Tkinter root=Tkinter.Tk() ftp=ftputil.FTPHost('some imaginary server') def LabelWidget(event): a=Tkinter.Label(root,text=) # Text must be only name and file format,example: sun.gif a.grid() b=Tkinter.Listbox(root) b.insert(Tkinter.END,ftp._dir('')) b.place() c=Tkinter.Button(root,text='PRINT THIS FILE IN NEW LABEL WIDGET') c.bind('<Button-1>',LabelWidget) c.grid() root.mainloop() THANKS!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! From carsten at uniqsys.com Tue Aug 1 12:42:40 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 01 Aug 2006 12:42:40 -0400 Subject: Can't get LCHARVAR's with InformixDB In-Reply-To: <1154446906.915203.13790@m73g2000cwd.googlegroups.com> References: <1154437329.471918.35150@h48g2000cwc.googlegroups.com> <mailman.8792.1154437891.27775.python-list@python.org> <1154438862.714569.9130@b28g2000cwb.googlegroups.com> <mailman.8794.1154439925.27775.python-list@python.org> <1154446906.915203.13790@m73g2000cwd.googlegroups.com> Message-ID: <1154450560.452.53.camel@dot.uniqsys.com> On Tue, 2006-08-01 at 11:41, fhurley at gmail.com wrote: > Carsten Haese wrote: > > Could you possibly send me a minimal test script that shows the problem? > > Also, in case it matters, I'd like to know which versions of IDS and > > CSDK or Informix Connect you're using. > > > Here's a sample script: > > sql = '''select msg_tx from dev_log''' > import informixdb > conn = informixdb.connect('mydb') > cursor = conn.cursor() > cursor.execute(sql) > print 'description is <%s>' % cursor.description > print cursor.fetchall() Thanks, but I can't use this to reproduce the problem. I'll need the create table statement for dev_log. > Output is: > description is <('msg_tx', 'lvarchar', 0, 0, None, None, 1)> > [('',), ('',), ('',), ('',), ('',), ('',)] > > But one of them should be: > '''Something:SomethingElse - going for 221 possibilities [User: > HOST-NAME\XYZZY]: > Id OtherData > 5878 C > 5968 X > 6732 V > [many more lines like this] > ''' > > Some hunting around, and I found this: > > C:\Program Files\Informix\Client-SDK\bin>esql > IBM Informix CSDK Version 2.80, IBM Informix-ESQL Version 9.52.TC1 > > Not sure what IDS is... the Informix Server version is: 9.3 FC3, > according to the DBA guy. IDS = Informix Dynamic Server. The version numbers you gave me are what I was looking for. For what it's worth, I've tried a simple test script on my Linux server that creates a temp table with an lvarchar column, inserts into it, and reads from it, all without a problem. However, there are many differences between my test environment and yours, and I'll need to know your specific circumstances to isolate which difference is causing the problem. Thanks, Carsten. From subramanian2003 at indiatimes.com Wed Aug 16 23:25:28 2006 From: subramanian2003 at indiatimes.com (subramanian2003) Date: Thu, 17 Aug 2006 08:55:28 +0530 Subject: Python for arcgis Message-ID: <200608170208.HAA13239@WS0005.indiatimes.com> Hello All, From where can I get the python tutorial for arcgis customisation?. Bye, Subramanian. Sign Up for your FREE eWallet at www.wallet365.com From taleinat at gmail.com Tue Aug 8 14:09:26 2006 From: taleinat at gmail.com (taleinat) Date: Tue, 8 Aug 2006 18:09:26 +0000 (UTC) Subject: Looking for an intellisense with good help IDE for Python References: <1155022590.845074.256900@i42g2000cwa.googlegroups.com> Message-ID: <loom.20060808T193057-331@post.gmane.org> metaperl <metaperl <at> gmail.com> writes: > Hi, > > I would like an IDE that shows me all methods and functions I can call > on a particular data item. For instance, iter() can be called on any > sequence, but it is not a method. > > Nonetheless, I would like for something to show me every thing that I > can call on a particular data item. Most built-in functions which can be called on objects simply call the objects' respective __*__ method. But this isn't always true (as for iter()); it is an interesting idea for code completion. I haven't seen any Python IDE do this, but if you can convince me it's worth the effort, maybe that will change :) As for other functions (not built-in), since there is no way in Python for a function to declare a required type or interface for an argument, this seems quite impossible. Question: There are several built-in functions which can be called on any object, such as str(), repr(), dir(), id() and type() - would you really want to see all of those every time? I feel it would just clutter the completion list. As an implementation issue, silly programmers overriding built-in functions by accident would have to be taken into account... > This includes % after a string. But only if there are conversion specifiers in the string, right? ;) Seriously though, isn't it much, much simpler to just hit shift+5? I feel this would needlessly clutter the list of completions. Why do you want this? > I would also like browseable help with good examples on whatever > methods and functions and operators it pops up. Such help can easily be found in the Pydocs under "Built-in Functions". Under Windows, this is a .chm help file which is browseable. Also, many IDEs show calltips for functions, showing the arguments and/or docstring. > Thanks, > Terrence - Tal Einat reduce(lambda m,x:[m[i]+s[-1] for i,s in enumerate(sorted(m))], [[chr(154-ord(c)) for c in '.&-&,l.Z95193+179-']]*18)[3] From could.net at gmail.com Tue Aug 22 03:39:20 2006 From: could.net at gmail.com (could.net at gmail.com) Date: 22 Aug 2006 00:39:20 -0700 Subject: How can I enumerate all windows services and disable some of them? Message-ID: <1156232360.032758.176760@m73g2000cwd.googlegroups.com> I know that Module win32service has some functions on manipulating win32 services. But I still have 2 questions: 1. how to enumerate all services? 2. how to disable a certain one? Thanks in advance! From johnjsal at NOSPAMgmail.com Fri Aug 4 11:25:09 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 04 Aug 2006 15:25:09 GMT Subject: new Python release date (Sept. 12) Message-ID: <pFJAg.2640$No6.51794@news.tufts.edu> just in case you don't check the PEP obsessively like i do (i'm really excited for 2.5!), the new release dates are: rc 1: August 18, 2006 [planned] final: September 12, 2006 [planned] although in the Abstract it still shows August 19...where can that be reported? From mail at microcorp.co.za Sat Aug 26 04:52:00 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 26 Aug 2006 10:52:00 +0200 Subject: Consistency in Python References: <mailman.9855.1156495956.27775.python-list@python.org> <4l7srhFm908U2@uni-berlin.de> Message-ID: <01d801c6c8ed$052a4b20$03000080@hendrik> "Diez B. Roggisch" <deets at nospam.web.de> wrote, oder schrieb, of het geskryf: | Hendrik van Rooyen schrieb: | > Hi, | > | > for S where S is a Standard Python type: | > The slice notation S[n] returns either: | > The n'th element of S, or | > The value of the dictionary entry whose key is n. | > | > This is beautiful because as a programmer you don't have to worry what S is... | > (and as an aside - This consistency has already saved my butt when I thought I | > was working with a string that turned out to be a tuple instead - and still | > worked perfectly as expected...) | > | > Now consider what you have to do to add an element to S... | > (where "add" is used in its meaning of increasing the size of a set, and not 1 + | > 1 = 2) | > | > There seems to be no common methods such as- | > "prepend" - for adding something to the beginning | > "append" - for adding something to the end | > "insert[j]" - for adding something somewhere in the middle | > | > Or have I missed something ? | | Yes, the nature of collections. dictionaries have no notion of | "somewhere in the middle". Most of the time they are unordered. If they | are ordered, they can be ordered by insertion time, key or value value. | And they always need key, value | | So - all these three methods only make sense on sequences which imply a | key (the index), and are mutable of course - which is why they are | available on lists only. | | Diez I understand that dicts are actually a bit special - Its very simple to add something to a dict - you just do it - but the in the other cases what I have in mind is more in line with some of what Paul Boddie wrote... - Hendrik From max at alcyone.com Wed Aug 9 04:26:38 2006 From: max at alcyone.com (Erik Max Francis) Date: Wed, 09 Aug 2006 01:26:38 -0700 Subject: #!/usr/bin/python or #!/usr/bin/env python? In-Reply-To: <ebc58g$h22$1@kohl.informatik.uni-bremen.de> References: <fj5Cg.2658$No6.51984@news.tufts.edu> <bL6dnTXbq9adbkXZnZ2dnUVZ_u2dnZ2d@speakeasy.net> <ebbtor$evr$1@kohl.informatik.uni-bremen.de> <mailman.9130.1155106885.27775.python-list@python.org> <ebc288$g8s$1@kohl.informatik.uni-bremen.de> <vsgCg.66818$zy5.1253926@twister1.libero.it> <ebc58g$h22$1@kohl.informatik.uni-bremen.de> Message-ID: <JfOdncqW_fzdAUTZnZ2dnUVZ_uWdnZ2d@speakeasy.net> Stephan Kuhagen wrote: > Yes, the same happens with all Tcl-Scripts. I like to see this as a bug in > "file", not in the scripting... How does that make sense? `file` cannot possibly understand the semantics of files at that level, at least not without executing them. And that's exactly what you _don't_ want to do when you're using `file` ... The file _is_ a /bin/sh executable. You're just having that /bin/sh executable run something else -- how could `file` figure that out without a ridiculously complicated set of rules that rise to the level of a sh interpreter -- thereby, defeating the purpose? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Only those who dare to fail greatly can ever achieve greatly. -- Robert F. Kennedy From deets at nospam.web.de Tue Aug 8 06:03:13 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 08 Aug 2006 12:03:13 +0200 Subject: beginner questions on embedding/extending python with C++ References: <1155029311.885266.131980@m73g2000cwd.googlegroups.com> Message-ID: <4jr5jsF9d813U1@uni-berlin.de> > Since the main program is still going to be the C++ application, I > guess we need to embedding the python scripts in the C++ code. So at > initialization stage, the python script needs to be loaded into the C++ > code. And this code can be simple, like > player = Player() > game.loadPlayer(player) > > > But for this to work, the python code needs to know the Player class, > is it right? Does that mean I need to build a python wrapper class for > Player and "import Player" in the python code? But because this > application is built on top of a game engine, Player class inherits > many classes from there, I cannot possibly wrapping them all, right? > Also, some global objects are probably needed in this code of adding > players, how can the python code access them? You should look into SIP besides the tools you already mentioned - IMHO it is the best choice for wrapping C++. And yes, you need to wrap classes - but only those that are of interest for you! So if you need Player, wrap Player. No need to wrap it's base-classes, unless you want these for other purposes, too. And for global objects I'd create functions which return these. I suggest you try and download a project that uses one of the possible toolkits for wrapping - the most prominent user of SIP is of course PyQt. Go and have a look at the source, how things are done. There aresome tutorials I think, google should help you on that. HTH Diez From missdeer at gmail.com Wed Aug 2 13:09:02 2006 From: missdeer at gmail.com (Yang Fan) Date: Thu, 3 Aug 2006 01:09:02 +0800 Subject: PyImport_Import() failed Message-ID: <de59955b0608021009r22e01074g291d2e09fbecec21@mail.gmail.com> Hello, I'm new to Python.I want to embed Python interpreter into my C++ application powered by Borland C++ Builder 2006. I have written some C++ code in order to evaluate Python script file, but PyImport_Import() calls failed.I really don't know what's wrong with my cpp code.It always return a NULL value. Any advice is appreciated! int TPython::ExecuteScript(const char * pszFileName) { PyObject *pFileName, *pModule, *pDict, *pFunc; PyObject *pArgs, *pValue; pFileName = PyString_FromString(pszFileName); /* Error checking of pFileName left out */ if(!pFileName) { trace1(("pFileName == NULL ")); } pModule = PyImport_Import(pFileName); // always failed, returned NULL:( Py_DECREF(pFileName); if (pModule != NULL) { ................ } else { PyErr_Print(); trace1(("Failed to load \"%s\"\n", pszFileName)); return 1; } return 0; } -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060803/f258046f/attachment.html> From tjreedy at udel.edu Tue Aug 8 16:33:21 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 8 Aug 2006 16:33:21 -0400 Subject: Proposal: [... for ... while cond(x)] References: <1154879331.903490.106020@m73g2000cwd.googlegroups.com> <1155064682.499991.246170@h48g2000cwc.googlegroups.com> Message-ID: <ebaseh$ccf$1@sea.gmane.org> "Eighty" <eightyx at gmail.com> wrote in message news:1155064682.499991.246170 at h48g2000cwc.googlegroups.com... > > Eighty wrote: >> I suggest a new extension of the list comprehension syntax: >> >> [x for x in xs while cond(x)] This does not work. e(x) for x in xs if cond(x) is an abbreviation of for x in xs: if cond(x) yield e(x) and similarly with more for and if clauses, whereas the analogous expansion of your proposal for x in xs: while cond(x): yield e(x) is an infinite loop and not at all what you mean. >> which would be equivalent to >> >> list(itertools.takewhile(cond, xs)) And what would x for x in xs while cond(x) if blah(x) x for x in xs if blah(x) while cond(x) x*y for x in xs while cond(x) for y in ys mean? The ability to mix and match clauses after the first for clause is an important part of comprehension syntax. >> + "Takewhile operations" occur often, at least for me So keep using the function provided. I am pretty sure takewhile is rare for most other people. > So does no one have a comment on this? Ain't gonna happen. > The one objection I can come up with > is that this would change the set builder notation semantics too much Yes, to the point where you are hijacking the syntax, for no useful gain, more than extending it ;-). Terry Jan Reedy From fanglicheng at gmail.com Mon Aug 21 04:09:45 2006 From: fanglicheng at gmail.com (Licheng Fang) Date: 21 Aug 2006 01:09:45 -0700 Subject: Python and STL efficiency In-Reply-To: <pan.2006.08.21.07.48.24.455806@gmx.net> References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <pan.2006.08.21.07.48.24.455806@gmx.net> Message-ID: <1156147785.788817.261920@i3g2000cwc.googlegroups.com> Marc 'BlackJack' Rintsch wrote: > In <1156143136.020647.294290 at i42g2000cwa.googlegroups.com>, Licheng Fang > wrote: > > > Hi, I'm learning STL and I wrote some simple code to compare the > > efficiency of python and STL. > > > > //C++ > > #include <iostream> > > #include <string> > > #include <vector> > > #include <set> > > #include <algorithm> > > using namespace std; > > > > int main(){ > > vector<string> a; > > for (long int i=0; i<10000 ; ++i){ > > a.push_back("What do you know?"); > > a.push_back("so long..."); > > a.push_back("chicken crosses road"); > > a.push_back("fool"); > > } > > set<string> b(a.begin(), a.end()); > > unique_copy(b.begin(), b.end(), ostream_iterator<string>(cout, "\n")); > > } > > Why are you using `unique_copy` here? Sorry, that's a typo. Actually I used 'copy'. > > > #python > > def f(): > > a = [] > > for i in range(10000): > > a.append('What do you know') > > a.append('so long...') > > a.append('chicken crosses road') > > a.append('fool') > > b = set(a) > > for s in b: > > print s > > > > I was using VC++.net and IDLE, respectively. I had expected C++ to be > > way faster. However, while the python code gave the result almost > > instantly, the C++ code took several seconds to run! Can somebody > > explain this to me? Or is there something wrong with my code? > > There's a difference in data structures at least. The Python `set` type > is implemented with a hash algorithm, so the equivalent STL type would be > `hash_set`. `set` in Python does not store its contents sorted. > > Ciao, > Marc 'BlackJack' Rintsch Thank you for your comments. I tested with hash_set, but I didn't see much performance improvement. When I increased the loop to 1 million times, the python code still ran reasonably fast and the C++ code got stuck there. This totally surprised me, because according this page http://norvig.com/python-lisp.html, the speed of python is nowhere near that of C++. From faulkner612 at comcast.net Fri Aug 25 17:42:07 2006 From: faulkner612 at comcast.net (faulkner) Date: 25 Aug 2006 14:42:07 -0700 Subject: Newbie programmer question: How do parsers work?(Python examples?) In-Reply-To: <1156535724.221400.175230@m79g2000cwm.googlegroups.com> References: <1156535724.221400.175230@m79g2000cwm.googlegroups.com> Message-ID: <1156542126.971664.127500@i42g2000cwa.googlegroups.com> http://pages.cpsc.ucalgary.ca/~aycock/spark/ http://www-128.ibm.com/developerworks/library/l-spark.html bio_enthusiast wrote: > I was wondering exactly how you create a parser. I'm learning > Python and I recently have come across this material. I'm interested > in the method or art of writing a parser. > > If anyone has some python code to post for an abstract parser, or links > to some informative tutorials, that would be great. From sjmachin at lexicon.net Thu Aug 10 18:41:02 2006 From: sjmachin at lexicon.net (John Machin) Date: 10 Aug 2006 15:41:02 -0700 Subject: semi-Newbie question In-Reply-To: <1155229897.356144.183750@m79g2000cwm.googlegroups.com> References: <1155229897.356144.183750@m79g2000cwm.googlegroups.com> Message-ID: <1155249662.630469.179180@74g2000cwt.googlegroups.com> len wrote: > Hi all > > I have a file that I receive from another party which is basicly a csv > file containing the following type of information; > > Tagname Scope Value > "first_name","POL01","John" > "last_name","POL01","Doe" > "birthday","POL01","04/03/61" > etc > > I need to convert this file info into my file format used in my > application. > > I have been given a file from the other company that gives me all of > the tagname that could be used and their scope. I want to build a > table which would have all of the various tagnames, scope, and put a > fieldname equivalent in the fieldname in my file structure in my > application. Then read through the vendors csv file index into my > table file and get the field name of where to move the data into my > data structure. > > Here is my question? basicly I need to get the data referenced by > fieldname variable in my table and then use that data as a variable > name in a python assignment statement. Thus changing the actual python > code at each iteration through the lines in the csv file. > > for i in tagfile > find tagname in tagtable > > *** the following line of code would change through each iteration *** > myfirst = value > > *** next iteration > mylast = value > > *** next iteration > mybirth = value > > etc > > I hope this make sense. I remember seeing something like this > somewhere. > You need to define the problem much better than you have in your two postings so far. Give a small realistic sample of input file and the relevant parts of the xref file plus (the main missing component so far) the actual OUTPUT that you desire from that input. Then we can talk about implementatiion. However while we're waiting, wtite this on your whiteboard: (1) *DO* use the csv module; DIY approaches blow up spectacularly when presented with data which has embedded commas and quotes, and don't say it can't happen because it does. (2) *DON'T* pay any attention to suggestions that you should use exec or eval. The likelihood that your problem *needs* that "the following line of code would change through each iteration" is very small. The likelihood that the solution can be written in a straight-forward manner is high. What are your "SQL files"? Do you mean insert scripts that you will use to inject the transformed incoming into a database, or something else? Again, a short *example* of what you are referring to would help. HTH, John From aahz at pythoncraft.com Fri Aug 25 10:34:50 2006 From: aahz at pythoncraft.com (Aahz) Date: 25 Aug 2006 07:34:50 -0700 Subject: Don't use __slots__ (was Re: performance of dictionary lookup vs. object attributes) References: <mailman.9853.1156495094.27775.python-list@python.org> <1156508104.583914.323700@b28g2000cwb.googlegroups.com> Message-ID: <ecn1qa$ksp$1@panix2.panix.com> In article <1156508104.583914.323700 at b28g2000cwb.googlegroups.com>, <bearophileHUGS at lycos.com> wrote: >Andre Meyer: >> >> Is the test meaningful and are you surprised by the results? >> I am, actually, because I would have assumed that attribute access >> with an object should be faster because lookup can be precompiled. > >The results seem okay. Python is a dynamic language, object attributes >(and methods, etc) are kept inside a dict, where you can add and remove >them when you like. So using a dict is faster. >You can also take a look at __slots__ Taking a look at __slots__ is fine as long as you don't actually use them. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." --Brian W. Kernighan From johnjsal at NOSPAMgmail.com Tue Aug 8 11:30:33 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 08 Aug 2006 15:30:33 GMT Subject: Tkinter module not found In-Reply-To: <1155049496.292471.37020@h48g2000cwc.googlegroups.com> References: <1155049496.292471.37020@h48g2000cwc.googlegroups.com> Message-ID: <t62Cg.2648$No6.52006@news.tufts.edu> Shuaib wrote: > Hey, > > Even though I freshly installed Tcl and Tk, python still seem to have > problems accessing Tkinter module. Here is what says when I do "import > Tkinter" > > == > Traceback (most recent call last): > File "<stdin>", line 1, in ? > ImportError: No module named Tkinter > == > > Any ideas how to fix this problem? (Gentoo distribution) > > Thanks. > The cause of this is usually that you are using a different version of Python than the one you installed Tkinter into, but being a Linux newbie I have yet to discover how to redirect the 'python' command to invoke the newer version of Python. From steve at holdenweb.com Thu Aug 17 12:08:17 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 17 Aug 2006 17:08:17 +0100 Subject: Python2.5 RC1 vs sgmlop.c In-Reply-To: <44E48D25.2000900@chamonix.reportlab.co.uk> References: <44E48D25.2000900@chamonix.reportlab.co.uk> Message-ID: <44E49471.3010004@holdenweb.com> Robin Becker wrote: > I have a segfault problem in Python2.5 RC1 (win32) when using the venerable > extension sgmlop.c. > > In case that was just because our copy was very old I downloaded a later source > from http://pyxml.cvs.sourceforge.net, but that code (version 1.14 loewis) still > suffers from this problem. > > The problem occurs after a call to free at line so I'm guessing something has > changed related to allocations. Is there some magic going on which redefines > malloc/realloc etc etc? I'm fairly sure the object in question (-->buffer) isn't > passed directly to python so I would have thought that malloc/realloc/free were > appropriate. Another parser attribute does hold an array of pointers to python > objects, but again I don't think that should be a problem. > > Has anyone got any clue what the problem might be or a fixed version of the code? I'm guessing this might be to do with the changes that have been made to enable 64-bit readiness in the code, but I couldn't suggest specifics. Suspect all pointers and integers first :-) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From cemerick at snowtide.com Wed Aug 23 12:15:33 2006 From: cemerick at snowtide.com (Chas Emerick) Date: Wed, 23 Aug 2006 12:15:33 -0400 Subject: Python + Java Integration In-Reply-To: <mailman.35559.1156348202.27774.python-list@python.org> References: <mailman.35559.1156348202.27774.python-list@python.org> Message-ID: <BE0BE96E-3C85-40F7-A0A6-C839415D8599@snowtide.com> On Aug 23, 2006, at 11:50 AM, Ben Sizer wrote: > Chas Emerick wrote: >> There is no doubt that Ruby's success is a concern for anyone who >> sees it as diminishing Python's status. One of the reasons for >> Ruby's success is certainly the notion (originally advocated by Bruce >> Tate, if I'm not mistaken) that it is the "next Java" -- the language >> and environment that mainstream Java developers are, or will, look to >> as a natural next step. > > Is it? I thought it was more along the lines of "you've been > struggling > with Java to build web-apps all this time - here, have Ruby on Rails > which is much easier". Python provides just as much simplicity in the > web frameworks, but no consensus on what is 'best' (recent BDFL > pronouncement aside), and thus only a small community for each > framework. I bet that if Django or TurboGears had been fully ready for > prime-time before Ruby on Rails, we wouldn't be having this > discussion. There's a lot of truth in that, but there's no doubt that there is a meme out there that Ruby is the "next Java", regardless of any technical facts. This is all marketing and perception, which is why I was positing JPype as being a wildcard that could help Python significantly by providing an easy migration path for Java folk who are tied to specific libraries. >> One thing that would help Python in this "debate" (or, perhaps simply >> put it in the running, at least as a "next Java" candidate) > > Java itself never deserved to be the 'next' anything anyway. It was > sold on hype and has never lived up to it. I can see your point from a > business perspective but I like to think Python is sold on its merits > and not on being the new panacea for middle managers to deploy. I was having a discussion with a friend of mine recently, where I told him how depressed I became for a period after I realized that sales, marketing, and perception are all that really matter in this kooky technical world we spend so much time in. For years I thought that "most people" make technical decisions based on the facts on the ground and the merits of each alternative. While that's a great ideal to aspire to, it's not realistic as long as technical laypersons make very technical decisions -- in such an environment, heuristics, guidelines, and rules-of-thumb rule. Ergo, it's good to have marketing firepower, because that can move the needle on rules- of-thumb *really* easily. So, back on topic, I think regardless of how we got here, or who's better (Ruby or Python -- and really, it's better for the larger universe of 'agile' languages to grow anyway), if we want to improve Python's attractiveness to mainstream Java developers and their managers, providing (and promoting!) an easy migration route like JPype is a no-brainer. Cheers, Chas Emerick Founder, Snowtide Informatics Systems Enterprise-class PDF content extraction cemerick at snowtide.com http://snowtide.com -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060823/b9216c55/attachment.html> From bborcic at gmail.com Tue Aug 1 18:54:53 2006 From: bborcic at gmail.com (Boris Borcic) Date: Wed, 02 Aug 2006 00:54:53 +0200 Subject: cleaner way to write this try/except statement? In-Reply-To: <UVOzg.2616$No6.51297@news.tufts.edu> References: <UVOzg.2616$No6.51297@news.tufts.edu> Message-ID: <44cfdbdd$1_6@news.bluewin.ch> John Salerno wrote: > The code to look at is the try statement in the NumbersValidator class, > just a few lines down. Is this a clean way to write it? i.e. is it okay > to have all those return statements? Is this a good use of try? Etc. > > Thanks. > > ---------------------------- > > import wx > > > class NumbersValidator(wx.PyValidator): > > def __init__(self): > wx.PyValidator.__init__(self) > > def Clone(self): > return NumbersValidator() > > def Validate(self, parent): > text_ctrl = self.GetWindow() > text = text_ctrl.GetValue() > > try: > if not text or int(text) <= 0: > wx.MessageBox('Enter a valid time.', 'Invalid time > entered', wx.OK | wx.ICON_ERROR) > return False > else: > return True > except ValueError, error: > wx.MessageBox('Enter a valid time.', 'Invalid time entered', > wx.OK | wx.ICON_ERROR) > return False well, assuming you are unsatisfied with the above, you could try to assert the validation condition and catch together all failures, eg : def Validate(self, parent): text_ctrl = self.GetWindow() text = text_ctrl.GetValue() try : assert int(text)>0 return True except (ValueError,AssertionError) : wx.MessageBox('Enter a valid time.', 'Invalid time entered', wx.OK | wx.ICON_ERROR) return False hth, BB From mfenner at gmail.com Thu Aug 17 22:13:09 2006 From: mfenner at gmail.com (Mark E. Fenner) Date: Fri, 18 Aug 2006 02:13:09 GMT Subject: Optimizing Inner Loop Copy References: <Ja6Fg.17560$Ji1.17100@trnddc05> <1155863280.800878.127310@p79g2000cwp.googlegroups.com> <Ni9Fg.11548$5M.9705@trnddc02> Message-ID: <Vm9Fg.11552$5M.8900@trnddc02> Mark E. Fenner wrote: > John Machin wrote: > >> >> Mark E. Fenner wrote: >> >>> Here's my class of the objects being copied: >> >> Here's a couple of things that might help speed up your __init__ >> method, and hence your copy method: >> >>> >>> class Rule(list): >>> def __init__(self, lhs=None, rhs=None, nClasses=0, nCases=0): >> >> def __init__(self, lhs=None, rhs=(), nClasses=0, nCases=0): >> >>> self.nClasses = nClasses >>> self.nCases = nCases >>> >>> if lhs is not None: >>> self.extend(lhs) >> what does the extend method do? If it is small, perhaps inline a copy >> of its code here. >>> >>> if rhs is None: >>> self.rhs=tuple() >>> else: >>> self.rhs=rhs >> >> Replace the above 4 lines by: >> self.rhs = rhs >> >> HTH, >> John > > John, > > Thanks. I thought of those at the same you did! I also incorporated one > other use of the default=() + no conditional: > > class Rule(list): > def __init__(self, lhs=(), rhs=(), nClasses=0, nCases=0): > self.nClasses = nClasses > self.nCases = nCases > self.extend(lhs) # note, self is a list so this is list.extend > self.rhs=rhs > > def copy(self): > return Rule(self, > self.rhs, > self.nClasses, > self.nCases) Actually, I also removed the "passthrough" that copy was doing and just called the constructor directly. So, at the top level code, we have: allNew = [] for params in cases: # newobj = initialObject.copy() newObj = Rule(initialObject, initialObject.rhs, initialObject.nClasses, initialObject.nCases) newObj.modify(params) allNew.append(newObj) return allNew Regards, Mark From sjdevnull at yahoo.com Wed Aug 30 13:07:18 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 30 Aug 2006 10:07:18 -0700 Subject: Allowing ref counting to close file items bad style? In-Reply-To: <7xodu2ekb6.fsf@ruckus.brouhaha.com> References: <9U6Jg.951$Xw6.283@trndny02><7x4pvvylrh.fsf@ruckus.brouhaha.com> <1156910432.917443.259720@p79g2000cwp.googlegroups.com> <7xmz9mkgnv.fsf@ruckus.brouhaha.com> <1156921226.069647.233550@p79g2000cwp.googlegroups.com> <7xodu2ekb6.fsf@ruckus.brouhaha.com> Message-ID: <1156957638.345092.169460@m73g2000cwd.googlegroups.com> Paul Rubin wrote: > "sjdevnull at yahoo.com" <sjdevnull at yahoo.com> writes: > > > > (And personally I think the benefits to programmers of guaranteeing > > > > ref-counting semantics would outweigh the additional headaches for > > > > Jython and other alternative implementations). > > Ref counting is a rather primitive GC technique I disagree strongly with this assertion. It's not as efficient overall as other GC implementations, but it's not a case of "less efficient to do the same task". Reference counting buys you deterministic GC in the pretty common case where you do not have circular references--and determinism is very valuable to programmers. Other GCs be faster, but they don't actually accomplish the same task. I can come up with plenty of "superior" algorithms for all kinds of tasks if I'm not bound to any particular semantics, but losing correctness for speed is rarely a good idea. From aldonnelley at gmail.com Mon Aug 14 08:42:40 2006 From: aldonnelley at gmail.com (aldonnelley at gmail.com) Date: 14 Aug 2006 05:42:40 -0700 Subject: Strange problem with Tkinter... photos don't show on first iteration. In-Reply-To: <1155558716.123702.22370@m79g2000cwm.googlegroups.com> References: <1155541228.511218.128500@m79g2000cwm.googlegroups.com> <mailman.9299.1155548451.27775.python-list@python.org> <1155558716.123702.22370@m79g2000cwm.googlegroups.com> Message-ID: <1155559360.033920.224390@74g2000cwt.googlegroups.com> And I say once again: I can't thank you enough. YOU ROCK! cheers, al. (Just changed the code in my main program, and it WORKS! The previous thankyou was only a preliminary.) ps I really like python, too. :) aldonnelley at gmail.com wrote: > Yup, > That's the problem. Can't thank you enough. > I'd read about Tkinter "garbage collection", but, like car crashes and > lung cancer, you never think it's going to happen to you... > > thanks once again. > Cheers, Al. > > Fredrik Lundh wrote: > > aldonnelley at gmail.com wrote: > > > > > Just having a weird problem with tkinter. I'm trying to make a gui that > > > shows results from an image search, with a "forward" and "back" button > > > so the user can compare results from different pages. All that's > > > working fine... > > > The problem I'm having is that the images don't show onscreen the first > > > time the "first page" of results shows up. When I click the "search > > > again" button, and have more than the original results page to toggle > > > between, the images __do__ show up on the "first page" of results. (and > > > on the second, etc, etc.) > > > Which is to say, there's no error messages, and on the first "page", > > > the first time it's shown, the Toplevel formats correctly, and there > > > are spaces where the images should be that are the correct size, > > > just... no images. > > > It's baffling me. Perhaps someone can help. > > > > this is explained in the Python FAQ, and also in the note at the bottom > > of this page: > > > > http://effbot.org/tkinterbook/photoimage.htm > > > > </F> From fredrik at pythonware.com Tue Aug 29 05:31:54 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 29 Aug 2006 11:31:54 +0200 Subject: The lib email parse problem... References: <1156837260.222395.305960@b28g2000cwb.googlegroups.com><1156841437.692537.68200@i42g2000cwa.googlegroups.com><1156841950.866776.66400@b28g2000cwb.googlegroups.com> <1156842395.855885.183330@p79g2000cwp.googlegroups.com> Message-ID: <ed11j8$7tb$1@sea.gmane.org> "????" wrote: > the plain text is abcd, and the alternative content type is text/html, > i should prefer explain the html content, and i must not explaint the > two part ,so i want to get the boundary end. so use the email module: import email message_text = "..." message = email.message_from_string(message_text) for part in message.walk(): if part.get_content_type() == "text/html": print "html is", repr(part.get_payload()) (the message instances either contains a payload or sequence of submessages; use message.is_multipart() to see if it's a sequence or not. the walk() method used in this example loops over all submessages, in message order). </F> From you at cogeco.ca Sun Aug 20 05:50:00 2006 From: you at cogeco.ca (AlbaClause) Date: Sun, 20 Aug 2006 05:50:00 -0400 Subject: Permission Denied References: <mailman.9557.1156032685.27775.python-list@python.org> <1156038847.616137.61800@m79g2000cwm.googlegroups.com> <cPRFg.1547$dB.1365@read2.cgocable.net> <ec98pb$l01$2@lust.ihug.co.nz> Message-ID: <dbWFg.1314$sM1.1270@read1.cgocable.net> Lawrence D'Oliveiro wrote: > In message <cPRFg.1547$dB.1365 at read2.cgocable.net>, AlbaClause wrote: > >> Then, to execute the file from from the shell prompt, I had to create a >> 'bin' directory in my home folder, cuz I didn't want to litter >> my /usr/local/bin folder with useless Python scripts. > > Executable files can be kept anywhere, you don't need a special directory > for them. Yes, I know, but if you want to just enter the filename at the shell prompt, the file has to be somewhere that it can be found. Otherwise you get the dreaded "command not found" error. Unless I'm doing something wrong? -- -- There are several things that I will never be: * I will never be attracted to females. * I will never enjoy the company of others. Exactly how these realities bode for my enemy, is not of my concern. From gmt at sdf-eu.org Fri Aug 18 18:32:18 2006 From: gmt at sdf-eu.org (Max Yuzhakov) Date: Fri, 18 Aug 2006 22:32:18 +0000 (UTC) Subject: It is __del__ calling twice for some instances? References: <ebvnod$mp7$1@pandora.alkar.net> <Xns9821CFF0D1C70duncanbooth@127.0.0.1> <ec2qif$12qo$1@pandora.alkar.net> <Xns98235A0264C70duncanbooth@127.0.0.1> Message-ID: <ec5f5i$s9v$1@pandora.alkar.net> Duncan Booth wrote: DB> BTW, the behaviour is completely different if you use a new style class, DB> but still somewhat bizarre: for new style classes only the first 25 objects DB> get freed when you clear a, the remainder are only released by the garbage DB> collector. If to add the third call of stat() after the second, the result became such: -------------------- ini_cnt = 500001 del_cnt = 0 difference = 500001 -------------------- ini_cnt = 500001 del_cnt = 25 difference = 499976 -------------------- ini_cnt = 500001 del_cnt = 500001 difference = 0 Preceding call to gc.disable() has no influence on result. -- GMT More Then ... From jackson at hotmail.com Sun Aug 13 16:27:14 2006 From: jackson at hotmail.com (Jackson) Date: Sun, 13 Aug 2006 13:27:14 -0700 Subject: selecting base class from user input Message-ID: <ebo1v5$jos$1@skeeter.ucdavis.edu> I want a class that will determine its base class by the argument passed in. What I am about to write _does_not_work_, but it shows what I am trying to do. class ABC(some_super): def __init__(self,some_super): some_super.__init__(self) if some_super == list: self.append('ABC') elif some_super == dict: self['ABC'] = None Then, the user can call this function: >>> example = ABC(list) >>> print example ['ABC'] >>> example = ABC(dict) >>> print example {'ABC': None} Clearly, this is a bad example, but the central idea is what I am trying to do. ABC is a particular example which can be represented in various forms. I want an ABC class that will create the example in the form specified by the user. So how can I achieve this? Thanks. From wegwerp at gmail.com Sat Aug 19 15:58:28 2006 From: wegwerp at gmail.com (Bas) Date: 19 Aug 2006 12:58:28 -0700 Subject: ratfun-2.3 Polynomials and Rational Functions In-Reply-To: <oUGFg.16988$zg.13628@tornado.rdc-kc.rr.com> References: <oUGFg.16988$zg.13628@tornado.rdc-kc.rr.com> Message-ID: <1156017508.602717.69060@74g2000cwt.googlegroups.com> Are there any differences between this module and the one already present in numpy? http://www.scipy.org/doc/numpy_api_docs/numpy.lib.polynomial.html Cheers, Bas From socald.smit at gmail.com Tue Aug 8 07:37:24 2006 From: socald.smit at gmail.com (socald.smit at gmail.com) Date: 8 Aug 2006 04:37:24 -0700 Subject: ''Get free calling cards now '' Message-ID: <1155037044.277263.193040@m73g2000cwd.googlegroups.com> ''Get free calling cards now '' Hi Friends, I found a great site to call anywhere in the World for free! What we have to do is just signup and earn freecalling cards. After signingup with Globalfreecalling you can findout lot of very simple and easy offers (Just Contact Information Required).Some Offers may Required only E-Mail and Zip Code Only. Just complete the Offers and get Free calling Cards. signup with below link:: http://ww3.6URL.com/0P8U Hurry Up Friends ! From swangdb at auburn.edu Mon Aug 21 14:39:37 2006 From: swangdb at auburn.edu (swangdb) Date: 21 Aug 2006 11:39:37 -0700 Subject: Mailman - Sendmail problem Message-ID: <1156185577.165019.305040@74g2000cwt.googlegroups.com> I have a Sun Server running Solaris 10 and Sendmail 8.13.7. I have Majordomo and Listproc installed on this server and they work. I have several production majordomo and listproc mailing lists installed on this server and they work. I am trying to get Mailman to work on this server and so far, no luck. I installed the software (Mailman 2.1.8 and Python 2.4.3), reconfigured mm_cfg.py, started the software, added the cron entries, created a test mailing list, added the list information to /etc/aliases, ran newaliases and subscribed myself. When I send a message to the list, it doesn't send me a copy of the message (I am the only subscriber to the list). If I look on the list's web site, the message I sent is contained in the archives. In the Mailman error log, I get messages similar to the following when I send a message to the mailing list: *** Aug 21 12:52:07 2006 (3871) SHUNTING: 1156182726.7459469+ce82b7624960d1de5eea043fee45821044e3dfec Aug 21 13:28:00 2006 (3871) Uncaught runner exception: Use of the Sendmail.py delivery module is highly discouraged Aug 21 13:28:00 2006 (3871) Traceback (most recent call last): File "/usr/local/mailman/Mailman/Queue/Runner.py", line 111, in _oneloop self._onefile(msg, msgdata) File "/usr/local/mailman/Mailman/Queue/Runner.py", line 167, in _onefile keepqueued = self._dispose(mlist, msg, msgdata) File "/usr/local/mailman/Mailman/Queue/OutgoingRunner.py", line 73, in _dispose self._func(mlist, msg, msgdata) File "/usr/local/mailman/Mailman/Handlers/Sendmail.py", line 71, in process assert 0, 'Use of the Sendmail.py delivery module is highly discouraged' AssertionError: Use of the Sendmail.py delivery module is highly discouraged *** It's funny, Sendmail.py is included with the program source, but the documentation says that "Use of the Sendmail.py delivery module is highly discouraged." Is it possible to use Mailman with sendmail without using Sendmail.py? I'd like to use sendmail if possible. Thanks for any help you can give! -- David Swanger swangdb at auburn.edu From webraviteja at gmail.com Wed Aug 2 03:21:31 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 2 Aug 2006 00:21:31 -0700 Subject: Programming newbie coming from Ruby: a few Python questions In-Reply-To: <1154494954.082706.283750@b28g2000cwb.googlegroups.com> References: <mailman.8824.1154472963.27775.python-list@python.org> <1154494954.082706.283750@b28g2000cwb.googlegroups.com> Message-ID: <1154503291.850019.32940@i3g2000cwc.googlegroups.com> > Is this kind of cleverness what is usually known as "magic"? > I suspect that this has something to do with it, but not completely > sure... :-). It must be. Now Django has a "magic removal branch". From s_rowse at hotmail.com Wed Aug 16 01:55:56 2006 From: s_rowse at hotmail.com (Sam) Date: 15 Aug 2006 22:55:56 -0700 Subject: "wxmsw26uh_vc.dll not found" when using wxAgg backend Message-ID: <1155707756.522298.11930@75g2000cwc.googlegroups.com> Hello, I've installed matplotlib recently because I want to add graphing functionality to a GUI that i'm making. I decided to try using the wxAgg backend instead of plain old wx because: a) I hear it's quicker, and b) when i use the wx backend, the axis labels don't seem to work properly - i can't change their font, and the axis label always overwrites my tickbox labels. So i'm not too concerned about these wx problems anymore because i'm changing to wxAgg. Here's the problem i'd like help with. - i import the wxAgg backends, Figurecanvas, etc. - i run the file - the following error box pops up: "This application has failed to start because wxmsw26uh_vc.dll was not found. Reinstalling the application may fix this problem." This problem occurs even when I run the matplotlib example files that you can download from the matplotlib homepage. I have tried reinstalling, and that has not rectified the problem. I googled for wxmsw26uh_vc.dll and found a small number of posts. The following post: https://svn.enthought.com/enthought/ticket/774 suggests that it will be "fixed in 1.0.0.rc1" which was supposedly released a few weeks ago. I didn't really follow the discussion of why this error is occurring, i just want to find out how to fix it! I'm running a windows XP machine with: python 2.4, matplotlib 87.4 and wxPython ansi-2.6.3.3 Any help would be much appreciated Cheers Samantha From tal.no.no.spam at gmail.com Sun Aug 27 02:11:16 2006 From: tal.no.no.spam at gmail.com (Tal Einat) Date: 26 Aug 2006 23:11:16 -0700 Subject: Learning Python In-Reply-To: <Xns982BA8EED5C6duncanbooth@127.0.0.1> References: <44f03c80$0$75042$14726298@news.sunsite.dk> <1156597310.493911.241160@i42g2000cwa.googlegroups.com> <44f0540a$0$75041$14726298@news.sunsite.dk> <Xns982BA8EED5C6duncanbooth@127.0.0.1> Message-ID: <1156659076.855399.87430@h48g2000cwc.googlegroups.com> Duncan Booth wrote: > JAG CHAN wrote: > > > Whenever I try to open IDLE, my zone firewall tells me pythonw.exe is > > trying to access the trusted zone. > > Whenever I try to open new IDLE window I get the following message: > > "IDLE's subprocess didn't make connection.Either IDLE can't start a > > subprocess or personal firewall software is blocking the connection." > > I will be grateful if you kindly suggest a way out, then, I won't have > > to install another editor. > > You need to configure your firewall to permit IDLE to make the connection. > Most firewall software when it warns you will give you the option of > permitting this: > > e.g. Windows Firewall says "To help protect your computer, Windows Firewall > has blocked some features of this program. Do you want to keep blocking > this program?" with options "Keep Blocking", "Unblock", and "Ask me later". > All you have to do is click "Unblock" and IDLE will work. IDLE doesn't connect to the internet, but it uses a socket interface to communicate between two different processes. Some security software falsely recognizes this as an attempt to connect to the internet, although it is not a security hazard at all. Another solution is to run IDLE with the -n flag, which will cause it to run in one process (instead of two) and not create a socket. For the most part you will not notice a difference in IDLE's behavior when running it this way. On windows you can create a shortcut to idle.bat and add -n at the end of the "target" entry. When running IDLE with -n, you should see "==== No Subprocess ====" on one of the first lines of the Shell window. You probably have your Windows security settings set quite high, usually I don't see this on Windows systems with default settings. - Tal reduce(lambda m,x:[m[i]+s[-1] for i,s in enumerate(sorted(m))], [[chr(154-ord(c)) for c in '.&-&,l.Z95193+179-']]*18)[3] From paul at boddie.org.uk Tue Aug 22 06:19:23 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 22 Aug 2006 03:19:23 -0700 Subject: What do you want in a new web framework? References: <1156100331.329889.216340@p79g2000cwp.googlegroups.com> <pan.2006.08.20.19.48.34.996227@gmx.net> <1156156636.515678.118210@75g2000cwc.googlegroups.com> <4jele2pe011di99c5dnq4olclglrkieggc@4ax.com> Message-ID: <1156241963.453892.196790@h48g2000cwc.googlegroups.com> Tim Roberts wrote: > > Consider Ruby. If someone asks, "I'd like to do a web site with Ruby, what > should I use?", the answer comes back loud, clear, and unanimous: Ruby on > Rails. I actually believe that people in most buzzword shortlist situations see Rails as being the name in the list of candidates, not Ruby - it's somewhat like Zope being in the list rather than Python, or Struts/Tapestry/Apache-project-of-the-month being in the list rather than Java (albeit with a fairly warm corporate feeling that Java is there underneath). > If someone asks, "I'd like to do a web site with Python, what > should I use?", she gets 25 different answers. "Look at HTMLGen, Cheetah, > WebWare, CherryPy, Karrigell, Django, Pylons, Plone, Zope, TurboGears, > etc., etc.", none of which are pre-installed in the typical Linux > distribution. To the non-programming decision maker, that kind of response > makes Python look unprofessional -- a toy. Indeed. That's why, after enumerating the uncontrollably expanding list of solutions for a time [1], I wanted to concentrate on showing the viable options with all their differentiating features in the Python Web Frameworks Overview [2]. Ultimately, that content was moved to the python.org Wiki [3] and everyone got their chance to hype their pet project - it became like a random set of links. Sure, everyone wants everyone else to see their work, but there's a role in the community for objective education about the right tool for the job rather than either graphically showing the little fish tear each other apart, or jumping on the bandwagon with the most momentum and hyping it to the exclusion of everything else. In the latter case, the end result is to promote the big fish to the bigger pool (that stuff about Rails, Zope, Struts & friends above), creating another generation of "agile frameworks". [...] > I agree with Marc. PLEASE do not create "yet another Python web > framework." Let's pick one, and join together to turn it into the One, > True, Unquestioned Web Solution. Let's say we go for front-runner "du jour", Django. I've looked at Django, and I'll admit that parts of the core API are fairly well done when compared to certain other frameworks. However, let's say that we want to "do it right" whilst expressing our dissatisfaction with the templating, noting that when doing XML-oriented templating (that's HTML, XHTML, XML and so on) I prefer something which upsets my Web page editor less than it already is. So we unplug the templating somehow and offer other options which plug into whatever magic that exists in Django to make everything work smoothly. Let's say we unplug the database abstraction layer because it doesn't do everything we want, either, noting that I don't have any strong opinions about Django's object-relational mapper, but I am wary of Web frameworks which apparently encourage a database installation just for "hello world" even if it isn't strictly required from a technical perspective. Ultimately, we end up in a situation that is described far better in the following article: http://www.cmlenz.net/blog/2006/08/the_python_web_.html In my opinion, what has damaged the Python Web frameworks scene has been the continual hype and land-grabbing, the refusal to cede ground on even the most basic stuff ("my magic form request variables are better than yours", even though the majority of such magic solutions are lacklustre at best), and that continual sighting of a grand prize that at best gives you a ticket to Zopeworld - you get your own "business ecosystem" while everyone else starts working on the next thing to undo you. I'd like to hear suggestions on how some cooperation can be encouraged above the WSGI level, which despite the fanfare didn't really give so many good answers to those confused users looking for a solution. As I've said often enough before, the abstract "paper comparison" of Web frameworks evolved into WebStack [4] which was originally an exercise in seeing just how different many frameworks are at the lower levels: the answer, given that you can paper over them in that way, is "different only in unhelpful ways but not irreconcilably so". One day, the Python Web frameworks scene may grow up and realise this fact. Paul [1] http://web.archive.org/web/20041011015154/http://thor.prohosting.com/~pboddie/Python/web_modules.html [2] http://www.boddie.org.uk/python/web_frameworks.html [3] http://wiki.python.org/moin/WebProgramming [4] http://www.python.org/pypi/WebStack From jason at adapt.com Tue Aug 15 06:50:15 2006 From: jason at adapt.com (Jason Nordwick) Date: Tue, 15 Aug 2006 03:50:15 -0700 Subject: yet another noob question In-Reply-To: <ebs836$ppn$1@sea.gmane.org> References: <1155492110.659011.196280@75g2000cwc.googlegroups.com> <mailman.9291.1155516281.27775.python-list@python.org> <ebpefi$2f3n$1@ulysses.news.tiscali.de> <mailman.9317.1155578305.27775.python-list@python.org> <1155579814.930093.99840@75g2000cwc.googlegroups.com> <mailman.9322.1155582209.27775.python-list@python.org> <1155621690.639191.309980@i3g2000cwc.googlegroups.com> <44E19FE9.5010903@adapt.com> <ebs836$ppn$1@sea.gmane.org> Message-ID: <44E1A6E7.1020903@adapt.com> That isn't what I meant. If there was a a point (and I'm not really sure that I'm even trying to make one), the point was that Google makes heavy use of reduce-like functionality, essentially implementing a distributed reduce across a cluster. From what I hear, they use a lot of Python and hired van Rossum for a reason. It just seems odd (don't read anything into this than mere cocked eyebrows) that the language designer that they hired and obviously have a lot of trust in would decide that reduce was essentially pointless. Google's distributed reduce seems to point in opposite way. However, if reduce could be rolled into the list comprehension syntax, that would be even better. Or take it that extra step and roll a grouping functionality in there too, then you would have map, reduce, group, and filter all in one construct. You could call it select (joins are merely indexes into other structures). -j Steve Holden wrote: > Jason Nordwick wrote: >> I use reduce to also do indexing, hashing with upsert semantics of lists of key-value pairs, transitioning through a state table, etc... >> >> Somebody else pointed out to me how odd it is of Python to be ditching reduce when Guido van Rossum was hired by Google, and Google is literally built on map and reduce (http://en.wikipedia.org/wiki/Mapreduce). >> > > That seems a bit literal. Just because they use a tool called MapReduce > that doesn't imply that thay chose to implement it with the Python map() > and reduce() functions. It's a distributed application, in case you > hadn't noticed ... > > regards > Steve From psnim2000 at gmail.com Tue Aug 29 13:32:19 2006 From: psnim2000 at gmail.com (Chaos) Date: 29 Aug 2006 10:32:19 -0700 Subject: Desktop Notification/Alerts In Python In-Reply-To: <1156839399.221845.238200@p79g2000cwp.googlegroups.com> References: <1156781259.354526.142680@m79g2000cwm.googlegroups.com> <1156839399.221845.238200@p79g2000cwp.googlegroups.com> Message-ID: <1156872739.394427.111790@74g2000cwt.googlegroups.com> alex23 wrote: > Chaos wrote: > > I am looking for ways to have a Desktop Alert, like the one most IM > > Messengers have (MSN, AIM) at the lower right above the taskbar. Can > > anyone point me to the right resources to use? > > Under Windows, they're called "balloon tips". Here's a thread from a > few years back asking for the exact same thing: > > http://groups.google.com/group/comp.lang.python/browse_frm/thread/f6f6083650b50f1d/f26db0efc52462f9#f26db0efc52462f9 > > There's even a working demo linked to at the end of the thread, and the > link is still live. > > Thanks for prompting me to look, I've vaguely wanted something like > this for a while :) > > -alex23 Is there a way to make it a window, instead of a baloon time. One that slides up from the taskbar? From tim.peters at gmail.com Fri Aug 11 10:57:41 2006 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 11 Aug 2006 10:57:41 -0400 Subject: datetime to timestamp In-Reply-To: <44dc8891$1@news.eftel.com> References: <mailman.9246.1155302262.27775.python-list@python.org> <44dc87b7$1@news.eftel.com> <44dc8891$1@news.eftel.com> Message-ID: <1f7befae0608110757j64686f65m18fad02d51d7b84d@mail.gmail.com> [Simen Haugen] >>> How can I convert a python datetime to a timestamp? It's easy to convert >>> a timestamp to datetime (datetime.datetime.fromtimestamp(), but the >>> other way around...?) [John Machin] >> Is the timetuple() method what you want? >> >> #>>> import datetime >> #>>> n = datetime.datetime.now() >> #>>> n >> datetime.datetime(2006, 8, 11, 23, 32, 43, 109000) >> #>>> n.timetuple() >> (2006, 8, 11, 23, 32, 43, 4, 223, -1) [also John] > Aaaarrrggghhh no it's not what you want Yes, it is ;-) > -- looks like you have to do the arithmetic yourself, starting with toordinal() It's just one step from the time tuple: import time time.mktime(some_datetime_object.timetuple()) The datetime module intended to be an island of relative sanity. Because the range of dates "timestamps" can represent varies across platforms (and even "the epoch" varies), datetime doesn't even try to produce timestamps directly -- datetime is more of an alternative to "seconds from the epoch" schemes. Because datetime objects have greater range and precision than timestamps, conversion is problem-free in only one direction. It's not a coincidence that that's the only direction datetime supplies ;-) From bounces at foo.org Mon Aug 7 23:41:53 2006 From: bounces at foo.org (Dan) Date: Tue, 08 Aug 2006 03:41:53 GMT Subject: Question on try/except Message-ID: <5KTBg.4514$Jg1.2316@trndny05> While perusing sre.py in the standard library, I came upon this snippet of code in the _compile() function definition: try: p = sre_compile.compile(pattern, flags) except error, v: raise error, v # invalid expression Is there some particular use in catching an exception and immediately re-raising it? Why catch it at all? /Dan -- dedded att verizon dott net From bj_666 at gmx.net Sat Aug 26 03:57:24 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 26 Aug 2006 09:57:24 +0200 Subject: Open Office and Python References: <ecmprj$id4$1@sunce.iskon.hr> <44ef44bb$0$8917$88260bb3@free.teranews.com> <44ef64a2$0$8856$88260bb3@free.teranews.com> Message-ID: <pan.2006.08.26.07.57.23.856928@gmx.net> In <44ef64a2$0$8856$88260bb3 at free.teranews.com>, tobiah wrote: > I should have pointed out that the delimiter is a tab > right now. That's what I use in general, but I still > call the files .csv files. Also this doesn't check > for, or handle quoted fields. Why don't you use the `csv` module from the standard library? Ciao, Marc 'BlackJack' Rintsch From bobrien18 at yahoo.com Fri Aug 18 11:32:19 2006 From: bobrien18 at yahoo.com (KraftDiner) Date: 18 Aug 2006 08:32:19 -0700 Subject: Type conversion? Message-ID: <1155915139.622448.178160@m73g2000cwd.googlegroups.com> I have the following code... import array len32 = array.array('L') len16 = array.array('H') len32.append(0) len16.append(0) y = len32[0] print y.__class__ <type 'long'> z = len16[0] print z.__class__ <type 'int'> how can I change Zs type to long? Or how how can I change an arrays type? From deets at nospam.web.de Tue Aug 1 11:13:00 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 01 Aug 2006 17:13:00 +0200 Subject: fast pythonic algorithm question References: <1154443185.562918.140090@s13g2000cwa.googlegroups.com> <7x64hcjyge.fsf@ruckus.brouhaha.com> <1154444521.644351.226760@75g2000cwc.googlegroups.com> Message-ID: <4j996eF6ti6jU1@uni-berlin.de> Guyon Mor?e wrote: > Memory is no problem. It just needs to be as fast as possible, if > that's what this is, fine. > > If not, I'd like to find out what is :) I'd say it is as fast as it can get - using hashing for lookups is O(n) in most cases, where bisection or other order-based lookups have O(log n) Additionally, dict lookups are fully written in C. Diez From mail at microcorp.co.za Wed Aug 30 03:23:37 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 30 Aug 2006 09:23:37 +0200 Subject: TNEF decoder References: <TbDIg.1431$4O4.1306@trnddc02> <1156901227.576728.203500@74g2000cwt.googlegroups.com> Message-ID: <00e901c6cc06$6fc3a280$03000080@hendrik> "Simon Forman" <rogue_pedro at yahoo.com> wrote: 8<----------------------------- | A place I once worked at had a project that included some TNEF | handling. There was one developer assigned fulltime to it. He was the | one who sat at his desk hurling curses at his workstation at the top of | his lungs, later he developed a pretty severe drinking problem. Should I take this to mean: " Don't go near TNEF because your underwear will become carnivorous and consume your genitalia? " - Hendrik From jojoba12 at hotmail.com Tue Aug 15 20:19:13 2006 From: jojoba12 at hotmail.com (jojoba) Date: 15 Aug 2006 17:19:13 -0700 Subject: idea on how to get/set nested python dictionary values In-Reply-To: <1155683850.888452.181590@m73g2000cwd.googlegroups.com> References: <1155663671.716249.18780@m79g2000cwm.googlegroups.com> <1155678816.942660.296140@74g2000cwt.googlegroups.com> <1155683850.888452.181590@m73g2000cwd.googlegroups.com> Message-ID: <1155687553.392080.290820@b28g2000cwb.googlegroups.com> Once again, Thanks to all!!!! I did not expect to receive such a response. Very very helpful indeed, jojoba o(-_-)o From bearophileHUGS at lycos.com Tue Aug 22 21:38:43 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 22 Aug 2006 18:38:43 -0700 Subject: swapping numeric items in a list In-Reply-To: <mailman.9675.1156291509.27775.python-list@python.org> References: <mailman.9675.1156291509.27775.python-list@python.org> Message-ID: <1156297123.390044.311460@h48g2000cwc.googlegroups.com> Jiang Nutao: > To convert list > aa = [0x12, 0x34, 0x56, 0x78] > into > [0x34, 0x12, 0x78, 0x56] > How to do it fast? My real list is huge. Note that: >>> a = range(6) >>> a [0, 1, 2, 3, 4, 5] >>> a[::2] [0, 2, 4] >>> a[1::2] [1, 3, 5] So you can do: >>> a[::2], a[1::2] = a[1::2], a[::2] >>> a [1, 0, 3, 2, 5, 4] Bye, bearophile From crystalattice at gmail.com Mon Aug 7 18:23:02 2006 From: crystalattice at gmail.com (crystalattice) Date: 7 Aug 2006 15:23:02 -0700 Subject: do people really complain about significant whitespace? References: <1154986984.740638.241130@m79g2000cwm.googlegroups.com> Message-ID: <1154989382.397374.138810@b28g2000cwb.googlegroups.com> infidel wrote: > Where are they-who-hate-us-for-our-whitespace? Are "they" really that > stupid/petty? Are "they" really out there at all? "They" almost sound > like a mythical caste of tasteless heathens that "we" have invented. > It just sounds like so much trivial nitpickery that it's hard to > believe it's as common as we've come to believe. Actually, some of the guys I work with complained about Python when they first had to learn it for our Zope server. One of them is an old-school Unix guy who spent the last 20+ years doing procedural languages with funky syntax, like C. The other one is a VB.NET junkie who I don't think has much experience outside of MS languages, except maybe Java. One of the complaints they had for the first few weeks was the white space issue and the fact Python doesn't have brackets or semicolons. Obviously they learned to "deal with it" but they sure made it seem like it was a painful transition. I think the biggest pain was the fact that they are forced to indent their code now so they can't be lazy anymore. From jo at durchholz.org Wed Aug 30 03:17:55 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Wed, 30 Aug 2006 09:17:55 +0200 Subject: A Sort Optimization Technique: decorate-sort-dedecorate In-Reply-To: <1f7befae0608291517h7a412533v90a129f746205f36@mail.gmail.com> References: <1156719092.603277.57390@b28g2000cwb.googlegroups.com> <1156723602.192984.49610@m79g2000cwm.googlegroups.com> <pan.2006.08.28.08.53.08.647908@gmx.net> <280820061150081729%jgibson@mail.arc.nasa.gov> <ed1682$l41$1@online.de> <7.0.1.0.0.20060829132302.05c9e758@yahoo.com.ar> <44F480EF.9080202@durchholz.org> <1f7befae0608291225o12985c18u95137d9b6ba928e2@mail.gmail.com> <44F49BCD.6000903@durchholz.org> <1f7befae0608291517h7a412533v90a129f746205f36@mail.gmail.com> Message-ID: <44F53BA3.30605@durchholz.org> Tim Peters schrieb: > > O() notation isn't being used I was replying to Gabriel's post: >>>>> In fact it's the other way - losing a factor of 2 is irrelevant, >>>>> O(2N)=O(N). The logN factor is crucial here. Regards, Jo From f.braennstroem at gmx.de Tue Aug 22 15:35:14 2006 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Tue, 22 Aug 2006 21:35:14 +0200 Subject: radio buttons in curses References: <ecaadb$ojt$1@sea.gmane.org> Message-ID: <ecfm93$v6q$1@sea.gmane.org> Sorry, me again... Does nobody have an idea or is it to stupid? * Fabian Braennstroem <f.braennstroem at gmx.de> wrote: > Hi, > > I want to add some radio and check buttons to my curses > script. As I understand it, there are no buttons in the > 'basic' curses module. Now, I found the curses-extra module, > but I not able to download and install it. > > Does anybody have an idea, where I can download the module > or, even better, how I can create radio and check buttons > with the 'ordinary' curses module? Would be nice... > > Greetings! > Fabian > > -- > http://mail.python.org/mailman/listinfo/python-list > Greetings! Fabian From davidfinance at gmail.com Thu Aug 24 15:38:15 2006 From: davidfinance at gmail.com (davidfinance at gmail.com) Date: 24 Aug 2006 12:38:15 -0700 Subject: Why can't I subclass off of "date" ? In-Reply-To: <mailman.9814.1156445937.27775.python-list@python.org> References: <1156444959.471657.201690@i3g2000cwc.googlegroups.com> <mailman.9814.1156445937.27775.python-list@python.org> Message-ID: <1156448295.523145.84290@m73g2000cwd.googlegroups.com> Wow, you guys are fast. Thanks Georg and Fredrik!! Fredrik Lundh wrote: > davidfinance at gmail.com wrote: > > > Ok, maybe this is a stupid question, but why can't I make a subclass of > > datetime.date and override the __init__ method? > > __init__ controls initialization of an already constructed object. to > control construction, you need to override __new__: > > http://pyref.infogami.com/__new__ > > e.g. > > class A(date): > def __new__(cls, a, b, c, d): > print a, b, c, d > return super(A, cls).__new__(cls, 2006, 12, 11) > > </F> From poorgeek at gmail.com Wed Aug 9 16:21:32 2006 From: poorgeek at gmail.com (poorgeek) Date: 9 Aug 2006 13:21:32 -0700 Subject: Announcing Switch, the CSS Preprocessor! In-Reply-To: <1155153903.774783.179440@m73g2000cwd.googlegroups.com> References: <1155149749.559985.177250@b28g2000cwb.googlegroups.com> <1155153903.774783.179440@m73g2000cwd.googlegroups.com> Message-ID: <1155154892.054041.74670@m79g2000cwm.googlegroups.com> The zip file contains HTML docs but the menus are broken so that you can't navigate them if you just want browse them from the local filesystem. fuzzylollipop wrote: > Dave wrote: > > Powered by Mod_Python, Switch CSS is a full featured, production ready > > > > > The sourceforge project link follows. We could really use some tire > > kickers... This group was invaluable in the early development process, > > so we're announcing it officially here, and on mod_python first. > > > > https://sourceforge.net/projects/switchcss/ > > > > Thanks, > > Dave Worley > > Is there any documentation or anything available? The sourceforge home > page is empty? From http Wed Aug 30 20:16:39 2006 From: http (Paul Rubin) Date: 30 Aug 2006 17:16:39 -0700 Subject: GC and security References: <44F61EEB.8040207@optonline.net> Message-ID: <7x4pvtpxnc.fsf@ruckus.brouhaha.com> Les Schaffer <schaffer at optonline.net> writes: > so i am curious. so long as i drop all reference to the passphrase > string(s), eventually it gets garbage collected and the memory recycled. > so "before long" the phrase is gone from memory. > > is there a best practice way to do this? You can't rely on anything like that, either on the Python GC side or from the OS (which might have long since written the passphrase out to the swap disk) without special arrangement. Some OS's have system calls to lock user pages in memory and prevent swapping, and GPG tries to use them. "Best practice" if you're doing a high security app involves using special hardware modules to wrap the keys. The relevant standard is FIPS 140-2, with FIPS-140-3 in preparation: http://csrc.nist.gov/cryptval/140-2.htm http://csrc.nist.gov/cryptval/140-3.htm For most purposes (e.g. some random web service), this stuff is overkill, though. From danb_83 at yahoo.com Tue Aug 15 18:45:30 2006 From: danb_83 at yahoo.com (Dan Bishop) Date: 15 Aug 2006 15:45:30 -0700 Subject: what is the keyword "is" for? In-Reply-To: <mailman.9363.1155636164.27775.python-list@python.org> References: <1155625097.784052.31330@p79g2000cwp.googlegroups.com> <44e16d6a$1@nntp0.pdx.net> <1155629086.617707.132900@b28g2000cwb.googlegroups.com> <44E182DA.20602@v.loewis.de> <1155630861.833751.19910@m73g2000cwd.googlegroups.com> <mailman.9363.1155636164.27775.python-list@python.org> Message-ID: <1155681930.592205.11270@m73g2000cwd.googlegroups.com> Steve Holden wrote: > daniel wrote: > > Martin v. L?wis wrote: > [...] > >>For some objects, "change the object" is impossible. If you have > >> > >>a = b = 3 > >> > >>then there is no way to change the object 3 to become 4 (say); > >>integer objects are "immutable". So for these, to make a change, > >>you really have to change the variable, not the value. > >> > > > > sounds reasonable, I tried tuple which is also immutable, it behaves > > the same as integers. > > > Well spotted. Tuples are indeed immutable, as are strings, unicode > strings, integers and floats. But tuples can contain mutable objects. >>> a = (0, [1]) >>> a[1].append(2) >>> a (0, [1, 2]) From quncao at gmail.com Tue Aug 8 20:21:13 2006 From: quncao at gmail.com (Qun Cao) Date: 8 Aug 2006 17:21:13 -0700 Subject: beginner questions on embedding/extending python with C++ In-Reply-To: <mailman.9087.1155036302.27775.python-list@python.org> References: <1155029311.885266.131980@m73g2000cwd.googlegroups.com> <mailman.9087.1155036302.27775.python-list@python.org> Message-ID: <1155082873.772175.285300@n13g2000cwa.googlegroups.com> Thanks for all the good pointers! I am still reading throught them, but Boost seems to be the way to go! Roman Yakovenko wrote: > On 8 Aug 2006 02:28:31 -0700, Qun Cao <quncao at gmail.com> wrote: > > Hi Everyone, > > > > I am a beginner on cross language development. My problem at hand is to > > build a python interface for a C++ application built on top of a 3D > > game engine. The purpose of this python interface is providing a > > convenient scripting toolkit for the application. > > As for me, Boost.Python is the way to go. > > Fortunately you are not the first one, and I hope not the last one :-) : > > http://language-binding.net/pyplusplus/quotes.html#who-is-using-pyplusplus > 1. Python-OGRE > * http://lakin.weckers.net/index_ogre_python.html > * http://tinyurl.com/mvj8d > > 2. http://cgkit.sourceforge.net/ - contains Python bindings for Maya C++ SDK > > 3. PyOpenSG - https://realityforge.vrsource.org/view/PyOpenSG/WebHome > The goal of PyOpenSG is to provide python bindings for the OpenSG > scene graph. > > > Since the main program is still going to be the C++ application, I > > guess we need to embedding the python scripts in the C++ code. > > Boost.Python is the only tool that provides complete functionality( > extending and > embedding ). Also I think cgkit is dealing with the problem too. > > > But for this to work, the python code needs to know the Player class, > > is it right? > > Right. > > Does that mean I need to build a python wrapper class for > > Player and "import Player" in the python code? But because this > > application is built on top of a game engine, Player class inherits > > many classes from there, I cannot possibly wrapping them all, right? > > It depends on how much functionality you want to export. > > > Also, some global objects are probably needed in this code of adding > > players, how can the python code access them? > > Boost.Python provides the functionality you need. > > > Btw, if you can point me to any source code of non-trivial projects > > utilizing SWIG/Boost.Python, that would be very helpful. I found the > > examples on the tutorials are far too simple. > > Those are tutorials, they should be simple, right :-) ? > > -- > Roman Yakovenko > C++ Python language binding > http://www.language-binding.net/ From diffuser78 at gmail.com Fri Aug 11 13:37:11 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 11 Aug 2006 10:37:11 -0700 Subject: Including python and wxPython in distutils Message-ID: <1155317831.486650.270220@i42g2000cwa.googlegroups.com> I wrote a small app in python and used wxPython in it. Now, I am trying to create an .rpm file for linux RedHat Distro. I want the ability in my installer to install python2.4 and wxPython too along with the .py files which are in the project. I am trying to use distutils. Can anybody give some pointers to do this fast ? Every help is greatly appreciated. From paul at boddie.org.uk Fri Aug 25 07:22:37 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 25 Aug 2006 04:22:37 -0700 Subject: Consistency in Python References: <mailman.9855.1156495956.27775.python-list@python.org> <1156497650.974905.196140@74g2000cwt.googlegroups.com> <oNAHg.27285$3l.6922@tornado.texas.rr.com> Message-ID: <1156504957.511315.223360@i3g2000cwc.googlegroups.com> Paul McGuire wrote: > > There's nothing wrong with returning self from a mutator. This was a common > idiom in Smalltalk (the syntax for this was "^self", which was probably the > most common statement in any Smalltalk program), and permitted the chaining > of property mutators into a single line, each invoking a mutator and > returning self, which was then used to invoke the next mutator, etc. Various Java APIs encourage this kind of behaviour, too, or at least encouraged it in earlier times. However, as I wrote, there is some kind of understanding that undoubtedly results from a policy decision in the design of Python's built-in types that saves the programmer from having to question the nature of a return value in such a way. [...] > But with mutators that return self, a client could write any of these: > > bx = Box().length(100).width(50).height(20) > bx = Box().width(50).height(20).length(100) > bx = Box().width(50).length(100).height(20) > ...etc... > > and the results are the same. This is very convenient, and I've often thought about doing such things in my own APIs, but there can sometimes be subtle problems introduced into programs when you decide to change the nature of such a mutator, or if you have another type/class whose mutators are of a different nature, such that the width method produces a new Box object (which is quite similar to what the questioner seemed to have in mind) instead of mutating (or failing to mutate) the existing object. Indeed, it may be important to know whether you're creating new objects or not, and without metadata the most convenient way to communicate this is quite probably to define a rigid interface (after all, why should width or append return an object?) which cannot be implemented on immutable things. Paul From nyamatongwe+thunder at gmail.com Tue Aug 8 19:11:07 2006 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Tue, 08 Aug 2006 23:11:07 GMT Subject: Proposal: [... for ... while cond(x)] In-Reply-To: <1155064682.499991.246170@h48g2000cwc.googlegroups.com> References: <1154879331.903490.106020@m73g2000cwd.googlegroups.com> <1155064682.499991.246170@h48g2000cwc.googlegroups.com> Message-ID: <fS8Cg.9029$rP1.2825@news-server.bigpond.net.au> Eighty: > So does no one have a comment on this? Similar proposals have appeared before (such as on python-dev about a year ago) and haven't attracted much positive comment. The benefits appear to be small compared to the cost of making the language larger. You could try the formal route of writing a PEP so that a detailed proposal and its reasons for (probable) rejection would be available for others. Neil From nicolasg at gmail.com Mon Aug 28 19:45:55 2006 From: nicolasg at gmail.com (Nicolas G) Date: Tue, 29 Aug 2006 02:45:55 +0300 Subject: Python web service ... In-Reply-To: <32822fe60608281459i56784c8bo20b3cacba0852423@mail.gmail.com> References: <1156590455.555359.247410@h48g2000cwc.googlegroups.com> <32822fe60608281459i56784c8bo20b3cacba0852423@mail.gmail.com> Message-ID: <7d2580610608281645u65941eabwf4a8e74802b84976@mail.gmail.com> If I want to run my program as a web service I need to setup a webserver , am I right ? Whars that difference ? can a webservice be run without a webserver ? On 8/29/06, Jorge Vargas <jorge.vargas at gmail.com> wrote: > On 26 Aug 2006 04:07:35 -0700, nicolasg at gmail.com <nicolasg at gmail.com> wrote: > > Hi folks, I have accomplished to make a python program that make some > > image manipulation to bmp files. > > I now want to provide this program as a web service. A user can visit a > > site and through a web interface he should upload the file to the web > > server , the server then will do the image process with the python > > program I have wrote and when it finish the user must get the image > > file back . > > > > My question is how difficult is to set up a web server that can run > > python easy ? should I try ZOPE or there is something better in mind ? > > is that webservice or webserver? > if webservice try ZSI of it's a webserver why don't you try CherryPy? > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > -- Nicolas G mobile: +30 69 45 714 578 From g.brandl-nospam at gmx.net Thu Aug 31 13:16:33 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Thu, 31 Aug 2006 19:16:33 +0200 Subject: M$ windows python libs installed in arbitrary directories forcustomized python distributions In-Reply-To: <rKudnWZVMvAq2WvZnZ2dnUVZ_o2dnZ2d@comcast.com> References: <mKydnXWdR_33KXPZnZ2dnUVZ_o-dnZ2d@comcast.com> <mailman.9861.1156503058.27775.python-list@python.org> <44f31d35$0$17268$9b622d9e@news.freenet.de> <YvOdnaKfZ8KlIW7ZnZ2dnUVZ_vWdnZ2d@comcast.com> <mailman.10057.1156868874.27775.python-list@python.org> <tNCdneQEBKvZe2nZnZ2dnUVZ_sydnZ2d@comcast.com> <mailman.10074.1156900774.27775.python-list@python.org> <rKudnWZVMvAq2WvZnZ2dnUVZ_o2dnZ2d@comcast.com> Message-ID: <ed75hi$s7s$1@news.albasani.net> alf wrote: > Robert Kern wrote: >> alf wrote: >> >>> Fredrik Lundh wrote: >>> >>>> http://www.catb.org/~esr/faqs/smart-questions.html#writewell >>>> >>>> </F> >>> >>> >>> and </F> means? >> >> >> It's his signature. >> > > The sig is delimited by '-- \n' Yes, and Earth is a disk. Georg From rupole at hotmail.com Fri Aug 4 02:47:34 2006 From: rupole at hotmail.com (Roger Upole) Date: Fri, 4 Aug 2006 02:47:34 -0400 Subject: OS independent files References: <1154632873.085941.281850@75g2000cwc.googlegroups.com> <eatkfv$d1d$1@nemesis.news.tpi.pl> <5qk5d21hmpk6coq7jkq0vb8rs3s44j3lsr@4ax.com> Message-ID: <1154673582_11637@sp6iad.superfeed.net> "Dennis Lee Bieber" <wlfraed at ix.netcom.com> wrote: > On Thu, 03 Aug 2006 21:55:21 +0200, Jarek Zgoda <jzgoda at o2.usun.pl> > declaimed the following in comp.lang.python: > >> crystalattice napisa?(a): >> >> > If I want to make sure the file/directory is made in a user's home >> > directory (e.g. /home/users/path/to/file) but also compatible w/ >> > Windows, how would I rewrite this (if required)? >> >> On Windows, there's no notion of user's home directory, there is a >> directory for user's profile that is treated as $HOME but isn't >> (%USERPROFILE%), something that looks like $HOME, bot in fact is not >> (%HOMEDRIVE% + %HOMEPATH%) and many other mess. Microsoft suggests using >> %USERPROFILE%, but they do not specify desired behaviour, when >> %USERPROFILE% == c:\. > > There is also the registry entry > > HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell > Folders\Personal > > which, on my machine, contains the value > > E:\UserData\Dennis Lee Bieber\My Documents According to this: http://blogs.msdn.com/oldnewthing/archive/2003/11/03/55532.aspx the Shell Folders key shouldn't be relied upon. You can retrieve user directories using SHGetFolderPath or SHGetSpecialFolderPath, both of which are wrapped by win32com.shell. Roger From apardon at forel.vub.ac.be Tue Aug 1 13:44:54 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 1 Aug 2006 17:44:54 GMT Subject: Nested function scope problem References: <mq4jc2topbu781vcdtaeog4it914r8hr57@4ax.com> <slrnecklc4.5a7.apardon@rcpc42.vub.ac.be> <mailman.8675.1154112875.27775.python-list@python.org> <slrnecn499.98c.apardon@rcpc42.vub.ac.be> <mailman.8703.1154198214.27775.python-list@python.org> <slrnecpavl.c6f.apardon@rcpc42.vub.ac.be> <mailman.8711.1154269113.27775.python-list@python.org> <1154400727.472816.243290@b28g2000cwb.googlegroups.com> <mailman.8800.1154441595.27775.python-list@python.org> <h00vc2tj5gpsuctgguoi2ol6pq3a1rm2en@4ax.com> Message-ID: <slrnecv4om.l2k.apardon@rcpc42.vub.ac.be> On 2006-08-01, Dennis Lee Bieber <wlfraed at ix.netcom.com> wrote: > On Tue, 1 Aug 2006 11:12:31 -0300, Gerhard Fiedler <gelists at gmail.com> > declaimed the following in comp.lang.python: > >> There's maybe a point in comparing Python variables to C pointers. But it >> lacks in the respect that a C programmer is used to modify memory locations >> through pointers. A Python programmer isn't used to modify memory locations >> in the first place, and simple objects don't get modified at all. There's >> no Python equivalent to "int*p=345; *p++;". (There's no need for that in >> Python; I'm not saying this shows a superiority of C. It just shows a >> different concept of what "variable" means.) >> > Python > > c = c + 100 > > pseudo-C (where I use _p to indicate explicit pointer; and all data > objects are a structure of the form: int ref_count; <object type> data) > > scratch_p = malloc() > scratch_p->data = c_p->data + 100 > scratch_p->ref_count = 1 > c_p->ref_count-- > if !c_p->ref_count > free(c_p) > c_p = scratch_p > > ------- > b = a > is > b = a > b->ref_count++ > > > >> For me, the point of this discussion was that it makes sense to look at it >> /differently/. Once you've done that, there's no problem in continuing to >> use the (vaguely defined) term "variable". >> > > Think the above is "different" enough <G> The above are implementation details. Suppose I write a C-interpreter and then would translate a statement like "c = c + 100" into actions the interpreter would have to take in order to excute that statement. Something like: c-addr_p = GetAddress("c"); c-value = *c-addr_p; sum = c-value + 100; *c-addr_p = sum; That look different enough from just "c = c + 100". So maybe C has no variables either. -- Antoon Pardon From claudio.grondi at freenet.de Fri Aug 25 10:39:14 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Fri, 25 Aug 2006 16:39:14 +0200 Subject: random writing access to a file in Python In-Reply-To: <mailman.9872.1156515341.27775.python-list@python.org> References: <ecn00i$t2o$1@newsreader2.netcologne.de> <mailman.9872.1156515341.27775.python-list@python.org> Message-ID: <ecn22h$3o5$1@newsreader2.netcologne.de> Tim Peters wrote: > [Claudio Grondi] > >> I have a 250 Gbyte file (occupies the whole hard drive space) > > > Then where is Python stored ;-)? > >> and want to change only eight bytes in this file at a given offset of >> appr. 200 >> Gbyte (all other data in that file should remain unchanged). >> >> How can I do that in Python? > > > Same way you'd do it in C, really: > > f = open(PATH_TO_FILE, "r+b") > f.seek(appr. 200 Gbyte) > f.write(A_STRING_CONTAINING_YOUR_NEW_8_BYTES) > f.close() > > This depends on your operating system and file system and platform C > library supporting seeks to very large offsets. For example, Windows > using NTFS does. Try it. Python should complain (raise an exception > during the seek() attempt) if your box refuses to cooperate. Use as > recent a released version of Python as you can. Thank you much for the quick response. The core of my problem was ... trying to use 'wb' or 'w+b' ... (stupid me ...) Claudio Grondi From michele.petrazzo at TOGLIunipex.it Mon Aug 21 04:31:45 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Mon, 21 Aug 2006 08:31:45 GMT Subject: py2exe: cannot identify image file In-Reply-To: <1155965446.309438.161740@74g2000cwt.googlegroups.com> References: <1155965446.309438.161740@74g2000cwt.googlegroups.com> Message-ID: <RbeGg.76621$zy5.1372239@twister1.libero.it> Daniel Mark wrote: > Hello all: > > It seems that function 'Image.open' cannot read image file under EXE > application. What should I do for this problem? > google and "pil py2exe", the first reply: http://starship.python.net/crew/theller/moin.cgi/PIL_20and_20py2exe > > Thank you -Daniel > Michele From squall_leonheart7 at netzero.net Wed Aug 30 13:00:56 2006 From: squall_leonheart7 at netzero.net (squall_leonheart7 at netzero.net) Date: Wed, 30 Aug 2006 17:00:56 GMT Subject: audio with graphics Message-ID: <20060830.100147.10554.687309@webmail18.nyc.untd.com> An embedded and charset-unspecified text was scrubbed... Name: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20060830/80e7dd6e/attachment.ksh> From bignose+hates-spam at benfinney.id.au Thu Aug 31 22:51:41 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 01 Sep 2006 12:51:41 +1000 Subject: introspection References: <ed8458$7od$1@solaris.cc.vt.edu> Message-ID: <87bqq0i9j6.fsf@benfinney.id.au> brad tilley <rtilley at vt.edu> writes: > How do I import a module and then ask it to show me its methods or other > aspects about itself during execution? I'd like to do something such as > this: > > import win32api > > print win32api.methods() > > I'd like to write some test scripts that load modules and probe them > for information about themselves. As well as the 'inspect' module, you may be able to get some distance just with builtin functionality:: >>> import re >>> dir(re) ['DOTALL', 'I', 'IGNORECASE', 'L', 'LOCALE', 'M', 'MULTILINE', 'S', 'U', 'UNICODE', 'VERBOSE', 'X', '__all__', '__builtins__', '__doc__', '__file__', '__name__', 'compile', 'engine', 'error', 'escape', 'findall', 'finditer', 'match', 'purge', 'search', 'split', 'sub', 'subn', 'template'] >>> [(n, getattr(re, n)) for n in dir(re)] [('DOTALL', 16), ('I', 2), ('IGNORECASE', 2), ('L', 4), ('LOCALE', 4), ('M', 8), ('MULTILINE', 8), ('S', 16), ('U', 32), ('UNICODE', 32), ('VERBOSE', 64), ('X', 64), ('__all__', ['match', 'search', 'sub', 'subn', 'split', 'findall', 'compile', 'purge', 'template', 'escape', 'I', 'L', 'M', 'S', 'X', 'U', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL', 'VERBOSE', 'UNICODE', 'error', 'finditer']), [...] ] >>> [n for n in dir(re) if hasattr(getattr(re, n), '__call__')] ['compile', 'escape', 'findall', 'finditer', 'match', 'purge', 'search', 'split', 'sub', 'subn', 'template'] -- \ "Madness is rare in individuals, but in groups, parties, | `\ nations and ages it is the rule." -- Friedrich Nietzsche | _o__) | Ben Finney From cliff at develix.com Tue Aug 15 03:24:58 2006 From: cliff at develix.com (Cliff Wells) Date: Tue, 15 Aug 2006 00:24:58 -0700 Subject: ReStructuredText Message-ID: <1155626698.16686.16.camel@devilbox> Started playing with docutils and don't understand why the following doesn't work: >>> from docutils.core import publish_parts >>> t = ''' ... ... 1. this is a test ... #. this is another line ... #. oh, screw it! ... ... ''' >>> publish_parts ( t, writer_name = 'html' ) [ 'body' ] u'<p>1. this is a test\n#. this is another line\n#. oh, screw it!</p>\n' >>> Why doesn't the above turn out an enumerated list? It looks like all the examples I've seen, and I've tried adding and removing blank lines around it to no avail. Regards, Cliff -- From tim.golden at viacom-outdoor.co.uk Tue Aug 22 08:13:22 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 22 Aug 2006 13:13:22 +0100 Subject: How to get database metadata information (i.e. existing tables andcolumns in tables) Message-ID: <CCAC78D42E32184F8E26DC163DB98306C1B3BA@vogbs009.gb.vo.local> [Chris Brat] | Is it possible to retrieve details about the database, specifically a | list of the tables in the database; and then to retrieve the columns | and their types for the tables? | | Is this dependant on the database? In effect it's dependent on the database. We're assuming you're talking about a relational databases for a start, since other databases don't necessarily even have tables. The major databases may support the INFORMATION_SCHEMA standard (random link: http://www.devx.com/getHelpOn/10MinuteSolution/20561) but they may not -- I don't think sqlite does, for example -- and their implementations may well vary etc. In short, try INFORMATION_SCHEMA first. Failing that, look at the specific db docs for the gen. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From tim at zoominternet.net Fri Aug 11 03:20:15 2006 From: tim at zoominternet.net (Tim Scheidemantle) Date: Fri, 11 Aug 2006 03:20:15 -0400 Subject: Password authentication systems In-Reply-To: <aIUCg.67141$Uy1.12506@read1.cgocable.net> References: <1155218165.193546.136090@h48g2000cwc.googlegroups.com> <aIUCg.67141$Uy1.12506@read1.cgocable.net> Message-ID: <44DC2FAF.1070907@zoominternet.net> Enabling shadow passwords stores them in /etc/shadow which is not world readable unlike /etc/passwd. They would be encrytped regardless of the file they are in. AlbaClause wrote: > neokosmos at gmail.com wrote: > > >> This may only be tangentially related to Python, but since I am coding >> a password authentication system in Python, I thought I would ask here. >> >> In Linux (and presumably other *NIX systems that support it), when >> shadow passwords are enabled, the actual password is not stored. >> Instead an encrypted version is stored. Then, to authenticate the >> password, the system re-encrypts the user's input to see if it matches >> the stored, encrypted version. >> >> > > Correct me if I'm wrong, but I believe that all Linux passwords are > encrypted whether you enable shadow passwords or not. I believe that when > you enable shadow passwords, the encrypted passwords are stored in a file > other than 'passwd'. Is this not correct? > > From larry.bates at websafe.com Tue Aug 1 15:21:27 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 01 Aug 2006 14:21:27 -0500 Subject: Finding the name of a class In-Reply-To: <u13vc2d68t3ih6kugmm2q7iri4r7j5lucn@4ax.com> References: <q684q3xmd11.ln2@news.conpoint.com> <44CF7569.9020509@websafe.com> <57a4q3xgf21.ln2@news.conpoint.com> <u13vc2d68t3ih6kugmm2q7iri4r7j5lucn@4ax.com> Message-ID: <BMudnZXCQ-ApNFLZnZ2dnUVZ_vadnZ2d@comcast.com> Dennis Lee Bieber wrote: > On Tue, 01 Aug 2006 10:56:52 -0500, Kirk Strauser <kirk at strauser.com> > declaimed the following in comp.lang.python: > >> Larry Bates wrote: >> >>> print print b.__class__.__name__ gives what you want >> That doesn't seem to do it, though. Here's the result of importing a module >> from my company's internally-developed library: >> >>>>> from Daycos.TableCopier.copyfro import StateProcessor >>>>> print StateProcessor.__class__.__name__ >> type >> >> I'm looking for something that would print 'StateProcessor' but am not >> having much luck. > > And what is "StateProcessor" > >>>> class SP(object): > ... pass > ... >>>> print SP.__class__.__name__ > type > > Looks like it is, itself, the class, not something within the class. > >>>> s=SP() >>>> print s.__class__.__name__ > SP >>>> DP = SP >>>> d = DP() >>>> print DP.__class__.__name__ > type >>>> print d.__class__.__name__ > SP When I do this: class foo(object): pass if __name__=="__main__": a=foo() print a.__class__.__name__ Note: You must do it on instance of the class not the class itself. it prints 'foo' for me. Not exactly sure why you get something very different. I've used this LOTS of times in my code, but I'll admit mostly with old-style classes. -Larry Bates From rosedb0 at gmail.com Wed Aug 2 21:15:42 2006 From: rosedb0 at gmail.com (hiaips) Date: 2 Aug 2006 18:15:42 -0700 Subject: Are there any AOP project in python community? In-Reply-To: <1154562487.677431.274440@i3g2000cwc.googlegroups.com> References: <1154562487.677431.274440@i3g2000cwc.googlegroups.com> Message-ID: <1154567742.168880.150920@h48g2000cwc.googlegroups.com> steve wrote: > I mean Aspect-Oriented Programming. > If any please give me some of links. > Thanks a lot. See http://en.wikipedia.org/wiki/Aspect-oriented_programming. There is a list of AOP implementations for a number of languages (including Python) near the bottom of the page. --hiaips From schouwla at yahoo.com Thu Aug 3 02:21:19 2006 From: schouwla at yahoo.com (schouwla at yahoo.com) Date: 2 Aug 2006 23:21:19 -0700 Subject: newbie...No module named win32com.client Message-ID: <1154586079.768002.310750@m79g2000cwm.googlegroups.com> This is my very first time to use Phyton! I am getting a problem with win32com.client missing from some existinf scripts. >python Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import win32com.client Traceback (most recent call last): File "<stdin>", line 1, in ? ImportError: No module named win32com.client I can see the packages in located in a lib.zip files.. how do I tell Phyton to use that zip file for it's packages? Lars From johnjsal at NOSPAMgmail.com Wed Aug 2 09:48:33 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 02 Aug 2006 13:48:33 GMT Subject: cleaner way to write this try/except statement? In-Reply-To: <eaploq$1lg$00$1@news.t-online.com> References: <UVOzg.2616$No6.51297@news.tufts.edu> <eaploq$1lg$00$1@news.t-online.com> Message-ID: <R22Ag.2621$No6.51548@news.tufts.edu> Peter Otten wrote: > John Salerno wrote: > >> The code to look at is the try statement in the NumbersValidator class, >> just a few lines down. Is this a clean way to write it? i.e. is it okay >> to have all those return statements? Is this a good use of try? Etc. >> >> Thanks. >> >> ---------------------------- >> >> import wx >> >> >> class NumbersValidator(wx.PyValidator): >> >> def __init__(self): >> wx.PyValidator.__init__(self) >> >> def Clone(self): >> return NumbersValidator() >> >> def Validate(self, parent): >> text_ctrl = self.GetWindow() >> text = text_ctrl.GetValue() >> >> try: >> if not text or int(text) <= 0: >> wx.MessageBox('Enter a valid time.', 'Invalid time >> >> entered', wx.OK | wx.ICON_ERROR) >> return False >> else: >> return True >> except ValueError, error: >> wx.MessageBox('Enter a valid time.', 'Invalid time entered', >> wx.OK | wx.ICON_ERROR) >> return False >> >> def TransferToWindow(self): >> return True >> >> def TransferFromWindow(self): >> return True > > Here's how I might do it: > > def is_positive_int_str(s): > try: > value = int(s) > except ValueError: > return False > return value > 0 > > class PositiveIntegerValidator(wx.PyValidator): > # ... > def Validate(self, parent): > text = self.GetWindow().GetValue() > if is_positive_int_str(text): > return True > wx.MessageBox(...) > return False > > Two usability notes: > - "Invalid time entered" is a confusing message when you actually want a > positive integer. > - Pop-up messages are a major annoyance. An alternative would be to change > the text color of the control and show a hint as to what input you expect > in a status bar. > > Peter > Thanks for all the help guys! I'm going to rework it a little and see what happens. Luckily, I'm also reading the chapter on exceptions in Python in a Nutshell, so maybe that will help solidify my understanding of how to construct them in this situation. From bwm at acm.org Mon Aug 21 01:09:28 2006 From: bwm at acm.org (Bernhard Mulder) Date: Mon, 21 Aug 2006 05:09:28 GMT Subject: Input from the same file as the script In-Reply-To: <1156096945.924216.14380@m73g2000cwd.googlegroups.com> References: <1156096945.924216.14380@m73g2000cwd.googlegroups.com> Message-ID: <cebGg.9678$%j7.4081@newssvr29.news.prodigy.net> you can (ab)use doc strings. See the doctest module for an example. From mail at microcorp.co.za Fri Aug 4 06:26:47 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Fri, 4 Aug 2006 12:26:47 +0200 Subject: Is there an obvious way to do this in python? References: <mailman.8853.1154537129.27775.python-list@python.org><44d128e5$0$13484$636a55ce@news.free.fr><mailman.8884.1154590374.27775.python-list@python.org><1154602887.279222.37980@75g2000cwc.googlegroups.com><mailman.8925.1154627441.27775.python-list@python.org> <82k5d258lj5sk7k1uppqsineqt3mg2ohv1@4ax.com> Message-ID: <006801c6b7b7$651aef40$03000080@hendrik> "Dennis Lee Bieber" <wlfraed at ix.netcom.com> wrote: | On Thu, 3 Aug 2006 16:50:15 +0200, "H J van Rooyen" | <mail at microcorp.co.za> declaimed the following in comp.lang.python: | > Now part of the reason I would like to go the transaction type route instead of | > the "per user" route is robustness and maintainability, and the ability it | > would give me to introduce new transaction types easily - as I see it if say an | > invoice's GUI code is stable I would never have to touch it again even if I | > combine it with anything else, as it would have been designed from the start to | > combine with others of it's own ilk, under a kind of communications controller | > that is standard... | > | Uhm... You've just described the "raison d'etre" of Object Oriented | design/programming. Oh No! - curses! It has slipped in under the radar! - I have always thought that the reason for going the OO route is to obfuscate the code so that mere mortals could never understand it... | | Each of your "transactions" (tasks/jobs/functions) would be a single | "class" (this does not mean they may not incorporate other classes as | part of them). Ideally, each class should be independent of the others | except for a defined API. The "invoice" would be one "class" (actually, | you may have a class for "invoice data" -- this being the information | passing between the client and the server; and a class for "invoice | presentation" -- the GUI. Plugging in another task should only involve | the main client (new menu entry) with maybe an "import new_task" so | picking the menu entry instantiates new_task. | -- Yes got it, thanks- Hendrik From sjmachin at lexicon.net Mon Aug 7 01:34:37 2006 From: sjmachin at lexicon.net (John Machin) Date: 6 Aug 2006 22:34:37 -0700 Subject: Nice unicode -> ascii translation? References: <1154916240.860577.35860@p79g2000cwp.googlegroups.com> Message-ID: <1154928877.002243.136740@n13g2000cwa.googlegroups.com> crowell at mit.edu wrote: > I'm using the ID3 tag of an mp3 file to query musicbrainz to get their > sort-name for the artist. A simple example is "The Beatles" -> > MusicBrainz -> "Beatles, The". I then want to rename the mp3 file > using this information. However, I would like the filename to contain > only ascii characters, while musicbrainz gives unicode back. So far, > I've got something like: > > >>> artist = u'B\xe9la Fleck' > >>> artist.encode('ascii', 'ignore') > 'Bla Fleck' Why do you want only ASCII characters? What platform are you running on? If it's just a display problem, and the Unicode doesn't stray outside the first 256 codepoints, you shouldn't have a problem e.g. Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32 [snip] IDLE 1.1.3 >>> artist = u'B\xe9la Fleck' >>> artist u'B\xe9la Fleck' >>> print artist B?la Fleck >>> import sys >>> sys.stdout.encoding 'cp1252' >>> print artist.encode('latin1') B?la Fleck On a *x box, using latin1 should work. > > However, I'd like to see the more sensible "Bela Fleck" instead of > dropping '\xe9' entirely. I believe this sort of translation can be > done using: > > >>> artist.translate(XXXX) > > The trick is finding the right XXXX. Has someone attempted this > before, or am I stuck writing my own solution? However if you really insist on having only ASCII characters, then you've pretty much got to make up your own translation table. There was a thread or two on this topic within the last few months. Merely stripping off accents umlauts cedillas etc etc off most European scripts where the basic alphabet is Roman/Latin is easy enough. However some scripts use characters which are not Latin letters with detachable decorations, and you will need 2 characters out for 1 in (e.g. German eszett, Icelandic thorn (the name of the god with the hammer is shown in ASCII as Thor, not Por!)). Scripts like Greek and Cyrillic would need even more work HTH, John From danielwong at berkeley.edu Tue Aug 15 22:01:34 2006 From: danielwong at berkeley.edu (danielx) Date: 15 Aug 2006 19:01:34 -0700 Subject: hide python code ! In-Reply-To: <1155300852.497741.73230@74g2000cwt.googlegroups.com> References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155300852.497741.73230@74g2000cwt.googlegroups.com> Message-ID: <1155693694.896386.169350@p79g2000cwp.googlegroups.com> Fuzzyman wrote: > Bayazee wrote: > > hi > > can we hide a python code ? > > if i want to write a commercial software can i hide my source code from > > users access ? > > we can conver it to pyc but this file can decompiled ... so ...!! > > do you have any idea about this ...? > > > > --------------------------------------- > > First Iranian Open Source Community : www.python.ir > > > You can distribute the compiled byte-code files (*.pyc) which are > harder to turn back into source code. > > There was a product called decompyle which could do it, but although > there is a version floating around which works for Python 2.4 I've > never heard of anyone getting it to work. > > Import hooks and encrypted source are a good option. > > Py2exe embeds the byte-code file for your main script into the > executable which is also pretty good. > > All of these make it hard enough to deter most people who will ever > want to abuse your source code. Until you have *lots* of users this is > probably enough. > > I never understand the knee-jerk reaction on this mailing list to > answer people who ask this question by telling them they don't really > want to do it... I'm I've compained about this before, but I'd say people apply that response to alot of other things too here on this mailing list. *** Earlier in this thread, people were making alot of noise about Bayazee trying to protect the code while it seemed he was part of an open source group. He never mentioned that he intended to hide any code produced for this open source group; indeed, he never mentioned any code he wished to hide at all. People must have been inferring that if one is part of an open source group, that all work one produces is for the group and must therefore be open source. Otherwise, people might have been thinking that being a member of an open source group makes you an open source evangelist. If the latter is true (and these cases are neither mutually exclusive nor exhaustive), then those who were so vocal in pointing out the "appearant discrepency" must have been projecting their own views on Bayazee. I'm not sure if this needs to be said, but just because someone posts on comp.lang.python does not mean he or she believe (or even should believe) the same things as you! My last statement applies to a few other things I've read around here, but I'm going to be done for now... > > Fuzzyman > http://www.voidspace.org.uk/python/index.shtml From grflanagan at yahoo.co.uk Wed Aug 16 07:07:34 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 16 Aug 2006 04:07:34 -0700 Subject: Printing n elements per line in a list In-Reply-To: <1155717984.236596.32390@h48g2000cwc.googlegroups.com> References: <1155685889.626881.37040@m73g2000cwd.googlegroups.com> <1155717152.198836.235070@p79g2000cwp.googlegroups.com> <1155717984.236596.32390@h48g2000cwc.googlegroups.com> Message-ID: <1155726453.965924.67070@b28g2000cwb.googlegroups.com> John Machin wrote: > Gerard Flanagan wrote: > > > > > just variations on previous answers: > > > > rng = range(1,101) > > > > #ad hoc > > for line in ( rng[i:i+5] for i in xrange(0,100,5) ): > > print ' '.join(map(str,line)) > > > > #in general > > def lines( seq, count=1 ): > > n = len(seq) > > for x in ( seq[i:i+count] for i in xrange(0,n,count) ): > > yield x > > > > Don't those last two lines deflate to: > for i in xrange(0,n,count): > yield seq[i:i+count] > ??? Yes! Thank you. (pre-caffeine...) Gerard From stk at mevis.de Wed Aug 9 05:14:35 2006 From: stk at mevis.de (Stephan Kuhagen) Date: Wed, 09 Aug 2006 11:14:35 +0200 Subject: #!/usr/bin/python or #!/usr/bin/env python? References: <fj5Cg.2658$No6.51984@news.tufts.edu> <bL6dnTXbq9adbkXZnZ2dnUVZ_u2dnZ2d@speakeasy.net> <ebbtor$evr$1@kohl.informatik.uni-bremen.de> <mailman.9130.1155106885.27775.python-list@python.org> <ebc288$g8s$1@kohl.informatik.uni-bremen.de> <vsgCg.66818$zy5.1253926@twister1.libero.it> <ebc58g$h22$1@kohl.informatik.uni-bremen.de> <JfOdncqW_fzdAUTZnZ2dnUVZ_uWdnZ2d@speakeasy.net> <ebc7e4$243u$3@news.uit.no> Message-ID: <ebc91r$i2c$1@kohl.informatik.uni-bremen.de> Tobias Brox wrote: > This is very off-topic, Sorry for starting that... > but if it's fairly common to begin tcl-scripts > as a /bin/sh-file with "exec tcl" at one of the first lines, I think > "file" ought to be able to recognize it. > > """exec" python is clearly an obscure hack not used by many, so I > don't see why "file" should ever recognize that :-) That's what I meant. It is okay for a Python-script not to be recognized by "file" that way, it is enough that I can do it, if I need to. But file should recognize this for Tcl, because it is common there. And if it needs to work for Tcl only, one can construct a simple mechanism for "file" to check this. Stephan From poggle.themammal at gmail.com Sun Aug 20 14:16:00 2006 From: poggle.themammal at gmail.com (poggle.themammal at gmail.com) Date: 20 Aug 2006 11:16:00 -0700 Subject: Access to sys.argv when python interpreter is invoked in some modes like 'python -c "command"' Message-ID: <1156097760.557614.195120@74g2000cwt.googlegroups.com> The python tutorial says "When the script name is given as '-' (meaning standard input), sys.argv[0] is set to '-'. When -c command is used, sys.argv[0] is set to '-c'. " but when we use a command say 'python -c "command"' where can we access "sys.argv" (are there some commands where "sys.argv" is accessed. I can run 'python -c "import sys sys.argv", I get an error message -Tiro From codecraig at gmail.com Mon Aug 7 08:14:47 2006 From: codecraig at gmail.com (abcd) Date: 7 Aug 2006 05:14:47 -0700 Subject: regex for replacing \r\n Message-ID: <1154952887.148348.295020@i3g2000cwc.googlegroups.com> I am trying to get a regex that will match \r\n in a string. ultimately i am trying to replace all \r\n with somethign else, say BLAH. For example: This is a message on a new line would become: This is a messageBLAHon a new line. any ideas? i tried re.compile('\r\n').match("This is a message" + os.linesep + "on a new line") ....but no match. And I am on windows, so os.linesep gives '\r\n' thanks From rogue_pedro at yahoo.com Wed Aug 23 20:01:06 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 23 Aug 2006 17:01:06 -0700 Subject: setting a breakpoint in the module In-Reply-To: <mailman.9740.1156369295.27775.python-list@python.org> References: <mailman.9734.1156362020.27775.python-list@python.org> <1156368470.107201.78400@m73g2000cwd.googlegroups.com> <mailman.9740.1156369295.27775.python-list@python.org> Message-ID: <1156377666.224828.161500@h48g2000cwc.googlegroups.com> Jason Jiang wrote: > Great! It's working now. Thank you so much. > > Jason You're welcome, it's a pleasure! :-D ~Simon From andy.terrel at gmail.com Thu Aug 10 02:12:11 2006 From: andy.terrel at gmail.com (Andy Terrel) Date: 9 Aug 2006 23:12:11 -0700 Subject: loop until keypress (Windows XP) In-Reply-To: <mailman.9181.1155188232.27775.python-list@python.org> References: <1155187164.696015.252920@b28g2000cwb.googlegroups.com> <mailman.9181.1155188232.27775.python-list@python.org> Message-ID: <1155190331.509218.241250@75g2000cwc.googlegroups.com> If you did want a linux version you could just make people send a KeyboardInterupt. try: print "Press ^C to stop" loop except KeyboardInterrupt: some stop action or just pass From jordan.taylor2 at gmail.com Thu Aug 17 00:25:22 2006 From: jordan.taylor2 at gmail.com (Jordan) Date: 16 Aug 2006 21:25:22 -0700 Subject: wxPython Grid Question Message-ID: <1155788722.147173.58730@m73g2000cwd.googlegroups.com> Hey Peoples, I'm wonderg if there is a way to make a subclass of wx.grid.Grid in which the coloumn labels for the grid appear on the bottom of the grid instead of the top. 1 2 3 4 5 a| | | | | | b| | | | | | c| | | | | | d| | | | | | e| | | | | | Just in case that wasn't clear (and because I just feel like typing more): The above grid has labels in the normal placement. The grid below has the labels in the places I want them. a| | | | | | b| | | | | | c| | | | | | d| | | | | | e| | | | | | 1 2 3 4 5 Thanks From neoedmund at gmail.com Wed Aug 30 21:35:02 2006 From: neoedmund at gmail.com (neoedmund) Date: 30 Aug 2006 18:35:02 -0700 Subject: A Sort Optimization Technique: decorate-sort-dedecorate In-Reply-To: <pan.2006.08.28.08.53.08.647908@gmx.net> References: <1156719092.603277.57390@b28g2000cwb.googlegroups.com> <1156723602.192984.49610@m79g2000cwm.googlegroups.com> <pan.2006.08.28.08.53.08.647908@gmx.net> Message-ID: <1156988102.266873.18660@i42g2000cwa.googlegroups.com> yeah, java also have 2 interface, Comparator and Comparable, which equal to python's compareTo() and __cmp__() Marc 'BlackJack' Rintsch wrote: > In <1156723602.192984.49610 at m79g2000cwm.googlegroups.com>, Tom Cole wrote: > > > In Java, classes can implement the Comparable interface. This interface > > contains only one method, a compareTo(Object o) method, and it is > > defined to return a value < 0 if the Object is considered less than the > > one being passed as an argument, it returns a value > 0 if considered > > greater than, and 0 if they are considered equal. > > > > The object implementing this interface can use any of the variables > > available to it (AKA address, zip code, longitude, latitude, first > > name, whatever) to return this -1, 0 or 1. This is slightly different > > than what you mention as we don't have to "decorate" the object. These > > are all variables that already exist in the Object, and if fact make it > > what it is. So, of course, there is no need to un-decorate at the end. > > Python has such a mechanism too, the special `__cmp__()` method > has basically the same signature. The problem the decorate, sort, > un-decorate pattern solves is that this object specific compare operations > only use *one* criteria. > > Let's say you have a `Person` object with name, surname, date of birth and > so on. When you have a list of such objects and want to sort them by name > or by date of birth you can't use the `compareTo()` method for both. > > Ciao, > Marc 'BlackJack' Rintsch From wildemar at freakmail.de Wed Aug 9 10:24:43 2006 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Wed, 09 Aug 2006 16:24:43 +0200 Subject: How to reverse tuples in a list? In-Reply-To: <1155081671.728757.228050@p79g2000cwp.googlegroups.com> References: <1155081671.728757.228050@p79g2000cwp.googlegroups.com> Message-ID: <44D9F02B.5060806@freakmail.de> Noah wrote (among other things ;)): > I have a list of tuples > I want to reverse the order of the elements inside the tuples. > But it seems like there should be a clever way to do this with > a list comprehensions. Problem is I can't see how to apply > reverse() to each tuple in the list because reverse() a > list method (not a tuple method) and because it operates > in-place (does not return a value). This kind of wrecks doing > it in a list comprehension. What I'd like to say is something like > this: > y = [t.reverse() for t in y] > Even if reverse worked on tuples, it wouldn't work inside a > list comprehension. This is a minor point, but I've got the impression you're not completely aware that tuples are immutable, and what that implies. I mean that t.reverse(), assuming the same semantics as the list method, is just not possible, as it would try to alter the tuple. This is not what tuples are for, so there. Sorry if you knew this, just wanted to point out that there is a conscious difference between tuples and lists. This is of course just a half-newbie crackin wise, so forgive me ;). wildemar From fredrik at pythonware.com Wed Aug 30 11:50:38 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 30 Aug 2006 17:50:38 +0200 Subject: xml.sax.writer In-Reply-To: <f278b2130608300606m63d082cdl448353890ac29c64@mail.gmail.com> References: <f278b2130608300606m63d082cdl448353890ac29c64@mail.gmail.com> Message-ID: <ed4c4e$8fd$1@sea.gmane.org> Dominic Fox wrote: > xml.sax.writer doesn't appear in the global module documentation, and > googling for it doesn't tell you all that much either. Is it actually > in the standard libraries, or is it an interloper from something else > (the libxml bindings, say) that just happens to have taken up > residence in the xml.sax namespace? iirc, it's a PyXML thing: http://pyxml.sourceforge.net/ </F> From jorge.vargas at gmail.com Mon Aug 28 18:04:32 2006 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Mon, 28 Aug 2006 18:04:32 -0400 Subject: class problem In-Reply-To: <ecvbu2$j8h$2@sea.gmane.org> References: <1156786617.162744.128870@h48g2000cwc.googlegroups.com> <Xns982DBFD76BA73duncanbooth@127.0.0.1> <ecvbu2$j8h$2@sea.gmane.org> Message-ID: <32822fe60608281504q68d99453m294f5ad1cfda520c@mail.gmail.com> On 8/28/06, Fredrik Lundh <fredrik at pythonware.com> wrote: > Duncan Booth wrote: > > > Yes, the first one is a syntax error because you aren't allowed empty > > parentheses in a class statement > > however, > > $ python > Python 2.5c1 /.../ > >>> class foo(): > ... pass > ... > >>> foo > <class __main__.foo at 0x00A3D840> > >>> > > </F> > > -- > http://mail.python.org/mailman/listinfo/python-list > D:\python>python Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> class foo(): File "<stdin>", line 1 class foo(): ^ SyntaxError: invalid syntax seems like a feature/bug of 2.5, why your learning a language with a beta version? From garyjefferson123 at yahoo.com Thu Aug 24 21:31:39 2006 From: garyjefferson123 at yahoo.com (garyjefferson123 at yahoo.com) Date: 24 Aug 2006 18:31:39 -0700 Subject: setup.py and file extensions like ".c++" Message-ID: <1156469499.816353.301520@m73g2000cwd.googlegroups.com> Is there any way to get setup.py to recognize file extensions like .c++ in lieu of .cpp? I'd love to not have to rename the source files for the library I'm trying to wrap in a python C extension. I get: error: unknown file type '.c++' (from 'parser.c++') when I type 'python setup.py build' thanks, Gary From jaysherby at gmail.com Tue Aug 29 14:26:59 2006 From: jaysherby at gmail.com (Putty) Date: 29 Aug 2006 11:26:59 -0700 Subject: python for flash drives Message-ID: <1156876019.177142.101730@e3g2000cwe.googlegroups.com> Is there such a thing as a special version of python that I can run more efficiently from a flash drive? I'll be at college for hours every day with hours of free time for the next few months, but the only computers at my disposal are windows PCs that use GoBack to auto-revert every reboot. So I'm kinda stuck. I don't want to have to reinstall python AND wxPython AND PIL every stinking time I log on. However, using it from my flash drive is painfully slow taking up to a minute just to execute some scripts. And it's not doing me any favors with I/O to the flash disk either. So I was wondering if anybody knew of some flash drive implementations of python that might exist out there somewhere? From wegein at gmail.com Thu Aug 24 00:46:21 2006 From: wegein at gmail.com (damacy) Date: 23 Aug 2006 21:46:21 -0700 Subject: all ip addresses of machines in the local network In-Reply-To: <1156393371.550249.138930@75g2000cwc.googlegroups.com> References: <1156387621.568779.191420@m73g2000cwd.googlegroups.com> <1156393371.550249.138930@75g2000cwc.googlegroups.com> Message-ID: <1156394781.155152.313080@i3g2000cwc.googlegroups.com> hi, sandra. no, it's not as complicated as that. all i want to do is to load a database onto different machines residing in the same network. i hope there is a way doing it. or perhaps i have a poor understanding of how networks work. regards, damacy Sandra-24 wrote: > damacy wrote: > > hi, there. i have a problem writing a program which can obtain ip > > addresses of machines running in the same local network. > > > > say, there are 4 machines present in the network; [a], [b], [c] and [d] > > and if i run my program on [a], it should be able to find "host names" > > and "ip addresses" of the other machines; [b], [c] and [d]? > > > > i have read some threads posted on this group, however, they only work > > for localhost, not the entire network. > > > > any hints if possible? > > > > thanks for your time. > > > > regards, damacy > > What is this for? Some kind of high availablity server setup? I don't > know anything that would be useful to you, but I am curious, and maybe > it will clarify your intentions for others. > > -Sandra From sbassi at gmail.com Thu Aug 31 10:51:11 2006 From: sbassi at gmail.com (Sebastian Bassi) Date: Thu, 31 Aug 2006 11:51:11 -0300 Subject: Timeline for Python? Message-ID: <b43bf2080608310751l62a8a4bem32a4beadc8cec8d3@mail.gmail.com> Hello all, I am working on a Python book, since it could be completed in about a year (writing time + edition + publishing) or more, I would like to know what version to target since I don't want to release a book that will be outdated just after is printed. I use 2.4 for everyday work but most webservers still carry 2.2 (and most programs runs w/o any modification, since I don't tend to use new features), but publishers know that people like to buy lasted version books. So, if the book is published in October 2007, should feature Python 3 or Python 2.5? I did read http://www.python.org/dev/peps/pep-3000/ but I still not sure about timeline. Best regards, SB. -- Bioinformatics news: http://www.bioinformatica.info Lriser: http://www.linspire.com/lraiser_success.php?serial=318 From snail at objmedia.demon.co.uk Wed Aug 9 10:10:20 2006 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Wed, 9 Aug 2006 15:10:20 +0100 Subject: do people really complain about significant whitespace? References: <1154986984.740638.241130@m79g2000cwm.googlegroups.com> <ebabqf$c3$1@panix2.panix.com> <mailman.9107.1155060736.27775.python-list@python.org> <2AY13sCznQ2EFw8+@objmedia.demon.co.uk> <mailman.9117.1155081436.27775.python-list@python.org> Message-ID: <w$3EInHMze2EFwem@objmedia.demon.co.uk> In message <mailman.9117.1155081436.27775.python-list at python.org>, Gerhard Fiedler <gelists at gmail.com> writes >But there is well-written code that is as much as reasonably possible >self-documenting, meaning easy to read and understand, with a clear >structure, helpful names, appropriate types (where applicable) etc etc. But that code is documenting what is does, not what it should do. That is the fallacy of self-documenting. It is simply a bogus concept. If you have the two together then if they match, most likely the program is written correctly. If you have only the one you can't make the comparison. I don't think you should have a line of comment per line of code. I once worked in a place where they insisted on 1 comment per 5 lines of code. I was the #1 troublemaker there after they created that rule - I hated it. It resulted in a lot of bogus comments that added nothing. Its what you write and where. The problem with the self-documenting crowd is they don't write anything so you can't follow their assumptions in the comments. It should be as sparse as you can get but enough so that each block/chunk of code can be validated by comparing it with the comment that describes what you are doing. My first code was basic on a VIC-20, then assembly on a variety of different 6502/6510 based machines (C64, C16, Atari...). I didn't bother much with comments back then. I was writing games and once they are done you never revisit them so you didn't care too much as long as you got the job done. I thought it was reasonably obvious what each function did etc. Ding! I went back some years later and looked at some of my own code. I had little idea what a lot of it did. I started commenting my code after that. So when it came time to port a game written for the 6510/6516/6502 to the 68000 (Atari ST) and IBM PC-AT (80286) the comments came in handy. Sadly the game never saw the light of day for legal reasons outside of my control. The game was a copy of the wonderful arcade game "Dingo" written by Ashbury Computers and Graphics (the team that later became Ultimate Play the Game who wrote for the Sinclair ZX Spectrum very successfully in the 1980s). A bit of history for you :-) Since someone mentioned assemblers and significant whitespace and I'm rambling about assembly: I don't every remember whitespace being significant for any of the assemblers I used (650x, 630x, 680x, 8085, 80286, 68000). There was a convention though - you indented to column 8 to write the mnemonics and used the first 6 or 7 chars for labels for branch/jmp instructions. >Come on, if you have been in the business for 23 years you know what I >mean. If you mean, should code be well written, thought about, well formatted, sensible class/variable names, redesigned if you find a better way, sure no problem with that. Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk/software.html Computer Consultancy, Software Development Windows C++, Java, Assembler, Performance Analysis, Troubleshooting From ms at cerenity.org Sun Aug 20 19:09:28 2006 From: ms at cerenity.org (Michael) Date: Mon, 21 Aug 2006 00:09:28 +0100 Subject: Text to MP3 using pyTTS - Non-programmer question References: <1155904799.935486.105460@i3g2000cwc.googlegroups.com> <PzRFg.2453$Te.1897@trnddc07> Message-ID: <44e8ea3c$0$3623$ed2e19e4@ptn-nntp-reader04.plus.net> Marc Shapiro wrote: > From what I've seen, pyTTS is Windows only. ?Is there a package that > runs on linux that provides similar functionality. ?I have festival and > festlite, but I would prefer a Python solution. From: http://www.cam.org/~nico/cicero/cicero-README.txt """ Cicero TTS: A Small, Fast and Free Text-To-Speech Engine. Copyright 2003-2006 Nicolas Pitre <nico at cam.org> Copyright 2003-2006 St?phane Doyon <s.doyon at videotron.ca> Version 0.7, March 2006 Our TTS engine currently speaks French and some resemblance of English, although we hope it can some day be taught to speak good English or other languages. The engine uses context-sensitive rules to produce phonemes from the text. It relies on MBROLA (http://tcts.fpms.ac.be/synthesis/mbrola.html) to generate actual audio output from the phonemes. The TTS engine is implemented using the Python programming language. We've come up with this TTS to try and meet our own needs as blind users. """ """ This is still an early release of our TTS, quality is beta-ish. Installation/integration surely has rough edges still, and pronunciation is constantly improving. The TODO-list is still generous. """ I've not tried this, but I suspect this might be a good place to start (though coaxing it to do english might well be a project in itself, depending on what they mean by "some semblance of English" :-) Regards, Michael. From maric at aristote.info Tue Aug 22 06:08:37 2006 From: maric at aristote.info (Maric Michaud) Date: Tue, 22 Aug 2006 12:08:37 +0200 Subject: convert a long string in binary In-Reply-To: <1156074920.467982.278610@p79g2000cwp.googlegroups.com> References: <mailman.9568.1156073739.27775.python-list@python.org> <1156074920.467982.278610@p79g2000cwp.googlegroups.com> Message-ID: <200608221208.39219.maric@aristote.info> Le dimanche 20 ao?t 2006 13:55, bearophileHUGS at lycos.com a ?crit?: > bussiere maillist: > > i've got a very long string > > and i wanted to convert it in binary > > Not much tested: > > _nibbles = {"0":"0000", "1":"0001", "2":"0010", "3":"0011", > "4":"0100", "5":"0101", "6":"0110", "7":"0111", > "8":"1000", "9":"1001", "A":"1010", "B":"1011", > "C":"1100", "D":"1101", "E":"1110", "F":"1111"} > > def toBase2(number): > if number < 16: > return "0000" + _nibbles["%X" % number] > else: > d1, d2 = "%X" % number > return _nibbles[d1] + _nibbles[d2] > > convbin = dict((chr(i), toBase2(i)) for i in xrange(256)) > > def binary(s): > return "".join(convbin[c] for c in s) > > print binary("testing string") > > Surely there are ways to make it shorter (But it's fast enough). > Maybe this one is more elegant : In [305]: trans = {} In [306]: for i in range(256) : .....: trans[chr(i)] = ''.join(i & 2**j and '1' or '0' .....: for j in reversed(range(8))) .....: In [307]: trans['a'] Out[307]: '01100001' In [308]: trans['\xee'] Out[308]: '11101110' In [309]: print ''.join(trans[e] for e in 'test string') 0111010001100101011100110111010000100000011100110111010001110010011010010110111001100111 > Bye, > bearophile -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From ptmcg at austin.rr._bogus_.com Thu Aug 3 06:21:42 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 03 Aug 2006 10:21:42 GMT Subject: need help of regular expression genius References: <1154532421.096157.289570@i42g2000cwa.googlegroups.com> <QDdAg.40847$rp4.22091@tornado.texas.rr.com> <1154590996.372956.113320@s13g2000cwa.googlegroups.com> Message-ID: <W6kAg.42283$rp4.38054@tornado.texas.rr.com> "GHUM" <haraldarminmassa at gmail.com> wrote in message news:1154590996.372956.113320 at s13g2000cwa.googlegroups.com... > Paul, > > > text = """ ... input source text ... "" > > from pyparsing import SkipTo,Literal,replaceWith > > ign1 = "$$" + SkipTo("$$") + "$$" > > ign2 = "$_$" + SkipTo("$_$") + "$_$" > > semi = Literal(";").setParseAction( replaceWith("; <***>") ) > > print (ign1 | ign2 | semi).transformString(text) > > Thank you very much! this really looks beautifull and short! How could > I forget about pyparsing? Old loves are often better then adventures > with RE. :) Good to hear from you again, Harald! I didn't recognize your "From" address, but when I looked into the details, I recognized your name from when we talked about some very early incarnations of pyparsing. > > Two questions remain: > 1) I did not succeed in finding a documentation for pyparsing. Is there > something like a "full list of Classes and their methods" ? > Pyparsing ships with JPG and PNG files containing class diagrams, plus an htmldoc directory containing epydoc-generated help files. There are also about 20 example programs included (also accessible in the wiki). > 2) as of missing 1) :)): something like > "setParseAction(splithereandreturnalistofelementssplittedhere) ? > I briefly considered what this grammar might look like, and rejected it as much too complicated compared to .split("<***>"). You could also look into using scanString instead of transformString (scanString reports the location within the string of the matched text). Then when matching on a ";", use the match location to help slice up the string and append to a list. But again, this is so much more complicated than just .split("<***>"), I wouldn't bother other than as an exercise in learning scanString. Good luck! -- Paul From bobrien18 at yahoo.com Wed Aug 16 14:33:03 2006 From: bobrien18 at yahoo.com (KraftDiner) Date: 16 Aug 2006 11:33:03 -0700 Subject: trouble understanding inheritance... Message-ID: <1155753183.207393.116940@m79g2000cwm.googlegroups.com> This is not working the way I think it should.... it would appear that fromfile and getName are calling the baseClass methods which are simple passes.... What have I done wrong? class baseClass: def __init__(self, type): if type == 'A': self = typeA() else: self = typeB() def fromfile(self): pass def getName(self): pass class typeA(baseClass): def __init__(self): self.name='A' print 'typeA init' def fromfile(self): print 'typeA fromfile' def getName(self): print self.name class typeB(baseClass): def __init__(self): self.name='B' print 'typeB init' def fromfile(self): print 'typeB fromfile' def getName(self): print self.name a = baseClass('A') a.fromfile() a.getName() b = baseClass('B') b.fromfile() b.getName() log: typeA init typeB init From atkedzierski at gmail.com Sun Aug 13 10:31:39 2006 From: atkedzierski at gmail.com (AndrewTK) Date: 13 Aug 2006 07:31:39 -0700 Subject: reading from sockets In-Reply-To: <1155404471.418202.252850@75g2000cwc.googlegroups.com> References: <1155227695.625250.17920@m73g2000cwd.googlegroups.com> <TFQCg.103113$hp.69833@read2.cgocable.net> <1155387684.513673.130770@75g2000cwc.googlegroups.com> <1155404471.418202.252850@75g2000cwc.googlegroups.com> Message-ID: <1155479499.449061.298560@m73g2000cwd.googlegroups.com> Simon Forman wrote: > So I'm guessing it's something wrong in your java server. Thanks then. I'll keep testing then... From wegein at gmail.com Wed Aug 30 20:54:06 2006 From: wegein at gmail.com (damacy) Date: 30 Aug 2006 17:54:06 -0700 Subject: all ip addresses of machines in the local network In-Reply-To: <mailman.9777.1156418398.27775.python-list@python.org> References: <1156387621.568779.191420@m73g2000cwd.googlegroups.com> <1156393371.550249.138930@75g2000cwc.googlegroups.com> <1156394781.155152.313080@i3g2000cwc.googlegroups.com> <1360b7230608240328r2c732f86ia8914aaba7a8fb83@mail.gmail.com> <mailman.9777.1156418398.27775.python-list@python.org> Message-ID: <1156985646.373443.55810@m73g2000cwd.googlegroups.com> Amit Khemka wrote: > On 8/24/06, Amit Khemka <khemkaamit at gmail.com> wrote: > > On 23 Aug 2006 21:46:21 -0700, damacy <wegein at gmail.com> wrote: > > > hi, sandra. > > > > > > no, it's not as complicated as that. all i want to do is to load a > > > database onto different machines residing in the same network. i hope > > > there is a way doing it. or perhaps i have a poor understanding of how > > > networks work. > > > > > > > I expect that you would know the IP range for your network. Then you > > can simply 'ping' each IP in the range to find wether its alive. > > Moreover by your description I guess you would actually want to find > > all machines in your network that run a particular network service, to > > allow you to "distribute the database". In such case you can use > > "nmap" with -p option, to find all the machines which are listening on > > the particular port. > > > > hth, > > amit. > It seems that I am not too busy, so here is a code which may work with > a few tweaks here and there: > _________________________________________________________________________ > import os > # base and range of the ip addresses > baseIP = "10.0.0." > r = 6 > interestingPort = 22 # port that you want to scan > myIPs = [] > > for i in range(r): > ip = baseIP+str(i) # It may need some customization for your case > print "scanning: %s" %(ip) > for output in os.popen("nmap %s -p %s" %(ip, > interestingPort)).readlines(): > if output.__contains__('%s/tcp open' > %interestingPort): # i guess it would be tcp > myIPs.append(ip) > __________________________________________________________________________ > print myIPs > > > hth, > amit. > -- > ---- > Amit Khemka -- onyomo.com > Home Page: www.cse.iitd.ernet.in/~csd00377 > Endless the world's turn, endless the sun's Spinning, Endless the quest; > I turn again, back to my own beginning, And here, find rest. thank you for your code. i had a look at nmap and i think it's got some cool features in it. however, i found it quite slow in my case as it takes extra time to process the output. in my program so far, multiple threads (255 threads in total) spawned at once with each one of them trying to call socket.gethostbyaddr(ip) function. i.e. if exception thrown, no machine found. i used .join() to wait for the threads to terminate. it's fully working however the problem is that it's too slow. it takes approx. 14 seconds to process (i tried using 'ping' but it's even slower.). my question is.. is there a way to improve performance of the program if i know what the port number would be? in my case, the port number will always be constant although i have no clue on what ip addresses would be (that's the reason all of 255 different addresses must be tested). i tried the same function with the port number specified, gethostbyaddr(ip:portno), but it is even 10-second slower than using the same function without a port number specified (i.e. approx. 25 seconds to complete). could anyone think of a better way of solving this problem? regards, damacy From ben at benfinney.id.au Mon Aug 7 21:06:48 2006 From: ben at benfinney.id.au (Ben Finney) Date: Tue, 08 Aug 2006 11:06:48 +1000 Subject: Import module with non-standard file name Message-ID: <874pwoyr13.fsf@benfinney.id.au> Howdy all, Question: I have Python modules named without '.py' as the extension, and I'd like to be able to import them. How can I do that? Background: On Unix, I write programs intended to be run as commands to a file with no extension. This allows other programs to use the command as an interface, and I can re-write the program in some other language without obsoleting the commandline interface. e.g., I might write 'frobnicate-foo' as a shell program so that other programs can 'frobnicate-foo --bar baz'. If I later decide to re-implement 'frobnicate-foo' in Python, I'll save the top level module to the same file name since it implements the same command-line interface. Now that I've got it written as a Python module, I'd like to write unit tests for that module, which of course will need to import the program module to test it. The unit test can explicitly add the directory where the program module lives to 'sys.path' for the purpose of importing that module. However, the Python reference tells me that 'import' (specifically, '__import__()') needs modules to live in files named a particular way: with a '.py' suffix. But my module is in a file called 'frobnicate-foo', with no suffix, and that's part of the definition of the program interface. I don't want symbolic links, or anything else that presents two filenames for the same module, because there's no need for that except for Python's apparent insistence on a particular naming convention. Also, avoiding symbolic links inside the source code tree makes version control smoother. What are my options to import a module from a file whose name can't change? -- \ "[W]e are still the first generation of users, and for all that | `\ we may have invented the net, we still don't really get it." | _o__) -- Douglas Adams | Ben Finney From gelists at gmail.com Wed Aug 2 18:46:23 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Wed, 2 Aug 2006 19:46:23 -0300 Subject: Windows vs. Linux References: <1154301694.445639.99580@m79g2000cwm.googlegroups.com> <44cddfb3$0$7761$7a628cd7@news.club-internet.fr> <e%szg.3$gY6.1@newssvr11.news.prodigy.com> <slrnecustl.dsk.sybrenUSE@schuimige.stuvel.eu> <mailman.8814.1154454507.27775.python-list@python.org> <slrnecvati.eia.sybrenUSE@schuimige.stuvel.eu> <mailman.8825.1154473236.27775.python-list@python.org> <slrned0lr7.f6d.sybrenUSE@schuimige.stuvel.eu> <mailman.8845.1154526941.27775.python-list@python.org> <Pk2Ag.2623$No6.51588@news.tufts.edu> <slrned1dlu.gbe.sybrenUSE@schuimige.stuvel.eu> <mailman.8862.1154546440.27775.python-list@python.org> <slrned235l.go1.sybrenUSE@schuimige.stuvel.eu> Message-ID: <zy5mciiqeqqj$.dlg@gelists.gmail.com> On 2006-08-02 17:36:06, Sybren Stuvel wrote: > IMO it's too bad that "they" chose \r\n as the standard. Having two > bytes as the end of line marker makes sense on typewriters and > similarly operating printing equipment. I may well be mistaken, but I think at the time they set that standard, such equipment was still in use. So it may have been a consideration. > Nowadays, I think having a single byte as the EOL maker is quite a bit > clearer. Rather than thinking in bytes and the like when inserting an EOL marker, inserting really an EOL marker (that then gets translated by low level code to the appropriate byte sequence as needed) is probably the less archaic way to do that :) > On the other hand, with the use of UTF-8 encodings and the like, the > byte-to-character mapping is gone anyway, so perhaps I should just get > used to it ;-) Yes :) "Bytes" is getting definitely too low level. Especially with higher level languages like Python... there are not many byte manipulation facilities anyway. The language is at a much higher level, and in that sense the classic strings are a bit out of line, it seems. >> Just as for MS there are good reasons not to "fix" the backslash now > > Which are those reasons, except for backward compatability? I don't know how many reasons you need besides backward compatibility, but all the DOS (still around!) and Windows apps that would break... ?!? I think breaking that compatibility would be more expensive than the whole Y2k bug story. And don't be fooled... you may run a Linux system, but you'd pay your share of that bill anyway. > Less FAQs in this group about people putting tabs, newlines and other > characters in their filenames because they forget to escape their > backslashes? Or forget to use raw strings. (If you don't want it to be escaped, please say so :) But similar as I wrote above with the EOL thing, I think that the whole backslash escape character story is not quite well-chosen. In a way, this a mere C compatibility pain in the neck... (Of course there are implementation and efficiency reasons, mainly because Python is based on C APIs, but all that is as arbitrary as the selection of the backslash as path separator.) There could be other solutions (in Python, I mean). Only accept raw strings in APIs that deal with paths? Force coders to create paths as objects, in a portable way, maybe by removing the possibility to create paths from strings that are more than one level in the path? Or introduce a Unicode character that means "portable path separator"? Or whatever... :) > Strings and filenames are usually tightly coupled in any program > handing files, though. Yes, and that's IMO something from way below in the implementation depths. While file names and paths are strings, not every string is a valid and useful file name or path. This shows that using strings for file names and paths has tradition (coming from low level languages like C), but IMO is not quite appropriate for a higher abstraction level. > Almost every programming language I know of uses it as the escape > character, except for perhaps VB Script and the likes. Not sure about > the different assembly languages, though. There are so many languages... and I know so few of them... http://en.wikipedia.org/wiki/Category:Programming_languages Now it may be predominant (I still think it's mostly present in languages that are in some way influenced by C), but in the 70ies? IIRC, Pascal uses '^' for a similar purpose (not quite the same, but similar). This form is still in ample use in documentation to mean "Ctrl-<char>"; probably much more common than the backslash notation. > Sure. I've talked more about this specific subject in this thread than > in the rest of my life ;-) There's a first for everything :) > I think cooperation and uniformity can be a very good thing. On the other > hand, Microsoft want the software written for their platform to stay on > their platform. That's probably one of the major reasons to remain > incompatible with other systems. Probably. But even if I'd had a say there (and I hate switching between separator characters just as much as the next guy, and possibly do so more than you given that I work on a Windows system, with slashes in repository paths and URIs), I'm not sure I'd make the jump away from the backslash as path separator. That's just breaking too much code. You don't want to have all these curses directed at you... Gerhard From aahz at pythoncraft.com Tue Aug 8 11:49:35 2006 From: aahz at pythoncraft.com (Aahz) Date: 8 Aug 2006 08:49:35 -0700 Subject: do people really complain about significant whitespace? References: <1154986984.740638.241130@m79g2000cwm.googlegroups.com> Message-ID: <ebabqf$c3$1@panix2.panix.com> In article <1154986984.740638.241130 at m79g2000cwm.googlegroups.com>, infidel <saint.infidel at gmail.com> wrote: > >Where are they-who-hate-us-for-our-whitespace? Are "they" really that >stupid/petty? Are "they" really out there at all? "They" almost sound >like a mythical caste of tasteless heathens that "we" have invented. >It just sounds like so much trivial nitpickery that it's hard to >believe it's as common as we've come to believe. When I put on my Python evangelist hat, I do get complaints about that regularly. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." --Brian W. Kernighan From max at alcyone.com Wed Aug 9 04:52:20 2006 From: max at alcyone.com (Erik Max Francis) Date: Wed, 09 Aug 2006 01:52:20 -0700 Subject: #!/usr/bin/python or #!/usr/bin/env python? In-Reply-To: <ebc7e4$243u$3@news.uit.no> References: <fj5Cg.2658$No6.51984@news.tufts.edu> <bL6dnTXbq9adbkXZnZ2dnUVZ_u2dnZ2d@speakeasy.net> <ebbtor$evr$1@kohl.informatik.uni-bremen.de> <mailman.9130.1155106885.27775.python-list@python.org> <ebc288$g8s$1@kohl.informatik.uni-bremen.de> <vsgCg.66818$zy5.1253926@twister1.libero.it> <ebc58g$h22$1@kohl.informatik.uni-bremen.de> <JfOdncqW_fzdAUTZnZ2dnUVZ_uWdnZ2d@speakeasy.net> <ebc7e4$243u$3@news.uit.no> Message-ID: <BumdnZCP_J3aP0TZnZ2dnUVZ_qednZ2d@speakeasy.net> Tobias Brox wrote: > This is very off-topic, but if it's fairly common to begin tcl-scripts > as a /bin/sh-file with "exec tcl" at one of the first lines, I think > "file" ought to be able to recognize it. > > """exec" python is clearly an obscure hack not used by many, so I > don't see why "file" should ever recognize that :-) The point is, they're all part of the same tactic -- the particulars of sh. Special casing each one is a task without an end. People will come up with variants that will do the right thing but foil `file`, intentionally or unintentionally -- just as we've seen in this thread. The right way to approach this with `file` is to acknowledge that such tricks are inherently sh-specific and leave it identified as a sh file. Because that is, of course, exactly what it is. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Only those who dare to fail greatly can ever achieve greatly. -- Robert F. Kennedy From miki.tebeka at gmail.com Tue Aug 29 14:39:30 2006 From: miki.tebeka at gmail.com (Miki) Date: 29 Aug 2006 11:39:30 -0700 Subject: sys.argv[0] doesn't always contain the full path of running script. In-Reply-To: <1156873037.590351.158120@i42g2000cwa.googlegroups.com> References: <1156873037.590351.158120@i42g2000cwa.googlegroups.com> Message-ID: <1156876770.687162.232630@74g2000cwt.googlegroups.com> Hello Max, > How can I find where exactly the current python script is running? > ... > That means sys.argv[0] doesn't always contain the full path of > running script. sys.path[0] is the script directory, combined with sys.argv[0] you can find the full path to the script. (Note that in some rare cases sys.path[0] might not contain the script directory. For example in an executable created by py2exe). HTH. -- Miki http://pythonwise.blogspot.com From grante at visi.com Wed Aug 9 14:21:20 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 09 Aug 2006 18:21:20 -0000 Subject: Python share CPU time? References: <1155146500.063665.282430@p79g2000cwp.googlegroups.com> Message-ID: <12dk9t0ikc5of61@corp.supernews.com> On 2006-08-09, Yannick <yannick.leteigner at gmail.com> wrote: > Hi, > > I would like to program a small game in Python, kind of like robocode > (http://robocode.sourceforge.net/). > Problem is that I would have to share the CPU between all the robots, > and thus allocate a time period to each robot. However I couldn't find > any way to start a thread (robot), and interrupt it after a given time > period. The robot code thread needs to block when it runs out of things to do. > Any suggestions on how to proceed? Just start a thread for each robot, and put a call to time.sleep(0.010) in the main loop for the robot code. Adjust the 0.010 value to taste. As an alternative to sleeping, you could wait for some sort of event each time through the loop. > Is Python just not adapted to this kind of things? It's quite well adapted to this sort of thing. -- Grant Edwards grante Yow! Why don't you at ever enter and CONTESTS, visi.com Marvin?? Don't you know your own ZIPCODE? From johnjsal at NOSPAMgmail.com Thu Aug 17 11:23:06 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 17 Aug 2006 15:23:06 GMT Subject: sqlite3 or mysqldb? Message-ID: <uR%Eg.2697$No6.52598@news.tufts.edu> I did a little experimentation with MySQL, and yesterday I was reading up on SQLite. Since they both use the SQL language, does this mean that the queries you write will be the same for both modules? I'm sure there are slight differences for how you connect to DBs, but since they both use the same DB API 2.0, and both use SQL, I was wondering how easily you could 'switch' them out if you needed to go from one to the other. (I know there are slight differences between the two in terms of SQL commands understood, but I'm mainly referring to the most important things, like simply accessing and changing DB information.) I was using mysqldb just because MySQL seems to be a pretty big standard, but now that sqlite3 is coming with Python 2.5, I might switch, since it seems to be easier to use. (And again, I'm such an amateur programmer that really I'm using these things just to learn them. It's not like I control my company's entire employee records or anything.) :) Thanks. From starGaming at gmail.com Tue Aug 15 02:01:30 2006 From: starGaming at gmail.com (starGaming at gmail.com) Date: 14 Aug 2006 23:01:30 -0700 Subject: yet another noob question In-Reply-To: <mailman.9322.1155582209.27775.python-list@python.org> References: <1155492110.659011.196280@75g2000cwc.googlegroups.com> <mailman.9291.1155516281.27775.python-list@python.org> <ebpefi$2f3n$1@ulysses.news.tiscali.de> <mailman.9317.1155578305.27775.python-list@python.org> <1155579814.930093.99840@75g2000cwc.googlegroups.com> <mailman.9322.1155582209.27775.python-list@python.org> Message-ID: <1155621690.639191.309980@i3g2000cwc.googlegroups.com> Jason Nordwick wrote: > *mouth agape* > > Wow. That really sucks. I make extensive use of reduce. It seems to run more than twice as fast as a for loop. > > >>> t = Timer('bino.reduceadd(bino.bits)', 'import bino') > >>> s = Timer('bino.loopadd(bino.bits)', 'import bino') > >>> t.timeit(10) > 1.2373670396656564 > >>> s.timeit(10) > 2.6450051612705039 > >>> t.timeit(100) > 11.312374896809501 > >>> s.timeit(100) > 25.817132345032689 > > where > > bits = map(lambda x:randint(0,1), xrange(1000000)) > > def reduceadd(v): > return reduce(add, v) > > def loopadd(v): > sum = 0 > for x in v: > sum = add(sum, x) > return sum > > > > (Yes, I know there are better ways to sum up a list, but I just wanted to test the performance of the loop against reduce. In most of my reduce usages, the function passed to reduce is much more complex.) [...] Assuming Guido van Rossum is right and reduce() is only useful for arithmetic expressions (could you show an example where you use it else?), you could take advantage of more "built-ins". To spoiler the result of this, the loop-variant is slightly (in this test: 2ms) faster. The results on my amd64 3k+ were: Reduce: 0.5686828074520.56633643382 For-loop: 0.56633643382 #!/usr/bin/env python # # from random import randint from timeit import Timer from operator import add def bits(): return [randint(0,1) for x in xrange(1000)] # use def & list comprehension since lambda/map will be removed in Python 3.0, too print bits()[0:5] print bits()[0:5] # it's working. def reducefunc(x): return reduce(add,x) def loopfunc(x): y = 0 for i in x: y += i return y x = bits() print reducefunc(x) print loopfunc(x) # both give proper output print sum(Timer("reducefunc(bits())", "from __main__ import bits, reducefunc").repeat(20,100))/20 print sum(Timer("loopfunc(bits())", "from __main__ import bits, loopfunc").repeat(20,100))/20 From fakeaddress at nowhere.org Sun Aug 13 01:52:08 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 13 Aug 2006 05:52:08 GMT Subject: start a multi-sockets server (a socket/per thread) with different ports but same host In-Reply-To: <1155398402.738765.238610@m73g2000cwd.googlegroups.com> References: <1155398402.738765.238610@m73g2000cwd.googlegroups.com> Message-ID: <c6zDg.5006$%j7.3352@newssvr29.news.prodigy.net> zxo102 wrote: > I am doing a small project using socket server and thread in python. > This is first time for me to use socket and thread things. > Here is my case. I have 20 socket clients. Each client send a set > of sensor data per second to a socket server. The socket server will > do two things: 1. write data into a file via bsddb; 2. forward the data > to a GUI written in wxpython. > I am thinking the code should work as follow (not sure it is > feasible) > 20 threads, each thread takes care of a socket server with a > different port. > I want all socket servers start up and wait for client connection. > In the attached demo code, It stops at the startup of first socket > server somewhere in the following two lines and waits for client call: > > lstn.listen(5) > (clnt,ap) = lstn.accept() It will block there, waiting for connection. > Any ideas how to handle these 20 clients? Really appreciate your > suggestions. One reserved port for each client strikes me as whacked, as does coding a server to handle exactly 20 of them. Since you say this is your first socket server, maybe you just haven't seen the usual techniques. Normally, one listener socket accepts all the connections. Each call to accept() returns a new, independent socket for the connection. You can then start a thread to handle the new socket. Untested: listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listener.bind(('', 2000)) listener.listen(5) while True: # or some should_continue() thing sock, _ = listener.accept() thread.start_new_thread(service_function, (sock,)) # Or start threads via class Threading To update the GUI, you could use the Queue from the Python library, and call wxPostEvent to tell the GUI go wake up and check the queue. -- --Bryan From btowle at carnegielearning.com Wed Aug 9 12:47:14 2006 From: btowle at carnegielearning.com (Brendon Towle) Date: Wed, 9 Aug 2006 12:47:14 -0400 Subject: Eval (was Re: Question about using python as a scripting language) In-Reply-To: <17626.1896.637896.271015@montanaro.dyndns.org> References: <73BFFFC6-760D-4794-9B5C-AA749287B78A@carnegielearning.com> <20060809150432.GA15121@kateandchris.net> <B8AFCCDC-64A0-4674-B335-DAAD7E8DEDE3@carnegielearning.com> <17626.1896.637896.271015@montanaro.dyndns.org> Message-ID: <093E4A54-9A5D-460F-AB77-8D3450EB062A@carnegielearning.com> On 9 Aug 2006, at 12:03 PM, skip at pobox.com wrote: > > Brendon> I could do that, or I could do something like the re.* > trick > Brendon> mentioned by another poster. But, doesn't it offend > anyone else > Brendon> that the only clean way to access functionality that's > already > Brendon> in Python is to write long complicated Python code? > Python > Brendon> already knows how to extract a list object from a > string; why > Brendon> should I have to rewrite that? > > Doesn't bother me at all. One, it's not actually Python code, it's > JavaScript. It's just serendipity that the table can be parsed as > a Python > list. Two, there's nothing to prevent the authors from changing the > formatting in an incompatible way in the future. I think that these are actually the same reason, and can be safely ignored, because item 2 is true no matter what method I use to parse the data. Sure, it's serendipity, but that happens to be the hand I'm dealt at the moment; why not exploit the serendipity? > Three, it's completely > untrusted input and shouldn't be fed to eval(). This is the crucial point, and the reason I asked the question to begin with. Lisp (which I'm used to) has the read-eval-print loop; I think that my confusion was because: 1. Python's eval(X) is essentially the same as Lisp's (eval (read- from-string X)), not Lisp's (eval X) or Lisp's (read-from-string X); 2. The '[' character that begins a list should actually be read as a function call, not a data delimiter. (Which, in the context of list comprehensions, makes a lot of sense as I think about it.) > Four, it's not actually > complicated code (using the csv module would probably be simpler). I'll look into the csv module. And, it may not be complicated on an absolute scale, but Chris' re.* method turned one line of code into about 15; that's certainly a non- trivial increase in complexity. > Five, you have to stop thinking of it a "list > object". It's just a string of bytes which happens at this point > in time to > intersect with the definition of a Python list. You're trying to > wish it > was something that it's not. I must be confused here. If I call the following function: eval('[1, 2, 3]') what does that function call return, if not a list object? Sure, the string isn't a list object; it's a string of bytes that happens to be syntactically identical to the definition of a list in python code. I was hoping for a clean and safe way to exploit that identical-ness; apparently, all the clean ways are unsafe, and all the safe ways are unclean. B. -- Brendon Towle, PhD Cognitive Scientist +1-412-690-2442x127 Carnegie Learning, Inc. The Cognitive Tutor Company ? Helping over 375,000 students in 1000 school districts succeed in math. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060809/d84f36a9/attachment.html> From johnjsal at NOSPAMgmail.com Sat Aug 19 17:52:39 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 19 Aug 2006 17:52:39 -0400 Subject: text editor suggestion? In-Reply-To: <slrneedmfb.2qv.sybrenUSE@schuimige.stuvel.eu> References: <44e66724$0$2363$c3e8da3@news.astraweb.com> <mailman.9525.1155953260.27775.python-list@python.org> <44e6ab26$0$12557$c3e8da3@news.astraweb.com> <slrneedmfb.2qv.sybrenUSE@schuimige.stuvel.eu> Message-ID: <44e788fd$0$12550$c3e8da3@news.astraweb.com> Sybren Stuvel wrote: > John Salerno enlightened us with: >> I'd really like to learn vim, but I spent days just trying to figure >> out how to get the syntax highlighting and indentation working, >> where these settings are and how to edit them > > Stop being a man and just ask for directions :) Oh don't worry, I have no shame. I was asking a ton of questions, yet I still couldn't figure it out. > >> It just feels so insurmountable that I can't even start working with >> it yet because I don't know how to tailor the settings. > > "vim ~/.vimrc" is all you need on any system but Windows. There IIRC > you need to edit C:\Program Files\VIM\_vimrc. But what about customizing syntax coloring? Is this also in the same file? I've noticed a separate file called python.vim (in Windows, this file exists in a 'syntax' folder, and also another file of the same name in an 'indent' folder, so I'm *still* confused about which files are used for which settings. From david_wahler at bic.ky Tue Aug 15 02:14:18 2006 From: david_wahler at bic.ky (david_wahler at bic.ky) Date: 15 Aug 2006 01:14:18 -0500 Subject: =?utf-8?Q?Re:_python=2Ddev_Summary_for_2006=2D07=2D01_through_2006=2D07=2D15?= Message-ID: <20060815061418.4843.qmail@BICSRV1011.bic.ky> I'll be out of the office until approximately August 20th. If you have any questions, please email support at bic.ky. -- David Wahler From zxo102 at gmail.com Sat Aug 12 13:44:29 2006 From: zxo102 at gmail.com (zxo102) Date: 12 Aug 2006 10:44:29 -0700 Subject: start a multi-sockets server (a socket/per thread) with different ports but same host In-Reply-To: <mailman.9270.1155401560.27775.python-list@python.org> References: <1155398402.738765.238610@m73g2000cwd.googlegroups.com> <mailman.9270.1155401560.27775.python-list@python.org> Message-ID: <1155404669.209725.45840@i3g2000cwc.googlegroups.com> Jean-Paul, Thanks a lot. The code is working. The python twisted is new to me too. Here are my three more questions: 1. Since the code need to be started in a wxpyhon GUI (either by clicking a button or up with the GUI), do I have to run the code in a thread (sorry, I have not tried it yet)? 2. How can I grab the client data in the code? Can you write two lines for that? I really appreciate that. 3. After I change self.transport.write(''.join(self.data)) to self.transport.write(''.join(data)) and scan all the ports with the following code twice (run twice). First round scanning says "succefully connected". But second round scanning says "failed". I have to restart your demo code to make it work. Ouyang import sys, threading, socket class scanner(threading.Thread): tlist = [] # list of all current scanner threads maxthreads = int(sys.argv[2]) # max number of threads we're allowing evnt = threading.Event() # event to signal OK to create more threads lck = threading.Lock() # lock to guard tlist def __init__(self,tn,host): threading.Thread.__init__(self) #self.threadnum = tn # thread ID/port number self.threadnum = 2000+tn # thread ID/port number self.host = host # checking ports on this host def run(self): s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: s.connect((self.host, self.threadnum)) print "%d: successfully connected" % self.threadnum s.close() except: print "%d: connection failed" % self.threadnum # thread is about to exit; remove from list, and signal OK if we # had been up against the limit scanner.lck.acquire() scanner.tlist.remove(self) print "%d: now active --" % self.threadnum, scanner.tlist if len(scanner.tlist) == scanner.maxthreads-1: scanner.evnt.set() scanner.evnt.clear() scanner.lck.release() def newthread(pn,hst): scanner.lck.acquire() sc = scanner(pn,hst) scanner.tlist.append(sc) scanner.lck.release() sc.start() print "%d: starting check" % pn print "%d: now active --" % pn, scanner.tlist newthread = staticmethod(newthread) def main(): host = sys.argv[1] #for i in range(1,100): for i in range(20): scanner.lck.acquire() print "%d: attempting check" % i # check to see if we're at the limit before starting a new thread if len(scanner.tlist) >= scanner.maxthreads: # too bad, need to wait until not at thread limit print "%d: need to wait" % i scanner.lck.release() scanner.evnt.wait() else: scanner.lck.release() scanner.newthread(i,host) for sc in scanner.tlist: sc.join() if __name__ == '__main__': main() Jean-Paul Calderone ??? > On 12 Aug 2006 09:00:02 -0700, zxo102 <zxo102 at gmail.com> wrote: > >Hi, > > I am doing a small project using socket server and thread in python. > > This is first time for me to use socket and thread things. > > Here is my case. I have 20 socket clients. Each client send a set > >of sensor data per second to a socket server. The socket server will > >do two things: 1. write data into a file via bsddb; 2. forward the data > >to a GUI written in wxpython. > > I am thinking the code should work as follow (not sure it is > >feasible) > > 20 threads, each thread takes care of a socket server with a > >different port. > > I want all socket servers start up and wait for client connection. > >In the attached demo code, It stops at the startup of first socket > >server somewhere in the following two lines and waits for client call: > > > > Threads aren't the best way to manage the concurrency present in this > application. Instead, consider using non-blocking sockets with an > event notification system. For example, using Twisted, your program > might look something like this: > > from twisted.internet import reactor, protocol, defer > > class CumulativeEchoProtocol(protocol.Protocol): > def connectionMade(self): > # Stop listening on the port which accepted this connection > self.factory.port.stopListening() > > # Set up a list in which to collect the bytes which we receive > self.received = [] > > > def connectionLost(self, reason): > # Notify the main program that this connection has been lost, so > # that it can exit the process when there are no more connections. > self.factory.onConnectionLost.callback(self) > > def dataReceived(self, data): > # Accumulate the new data in our list > self.received.append(data) > # And then echo the entire list so far back to the client > self.transport.write(''.join(self.data)) > > def allConnectionsLost(): > # When all connections have been dropped, stop the reactor so the > # process can exit. > reactor.stop() > > def main(): > # Set up a list to collect Deferreds in. When all of these Deferreds > # have had callback() invoked on them, the reactor will be stopped. > completionDeferreds = [] > for i in xrange(20): > # Make a new factory for this port > f = protocol.ServerFactory() > > # Make a Deferred for this port's connection-lost event and make > # it available to the protocol by way of the factory. > d = defer.Deferred() > f.onConnectionLost = d > completionDeferreds.append(d) > f.protocol = CumulativeEchoProtocol > > # Start listening on a particular port number with this factory > port = reactor.listenTCP(2000 + i + 1, f) > > # Make the port object available to the protocol as well, so that > # it can be shut down when a connection is made. > f.port = port > > # Create a Deferred which will only be called back when all the other > # Deferreds in this list have been called back. > d = defer.DeferredList(completionDeferreds) > > # And tell it to stop the reactor when it fires > d.addCallback(lambda result: allConnectionsLost()) > > # Start the reactor so things can start happening > reactor.run() > > if __name__ == '__main__': > main() > > Hope this helps, > > Jean-Paul From stanc at al.com.au Fri Aug 18 15:17:07 2006 From: stanc at al.com.au (Astan Chee) Date: Sat, 19 Aug 2006 05:17:07 +1000 Subject: a bug in list.remove? In-Reply-To: <44E60E40.3030400@tim.thechases.com> References: <44E5FA22.7050304@al.com.au> <44E60E40.3030400@tim.thechases.com> Message-ID: <44E61233.10705@al.com.au> Tim Chase wrote: >> I have 2 lists. What Im doing is check the first list and remove all >> occurances of the elements in the second list from the first list, >> like so: >> >>> ps = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] >> >>> qs = [6,7,8,9,10,11,12,1,2] >> >>> for p in ps: >> if p in qs: >> ps.remove(p) >> >> The problem Im having is that when I do >> >>> print ps >> it gives me >> [2, 3, 4, 5, 7, 9, 11, 13, 14, 15] >> which is incorrect since 2,7,9,11 shouldnt be in that list. Is this a >> bug in .remove? or is my algorithm somewhat flawed? > > > > I'd go with the "somewhat flawed" answer. > > I'd just use > > ps = [x for x in ps if x not in qs] > > which will remove *all* instances of x from ps if it exists in qs. > There's a subtle difference from the remove() method, which will only > remove the first instance: > > >>> help([].remove) > Help on built-in function remove: > > remove(...) > L.remove(value) -- remove first occurrence of value > > > > If qs is large, you'll get improved performance by converting it to a > set first: > > >>> s = set(qs) > >>> ps = [x for x in ps if x not in s] > > > As for your algorithm, you're modifying the list over which you're > iterating--at best, often considered bad form...at worst, I've had > Python throw exceptions at me for attempting it. > > -tkc Thanks for that. Really helpful! Cheers Astan From fredrik at pythonware.com Fri Aug 25 19:33:15 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 26 Aug 2006 01:33:15 +0200 Subject: Avoiding if..elsif statements References: <1156545375.962486.49540@h48g2000cwc.googlegroups.com><mailman.9905.1156546443.27775.python-list@python.org> <1156547346.647480.187910@b28g2000cwb.googlegroups.com> Message-ID: <eco1bt$hg1$1@sea.gmane.org> "unexpected" <sumesh.chopra at gmail.com> wrote: > However, I'm passing in a few variables, so I can't just take it > out-though every single function would be passing the same variables. > > so something.func() is actually > something.func(string, list) > > How would I modify it to include them? just add the parameters to the call: dispatch[value](string, list) # note: do the call here! in Python, an explicit call is always written as expression(argument list) where expression yields a callable object. in your original case, the expression was a bound method; in the modified example, the expression is a dictionary lookup. the actual call part looks the same way, in both cases. </F> From __peter__ at web.de Wed Aug 23 06:10:00 2006 From: __peter__ at web.de (Peter Otten) Date: Wed, 23 Aug 2006 12:10:00 +0200 Subject: Finding the type of indexing supported by an object? References: <slrneeo9ac.p1u.dpeschel@eskimo.com> Message-ID: <ech9he$as$02$1@news.t-online.com> Derek Peschel wrote: > Here are two functions. > > def invert_dict_to_lists(dict): > lists = {} > for key in dict: > value = dict[key] > if not value in lists: > lists[value] = [key] > else: > lists[value].append(key) > return lists > > def invert_list_to_lists(list): > lists = {} > for key in range(len(list)): > value = list[key] > if not value in lists: > lists[value] = [key] > else: > lists[value].append(key) > return lists > > They are the same except for the expression in "for key in ...". Can they > be combined into one function? How can I determine if the argument is > like a list (with numeric indices that are not stored in the list) or a > dict > (with arbitrary keys that are stored)? I said "object" in the subject, > but I want to support Python primitive types, class instances, extension > module types (array, dictproxy, dbm, gdbm, etc.), and any future types. > > I've thought about looking for keys(), looking for the special method > names that allow you to override indexing behavior, and looking at the > class or > type of the object. I could be wrong, but I don't think any of those > strategies will work with all arguments. Instead of the (unreliable) introspection approach you could let the client code decide: >>> def invert(pairs): ... result = {} ... for k, v in pairs: ... if v in result: ... result[v].append(k) ... else: ... result[v] = [k] ... return result ... >>> invert(dict(a=1, b=2, c=1).iteritems()) {1: ['a', 'c'], 2: ['b']} >>> invert(enumerate([1,1,2,3])) {1: [0, 1], 2: [2], 3: [3]} Peter From northband at gmail.com Tue Aug 1 07:47:32 2006 From: northband at gmail.com (northband) Date: 1 Aug 2006 04:47:32 -0700 Subject: Using Python for my web site In-Reply-To: <1154420823.138580.84070@i3g2000cwc.googlegroups.com> References: <1154361480.915174.262720@b28g2000cwb.googlegroups.com> <1154416936.743642.50900@i42g2000cwa.googlegroups.com> <1154420823.138580.84070@i3g2000cwc.googlegroups.com> Message-ID: <1154432852.798532.113170@p79g2000cwp.googlegroups.com> Awesome response, thanks. I am definitely interested in the MVC and am looking into it now. Yes, we are migrating to Python mainly because we want unicode support, more stability, and faster performance than what we are getting now. We were going to move to php but seem python is the better choice, plus php 5.0 still doesn't support unicode. -Adam O From slawomir.nowaczyk.847 at student.lu.se Thu Aug 10 16:09:00 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Thu, 10 Aug 2006 22:09:00 +0200 Subject: converting a nested try/except statement into try/except/else In-Reply-To: <lsHCg.2671$No6.52074@news.tufts.edu> References: <44da5e3f$0$19111$626a54ce@news.free.fr> <lsHCg.2671$No6.52074@news.tufts.edu> Message-ID: <20060810220706.EFA0.SLAWOMIR.NOWACZYK.847@student.lu.se> On Thu, 10 Aug 2006 14:32:49 +0000 (GMT) John Salerno <johnjsal at NOSPAMgmail.com> wrote: #> Bruno Desthuilliers wrote: #> #> > try: #> > if int(text) <= 0: raise ValueError #> #> Hmm, I'm actually not so sure about this line now. It doesn't seem right #> to raise a ValueError when the result of the expression is negative, #> because even though it's a problem for my program, it isn't really a #> "ValueError," right? Well, you could always do something like try: int("-"+text) Now, this *will* be a real ValueError for negative integers ;-) ;-) ;-) But no, I am not suggesting that... especially since "-0" is valid. -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) COMMAND: A suggestion made to a computer. From rhamph at gmail.com Thu Aug 10 18:01:58 2006 From: rhamph at gmail.com (Rhamphoryncus) Date: 10 Aug 2006 15:01:58 -0700 Subject: Python share CPU time? References: <1155146500.063665.282430@p79g2000cwp.googlegroups.com> Message-ID: <1155247318.484983.243660@m73g2000cwd.googlegroups.com> Yannick wrote: > Hi, > > I would like to program a small game in Python, kind of like robocode > (http://robocode.sourceforge.net/). > Problem is that I would have to share the CPU between all the robots, > and thus allocate a time period to each robot. However I couldn't find > any way to start a thread (robot), and interrupt it after a given time > period. > Any suggestions on how to proceed? > Is Python just not adapted to this kind of things? If your intent is to allow the user to program a robot using python then no it's NOT suitable. There's no builtin way to restrict what code can do (but Zope might have a way), nor can you force it to pause after a predetermined amount of time, nevermind making that amount of time deterministic enough to be fair in a game. However, if your intent was to have only trusted code then Python would work fine. My preference would be for generators (especially once Python 2.5 is released), but YMMV. From snmishra at XXXhotYYYpop.com Mon Aug 14 14:37:49 2006 From: snmishra at XXXhotYYYpop.com (Satya) Date: Mon, 14 Aug 2006 12:37:49 -0600 Subject: Best IDE for Python References: <1155541849.350392.31190@h48g2000cwc.googlegroups.com> Message-ID: <44e0b5cf$0$11765$88260bb3@free.teranews.com> stylecomputers at gmail.com wrote: > Hi All, What do you find the best IDE for creating web applications in > Python is? Preferably FOS IDE. WingIDE appears to be the best, especially if you are an Emacs user and are used to its niceties. It is however, not free. PyScripter is pretty good too -- light weight, lots of features. Satya -- Posted via a free Usenet account from http://www.teranews.com From hipertracker at gmail.com Thu Aug 31 10:25:22 2006 From: hipertracker at gmail.com (Jaroslaw Zabiello) Date: 31 Aug 2006 07:25:22 -0700 Subject: Pros/Cons of Turbogears/Rails? References: <WXmIg.20772$gY6.18513@newssvr11.news.prodigy.com> Message-ID: <1157034321.926854.123520@m79g2000cwm.googlegroups.com> kenneth.m.mcdonald at sbcglobal.net wrote: > + SqlObject allows working with the DB tables without > using SQL itself. Rails has ActiveRecord ORM, which IMO has nicer and simpler syntax than SQLObject. Rails has migrations, TB - not (Migrations is versioning system for evolving database schema) > + Likely to be faster because as far as I'm aware, Python > is significantly faster. Python is maybe faster, but with YARM (which is not stable yet) Ruby will be about 10x faster. YARM is full virtual machine like Java. > + Easy access to other libraries (such as the Python > Imaging Library) that Ruby, being a relatively newer > language, doesn't have equivalents to. Ruby is not so young you think. It became more popular when Rails has appeared. > + Built-in default SQLite makes it easier to set up? What? :) YAML is much easier. > (as far as I can tell, Ruby requires MySql by default--don't > know how easy this is to change.) Change in config/database.yml driver: mysql to any you want, like db2, postgres, sqlserver, sqlite, firebird, oracle etc. You can change default settings as well. See: rails --help > + I find the templating system somewhat cleaner; code in > py: xml namespace allows pure .html templates, instead > of equivalent of .rhtml files. But rhtml is much more flexible because it can generate *any content*, not only xml. But Rails has THREE template systems: rhtml (main), rxml (for rss and xml generation) and rjs (for javascript and AJAX). And last but not least, TG is based on poor, unstable and buggy CherryPy server. We had huge problems with CherryPy. I think that Django or Pylons are much better frameworks. IMO TG is no competition for Rails at all. The only real competition is Django or Pylons. -- Jaroslaw Zabiello http://blog.zabiello.com From aleax at mac.com Fri Aug 4 00:58:23 2006 From: aleax at mac.com (Alex Martelli) Date: Thu, 3 Aug 2006 21:58:23 -0700 Subject: E' possibile integrare ironpython con visual studio 2005? References: <44d25f48$0$47956$4fafbaef@reader3.news.tin.it> Message-ID: <1hjikzd.1ym4sp75xbujvN%aleax@mac.com> LaGuna <nomail at nomail.it> wrote: > Se si come? > > Ciao by Enzo Questo newsgroup preferisce l'inglese -- per favore, chiedi su it.comp.lang.python invece che qui. This newsgroup prefers English -- please ask on it.comp.lang.python rather than here. Alex From maxerickson at gmail.com Thu Aug 10 10:59:45 2006 From: maxerickson at gmail.com (Max Erickson) Date: Thu, 10 Aug 2006 14:59:45 +0000 (UTC) Subject: Eval (was Re: Question about the use of python as a scripting language) References: <mailman.33888.1155215103.27774.python-list@python.org> <CC0D63AF-2F0C-4B84-A8BA-BFE5BBE1036B@carnegielearning.com> <17627.14233.684281.17915@montanaro.dyndns.org> <16E7238C-8601-4A9D-B244-E9D8668966DE@carnegielearning.com> <17627.18125.510532.334070@montanaro.dyndns.org> Message-ID: <Xns981B700A6E1A6maxericksongmailcom@80.91.229.5> skip at pobox.com wrote: > > Brendon> A shortcut occurs to me; maybe someone can tell me > what's wrong Brendon> with my reasoning here. It seems that > any string that is unsafe Brendon> to pass to eval() must > involve a function call, and thus must Brendon> contain an > opening paren. Given that I know that the data I Brendon> > expect contains no parens, would people expect this code to > be Brendon> safe: > > Unfortunately, no. If I define a class which has properties, > attribute assignment can involve arbitrary numbers of function > calls. > > Skip Is it possible to define a class and create an instance without using an open parens? I don't know how, but that isn't saying a great deal... max From baitas at zmail.pt Thu Aug 24 08:09:26 2006 From: baitas at zmail.pt (Tiago =?iso-8859-1?Q?Sim=F5es?= Batista) Date: Thu, 24 Aug 2006 13:09:26 +0100 Subject: setuid root Message-ID: <ZMAIL.PT-F200608241309.AA09260143@zmail.pt> Hello all I have a situation that requires that a python script, that is run from a webpage (via php exec()) must be run with root privileges. The sysadmin already set the setuid bit on the script, but it still fails when it tries to write to any file that only root has write access to. I read somewhere that any scripts that start with "#!" will no honour the setuid bit... I also tried os.setuid(0), with the setuid bit on, but this call failed. I am now out of ideas :( Any sugestions? Tiago From rosedb0 at gmail.com Wed Aug 23 12:11:15 2006 From: rosedb0 at gmail.com (hiaips) Date: 23 Aug 2006 09:11:15 -0700 Subject: Python + Java Integration In-Reply-To: <1156347822.349659.147270@75g2000cwc.googlegroups.com> References: <mailman.9706.1156346437.27775.python-list@python.org> <1156347822.349659.147270@75g2000cwc.googlegroups.com> Message-ID: <1156349474.995343.78940@i3g2000cwc.googlegroups.com> > Java itself never deserved to be the 'next' anything anyway. It was > sold on hype and has never lived up to it. I can see your point from a > business perspective but I like to think Python is sold on its merits > and not on being the new panacea for middle managers to deploy. Bravo. I could not have said it any better. From meyer at acm.org Thu Aug 24 22:06:38 2006 From: meyer at acm.org (Andre Meyer) Date: Fri, 25 Aug 2006 04:06:38 +0200 Subject: dictionaries vs. objects Message-ID: <7008329d0608241906t551f39efif0afeb666d9df0fc@mail.gmail.com> Hi all I have the following question: I need a representation of a physically inspired environment. The environment contains a large number of objects with varying attributes. There may be classes of objects, but there is not necessarily a strictly defined hierarchy among them. Object access should be fast, because there a many objects that change often (e.g., moving objects). My approach is to use a dictionary for the environment model and store each object as a slot, which contains either a dictionary or an object. Now, which is better? What is the performance of Python to look up attributes as either slots of a dictionary or attributes of an object? What feels more logical? What is more pythonic and performs better? Which is constructed and modified easier and quicker? Are there effects that I am not yet aware of? thanks for your thoughts Andre -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060825/d6ddc94f/attachment.html> From joel.hedlund at gmail.com Thu Aug 31 19:12:47 2006 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Fri, 01 Sep 2006 01:12:47 +0200 Subject: Python style: to check or not to check args and data members Message-ID: <ed7q6j$9mh$1@news.lysator.liu.se> Hi! The question of type checking/enforcing has bothered me for a while, and since this newsgroup has a wealth of competence subscribed to it, I figured this would be a great way of learning from the experts. I feel there's a tradeoff between clear, easily readdable and extensible code on one side, and safe code providing early errors and useful tracebacks on the other. I want both! How do you guys do it? What's the pythonic way? Are there any docs that I should read? All pointers and opinions are appreciated! I've also whipped up some examples in order to put the above questions in context and for your amusement. :-) Briefly: class MyClass(object): def __init__(self, int_member = 0): self.int_member = int_member def process_data(self, data): self.int_member += data The attached files are elaborations on this theme, with increasing security and, alas, rigidity and bloat. Even though maximum_security_module.py probably will be the safest to use, the coding style will bloat the code something awful and will probably make maintenance harder (please prove me wrong!). Where should I draw the line? These are the attached modules: * nocheck_module.py: As the above example, but with docs. No type checking. * property_module.py Type checking of data members using properties. * methodcheck_module.py Type checking of args within methods. * decorator_module.py Type checking of args using method decorators. * maximum_security_module.py Decorator and property type checking. Let's pretend I'm writing a script, I import one of the above modules and then execute the following code ... my_object = MyClass(data1) my_object.process_data(data2) and then let's pretend dataX is of a bad type, say for example str. nocheck_module.py ================= Now, if data2 is bad, we get a suboptimal traceback (possibly to somewhere deep within the code, and probably with an unrelated error message). However, the first point of failure will in fact be included in the traceback, so this error should be possible to find with little effort. On the other hand, if data1 is bad, the exception will be raised somewhere past the point of first failure. The traceback will be completely off, and the error message will still be bad. Even worse: if both are bad, we won't even get an exception. We will trundle on with corrupted data and take no notice. Very clear code, though. Easily extensible. property_module.py ================== Here we catch that data1 failure. Tracebacks may still be inconcise with uninformative error messages, however they will not be as bad as in nocheck_module.py. Bloat. +7 or more lines of boilerplate code for each additional data member. Quite clear code. Readily extensible. methodcheck_module.py ===================== Good, concise tracebacks with exact error messages. Lots of bloat and obscured code. Misses errors where data members are changed directly. Very hard to read and extend. decorator_module.py =================== Good, concise tracebacks with good error messages. Some bloat. Misses errors where data members are changed directly. Clear, but somewhat hard to extend. Decorators for *all* methods?! This cannot be the purpose of python!? maximum_security_method.py ========================== Good, concise tracebacks with good error messages. No errors missed (I think? :-) . Bloat. Lots of decorators and boilerplate property code all over the place (thankfully not within functional code, though). Is this how it's supposed to be done? And if you've read all the way down here I thank you so very much for your patience and perseverance. Now I'd like to hear your thoughts on this! Where should the line be drawn? Should I just typecheck data from unreliable sources (users/other applications) and stick with the barebone strategy, or should I go all the way? Did I miss something obvious? Should I read some docs? (Which?) Are there performance issues to consider? Thanks again for taking the time. Cheers! /Joel Hedlund -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: methodcheck_module.py URL: <http://mail.python.org/pipermail/python-list/attachments/20060901/85119ccf/attachment.ksh> -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: nocheck_module.py URL: <http://mail.python.org/pipermail/python-list/attachments/20060901/85119ccf/attachment-0001.ksh> -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: property_module.py URL: <http://mail.python.org/pipermail/python-list/attachments/20060901/85119ccf/attachment-0002.ksh> -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: decorator_module.py URL: <http://mail.python.org/pipermail/python-list/attachments/20060901/85119ccf/attachment-0003.ksh> -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: maximum_security_module.py URL: <http://mail.python.org/pipermail/python-list/attachments/20060901/85119ccf/attachment-0004.ksh> From khemkaamit at gmail.com Wed Aug 23 09:28:07 2006 From: khemkaamit at gmail.com (Amit Khemka) Date: Wed, 23 Aug 2006 18:58:07 +0530 Subject: find, replace and save string in ascii file In-Reply-To: <1156337317.644501.120480@m73g2000cwd.googlegroups.com> References: <1156337317.644501.120480@m73g2000cwd.googlegroups.com> Message-ID: <1360b7230608230628w54663c68qbd9b1d75efddf9a1@mail.gmail.com> On 23 Aug 2006 05:48:37 -0700, peter <borique at gmail.com> wrote: > Hello all, > > I'm looking for an advice. > > Example (one block in ascii file): > $------------------------ > NAME='ALFA' > CODE='x' > $------------------------ > > There are many similar blocks in the file with different NAMEs and > different CODEs. What I'm looking for is a script that searchs through > whole file and finds all strings with name ALFA and based on what CODE > is after each ALFA (can be x, y or z) the ALFA name is replaced by > BETAx,BETAy or BETAz and so changed file saves. > > What I did is that I can find all strings which I need, next I change > these strings based on CODE, but what I can't is to replace old string > with new one, on the same position in the file. It always writes new > string at the end of the file. Here is my code.... A simpler way can be: 1. Read a 'block' from the input file, ( you can simply read a line starting with 'NAME' and keep on reading till you find a line with starting 'CODE') 2. Once you have read a 'block', make whatever you want changes to the NAME and then write the 'block' to a temperory file. If you want the output to be written to same file just 'move' this temperory file to the input file once you are done. Note: if there is other stuff in the input file, apart from such 'blocks' that you want to preserve, a small modification in step 1 would take care of it. hth, amit. -- ---- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. From duncan.booth at invalid.invalid Tue Aug 22 10:02:48 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 22 Aug 2006 14:02:48 GMT Subject: CONSTRUCT - Module Attributes and Execution Environment References: <1156253227.092971.36510@74g2000cwt.googlegroups.com> Message-ID: <Xns98279912C17D7duncanbooth@127.0.0.1> lazaridis_com wrote: > Are ther alternative constructs/mechanism available, which could be > used to add this functionality possiby directly to a code-module? How about something along these lines: ------------------ auto.py --------- import sys, atexit def main_body(f): if f.func_globals['__name__']=='__main__': atexit.register(f, sys.argv) return f @main_body def auto(args): print "auto run", args ------------------------------------ If you run auto.py as a script then the decorated function executes. If you import it then the decorated function doesn't execute. In your own script you just need an import statement and to put the decorator on your main function. From rtw at freenet.co.uk Sun Aug 6 19:08:02 2006 From: rtw at freenet.co.uk (Rob Williscroft) Date: Sun, 06 Aug 2006 18:08:02 -0500 Subject: Trouble displaying image with tkinter References: <CWfBg.7694$gY6.5173@newssvr11.news.prodigy.com> Message-ID: <Xns981819423AC4rtwfreenetREMOVEcouk@216.196.109.145> sj wrote in news:CWfBg.7694$gY6.5173 at newssvr11.news.prodigy.com in comp.lang.python: > I am just learning to use Tkinter and am having problems displaying > image files. I am able to display an image using tutorials (such as > http://www.daniweb.com/code/snippet296.html) But when I try my own > code all I get is an empty widget. What is wrong with the following > program? > The problem is that CPython is (garbage) collecting the image. The canvas object is using it (i.e. passing to TCL/TK) but not keeping a reference to it. change idata to self.idata and all should be well. > > from Tkinter import * > > class Foo(Frame): [snip] > > idata = > PhotoImage(file="/home/sj/documents/projects/xaed/images/cat_001.gif") > self.idata = PhotoImage ..... > canvas = Canvas(width=300,height=200) Your missing a parent reference in there (self in this case) i.e.: canvas = Canvas(self, width=300,height=200) but when I tested it it didn't seem to matter. I'd guess however that when the layout gets more complex it will make a difference. Rob. -- http://www.victim-prime.dsl.pipex.com/ From g.brandl-nospam at gmx.net Tue Aug 22 13:09:13 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Tue, 22 Aug 2006 19:09:13 +0200 Subject: how do you get the name of a dictionary? In-Reply-To: <1156264475.968894.221710@p79g2000cwp.googlegroups.com> References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <pan.2006.08.21.03.33.27.84160@REMOVEME.cybersource.com.au> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> <mailman.9631.1156227418.27775.python-list@python.org> <1156264475.968894.221710@p79g2000cwp.googlegroups.com> Message-ID: <ecfdnr$k0f$1@news.albasani.net> jojoba wrote: > Hello again, > > Fredrick said: > >> Python's object model. an object has a value, a type, and an identity, >> but no name. > > I say: > > Thank you Fredrick for the reply! > However, although python's object model does not currently support what > i am asking for, how difficult would it be to assign a string name(s) > to an object upon creation (and upon referencing)? > > please note: > i don't want to do anything sophisticated with this, i am really only > looking for a TITLE for my dictionary when i throw it in a tree editor > that i have built. And i do realize that its not possible now. I am > just pressing a point here. > > Sorry to ruffle everyone's feathers, but this is a fairly curious > problem. Why not add a "name" attribute to your objects? e.g. class NamedDict(dict): def __init__(self, _name_, *args, **kwargs): self.name = _name_ dict.__init__(self, *args, **kwargs) Georg From reply.in.the.newsgroup at my.address.is.invalid Sun Aug 13 14:34:48 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sun, 13 Aug 2006 20:34:48 +0200 Subject: yet another noob question References: <1155492110.659011.196280@75g2000cwc.googlegroups.com> Message-ID: <urrud2leqrqd1mvbt2o5dn7uiromb60kqi@4ax.com> mike_wilson1333: >I would like to generate every unique combination of numbers 1-5 in >a 5 digit number [...] What would be the best way to do this? Ask the Java newsgroup to design a clever algorithm and post it here for pythonification. Ask for the pseudocode, not the Java code. -- Ren? Pijlman From gagsl-py at yahoo.com.ar Mon Aug 28 22:17:27 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 28 Aug 2006 23:17:27 -0300 Subject: unit test for a printing method In-Reply-To: <ecv3t6$lmq$2@sea.gmane.org> References: <1156780399.289589.58750@m73g2000cwd.googlegroups.com> <ecv3t6$lmq$2@sea.gmane.org> Message-ID: <7.0.1.0.0.20060828231358.05c4fec8@yahoo.com.ar> At Monday 28/8/2006 12:59, Fredrik Lundh wrote: > > What is the proper way to test (using unit test) a method that print > > information? > > for example: > > > > def A(s): > > print '---'+s+'---' > > > > and i want to check that A("bla") really print out "---bla---" > >http://docs.python.org/lib/module-doctest.html When the output goes a bit more complicated, consider splitting such method in parts: some generate the output, others just print it. Then you can test the former using the standard unittest framework. Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From peter at peter-b.co.uk Mon Aug 28 13:06:36 2006 From: peter at peter-b.co.uk (Peter TB Brett) Date: Mon, 28 Aug 2006 18:06:36 +0100 Subject: Detecting window focus events in PyGTK Message-ID: <pan.2006.08.28.17.06.36.690797@peter-b.co.uk> Hi folks, I'm currently trying to work out how to detect when a PyGTK window receives the focus from the window manager -- I assume that it must receive some kind of X event, but I can't work out which signal it generates. Searching around the subject on the web doesn't seem to pull up anything useful. I tried the "focus" signal, but that doesn't work the way I'd like it to. For example, the following code only prints the message "Received focus!" once (immediately after startup) even when it _isn't_ the active window. #!/usr/bin/env python import pygtk pygtk.require('2.0') import gtk def event_focus(widget, direction): print "Received focus!" window = gtk.Window() window.set_size_request(100, 100) window.connect("focus", event_focus) window.show_all() gtk.main() I suspect that I'm hacking in the wrong place, so any hints or tips much appreciated! Thanks, Peter -- v2sw6YShw7$ln5pr6ck3ma8u6/8Lw3+2m0l7Ci6e4+8t4Eb8Aen5+6g6Pa2Xs5MSr5p4 hackerkey.com From bborcic at gmail.com Thu Aug 10 17:25:11 2006 From: bborcic at gmail.com (Boris Borcic) Date: Thu, 10 Aug 2006 23:25:11 +0200 Subject: converting a nested try/except statement into try/except/else In-Reply-To: <44db95a4$0$31535$626a54ce@news.free.fr> References: <s8qCg.2663$No6.52066@news.tufts.edu> <mailman.9217.1155226383.27775.python-list@python.org> <44db91a8$1_6@news.bluewin.ch> <44db95a4$0$31535$626a54ce@news.free.fr> Message-ID: <44dba471$1_4@news.bluewin.ch> Bruno Desthuilliers wrote: > Boris Borcic a ?crit : >> Slawomir Nowaczyk wrote: >> >>> >>> try: >>> if int(text) > 0: >>> return True >>> except ValueError: >>> pass >>> self.error_message() >>> return False >>> >> >> Nicely DRY. To make it even more compact, it may be noticed that the >> default return value None is false in a boolean context - so that the >> last line is superfluous if the return value is only wanted to test it >> in such a context. > > While it's technically true - and I while I have a taste for compactness > - skipping the explicit 'return False' somehow hurts my sense of > esthethic... Unless you propose to return object or type instead of > True - but then it begins to look very strange !-) so what about simplifying your solution 1 to try : return int(text)>0 or int('garbage') except ValueError : self.error_message() it still returns True on success, but hides it well :) and while perhaps a bit too clever I feel it competes well on readability, precisely because it is compact and because int('garbage') mimics int(text) while standing just before 'except ValueError'. That mimicry kind of encapsulates your and infidel's answer to the OP's objection to raising ValueError if int(text)<=0. From chris at kateandchris.net Fri Aug 25 11:27:48 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Fri, 25 Aug 2006 11:27:48 -0400 Subject: soap comlex data to plain xml In-Reply-To: <b8c8c4110608181103s692d919q39471fe914b484da@mail.gmail.com> References: <b8c8c4110608181103s692d919q39471fe914b484da@mail.gmail.com> Message-ID: <20060825152748.GA32196@kateandchris.net> You would probably get more responses on the pywebsvcs mailing list http://pywebsvcs.sf.net SOAP goes over HTML, so you can use httplib to do what you want. Just go look up the protocol details (hint use Google). You will probably want to use ZSI or SOAPpy to serialize the request body to xml for you. -Chris On Fri, Aug 18, 2006 at 11:03:48AM -0700, Ig B wrote: > Hi all, > > would anyone give me a hint how to get SOAP data as plain XML and not as > complex data > > this is sample code: > > myProxy = SOAPpy.SOAPProxy(MY_SERVICE_PATH, header = my_headers) > query = SOAPpy.structType () > > result = myProxy.callMyProcedure(query) > > result returned as complex data, but i need plain xml text - kind of you > see when > myProxy.config.dumpSOAPIn = 1 > > thank you in advance. > > ~GB > -- > http://mail.python.org/mailman/listinfo/python-list From skip at pobox.com Wed Aug 30 11:37:52 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 30 Aug 2006 10:37:52 -0500 Subject: How ahead are you guys in the (Python) real world? In-Reply-To: <12fb9lgmt595b79@corp.supernews.com> References: <1156821234.820929.299740@p79g2000cwp.googlegroups.com> <XGgJg.2715$No6.53253@news.tufts.edu> <12fb9lgmt595b79@corp.supernews.com> Message-ID: <17653.45264.154502.692943@montanaro.dyndns.org> Grant> So the questions when considering an upgrade are: Grant> 1) Is there a new feature I want? Grant> 2) Is that feature worth fixing the update breaking? 3) Has the version I'm running reached "end of support"? If it has and you encounter a bug, you may be forced to upgrade at an inopportune time. Skip From claudio.grondi at freenet.de Mon Aug 28 06:40:55 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Mon, 28 Aug 2006 12:40:55 +0200 Subject: Misleading error message when opening a file (on Windows XP SP 2) In-Reply-To: <mailman.9968.1156757977.27775.python-list@python.org> References: <ecu65e$12o$1@newsreader2.netcologne.de> <mailman.9968.1156757977.27775.python-list@python.org> Message-ID: <ecuh7n$kk2$1@newsreader2.netcologne.de> Tim Peters wrote: > [Claudio Grondi] > >> Here an example of what I mean >> (Python 2.4.2, IDLE 1.1.2, Windows XP SP2, NTFS file system, 80 GByte >> large file): >> >> >>> f = file('veryBigFile.dat','r') >> >>> f = file('veryBigFile.dat','r+') >> >> Traceback (most recent call last): >> File "<pyshell#1>", line 1, in -toplevel- >> f = file('veryBigFile.dat','r+') >> IOError: [Errno 2] No such file or directory: 'veryBigFile.dat' >> >> Is it a BUG or a FEATURE? > > > Assuming the file exists and isn't read-only, I bet it's a Windows > bug, and that if you open in binary mode ("r+b") instead I bet it goes > away (this wouldn't be the first large-file text-mode Windows bug). I knew already that 'r+b' fixes it. Yes, you have won the bet :) . I suppose, like you do, that because there is a difference between text and binary files on Windows and the text files are e.g. opened being buffered using a 32-bit buffer pointer, this fails on too large NTFS files. I could also imagine that Python tries to buffer the text file and fails because it uses the wrong pointer size when asking Windows for the content. I have not yet looked into the C-code of Python - any hint which file I should take a closer look at? Just curious to see for myself, that the bug is on the Windows side. Claudio Grondi From rogue_pedro at yahoo.com Mon Aug 28 00:10:10 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 27 Aug 2006 21:10:10 -0700 Subject: import function from user defined modules In-Reply-To: <1156717616.491849.137460@p79g2000cwp.googlegroups.com> References: <1156717616.491849.137460@p79g2000cwp.googlegroups.com> Message-ID: <1156738210.508343.130870@h48g2000cwc.googlegroups.com> groves wrote: > Can anybody give me an example of how to import a function of module X > in module y. And please if yu can use classes(Object oriented approach) > would be great. > > The problem is that I have created a text on canvas, and now I want > that whenever a user right clicks on it, the option COMMAND should > invoke a function defined in some other module say Y. > > thanks a lot to all who will look into problem, any help would be > appreciated. from X import func Then you can call func() in your module. Peace, ~Simon From apardon at forel.vub.ac.be Fri Aug 4 11:12:44 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Aug 2006 15:12:44 GMT Subject: Nested function scope problem References: <20060804094245.A9AF.SLAWOMIR.NOWACZYK.847@student.lu.se> <1okvniwl5zgqj.dlg@gelists.gmail.com> <mailman.8983.1154702472.27775.python-list@python.org> Message-ID: <slrned6ovc.vkd.apardon@rcpc42.vub.ac.be> On 2006-08-04, Slawomir Nowaczyk <slawomir.nowaczyk.847 at student.lu.se> wrote: > On Fri, 04 Aug 2006 10:10:45 -0300 > Gerhard Fiedler <gelists at gmail.com> wrote: > > #> You can hardly claim that what gets printed is the "id" of the variable c. > #> (Well, you can claim, but few C programmers would follow you.) > > That's possible. I wouldn't expect too many C programmers to have any > notion of "id of a variable". I, for example, never thought about such > thing before this thread. But even in Python we don't speak of "id of a variable". It is not the variable that has an id. It is the object that is currently attached to the variable that has an id. Yes we can use "id of a variable" as a shortcut for the correct formulation as long as you keep in mind that it is not the variable itself that has an id. -- Antoon Pardon From chase at noway.com Thu Aug 24 03:53:49 2006 From: chase at noway.com (Jo Chase) Date: Thu, 24 Aug 2006 07:53:49 GMT Subject: Record Audio Analysis Message-ID: <hWcHg.69909$zg.46493@tornado.rdc-kc.rr.com> I would like to record audio from a mic and perform some basic analysis on the audio wave patterns produced. What would be the easiest way to accomplish this in Python? From psnim2000 at gmail.com Tue Aug 8 11:42:34 2006 From: psnim2000 at gmail.com (Chaos) Date: 8 Aug 2006 08:42:34 -0700 Subject: Urllib2/Pycurl/HTTP Speeds? Message-ID: <1155051754.896243.300080@75g2000cwc.googlegroups.com> For the Program I Am Making I Make Multiple HTTP Request to My Server. I found that using urllib2 it was pretty slow, when I activated the program and tested it it would hang from 2secs-5secs since I am doing it multiple times I wanted to speed it up by using pycurl. But I got the samething. Here is my code: import urllib import os.path import cookielib import pycurl import StringIO class GoToPage: #HTTPHeaders = {'User-agent' : self.browser, 'Accept-Language: en-us' : 'en-us', 'Accept-Encoding' : 'deflate'} FireFox_15 = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6" IE7_B2 = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)" Opera_85 = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; en) Opera 8.51" IE6 = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)" Mozilla_17 = "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.7b) Gecko/20040404" def __init__(self, myName): self.browser = self.FireFox_15 self.lastPage = "" self.cookies = "" self.name = myName self.wrapper = pycurl.Curl() #self.wrapper.setopt(pycurl.AUTOREFERER, 0) self.wrapper.setopt(pycurl.COOKIEFILE, self.name) #self.cookieJar = cookielib.LWPCookieJar() #if self.cookieJar != None: # if os.path.isfile(self.name): # self.cookieJar.load(self.name) #self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookieJar)) #urllib2.install_opener(self.opener) return #end Function def buildHeaders(self, browser, referer=""): if referer != "": buildHeaders = ['User-agent: ' + self.browser, 'Accept-Language: en-us', 'Accept-Encoding: gzip,compress;q=0.9,deflate;q=0', 'Referer:' + referer] else: buildHeaders = ['User-agent: ' + self.browser, 'Accept-Language: en-us', 'Accept-Encoding: gzip,compress;q=0.9,deflate;q=0'] return buildHeaders def saveCookies(self, cookies): fileHandle = open (self.name, 'w') fileHandle.write (cookies) fileHandle.close() def GetPage(self, URL, referer=""): theHeaders = self.buildHeaders(self.browser, referer) returnVal = StringIO.StringIO() self.wrapper.setopt(pycurl.URL, URL) self.wrapper.setopt(pycurl.HTTPHEADER, theHeaders) self.wrapper.setopt(pycurl.WRITEFUNCTION, returnVal.write) self.wrapper.perform() self.wrapper.close() #self.saveCookies(self.wrapper.getinfo(pycurl.COOKIELIST)) #self.cookieJar.save(self.name) return returnVal.getvalue() def PostPage(self, URL, data, referer=""): timer = wx.StopWatch() theHeaders = self.buildHeaders(self.browser, referer) print timer.Time() timer.Start(0) returnVal = StringIO.StringIO() self.wrapper.setopt(pycurl.URL, URL) self.wrapper.setopt(pycurl.POSTFIELDS, data) self.wrapper.setopt(pycurl.HTTPHEADER, theHeaders) self.wrapper.setopt(pycurl.WRITEFUNCTION, returnVal.write) print str(timer.Time()) + ' before perform' timer.Start(0) self.wrapper.perform() print str(timer.Time()) + ' after perform' self.wrapper.close() #self.saveCookies(self.wrapper.getinfo(pycurl.COOKIELIST)) #self.cookieJar.save(self.name) return returnVal.getvalue() The Urlib2 source is lost, and there are timer functions in there. I call it like this import GoToPage newHTTP = GoToPage.GoToPage("name") From diffuser78 at gmail.com Thu Aug 10 16:10:25 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 10 Aug 2006 13:10:25 -0700 Subject: How to write a Installer for a Python App in Linux Message-ID: <1155240625.157696.143230@i42g2000cwa.googlegroups.com> Hi, I have known python for about 3-4 months now. My knowledge is still very limited. I wrote a small app using wxPython. Now, I want to create an installer for it (on Linux platform.) for the people I developed this small utility. These people use some customized variant of Red Hat Linux. I found on the web python2.4 and the corresponding wxPython files. How can I write a Installer file which will install all the needed programs in the correct path, so that my wxPython app is ready to run and end user doesn't need to bother installing required files. Give me some pointers and I will try to write the script on my own. Every help is greatly appreciated. From jean.moser at neuf.fr Fri Aug 11 17:10:50 2006 From: jean.moser at neuf.fr (jean-jeanot) Date: 11 Aug 2006 14:10:50 -0700 Subject: Read a file with open command In-Reply-To: <oE4Dg.67216$Uy1.48201@read1.cgocable.net> References: <1155288288.954142.293000@i3g2000cwc.googlegroups.com> <slrnedojvt.q7g.sybrenUSE@schuimige.stuvel.eu> <1155316508.381805.56520@m73g2000cwd.googlegroups.com> <oE4Dg.67216$Uy1.48201@read1.cgocable.net> Message-ID: <1155330650.289766.96650@74g2000cwt.googlegroups.com> Sorry, I regret my reaction. Jean-jeanot AlbaClause a ?crit : > jean-jeanot wrote: > > > Dear Sybrel, > > > > I am delighted to know that you have been enlighted through my > > question. > > I am aware of my stupidity and I would say of my ignorance.If all > > Python users were not ignorant I suppose the Python group would be > > superfluous. I would suggest that if if you think that a question is > > supid please do not answer it.In French we say: "There is no stupid > > question but answers can be stupid". For the citation of Zappa I am > > convinced that when Zappa is speaking of world stupidity he is thinking > > to stupidity and wickedness of mankind and not to ignorance. > > Ummm, he did not say that your question was stupid. The Zappa quote is > included as part of what we refer to as a 'signature'. In the case of > Sybren Stuvel's posts to this newsgroup, the Frank Zappa quote is included > in every message that he posts. Not just messages that he posts to you. > > Secondly, I notice that when you quoted Sybren's message in your reply, your > newsreader attributed the quoted text with: "Sybren Stuvel a ?crit :" > Likewise, when Sybren replied to your message, his newsreader attributed > the quoted text with, "jean-jeanot enlightened us with:" > > Do you see what I mean? You didn't write "Sybren Stuvel a ?crit" because > Sybren was french, did you? Of course, not! Your mail/news application > included that attribution by default. By the same token, Sybren's > mail/news application defaulted to this attribution: 'jean-jeanot > enlightened us with:" > > When reading people's responses to your queries, stick to the material that > they actually "write" at the time of the response. Ignore the stuff that > they entered while configuring their respective news/mail reader. Little > items like message signatures and quote attributions are, at best, > reflective of the personality and/or philosophy of the author, and say > nothing of the person receiving the message. :-) From wegein at gmail.com Tue Aug 22 01:47:33 2006 From: wegein at gmail.com (damacy) Date: 21 Aug 2006 22:47:33 -0700 Subject: exception handling; python program that interacts with postgresql db In-Reply-To: <1156216416.390620.52240@75g2000cwc.googlegroups.com> References: <1154567757.143305.19910@75g2000cwc.googlegroups.com> <vuo5d2p5fp9h0ekrij245h8rd0gljutf7p@4ax.com> <1156216416.390620.52240@75g2000cwc.googlegroups.com> Message-ID: <1156225653.179882.300990@h48g2000cwc.googlegroups.com> oh, fixed when i set isolation level to 0. thanks anyway! damacy wrote: > thanks. i started to use psycopg. > > however, i have this error message and i don't quite get what it means. > > it says "DROP DATABASE cannot run inside a transaction block". > > does anyone have a clue? > > Tim Roberts wrote: > > "damacy" <wegein at gmail.com> wrote: > > > > >hi, there. i have this question which might sound quite stupid to some > > >people, but here we go anyway. > > > > > >i have written a python program which interacts with a postgresql > > >database. what it does is simply drops an existing database called > > >'mytempdb'. > > > > > >the code looks like below; > > > > > >link = subprocess.Popen(command, stdin = subprocess.PIPE, stdout = > > >subprocess.PIPE, shell = True) > > >link.communicate(password) > > >link.wait() > > > > > >where command looks like "psql -h 127.0.0.1 -U postgres -W -f filename" > > >and > > >filename is the name of the file which contains a single SQL command > > >which is "drop database mytempdb". > > > > hiaips is right. The right way to do this is to use a Postgres module. > > psycopg is my favorite, but there are several alternatives. > > > > import psycopg > > db = psycopg.connect( > > "dbname=template1 user=postgres password=%s" % password ) > > c = db.cursor() > > c.execute( "drop database mytempdb;" ) > > -- > > - Tim Roberts, timr at probo.com > > Providenza & Boekelheide, Inc. From dasn at bluebottle.com Mon Aug 21 09:50:11 2006 From: dasn at bluebottle.com (Dasn) Date: Mon, 21 Aug 2006 08:50:11 -0500 Subject: Problem of function calls from map() Message-ID: <200608211350.k7LDoBJb032411@fe12.bluebottle.com> Hi, there. 'lines' is a large list of strings each of which is seperated by '\t' >>> lines = ['bla\tbla\tblah', 'bh\tb\tb', ... ] I wanna split each string into a list. For speed, using map() instead of 'for' loop. 'map(str.split, lines)' works fine , but... when I was trying: >>> l = map(str.split('\t'), lines) I got "TypeError: 'list' object is not callable". To avoid function call overhead, I am not willing to use lambda function either. So how to put '\t' argument to split() in map() ? Thanks. From nevillednz at gmail.com Tue Aug 15 19:40:33 2006 From: nevillednz at gmail.com (NevilleDNZ) Date: 15 Aug 2006 16:40:33 -0700 Subject: proc A def/calls proc B: variable scoping rules. Message-ID: <1155685233.002415.184150@74g2000cwt.googlegroups.com> Can anyone explain why "begin B: 123" prints, but 456 doesn't? $ /usr/bin/python2.3 x1x2.py begin A: Pre B: 123 456 begin B: 123 Traceback (most recent call last): File "x1x2.py", line 13, in ? A() File "x1x2.py", line 11, in A B() File "x1x2.py", line 7, in B print "begin B:",x1,x2 UnboundLocalError: local variable 'x2' referenced before assignment $ cat x1x2.py #!/usr/bin/env python def A(): print "begin A:" x1=123; x2=456; def B(): print "begin B:",x1,x2 x2 = x2 - 1; # comment out this line and script x1x2 magically works!! print "end B:",x1,x2 print "Pre B:",x1,x2 B() print "end A:",x1,x2 A() $ /usr/bin/python2.3 Python 2.3.4 (#1, Mar 10 2006, 06:12:09) [GCC 3.4.5 20051201 (Red Hat 3.4.5-2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> $ /usr/bin/python2.3 -V Python 2.3.4 $ /usr/local/bin/python2.4 -V Python 2.4.2 $ /usr/local/bin/python2.4 x1x2.py begin A: Pre B: 123 456 begin B: 123 Traceback (most recent call last): File "x1x2.py", line 13, in ? A() File "x1x2.py", line 11, in A B() File "x1x2.py", line 7, in B print "begin B:",x1,x2 UnboundLocalError: local variable 'x2' referenced before assignment # I compiled up 2.4 from the FC4 source, but 2.3 was from SL4.3 $ python -V Python 2.4.2 $ python Python 2.4.2 (#1, Aug 15 2006, 21:51:33) [GCC 3.4.5 20051201 (Red Hat 3.4.5-2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> $ From penneys at bigfoot.com Tue Aug 22 03:23:10 2006 From: penneys at bigfoot.com (MrBlueSky) Date: 22 Aug 2006 00:23:10 -0700 Subject: Modules... paths... newbie confusion In-Reply-To: <4ktuo2Fdf60sU1@news.dfncis.de> References: <1156166327.327422.149470@b28g2000cwb.googlegroups.com> <4ktuo2Fdf60sU1@news.dfncis.de> Message-ID: <1156231390.380360.133780@i3g2000cwc.googlegroups.com> Thanks for the suggestions, folks.. site-packages ~~~~~~~~~~ OK, I'm been trying to get MSSQL into c:\Python24\lib\site-packages. MSSQL comes (as a tar'd, zip'd file) with a folder hierarchy with MSSQL.py at the top level and then bin\python2.3\mssqldb.pyd. If I try and copy this folder hierarchy into site-packages and "import MSSQL" then it recognises MSSQL.py but fails to import mssqldb, as that's imported from MSSQL.py. I've noticed a setup.py in the MSSQL folder, but it looks like it has odd hard-coded paths in it (D:\...) and anyway when I tried to run it, I found the Usage message less than helpful! I really apologise if this is Bleeding Obvious to everyone else - is there a web page that will explain all this so the lightbulb will go on over my head?! John From fredrik at pythonware.com Wed Aug 30 01:45:34 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 30 Aug 2006 07:45:34 +0200 Subject: A Sort Optimization Technique: decorate-sort-dedecorate In-Reply-To: <1f7befae0608291225o12985c18u95137d9b6ba928e2@mail.gmail.com> References: <1156719092.603277.57390@b28g2000cwb.googlegroups.com> <1156723602.192984.49610@m79g2000cwm.googlegroups.com> <pan.2006.08.28.08.53.08.647908@gmx.net> <280820061150081729%jgibson@mail.arc.nasa.gov> <ed1682$l41$1@online.de> <7.0.1.0.0.20060829132302.05c9e758@yahoo.com.ar> <44F480EF.9080202@durchholz.org> <1f7befae0608291225o12985c18u95137d9b6ba928e2@mail.gmail.com> Message-ID: <ed38lv$b6k$2@sea.gmane.org> Tim Peters wrote: > OTOH, current versions of Python (and Perl) just curious, but all this use of (& Perl) mean that the Perl folks have implemented timsort ? </F> From deets at nospam.web.de Wed Aug 2 12:10:22 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 02 Aug 2006 18:10:22 +0200 Subject: Newbie Q: Class Privacy (or lack of) References: <44C586A2.4D4BFFEE@rotten.apple.commie> <1154080289.251993.137560@b28g2000cwb.googlegroups.com> <pan.2006.07.28.10.38.28.699830@gmx.net> <slrned1ikh.o5q.apardon@rcpc42.vub.ac.be> Message-ID: <4jc0toF7607eU1@uni-berlin.de> > I find that a strange purpose because when you are working on a class, > you don't necessarily know if you will ever know many instance of that > class. So should I use __slots__ in all my classes, just to be sure > for when someone wants many instances of one? I find that a strange reasoning because when you are working on a class, you don't necessarily know if you will ever know if it needs a __getitem__-method. So do you use __getitem__ in all your classes, just to be sure for when someone wants __getitem__ in one? To my experience programming often means that requirements change - and one has to adapt. If memory becomes an issue, you might overcome it using slots. Or a disk cache. Or buy new memory. Does that imply for you that you buy new disks and memory each time you start coding? Diez From deets at nospam.web.de Sun Aug 27 07:59:28 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 27 Aug 2006 13:59:28 +0200 Subject: How to let a loop run for a while before checking for break condition? In-Reply-To: <ecrqe1$9j$1@newsreader2.netcologne.de> References: <ecrqe1$9j$1@newsreader2.netcologne.de> Message-ID: <4ldfp0F1csmpU1@uni-berlin.de> Claudio Grondi schrieb: > > Sometimes it is known in advance, that the time spent in a loop will be > in order of minutes or even hours, so it makes sense to optimize each > element in the loop to make it run faster. > One of instructions which can sure be optimized away is the check for > the break condition, at least within the time where it is known that the > loop will not reach it. > > Any idea how to write such a loop? > > e.g. > > counter = 2*64 > > while counter(BUT DON'T CHECK IT THE FIRST ONE HOUR LONG): now = time.time() while time.time() - now < 3600.0 or some_other_condition: ... The short circuiting of the or will prevent the execution of some_other_condition. > ... do something ... # and decrease the counter > > Thanks for any hint, but in particular if related to timers on the > Windows 2000/XP system I am mainly working with. > > What do you think about this idea? Does it make sense? What idea? Diez From yuxi at ece.gatech.edu Mon Aug 14 13:08:27 2006 From: yuxi at ece.gatech.edu (Yu-Xi Lim) Date: Mon, 14 Aug 2006 13:08:27 -0400 Subject: recommended general-purpose string template packages? In-Reply-To: <1155528993.321226.103240@m79g2000cwm.googlegroups.com> References: <1155523735.614470.199840@h48g2000cwc.googlegroups.com> <1155528993.321226.103240@m79g2000cwm.googlegroups.com> Message-ID: <ebqam9$31t$1@news-int.gatech.edu> Ravi Teja wrote: > Most Python templating engines are general purpose. Choice between them > however is sometimes a matter of preference, like editors. I settled > down on Cheetah for most part. I second Cheetah. It's suitable for most text templates. Many others are specific for XML or HTML documents. From rup at invalid.com Thu Aug 24 11:41:06 2006 From: rup at invalid.com (JAG CHAN) Date: 24 Aug 2006 15:41:06 GMT Subject: Best Editor References: <44ed8db6$0$75034$14726298@news.sunsite.dk> <slrneer6l0.1is.horpner@FIAD06.norwich.edu> Message-ID: <44edc892$0$75040$14726298@news.sunsite.dk> Neil Cerutti <horpner at yahoo.com> wrote in news:slrneer6l0.1is.horpner at FIAD06.norwich.edu: > Start with IDLE, which will likely be available everywhere you > use Python. The full instructions for using IDLE take up about > two pages of text, which means it's lightweight, and it comes > preconfigured with good Python integration. > > Learning a highly portable, industrial-strength program like Vim > or emacs is something I highly recommend, but it's not > necessarily a productive thing to do that at the same time you're > learning Python. > Thanks friends. As you say, as a beginner will start with IDLE. From tjreedy at udel.edu Wed Aug 23 18:25:11 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 23 Aug 2006 18:25:11 -0400 Subject: callable to disappear? References: <slrneeopqs.a7l.apardon@rcpc42.vub.ac.be> <1156357324.838315.234500@i42g2000cwa.googlegroups.com> Message-ID: <ecikk6$6qc$1@sea.gmane.org> "faulkner" <faulkner612 at comcast.net> wrote in message news:1156357324.838315.234500 at i42g2000cwa.googlegroups.com... > what's wrong with hasattr(obj, '__call__')? I have the impression that this is not currently true for all callables . If not, this may be improved in the future. >> Antoon Pardon >> Is there a chance this will be reconsidered? The items in PEP 3100 have different levels of certainly. Some may even get changed after experience with the alpha versions. Guido is allowing a year from first alpha (early 2007?) to final release, instead of the current 4-5 months. There has been recent discussion since of iscallable and some other isxxxx()s. The points you mentioned were raised and considered. I don't remember if there was a decision for the present. Two of the bigger negatives for 'iscallable': 1. You cannot know for sure until you call and get a return. 2. It does not say if the candidate is callable with any particular number or set of parameters. Terry Jan Reedy From rogue_pedro at yahoo.com Sat Aug 12 13:59:32 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 12 Aug 2006 10:59:32 -0700 Subject: self=pickle.load(file)? (Object loads itself) In-Reply-To: <ebl02g$3dv$1@gwdu112.gwdg.de> References: <ebl02g$3dv$1@gwdu112.gwdg.de> Message-ID: <1155405572.723597.161920@p79g2000cwp.googlegroups.com> Anton81 wrote: > Hi! > > it seems that > > class Obj: > def __init__(self): > f=file("obj.dat") > self=pickle.load(f) > ... > > doesn't work. Can an object load itself with pickle from a file somehow? > What's an easy solution? > > Anton Why are you trying to do this? Usually you would just say obj = pickle.load(f) and be done with it (you could manipulate obj after it's created, of course.) Why do you want to do obj = Obj() but have the obj come from "obj.dat"? Just curious. Peace, ~Simon From onurb at xiludom.gro Wed Aug 9 05:52:21 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 09 Aug 2006 11:52:21 +0200 Subject: Class data being zapped by method In-Reply-To: <1155081910.390971.249200@p79g2000cwp.googlegroups.com> References: <1155065906.910642.77320@75g2000cwc.googlegroups.com> <mailman.9111.1155066643.27775.python-list@python.org> <1155076971.519157.92540@i42g2000cwa.googlegroups.com> <1155081910.390971.249200@p79g2000cwp.googlegroups.com> Message-ID: <44d9b057$0$21148$7a628cd7@news.club-internet.fr> Simon Forman wrote: (snip) > Not that this has anything to do with your actual question, but there > are a number of small details that I noticed while reading your code: > > > 2.) Reading lines from a file is better done like so: > > arrLines = open('datafiles/'+filename+'.tabdata').readlines() Actually, it's better done like so: fpath = os.path.join('datafiles', filename + ".tabdata") f = open(fpath) try: process_opened_file(f) finally: f.close() From danielwong at berkeley.edu Wed Aug 9 22:22:10 2006 From: danielwong at berkeley.edu (danielx) Date: 9 Aug 2006 19:22:10 -0700 Subject: Open file handles? In-Reply-To: <1155074190.804203.173840@b28g2000cwb.googlegroups.com> References: <PvmdnW7gW8hCn0TZnZ2dnUVZ_oSdnZ2d@telcove.net> <1155074190.804203.173840@b28g2000cwb.googlegroups.com> Message-ID: <1155176530.509468.277200@h48g2000cwc.googlegroups.com> Is there an equivalent in windows? Jon wrote: > Perhaps using os you could work with lsof > [http://www.linuxcommand.org/man_pages/lsof8.html] > > Jon > > Thomas Bartkus wrote: > > This may be more of a Linux question, but I'm doing this from Python. ..... > > > > How can I know if anything (I don't care who or what!) is in the middle of > > using a particular file? > > > > This comes in context of needing to copy a file BUT only if I can verify > > that something else doesn't have an open write handle to that file. IOW - I > > need to decline the operation if something else hasn't finished writing to > > the file. > > > > How can I know? > > Thomas Bartkus From mturillo at gmail.com Sun Aug 20 17:14:11 2006 From: mturillo at gmail.com (Perseo) Date: 20 Aug 2006 14:14:11 -0700 Subject: Create a Multilanguage PDF in Python In-Reply-To: <87mz9z4f8h.fsf@smsnet.pl> References: <1156073383.983914.149180@i3g2000cwc.googlegroups.com> <87mz9z4f8h.fsf@smsnet.pl> Message-ID: <1156108451.762961.70140@h48g2000cwc.googlegroups.com> Hi again, WORKS!!! I download all I need as python + reportlab. Only 2 questions: 1. I need all of this package? because it is 6Mb! 2. How can I connect my software with MySql. In my Hosting is present the Python support but I don't thing that the MySQLdb is present. How can I solve this little problem? Thanks Perseo Rob Wolfe wrote: > "Perseo" <mturillo at gmail.com> writes: > > > Hi guys, > > > > I'm disprate with the Pdf Unicode. I try to create a class using ufpdf > > but some chars are not correct and now I would like try Python because > > a friend tolds me that it's very powerful. > > I need a simple script in Python that grab all Records from a MySql > > table and print in the pdf file. > > > > The languages stored in my db are about 25 and they are: > > Greek English French Hungarian Italian Lithuanian Dutch Portuguese > > Albanian > > Czech Danish German Spanish Estonian Finnish Irish Latvian Maltese > > Polish Romanian > > Russian Slovene Slovak Swedish > > You can give reportlab [1] a try. It has support for TrueType fonts > and unicode translation using UTF-8. I used to use it for pdf files > with polish chars. > > Some example code: > > <code> > from reportlab.pdfbase import pdfmetrics > from reportlab.pdfbase.ttfonts import TTFont > from reportlab.pdfgen import canvas > > pdfmetrics.registerFont(TTFont('Verdana', 'Verdana.ttf')) > c = canvas.Canvas("pl.pdf") > c.setFont("Verdana", 12) > c.drawString(100, 600, "Witaj, ?wiecie!".decode("iso-8859-2").encode("utf-8")) > c.showPage() > c.save() > </code> > > > [1] http://www.reportlab.org/ > > -- > HTH, > Rob From ddvlad at gmail.com Wed Aug 9 07:11:34 2006 From: ddvlad at gmail.com (Vlad Dogaru) Date: Wed, 9 Aug 2006 11:11:34 +0000 (UTC) Subject: Session implementation for Python Message-ID: <Xns981A90874AA20ddvladgmailcom@81.174.50.80> Hello, is there any PHP-like implementation for sessions in Python? I fear that writing my own would be seriously insecure, besides I could actually learn a lot by inspecting the code. The reason I am asking is that I would like to implement simple scripts which require login with CGI (no mod_python or Django -- I want to learn CGI first). Thanks in advance, Vlad -- There is nothing more dangerous than an idea when it is the only one you have. From richardjones at optushome.com.au Fri Aug 25 00:32:47 2006 From: richardjones at optushome.com.au (Richard Jones) Date: Fri, 25 Aug 2006 14:32:47 +1000 Subject: Best Practices for Python Script Development? References: <1156471481.265329.291360@m79g2000cwm.googlegroups.com> Message-ID: <44ee7d6f$0$5107$afc38c87@news.optusnet.com.au> metaperl wrote: > Searching cheeseshop.python.org/pypi for getopt modules does not work > very well by the way. http://docs.python.org/lib/module-getopt.html Richard From rpdooling at gmail.com Wed Aug 2 13:27:32 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 2 Aug 2006 10:27:32 -0700 Subject: Programming newbie coming from Ruby: a few Python questions In-Reply-To: <1154539223.873418.286830@i42g2000cwa.googlegroups.com> References: <mailman.8824.1154472963.27775.python-list@python.org> <1154494954.082706.283750@b28g2000cwb.googlegroups.com> <44d06f9f$0$19127$626a54ce@news.free.fr> <1154539223.873418.286830@i42g2000cwa.googlegroups.com> Message-ID: <1154539652.256975.155200@i3g2000cwc.googlegroups.com> simonharri... at fastmail.co.uk wrote: >> The Ruby crowd says you guys are no where >> near as friendly as them! Slander! Defamation! From pmaupin at gmail.com Sat Aug 26 16:49:25 2006 From: pmaupin at gmail.com (Patrick Maupin) Date: 26 Aug 2006 13:49:25 -0700 Subject: Don't use __slots__ (was Re: performance of dictionary lookup vs. object attributes) In-Reply-To: <mailman.9927.1156624141.27775.python-list@python.org> References: <mailman.9853.1156495094.27775.python-list@python.org> <1156508104.583914.323700@b28g2000cwb.googlegroups.com> <ecn1qa$ksp$1@panix2.panix.com> <7.0.1.0.0.20060825122244.03790010@yahoo.com.ar> <mailman.9880.1156520034.27775.python-list@python.org> <1156621904.481215.243080@m73g2000cwd.googlegroups.com> <mailman.9927.1156624141.27775.python-list@python.org> Message-ID: <1156625365.346825.18630@74g2000cwt.googlegroups.com> skip at pobox.com wrote: > Aahz> Taking a look at __slots__ is fine as long as you don't actually > Aahz> use them. > > Gabriel> Why? > > Skip> http://groups.google.com/group/comp.lang.python/browse_thread/thread/451ad25f9c648404/f4ac2dfde32b16fd?lnk=st&q=Python+__slots__+aahz&rnum=2#f4ac2dfde32b16fd > > Patrick> The subject of __slots__ really seems to get some people's > Patrick> dander up, to the extent where the heat/light ratio in the > Patrick> discussion becomes uncomfortably high. Right here, we have > Patrick> Skip referring to a post by Aahz, where Aahz says that Guido > Patrick> says that slots are bad mojo, without anybody ever giving > Patrick> concrete examples about why this may be the case. The only > Patrick> assertion that was made explicitly enough to be testable came > Patrick> about in a followup to Aahz's original post, only AFTER someone > Patrick> asked what the side-effects associated with __slots__ were. > Patrick> Aahz responded: > > No dander on my part. I was just pointing out an earlier thread on the > topic. Note however that the ultimate source of the anti-slots fervor in > that thread is Guido himself (may he live long and prosper as BDFL). If > Guido thinks it's bad mojo, that's good enough for me. Also, if he thinks > it's bad mojo now, my suspicion is that you won't see it in Py3k. > > That said, It's not mentioned on the Python3.0 page of the wiki: > > http://wiki.python.org/moin/Python3.0 > > or in PEP 3000: > > http://www.python.org/dev/peps/pep-3000/ > > and I see no discussion about it in the Python 3000 mailing list archives: > > http://mail.python.org/pipermail/python-3000/ > > though Ian Bicking asks about it here: > > http://wiki.python.org/moin/Python3%2e0Suggestions#head-fc89a0fe3f697418776925f4828ea863031fbbd2 > > Skip I didn't actually sense any dander on your part, so it was probably a bit unfortunate that I chose to respond to that particular message. I do (rightly or wrongly) sense some dander on Aahz's part, and this was the second or third thread where I saw him respond in a similar terse fashion, but I wasn't really motivated to respond until I saw your response to his response to, well, you know... And I know that the BDFL thinks it's a mistake, and he's probably right. In my previous post, I attempted to rationalize why this is true. For a start, Guido is probably continually hounded by people asking stupid __slots__ questions. Nonetheless, this is one of the few topics on CLP where innocent, rational questions are more often than not answered with "because I said so", so I was trying to inject a bit of nuance into the discussion. (For most similar technical questions, someone will post a pointer to a post or document which explains in clear technical detail WHY things are bad, but for this issue there seems to be no comparable source -- just that rant of the BDFL, which certainly carries a lot of weight in terms of best practices, but which I find woefully inadequate in terms of explanations which are dumbed-down enough for me to follow.) Also, as I noted, I _do_ use them on occasion, so if there really _are_ potential pitfalls there, I would like to understand exactly what they are, so my ears perk up whenever I notice a __slots__ discussion, but so far I have been repeatedly disappointed, in that I always see someone saying "don't do that" but I have never seen a cogent technical argument about how my scripts which __slots__ are going to suddenly, irretrievably break one day. Regards, Pat From mturillo at gmail.com Wed Aug 23 12:29:25 2006 From: mturillo at gmail.com (Perseo) Date: 23 Aug 2006 09:29:25 -0700 Subject: Create a Multilanguage PDF in Python In-Reply-To: <1156346130.927241.296190@75g2000cwc.googlegroups.com> References: <1156073383.983914.149180@i3g2000cwc.googlegroups.com> <87mz9z4f8h.fsf@smsnet.pl> <1156108451.762961.70140@h48g2000cwc.googlegroups.com> <1156143575.547217.237270@p79g2000cwp.googlegroups.com> <1156172609.125230.218190@i42g2000cwa.googlegroups.com> <4ku5d0Fdsn8fU1@uni-berlin.de> <1156272524.800930.27710@p79g2000cwp.googlegroups.com> <1156325189.795356.45770@b28g2000cwb.googlegroups.com> <1156346130.927241.296190@75g2000cwc.googlegroups.com> Message-ID: <1156350564.939303.86990@p79g2000cwp.googlegroups.com> It's too difficult for me, anyone can help me contact me thru chat or something else, please. It drives me crazy! Perseo wrote: > PERFECT! Done! Thanks > Now I create a little file in pdf format but the data are in the MySql > database! :( > How can I connect to it? > > Thanks for all suggestions > Perseo > > > Rob Wolfe wrote: > > Perseo wrote: > > > Nothing to do! > > > I enable test2.py and the folder with 777 permission and I write at the > > > top of the file the PYTHONPATH "#!/usr/bin/python" as you told me but > > > it doesn't works as well. > > > > #!/usr/bin/python is not PYTHONPATH. I think you should > > read this: > > http://docs.python.org/tut/node4.html#SECTION004220000000000000000 > > > > > The verdana font doesn't exist in the reportlab fonts folder. I try to > > > delete the rows where it is called like (registerFont, setFont) but > > > nothing to do. > > > > Fonts are not part of reportlab package. You should find it > > in your OS or in the net. You need to know what font do you want to > > use. > > > > > any suggestion?! > > > > Install reportlab package in your home directory, for example > > /home/perseo/python/lib > > > > and then in the shell write this: > > > > export PYTHONPATH=/home/perseo/python/lib > > > > and look here: > > http://docs.python.org/tut/node8.html#SECTION008110000000000000000 > > > > HTH, > > Rob From steve at holdenweb.com Wed Aug 30 02:15:46 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 30 Aug 2006 07:15:46 +0100 Subject: refering to base classes In-Reply-To: <1156909737.259769.36160@e3g2000cwe.googlegroups.com> References: <1156862012.068397.284040@m73g2000cwd.googlegroups.com> <ed1kev$52o$1@sunnews.cern.ch> <1156909737.259769.36160@e3g2000cwe.googlegroups.com> Message-ID: <44F52D12.6020404@holdenweb.com> glenn wrote: > Hi Roberto > >>If you want dog.voice() to just print "voice: bark", you just have to omit >>the voice method for the dog class: it will be inherited from creature. >> > > I would have thought this would be correct, but in this case, plus in > others im playin with, I get this issue: > ----------------------- > given animal.py is: > class creature: > def __init__(self): > self.noise="" > def voice(self): > return "voice:" + self.noise > > class dog(creature): > def __init__(self): > self.noise="bark" > > then I get this outcome... > >>>>import animal >>>>beagle=animal.dog [...] Shouldn't that be beagle = animal.dog() to create an instance? We've all done it ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From larry.bates at websafe.com Wed Aug 23 18:52:07 2006 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 23 Aug 2006 17:52:07 -0500 Subject: how to get file name of the running .py file In-Reply-To: <mailman.9749.1156373126.27775.python-list@python.org> References: <mailman.9749.1156373126.27775.python-list@python.org> Message-ID: <o4ednVqKyI-SQXHZnZ2dnUVZ_uudnZ2d@comcast.com> Jason Jiang wrote: > Hi, > > How to get the name of the running .py file like the macro _FILE_ in C? > > Thanks. > Jason > > > import os import sys print sys.argv[0] or if you just want the script and not the full path print os.path.basename(sys.argv[0]) -Larry Bates From toby at rcsreg.com Wed Aug 23 16:23:57 2006 From: toby at rcsreg.com (Tobiah) Date: Wed, 23 Aug 2006 20:23:57 +0000 Subject: smtplib needs me to put from/to headers in the message? In-Reply-To: <mailman.9750.1156376244.27775.python-list@python.org> References: <44ecd0c9$0$8817$88260bb3@free.teranews.com> <mailman.9750.1156376244.27775.python-list@python.org> Message-ID: <44ECB95D.7090706@rcsreg.com> Thank you for the valuable clarification, and the pointers. I will look into the RFC's. I wonder though, whether that will solve my main question, which is why the python.org example mandates that I specify 'from' and 'to' twice. Thanks, Tobiah Ben Finney wrote: > tobiah <st at tobiah.org> writes: > > >>In the example at: >> http://docs.python.org/lib/SMTP-example.html >> >>The text of the email message ends up with the From: and To: headers >>in it, and yet the call to sendmail() on the server object requires >>me to specify them again. > > > [Pet hate issue: Every RFC 2822 email message has exactly *one* body > and *one* header. From tjreedy at udel.edu Sun Aug 27 09:21:59 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Aug 2006 09:21:59 -0400 Subject: MapReduce, Distributed Computing, and Ruby References: <bx8Ig.68197$Nt2.7820@tornado.rdc-kc.rr.com> <1156660633.976360.106340@74g2000cwt.googlegroups.com> Message-ID: <ecs69p$eg0$1@sea.gmane.org> <raviteja.bhupatiraju at gmail.com> wrote in message news:1156660633.976360.106340 at 74g2000cwt.googlegroups.com... .rufy.com/2006/08/mapreduce-for-ruby-ridiculously-easy.html > > Consider bugging this guy to release the code. > http://agentmine.com/blog/2005/11/30/mapreduce-in-python WARNING This site downloaded IExplore trojan VBS/Psyme. VirusScan blocked it for me. > http://agentmine.com/blog/2006/02/19/mapreduce-in-python-2 Don't, he already said he will release when done and is bugged about requests already. From bumperdoc at gmail.com Wed Aug 16 20:42:01 2006 From: bumperdoc at gmail.com (bumperdoc at gmail.com) Date: 16 Aug 2006 17:42:01 -0700 Subject: Python and SAFEARRAY Message-ID: <1155775321.663735.105010@h48g2000cwc.googlegroups.com> Hi I'm using win32com.client to dispatch a COM server....one of the interface methods has the below parameter: ..., [in, out] SAFEARRAY(BYTE) *Buffer, ... This method goes and queries something and puts it in this buffer...how can I use this method in Python? What type of variable needs to be passed in when calling this method? Thanks in advance. AC From claird at lairds.us Wed Aug 16 09:21:15 2006 From: claird at lairds.us (Cameron Laird) Date: Wed, 16 Aug 2006 13:21:15 +0000 Subject: round not rounding to 0 places References: <1155712764.516132.251800@m73g2000cwd.googlegroups.com> <mailman.9407.1155714428.27775.python-list@python.org> Message-ID: <bnibr3-sie.ln1@lairds.us> In article <mailman.9407.1155714428.27775.python-list at python.org>, Tim Leslie <tim.leslie at gmail.com> wrote: >On 16 Aug 2006 00:19:24 -0700, Fuzzydave <Fuzzygoth at gmail.com> wrote: >> I have been using a round command in a few places to round >> a value to zero decimal places using the following format, >> >> round('+value+', 0) >> >> but this consistantly returns the rounded result of the value >> to one decimal place with a zero >> >> EG: >> >> 4.97 is returned as 5.0 when i want it returned as 5, does >> anyone know why this is and if i can get the round to make >> the value 5? > >round returns a float. You probably want to convert it to an int. > >>>> int(round(4.97)) >5 . . . I'm surprised no one has recommended "%.0f" % 4.97 From kylotan at gmail.com Fri Aug 4 10:04:34 2006 From: kylotan at gmail.com (Ben Sizer) Date: 4 Aug 2006 07:04:34 -0700 Subject: Need a compelling argument to use Django instead of Rails In-Reply-To: <1154638178.465322.198390@i3g2000cwc.googlegroups.com> References: <mailman.8642.1154064538.27775.python-list@python.org> <1154077105.746752.153440@h48g2000cwc.googlegroups.com> <1154080209.603694.161170@i42g2000cwa.googlegroups.com> <1154092298.714808.158250@75g2000cwc.googlegroups.com> <44ca3420$0$30140$636a55ce@news.free.fr> <jeokc2tisel285nois1ini5qhh0o70m2s6@4ax.com> <5hnlc25hfj56btkhdamfdi5gb5a3b8ts45@4ax.com> <mailman.8731.1154352939.27775.python-list@python.org> <1154354727.457387.142840@h48g2000cwc.googlegroups.com> <3scsc252be3d7a814ogj1ibnud3aothc1l@4ax.com> <1154512062.251725.177140@m73g2000cwd.googlegroups.com> <7xejvz5mwj.fsf@ruckus.brouhaha.com> <1154638178.465322.198390@i3g2000cwc.googlegroups.com> Message-ID: <1154700274.659320.292690@m79g2000cwm.googlegroups.com> aaronwmail-usenet at yahoo.com wrote: > Paul Rubin wrote: > > A typical shared hosting place might > > support 1000's of users with ONE apache/php instance (running in a > > whole bunch of threads or processes, to be sure). > > You just need to run multiple apache > instances, which is advisable anyway. > The hosting service formerly known as > python-hosting has been doing this > for years. Would you need one instance per user? Is it practical to run 1000s of Apache instances on one server? -- Ben Sizer From rosedb0 at gmail.com Thu Aug 24 22:02:06 2006 From: rosedb0 at gmail.com (hiaips) Date: 24 Aug 2006 19:02:06 -0700 Subject: Is this a good idea or a waste of time? In-Reply-To: <1156449402.022781.292840@p79g2000cwp.googlegroups.com> References: <1156449402.022781.292840@p79g2000cwp.googlegroups.com> Message-ID: <1156471326.702471.278990@b28g2000cwb.googlegroups.com> asincero wrote: > Would it be considered good form to begin every method or function with > a bunch of asserts checking to see if the parameters are of the correct > type (in addition to seeing if they meet other kinds of precondition > constraints)? Like: > > def foo(a, b, c, d): > assert type(a) == str > assert type(b) == str > assert type(c) == int > assert type(d) == bool > # rest of function follows > > This is something I miss from working with more stricter languages like > C++, where the compiler will tell you if a parameter is the wrong type. > If anything, I think it goes a long way towards the code being more > self documenting. Or is this a waste of time and not really "the > Python way"? > > -- Arcadio Many developers who move from a statically-typed languages to dynamic ones go through this same sort of thought process. I was no different in that regard, but as I've done more and more Python, I've found that I just don't encounter type issues all that often. Above all, I see duck typing as a net benefit - its inherent flexibility far outweighs the lack of "compile-time" type safety, in my mind. Along these lines, I'll point you to this article by Bruce Eckel called "Strong Typing vs. Strong Testing": http://www.mindview.net/WebLog/log-0025. The bottom line: Focus on unit tests rather than explicit type checks when you want to verify the runtime safety of your code. You'll find many more errors this way. Hope this helps... --dave From elliot.hughes at gmail.com Sun Aug 20 13:47:10 2006 From: elliot.hughes at gmail.com (Elliot Hughes) Date: 20 Aug 2006 10:47:10 -0700 Subject: Send to all clients using UDP in Twisted Message-ID: <1156096030.610574.279220@h48g2000cwc.googlegroups.com> Hi Everyone, I am trying to right a server that can receive a message and send it to all clients using UDP on twisted. I have got it so far that it can echo to the client that sent the message but not to the rest. I tried using multicast but that requires almost total rewrite, and the client which is not in python can't handle it. Are there any alternative methods or a workaround? Thanks alot for your time! From alpersoyler at yahoo.com Thu Aug 31 09:01:09 2006 From: alpersoyler at yahoo.com (alper soyler) Date: Thu, 31 Aug 2006 06:01:09 -0700 (PDT) Subject: a question about my script In-Reply-To: <7.0.1.0.0.20060829041316.03da8e20@yahoo.com.ar> Message-ID: <20060831130109.54725.qmail@web56501.mail.re3.yahoo.com> Hi, I changed the script as you wrote below: from ftplib import FTP def handleDownload(block): file.write(block) print ".", ftp = FTP('ftp.genome.jp') print ftp.login() directory = 'pub/kegg/genomes' ftp.cwd(directory) k=0 for direct in ftp.nlst(): curdir = '%s/%s' % (directory, direct) ftp.cwd(curdir) for filename in ftp.nlst(): if not filename.endswith('.pep'): continue file = open(filename, 'wb') ftp.retrbinary('RETR %s/%s' % (curdir, filename), handleDownload) file.close() k=k+1 print ftp.close() However, it gave the same error message: 230 Anonymous access granted, restrictions apply. Traceback (most recent call last): File "ftp1.0.py", line 18, in ? ftp.cwd(curdir) File "/usr/lib/python2.4/ftplib.py", line 494, in cwd return self.voidcmd(cmd) File "/usr/lib/python2.4/ftplib.py", line 246, in voidcmd return self.voidresp() File "/usr/lib/python2.4/ftplib.py", line 221, in voidresp resp = self.getresp() File "/usr/lib/python2.4/ftplib.py", line 216, in getresp raise error_perm, resp ftplib.error_perm: 550 pub/kegg/genomes/aae: No such file or directory However, in ftp.genome.jp/pub/kegg/genomes/ site, there is 'aae' directory. What can be the reason? regards, alper ----- Original Message ---- From: Gabriel Genellina <gagsl-py at yahoo.com.ar> To: alper soyler <alpersoyler at yahoo.com> Cc: Python-list at python.org Sent: Tuesday, August 29, 2006 10:26:57 AM Subject: Re: a question about my script At Tuesday 29/8/2006 03:55, alper soyler wrote: >I am trying to get some files from an ftp site by ftplib module and >I wrote the below script. However I have a problem. With my script, >I login to ftp.genome.jp site. then, I am changing the directory to >pub/kegg/genomes/afm and I am downloading "a.fumigatus.pep" file. >However, what I want is to connect pub/kegg/genomes directory and in >this directory there are 3 letters name files 3 letters *files*? or 3 letters *directories*? >e.g. 'afm' and in each of these 3 letters files there is a file with >the extension of '.pep' like a.fumigatus.pep. I want to get these >'.pep' files from the 3 letter named files. If you help me I will be >very glad. Thanks you in advance. Do a cwd() starting one level above (that is, pub/kegg/genomes); using ftp.dir() you can get the subdirectories, then iterate over all of them, using another dir() to find the .pep files needed. >directory = 'pub/kegg/genomes/ afm' Is that whitespace intentional? (If you just want to download the files and don't need really a Python script, try wget...) Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060831/51c6c24e/attachment.html> From http Sun Aug 13 15:55:58 2006 From: http (Paul Rubin) Date: 13 Aug 2006 12:55:58 -0700 Subject: yet another noob question References: <1155492110.659011.196280@75g2000cwc.googlegroups.com> <7xhd0g1kfh.fsf@ruckus.brouhaha.com> Message-ID: <7xd5b41kc1.fsf@ruckus.brouhaha.com> Paul Rubin <http://phr.cx at NOSPAM.invalid> writes: > Now you can use the function to print the list you wanted: > > for i in xrange(1234,1333): > print base5x(i, 5) Whoops, pasted the wrong thing from my test window. Sorry. That was supposed to say: for i in xrange(5**5): print base5x(i, 5) From onurb at xiludom.gro Fri Aug 4 06:41:52 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 04 Aug 2006 12:41:52 +0200 Subject: threads, file access and stuff In-Reply-To: <1154646563.392923.76850@p79g2000cwp.googlegroups.com> References: <1154646563.392923.76850@p79g2000cwp.googlegroups.com> Message-ID: <44d32471$0$32196$636a55ce@news.free.fr> Slackydude at gmail.com wrote: > Hi, > i'm trying to make a download manager (getright, flashget, etc..) for > linux (pygtk), i'm using pyCurl, so the thing is.. > the app need to be able to use mirrors, like : i download the first 400 > kb from X, and the second 200 kb from Y and the rest from Z. > i've plan to do this with threads and using Locks (This question has > been here before, so i have an idea..) > but the thing is, What if the app don't download a complete file in a > session (the user close the app, etc) and wants to complete the > download? Ok, i can seek the file and start to download again. but > where or how can i store that info?(where i left the download). Where : the convention on *n*x is to store this kind of stuff in a .<appname> file or directory in the users's home. How : this is up to you, but I'd start with the simplest solution, ie an ini file (ConfigParser is your friend here). HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From mensanator at aol.com Sun Aug 13 19:29:25 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 13 Aug 2006 16:29:25 -0700 Subject: yet another noob question In-Reply-To: <slrneduvj6.bb7.sybrenUSE@schuimige.stuvel.eu> References: <1155492110.659011.196280@75g2000cwc.googlegroups.com> <slrneduvj6.bb7.sybrenUSE@schuimige.stuvel.eu> Message-ID: <1155511765.081083.184460@h48g2000cwc.googlegroups.com> Sybren Stuvel wrote: > mike_wilson1333 enlightened us with: > > I would like to generate every unique combination of numbers 1-5 in a 5 > > digit number and follow each combo with a newline. So i'm looking at > > generating combinations such as: (12345) , (12235), (55554) and so on. > > Count from 0 to 44444 in a base-5 numbering, and add 11111 to every > number. > > b5_11111 = int('11111', 5) > > for i in range(int('44444', 5)+1): > i += b5_11111 > print i > > Only the print command needs to convert back to base-5. Does anyone > know of an elegant way to do that? Use the gmpy module which does base conversion in both directions. >>> import gmpy >>> b5_11111 = gmpy.mpz('11111',5) >>> b5_11111 mpz(781) >>> print gmpy.digits(b5_11111,5) 11111 > > Sybren > -- > The problem with the world is stupidity. Not saying there should be a > capital punishment for stupidity, but why don't we just take the > safety labels off of everything and let the problem solve itself? > Frank Zappa From lsumnler at gmail.com Thu Aug 17 17:35:02 2006 From: lsumnler at gmail.com (len) Date: 17 Aug 2006 14:35:02 -0700 Subject: Newbie SQL ? in python. Message-ID: <1155850502.852284.99590@74g2000cwt.googlegroups.com> I have tried both the pyodbc and mxODBC and with help from the ng been able to do what I want using either. My needs are pretty basic some simple selects and inserts. The current problem I have hit is the database I am inserting into have a special ODBC driver that using the files natively has an autoincrement feature. However, through the ODBC driver the autoincrement does not work. (The explanation I got was the creators did not anticapate a great need for insert.) Anyway, I figured not a problem I will just do a select on the table ordered by the ID field in descending order and fetch the first record and do the autoincrementing within the python program. The code , using pyodbc is as follows. c.execute("select state_sid from statecode order by state_sid DESC") sid = c.fetchone() newsid = sid.state_sid + 1 This code works fine and I get what I want. My concern is that this technique used on large files may cause problem. I really just want to get what is the last record in the database to get the last ID used. Is there a better way. I realize this may be more of an SQL question but I figured I would try here first. Len Sumnler From rupole at hotmail.com Sat Aug 12 02:08:21 2006 From: rupole at hotmail.com (Roger Upole) Date: Sat, 12 Aug 2006 02:08:21 -0400 Subject: Kill process based on window name (win32) References: <1155356918.399290.266470@p79g2000cwp.googlegroups.com> Message-ID: <1155362407_8127@sp6iad.superfeed.net> drodrig wrote: > Hi. > > I am trying to close/kill all processes that show visible windows on > Windows XP. So far I've created a script that uses win32gui.EnumWindows > to iterate through all windows, check for which windows are visible, > then send a WM_CLOSE message to the window to request that it closes. > Of course, not all apps want to close nicely. At this point I need to > use something like TerminateProcess to kill the app, but how do I find > the process id (hopefully based on the window id). > > Thanks for any help. > win32process.GetWindowThreadProcessId should do the trick. Roger From faulkner612 at comcast.net Sat Aug 26 19:31:05 2006 From: faulkner612 at comcast.net (faulkner) Date: 26 Aug 2006 16:31:05 -0700 Subject: Python daemon process In-Reply-To: <pan.2006.08.26.11.54.38.996300@localhost.localdomain> References: <pan.2006.08.26.11.54.38.996300@localhost.localdomain> Message-ID: <1156635065.292820.222780@74g2000cwt.googlegroups.com> process = subprocess.Popen(gnuchess) ... os.kill(process.pid, signal.SIGKILL) Thomas Dybdahl Ahle wrote: > Hi, I'm writing a program, using popen4(gnuchess), > The problem is, that gnuchess keeps running after program exit. > > I know about the atexit module, but in java, you could make a process a > daemon process, and it would only run as long as the real processes ran. I > think this is a better way to stop gnuchess, as you are 100% sure, that > it'll stop. > > Can you do this with popen? > > -- > Thomas From ty.2006 at yahoo.com Wed Aug 16 11:26:53 2006 From: ty.2006 at yahoo.com (T) Date: 16 Aug 2006 08:26:53 -0700 Subject: How to delete a directory tree in FTP Message-ID: <1155742012.987806.236060@75g2000cwc.googlegroups.com> I connect to a FTP server which can be either unix or windows server. Once in the FTP session, I would like to delete a directory tree on the server. Is there a command that will do this? If not, can someone point me to a right direction? Thanks! From tjreedy at udel.edu Wed Aug 23 22:01:38 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 23 Aug 2006 22:01:38 -0400 Subject: Translating Javascript programs to python. References: <1156264202.542785.172270@74g2000cwt.googlegroups.com><1156318571.722528.127110@h48g2000cwc.googlegroups.com> <1156371324.186510.273930@75g2000cwc.googlegroups.com> Message-ID: <ecj1a1$5cf$1@sea.gmane.org> "Vyz" <vyzasatya at gmail.com> wrote in message news:1156371324.186510.273930 at 75g2000cwc.googlegroups.com... > Its a module to transliterate from telugu language written in roman > script into native unicode. right now its running in a browser window > at www.lekhini.org I Intend to translate it into python so that I can > integrate into other tools I have. I am able to pass arguments and get > output from the script also would be OK. or how about ways to wrap > these javascript functions with python. Leaving aside the code the manipulated the display and user interaction, the code should be pretty straightforward logic (if-else statements) and table lookups, so translation to Python should be straightforward also. I checked parser.js. I don't know javascript but it looks to me like a mixture of C and Python. The for loop headers have to be rewritten, and the switch changed to if-elif. What looks different is the attachment as attributes of method functions to functions rather than classes. As for 'wrapping': can you get a standard javascript interpreter? If so, you could possibly adjust the js so you can pipe a roman string to the js program and have it pipe back the telegu unicode version. >> > I have a script with hundreds of lines of javascript spread accross 7 >> > files. Is there any tool out there to automatically or >> > semi-automatically translate the code into python. unicode.js is mostly a few hundred verbose lines like Unicode.codePoints[Padma.lang_TELUGU].letter_PHA = "\u0C2B"; that setup the translation dict. Because the object model is different, I suspect that these all need to be changed, but, I also suspect, in a mechanical way. If one were starting in Python, one might either just define a dict more compactly like TEL_uni = {letter_PHA:"\u0C2B", ...} *or* probably better, use the builtin unicodedata module as much as possible. >>> import unicodedata as u >>> pha = u.name(u'\u0c2b') >>> pha 'TELUGU LETTER PHA' >>> u.lookup(pha) u'\u0c2b' I don't know what you do with js statement like this: Unicode.toPadma[Unicode.codePoints[Padma.lang_TELUGU].misc_VIRAMA + Unicode.codePoints[Padma.lang_TELUGU].letter_KA] = Padma.vattu_KA; where a constant seems to be assigned to a sum. But whatever these do might correspond to the u.normalize function. This appears to be based on a generic Indian-script transliteration program (Padma), so there may be functions not really needed for Telegu. (I am familiar with Devanagri but know nothing of Telegu and its script except that it is Dravidian rather than Indo-European-Sanskritic.) Good luck. Terry Jan Reedy From pmartin at snakecard.com Thu Aug 17 18:31:11 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Thu, 17 Aug 2006 17:31:11 -0500 Subject: How to fill a form References: <20060815034051.89ef7e18.sulsa@gazeta.pl> <mailman.9336.1155608567.27775.python-list@python.org> <20060815050733.10e14112.sulsa@gazeta.pl> <12e2gau4jouhmcf@corp.supernews.com> <20060815054343.1c31f3f7.sulsa@gazeta.pl> Message-ID: <Nh6Fg.69372$LF4.4280@dukeread05> Sulsa wrote: > On Tue, 15 Aug 2006 03:37:02 -0000 > Grant Edwards <grante at visi.com> wrote: > >> On 2006-08-15, Sulsa <sulsa at gazeta.pl> wrote: >> >> > I want to fill only one smiple form so i would like not to use >> > any non standard libraries. >> >> Then just send the HTTP "POST" request containing the fields >> and data you want to submit. > > but i don't know how to post these data if i knew there there would > be no topic. You forgot thanks and regards From Eric_Dexter at msn.com Sun Aug 27 20:29:55 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 27 Aug 2006 17:29:55 -0700 Subject: newbe question about removing items from one file to another file In-Reply-To: <QPOdnVQ1let7vG_ZRVnyvg@bt.com> References: <1156714534.318183.326220@i3g2000cwc.googlegroups.com> <QPOdnVQ1let7vG_ZRVnyvg@bt.com> Message-ID: <1156724995.792792.273680@b28g2000cwb.googlegroups.com> PetDragon wrote: > Sounds like you need to use html parser, check it out in the > documentation.... > > > > <Eric_Dexter at msn.com> wrote in message > news:1156714534.318183.326220 at i3g2000cwc.googlegroups.com... > > def simplecsdtoorc(filename): > > file = open(filename,"r") > > alllines = file.read_until("</CsInstruments>") > > pattern1 = re.compile("</") > > orcfilename = filename[-3:] + "orc" > > for line in alllines: > > if not pattern1 > > print >>orcfilename, line > > > > I am pretty sure my code isn't close to what I want. I need to be able > > to skip html like commands from <defined> to <undefined> and to key on > > another word in adition to </CsInstruments> to end the routine > > > > I was also looking at se 2.2 beta but didn't see any easy way to use it > > for this or for that matter search and replace where I could just add > > it as a menu item and not worry about it. > > > > thanks for any help in advance > > I will look into that a little bit since that is so html like... maybe some of the examples can lead me in the right direction on alot of it.. http://www.dexrow.com From tim.leeuwvander at nl.unisys.com Tue Aug 22 05:26:05 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 22 Aug 2006 02:26:05 -0700 Subject: Python and STL efficiency In-Reply-To: <1156235875.990556.25990@74g2000cwt.googlegroups.com> References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <mailman.9595.1156153010.27775.python-list@python.org> <1156162237.274636.17850@i3g2000cwc.googlegroups.com> <1156165101.702758.148420@74g2000cwt.googlegroups.com> <1156235875.990556.25990@74g2000cwt.googlegroups.com> Message-ID: <1156238765.761842.160090@b28g2000cwb.googlegroups.com> Ray wrote: > Tim N. van der Leeuw wrote: > > > In which case, Licheng, you should try using the /GF switch. This will > > > tell Microsoft C++ compiler to pool identical string literals together. > > > > > > > > > :) > > > > The code still creates a new string - instance each time it tries to > > append a const char* to the vector<string> ... > > Yeah, you're right... I've been programming Java too long :) > Took me a while to see that too! Have been programming too much Java / Python as well. Anyways, when changing the Python version so that it adds 40.000 unique strings to the list (and proving that there are indeed 40.000 unique ids in the list, by making a set of all id()s in the list and taking the len() of that set), it still takes at most a second. I cannot test the speed of the c++ version on my computer, so nothing scientific here. I'm curious though, if on the OP's machine the slowed-down Python version is still faster than the C++ version. Cheers, --Tim From milosz.piglas at gmail.com Sat Aug 19 09:56:47 2006 From: milosz.piglas at gmail.com (milosz) Date: 19 Aug 2006 06:56:47 -0700 Subject: text editor suggestion? References: <44e66724$0$2363$c3e8da3@news.astraweb.com> Message-ID: <1155995807.052337.272990@i42g2000cwa.googlegroups.com> Did you try gedit? It has an options, which you need, I think. Regards. From MaaSTaaR at gmail.com Sun Aug 13 14:10:25 2006 From: MaaSTaaR at gmail.com (MaaSTaaR) Date: 13 Aug 2006 11:10:25 -0700 Subject: open() and Arabic language Message-ID: <1155492625.573013.78440@74g2000cwt.googlegroups.com> Hello ... firstly , sorry for my bad English . i have problem with open() function when i use it with file which name in Arabic , the open() will not find the file , and i am sure the file is exist . so how i can solve this problem ? From jweida at gmail.com Mon Aug 28 13:50:37 2006 From: jweida at gmail.com (Jerry) Date: 28 Aug 2006 10:50:37 -0700 Subject: wxPython and Py2exe crashes in "window" mode but not in "console" mode In-Reply-To: <44ef5ae6$0$21142$7a628cd7@news.club-internet.fr> References: <1156531893.746147.79070@b28g2000cwb.googlegroups.com> <44ef5ae6$0$21142$7a628cd7@news.club-internet.fr> Message-ID: <1156787437.758755.218590@h48g2000cwc.googlegroups.com> jean-michel, I'm at work at the moment and can't post with attachments. I will do so once I get home. jean-michel bain-cornu wrote: > I'd like to reproduce your crash, could you post a sample ? From spam at me.please Fri Aug 25 09:20:50 2006 From: spam at me.please (Skink) Date: Fri, 25 Aug 2006 15:20:50 +0200 Subject: django's view.py as class not just methods Message-ID: <ecmtfd$jjm$1@news2.ipartners.pl> Hi, I'm relatively new to django and maybe my question is stupid, but... Is it possible to map in urls.py some url not to function in views.py (which has first argument with HttpRequest) but to some class method? In that case each instance of such class would be created when session starts and for subsequent calls would be served as self ? I know, I know that HttpRequest has session member and I can use it. But maybe it would be good idea to have such url ==> class.method mapping. thanks, skink From Bulkan at gmail.com Thu Aug 3 19:40:16 2006 From: Bulkan at gmail.com (placid) Date: 3 Aug 2006 16:40:16 -0700 Subject: programming is hard In-Reply-To: <1154623085.994132.126620@m73g2000cwd.googlegroups.com> References: <1154609819.083694.22200@m73g2000cwd.googlegroups.com> <mailman.8910.1154614492.27775.python-list@python.org> <1154623085.994132.126620@m73g2000cwd.googlegroups.com> Message-ID: <1154648416.036565.224320@p79g2000cwp.googlegroups.com> Alas, all good arguments. I rest my case. :( Cheers From siona at chiark.greenend.org.uk Wed Aug 9 10:15:03 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 09 Aug 2006 15:15:03 +0100 (BST) Subject: Class data being zapped by method References: <1155065906.910642.77320@75g2000cwc.googlegroups.com> <1155076971.519157.92540@i42g2000cwa.googlegroups.com> <1155081910.390971.249200@p79g2000cwp.googlegroups.com> <44d9b057$0$21148$7a628cd7@news.club-internet.fr> Message-ID: <FZy*5TNnr@news.chiark.greenend.org.uk> Bruno Desthuilliers <onurb at xiludom.gro> wrote: >fpath = os.path.join('datafiles', filename + ".tabdata") fpath = os.path.join('datafiles', filename + os.path.extsep + "tabdata") 8-) I'm a bit bemused by extsep -- it didn't appear until 2.2, by which time there can't have been many people with an OS where it was anything other than '.'. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From deets at nospam.web.de Sun Aug 27 08:19:45 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 27 Aug 2006 14:19:45 +0200 Subject: unpaking sequences of unknown length In-Reply-To: <4ldfi6F1ckiqU1@uni-berlin.de> References: <mailman.9934.1156672890.27775.python-list@python.org> <4ldfi6F1ckiqU1@uni-berlin.de> Message-ID: <4ldgv1F1dcttU1@uni-berlin.de> >> Question: Is there an unpacking mechanism for cases in which I don't >> know--and don't need to know--how many elements I get, or an >> argument passing mechanism that is the inverse of the tuplifier (*args)? > > No. > > It looks a little bit as if you aren't aware of the symetry behind the * > and **-argument-passing schemes. I suggest reading up on them. Sorry - I was somewhat unconcentrated and missed the last part of the sentence. So it is No "generalized", yes, the inverse of *args is foo(*args) Sorry for the confusion. Diez From jyoti.chhabra at gmail.com Mon Aug 21 02:50:29 2006 From: jyoti.chhabra at gmail.com (JyotiC) Date: 20 Aug 2006 23:50:29 -0700 Subject: tkinter prob In-Reply-To: <mailman.9590.1156141532.27775.python-list@python.org> References: <1156140461.170856.136180@74g2000cwt.googlegroups.com> <mailman.9590.1156141532.27775.python-list@python.org> Message-ID: <1156143029.771346.22580@74g2000cwt.googlegroups.com> i have tried it out but it's not working. this is the code from Tkinter import * class abc: def __init__(self,parent): #make container myparent self.myparent=parent self.myparent.geometry("500x200") #make the initial frame self.frame=Frame(self.myparent) self.frame.pack() self.var=IntVar() self.var.set(0) a=Button(self.frame,text="button") a.pack() Checkbutton(self.frame,text="hello",variable=self.var,command=self.com(a)).pack() def com(self,a): if self.var.get()==1: a.config(state=ENABLED) else: a.config(state=DISABLED) root=Tk() abc(root) root.mainloop() Fredrik Lundh wrote: > JyotiC wrote: > > > i am making a GUI using Tkinter, > > I have a button and a checkbutton. > > i want the button to be enable when checkbutton is on and disble when > > the checkbutton is off. > > use the checkbutton's command option to install a callback that enables > or disables the button. > > </F> From paddy3118 at netscape.net Mon Aug 21 14:29:13 2006 From: paddy3118 at netscape.net (Paddy) Date: 21 Aug 2006 11:29:13 -0700 Subject: sum and strings In-Reply-To: <1156179281.249531.188460@b28g2000cwb.googlegroups.com> References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <slrneeatf3.nbt.sybrenUSE@schuimige.stuvel.eu> <1155922208.930580.135080@m79g2000cwm.googlegroups.com> <mailman.9516.1155930431.27775.python-list@python.org> <1155952305.848495.7060@i3g2000cwc.googlegroups.com> <7x4pw9h3yy.fsf@ruckus.brouhaha.com> <pan.2006.08.21.09.36.20.956098@REMOVEME.cybersource.com.au> <1156179281.249531.188460@b28g2000cwb.googlegroups.com> Message-ID: <1156184953.300553.116420@b28g2000cwb.googlegroups.com> Carl Banks wrote: > > and, you know, if you really want to concatenate strings with sum, you > can > > class noopadd(object): > def __add__(self,other): > return other > > sum(["abc","def","ghi"],noopadd()) ;-) - Pad. From fredrik at pythonware.com Tue Aug 15 17:57:41 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 15 Aug 2006 23:57:41 +0200 Subject: file object and eof In-Reply-To: <1155668786.644843.192830@m79g2000cwm.googlegroups.com> References: <1155660586.941712.114410@b28g2000cwb.googlegroups.com> <12e412ljneshoc3@corp.supernews.com> <1155668786.644843.192830@m79g2000cwm.googlegroups.com> Message-ID: <ebtg0c$4v4$1@sea.gmane.org> KraftDiner wrote: > how about?!: > > def eof(fileobj): > curloc = fileobj.tell() > ofloc = fileobj.seek(0,2) > fileobj.seek(curloc, 0) > if ofloc >= curloc: > return True > return False this doesn't work with text files on platforms that translates line endings, it doesn't work with streams, it's not very efficient, and as written, it doesn't work at all. and it's entirely pointless, since you need to check the return value from "read" anyway. </F> From rainbow.cougar at gmail.com Tue Aug 22 09:48:02 2006 From: rainbow.cougar at gmail.com (rainbow.cougar at gmail.com) Date: 22 Aug 2006 06:48:02 -0700 Subject: Problem installing Python 2.4.3 on FreeBSD 5.3-RELEASE-p31 In-Reply-To: <1156189853.305452.13080@i42g2000cwa.googlegroups.com> References: <1155845217.325852.170320@m73g2000cwd.googlegroups.com> <44E8A5B8.703@v.loewis.de> <1156189853.305452.13080@i42g2000cwa.googlegroups.com> Message-ID: <1156254482.788028.94090@i42g2000cwa.googlegroups.com> jamesuh wrote: > Martin v. L?wis wrote: > > james at uh-hosting.co.uk schrieb: > > > I assume this is related to the configure warning... ? Same error with > > > just a standard "./configure" and "make". > > > > > > Any help would be great :) > > > > If you don't need the curses module, go on with the installation. > > It's a known bug in FreeBSD's curses header file. > > > > Regards, > > Martin > > But I cannot continue because it seg faults and does not continue the > make - Forgive my ignorance, but how do I prevent the curses module > from being included? There is some severe problem here. I have this very version of Python on a FreeBSD 5.3 system (I'm typing on it now) and didn't have this problem. I think you may have some conflict in your object libs. If you don't need tkinter you can go to one of the FreeBSD ftp sites and download the packaged binary version. From bearophileHUGS at lycos.com Sat Aug 26 06:54:17 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 26 Aug 2006 03:54:17 -0700 Subject: question about class, functions and scope In-Reply-To: <1156583602.302530.206630@74g2000cwt.googlegroups.com> References: <1156583602.302530.206630@74g2000cwt.googlegroups.com> Message-ID: <1156589657.706430.69650@74g2000cwt.googlegroups.com> nephish: > is this legal ? is it pythonic? It's legan and pythonic. Functions are here for a purpose. Bye, bearophile From tenax.raccoon at gmail.com Mon Aug 7 18:16:55 2006 From: tenax.raccoon at gmail.com (Jason) Date: 7 Aug 2006 15:16:55 -0700 Subject: do people really complain about significant whitespace? References: <1154986984.740638.241130@m79g2000cwm.googlegroups.com> Message-ID: <1154989015.347690.109930@b28g2000cwb.googlegroups.com> infidel wrote: > Where are they-who-hate-us-for-our-whitespace? Are "they" really that > stupid/petty? Are "they" really out there at all? "They" almost sound > like a mythical caste of tasteless heathens that "we" have invented. > It just sounds like so much trivial nitpickery that it's hard to > believe it's as common as we've come to believe. I have a coworker who dislikes Python for the whitespace. He likes the idea that if someone is silly enough to put a whole program on one line, they can put it back together by following the braces. He also likes that the compiler can compile the program even if a normal person can't read it. I've pointed out that we format our code with the whitespace anyway. He points out that if some code gets accidentally dedented, it is difficult for another programmer to determine which lines were supposed to be in the indented block. I pointed out that if someone accidentally moves a curly brace, the same problem can occur. Anecdotally, I've never had either problem. Sadly, people who do dislike the whitespace do exist. I have also talked with several other programmers who were very turned off about the white-space thing and wouldn't give the language a chance. Eric S. Raymond wrote enthusiastically about Python, but was initially turned off by the whitespace rules. (See "http://www.python.org/about/success/esr/" for details.) I personally love that my logically formatted code imparts information logically to the language. (I haven't seen a good hate-us-for-our-whitespace thread go on for awhile. I do remember some good "We like Python, Now Add Our Favorite C/C++/LISP/INTERCAL Features or We'll Leave" threads on this newsgroup.) From python.list at tim.thechases.com Mon Aug 21 15:28:43 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 21 Aug 2006 14:28:43 -0500 Subject: List Splitting In-Reply-To: <1156187837.378252.36420@m73g2000cwd.googlegroups.com> References: <1156187837.378252.36420@m73g2000cwd.googlegroups.com> Message-ID: <44EA096B.2060007@tim.thechases.com> > For the purposes of this question, the list will be: > > t = [ "a", "b", "c", "n", "a", "a", "t", "t", "t" ] > > Now, I know that every 3rd element of the list belongs together: > > Group 1 = 0, 3, 6 > Group 2 = 1, 4, 7 > Group 3 = 2, 5, 8 > > I'm trying to sort this list out so that I get a list of lists that > contain the correct elements: > > Goal = [ [ "a", "n", "t"], [ "b", "a", "t"], > ["c", "a", "t" ] ] Well, the following worked for me: >>> t = [ "a", "b", "c", "n", "a", "a", "t", "t", "t" ] >>> stride = 3 >>> Goal = [t[i::stride] for i in range(stride)] >>> Goal [['a', 'n', 't'], ['b', 'a', 't'], ['c', 'a', 't']] Or, if you like, in this example: >>> [''.join(t[i::stride]) for i in range(stride)] ['ant', 'bat', 'cat'] if that's of any use. -tkc From tlinux at comcast.net Sat Aug 19 20:11:19 2006 From: tlinux at comcast.net (Tom Strickland) Date: Sat, 19 Aug 2006 19:11:19 -0500 Subject: Permission Denied Message-ID: <44E7A8A7.3030502@comcast.net> Hopefully this is a simple question. I've started to program in Python after an absence of about a year, so I'm very rusty. I wrote a short program and tried to run it using Python2.4 in Linux. I keep getting "permission denied" messages after entering the path to the program. I switched to the root directory and tried again, but got the same result.I ran a very similar program earlier and it ran fine. What am I doing wrong? The program is: #!/usr/bin/python2.4 i=1 while i<10000: print 'step 1',i i+=1 raw_input() print 'step 2' Thank you. Tom From rogue_pedro at yahoo.com Sat Aug 12 14:01:21 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 12 Aug 2006 11:01:21 -0700 Subject: trouble with replace In-Reply-To: <1155405212.364916.262570@m79g2000cwm.googlegroups.com> References: <1155401390.926925.252000@m79g2000cwm.googlegroups.com> <pan.2006.08.12.17.00.37.48229@gmx.net> <1155403894.003417.269870@i42g2000cwa.googlegroups.com> <1155405212.364916.262570@m79g2000cwm.googlegroups.com> Message-ID: <1155405681.707924.195980@b28g2000cwb.googlegroups.com> Simon Forman wrote: > f pemberton wrote: > > Marc 'BlackJack' Rintsch wrote: > > > In <1155401390.926925.252000 at m79g2000cwm.googlegroups.com>, f pemberton > > > wrote: > > > > > > > I've tried using replace but its not working for me. > > > > xdata.replace('abcdef', 'highway') > > > > xdata.replace('defgef', 'news') > > > > xdata.replace('effwer', 'monitor') > > > > > > `replace()` does not work in place. You have to bind the result to a name > > > like:: > > > > > > xdata = xdata.replace('abcdef', 'highway') > > > > > > Ciao, > > > Marc 'BlackJack' Rintsch > > > > lol, you probably will not believe me but I actually knew that already. > > I just forgot to add that part in my original post. When I try and > > replace what happens is the first replace works fine but when I try and > > do a second replace on a different part of the same string, the program > > will print the string a second time(which I do not want). > > Um, don't print the string until after you're done replacing? :-) > > Seriously though, since there are no print statements, etc.., in your > posted code, it's hard to understand exactly what your problem is. > > > How can you > > do 2 or more replaces in one line of code? > > In any event, there is a neat method of "single-pass multiple string > substitution using a dictionary" here: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330 It uses > a regular expression, so I'd guess it wouldn't be to hard to get it to > work in multiline mode. > > Peace, > ~Simon Or just: xdata = xdata.replace('abcdef', 'highway').replace('defgef', 'news').replace('effwer', 'monitor') Hahahahaha ~Simon From gagsl-py at yahoo.com.ar Thu Aug 24 12:54:03 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 24 Aug 2006 13:54:03 -0300 Subject: String formatting with nested dictionaries In-Reply-To: <1156436560.040352.162580@b28g2000cwb.googlegroups.com> References: <1156436560.040352.162580@b28g2000cwb.googlegroups.com> Message-ID: <7.0.1.0.0.20060824134318.050afa88@yahoo.com.ar> At Thursday 24/8/2006 13:22, linnorm at gmail.com wrote: >I've got a bit of code which has a dictionary nested within another >dictionary. I'm trying to print out specific values from the inner >dict in a formatted string and I'm running into a roadblock. I can't >figure out how to get a value from the inner dict into the string. To >make this even more complicated this is being compiled into a large >string including other parts of the outer dict. > >mydict = {'inner_dict':{'Value1':1, 'Value2':2}, 'foo':'bar', >'Hammer':'nails'} > >print "foo is set to %(foo)s - Value One is: %(inner_dict['Value1'])s >and Value Two is: %(inner_dict['Value2'])s -- Hammers are used to pound >in %(Hammer)s" % mydict > >The above fails looking for a key named 'inner_dict['Value1']' which >doesn't exist. I can think of two ways: a) Flatten your dictionary. That is, move the contents of inner_dict onto the outer dict: mydict.update(mydict['inner_dict']) Then use single names for interpolation b) Do the interpolation in two steps. template = "foo is set to %(foo)s - Value One is: %(Value1)s and Value Two is: %(Value2)s -- Hammers are used to pound in %(Hammer)s" output = template % mydict['inner_dict'] output = output % mydict Both methods assume that the inner dict takes precedence in case of name clashes; reverse the order if you want the opposite. Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From fredrik at pythonware.com Sat Aug 26 01:55:58 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 26 Aug 2006 07:55:58 +0200 Subject: Problem with List of List In-Reply-To: <ecomr9$ps1$1@sea.gmane.org> References: <1156569535.500196.7920@i3g2000cwc.googlegroups.com> <ecomr9$ps1$1@sea.gmane.org> Message-ID: <econpd$r4i$1@sea.gmane.org> Fredrik Lundh wrote: >> I have a code >> ==================CODE============= >> List=[['1', 'a', '6'], ['1', 'b', '6'], ['1', 'c', '6'], >> ['1', 'd', '6'],['2', 'a','6'], ['2', 'b', '6'], >> ['2', 'c', '6'], ['2', 'd', '6'], ['3', 'a', '6'], >> ['3','b', '6'], ['4', 'a', '6'], ['4', 'b', '6']] >> >> >> for x in List: >> temp=[] >> print x >> for y in List: >> if x[0]==y[0]: >> print y[0],y[1] >> temp.append(y) >> for z in temp: >> List.remove(z) >> print 'rem', z > > the for loop uses an internal index to fetch items from the list you're > looping over, so if you remove items from it, you'll end up skipping > over items. forgot to mention that the fix is to change the first for statement to: for x in List[:]: </F> From skip at pobox.com Fri Aug 4 09:52:05 2006 From: skip at pobox.com (skip at pobox.com) Date: Fri, 4 Aug 2006 08:52:05 -0500 Subject: SWIG Python Extension winth C++ Problematic In-Reply-To: <c56a14170608032129vde5306elbaf72cda998d70ee@mail.gmail.com> References: <c56a14170608032129vde5306elbaf72cda998d70ee@mail.gmail.com> Message-ID: <17619.20741.271987.946155@montanaro.dyndns.org> >> I have been working getting my C++ code to be used in Python ( >> Basically Extending ) This is the problem i am facing rite now. >> >> I have a function that returns a Pointer to a class in my C++ Code >> >> It looks like this ... >> I have used SWIG to get the Glue code. >> >> When i call this function ( in python ) and it eventually returns ( >> when it gets a connection in this case ) it crashes ! I get a SEG >> FAULT ! >> >> Is it some thing that cannot be done ? I'm certainly no SWIG expert, however: 1. Is your SLSocket class wrapped with SWIG? Do you maybe need a typemap? Can you explicitly create one from Python? If so, does that work? 2. What does your SWIG .i file look like? 3. Finally, have you tried asking on the SWIG mailing list (swig-user at lists.sourceforge.net)? There are probably many more SWIG experts there than here. Skip From jzgoda at o2.usun.pl Mon Aug 21 15:52:57 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Mon, 21 Aug 2006 21:52:57 +0200 Subject: The decentralized nature of the Python community is driving me crazy In-Reply-To: <1155157572.915538.280350@i3g2000cwc.googlegroups.com> References: <1155157572.915538.280350@i3g2000cwc.googlegroups.com> Message-ID: <ecd33m$7kc$1@nemesis.news.tpi.pl> metaperl.bzr at gmail.com napisa?(a): > So, I guess this is my way of letting you know how lost I feel about > this de-centralized community. Dont get me wrong. I'm glad to be part > but I was thinking it would be nice if there were a one-stop-shop for > all my chat and wares needs. But for now, I guess I need to just add > few more bookmarks to main places to keep on top of daily besides > pythonware.com/daily. Centralization is bad. Believe me, I lived nearly 20 years under communist regime, I know what I am saying. You don't need centralization, all you need is aggregation upon agreed rules. We have good aggregator on Planet Python, we have growing package index in Cheeseshop (already aggregated on Planet) and good tips list on ASPN (also aggregated on Planet). I see the future is bright for us. -- Jarek Zgoda http://jpa.berlios.de/ From fredrik at pythonware.com Sun Aug 20 09:44:12 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Aug 2006 15:44:12 +0200 Subject: write eof without closing In-Reply-To: <ec7b65$pfo$1@netlx020.civ.utwente.nl> References: <ec72ev$4e0$1@netlx020.civ.utwente.nl> <pan.2006.08.19.13.56.56.122014@gmx.net> <ec7b65$pfo$1@netlx020.civ.utwente.nl> Message-ID: <ec9ovc$b9t$1@sea.gmane.org> cage wrote: > I want to use a program that has a 'pipe' mode, in which you can use > stdin to send commands to the program. I found out that, when in pipe > mode and you are using the keyboard as input source you can do Ctrl-D to > 'signal' the program that you have finished typing your command. The > program parses and then performs the command, and it doesn't quit. It > quits after 'Quit\n' + Ctrl-D have you tried *flushing* the output stream after each command? </F> From collinw at gmail.com Tue Aug 1 15:57:10 2006 From: collinw at gmail.com (Collin Winter) Date: Tue, 1 Aug 2006 15:57:10 -0400 Subject: [ANNOUNCE] functional 0.7.0 released Message-ID: <43aa6ff70608011257m5f852c85p8bf0223839a9e25b@mail.gmail.com> Hello all, I have released version 0.7.0 of my functional module, a collection of higher-order and functional programming tools for Python. Currently offered are tools for function composition, partial function application, plus filter, flip, foldl, foldr, map, scanl and scanr functions. Two version of the release are available: one is written in pure Python and aims for maximum readability and portability. The other is coded as a C extension module and is focused on raw performance. Where to get it: ######### functional is available from the Python Package Index at http://cheeseshop.python.org/pypi/functional/ Both source tarballs and Python Eggs are available for both the pure Python and C releases. Eggs are available for Python versions 2.3, 2.4 and 2.5. Release Notes ######## + functional now includes map() and filter() functions. These are roughly equivalent to the Python built-in functions, though without some of the weird/incorrect behaviour of the built-ins. Specifically: functional.map() works like the built-in, except functional.map() 1) always takes a single iterable, and 2) doesn't support the None nonsense that the built-in does. functional.filter() works like the built-in, except functional.filter() 1) iterates over subclasses of str, unicode and tuple correctly, 2) doesn't support the None nonsense that the built-in does, 3) always returns a list, unlike the built-in. + Several reference counting-related bugs have been squashed in the C implementation. + The test suite has been enhanced to do reference count checking after each test, making it much easier to track down future errors in the C implementation. + The C implementation now supports Python 2.3, in addition to 2.4 and 2.5 As always, feedback welcome! Collin Winter From johnjsal at NOSPAMgmail.com Tue Aug 8 12:06:42 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 08 Aug 2006 16:06:42 GMT Subject: Tkinter module not found In-Reply-To: <1155052842.806353.18120@i3g2000cwc.googlegroups.com> References: <1155049496.292471.37020@h48g2000cwc.googlegroups.com> <t62Cg.2648$No6.52006@news.tufts.edu> <mailman.9099.1155052421.27775.python-list@python.org> <1155052842.806353.18120@i3g2000cwc.googlegroups.com> Message-ID: <mE2Cg.2651$No6.51848@news.tufts.edu> Shuaib wrote: > Hey again, > > I am using the latest python available on my system (2.4). So I don't > think that's the problem. > > Any more ideas? Do I need to install Tkinter as a seperate > module/package? As I said, I've already installed Tcl/Tk, though. Hmm, yes, I think tkinter is separate from Tk, so you might try doing a search for it in your repositories and see if something comes up that you don't have installed yet. From rbonvall at cern.ch Wed Aug 30 10:23:35 2006 From: rbonvall at cern.ch (Roberto Bonvallet) Date: 30 Aug 2006 14:23:35 GMT Subject: dictionary with object's method as thier items References: <1156944917.152606.213600@i42g2000cwa.googlegroups.com> Message-ID: <ed4717$m1h$1@sunnews.cern.ch> noro wrote: > Is it possible to do the following: > > for a certain class: [...] > by some way create a dictionary that look somthing like that: > > d= {'function one': <reference to C.func1()>, \ > 'function two': <reference to C.func2()>, \ > 'function three': <reference to C.func3()>} > > and so i could access every method of instances of C Something like this? >>> class C: ... def f1(self): ... print "i'm one" ... def f2(self): ... print "i'm two" ... >>> obj = C() >>> d = {'one': obj.f1, 'two': obj.f2} >>> d['one']() i'm one >>> d['two']() i'm two -- Roberto Bonvallet From ajaksu at gmail.com Mon Aug 21 12:50:50 2006 From: ajaksu at gmail.com (ajaksu) Date: 21 Aug 2006 09:50:50 -0700 Subject: What do you want in a new web framework? In-Reply-To: <1156173509.767030.255710@b28g2000cwb.googlegroups.com> References: <1156100331.329889.216340@p79g2000cwp.googlegroups.com> <pan.2006.08.20.19.48.34.996227@gmx.net> <1156156636.515678.118210@75g2000cwc.googlegroups.com> <1156173509.767030.255710@b28g2000cwb.googlegroups.com> Message-ID: <1156179050.748349.201550@h48g2000cwc.googlegroups.com> Hello Emrah :) I'd love to have a good framework with focus on static-content. Something simple and useful like rest2web (http://www.voidspace.org.uk/python/rest2web/) that could parse some of the many templates available and output nice (X)HTML+CSS. Bundle a simple GUI and you have something very interesting. hardemr wrote: Maybe, it's a mix of web frameworks. I want to > use dojo toolkit for javascript in my framework, and make a gui > designer like Visual Studio and Sun Creator, etc... How about skipping the framework and focusing on dojo + GUI? Choose a target (templating + framework, or a couple of targets), build a Visual Studio for AJAX and you'll be a hero. Hack wxScintilla and build something with good template highlighting and WYSIWYG-ish preview and you'll be very famous. Build a great framework and yours will be one of the many ;) Wishing you good luck, Daniel From sjmachin at lexicon.net Thu Aug 17 01:13:56 2006 From: sjmachin at lexicon.net (John Machin) Date: 16 Aug 2006 22:13:56 -0700 Subject: Newbie needs Help In-Reply-To: <s4s7e2tovtl41nnik6ij8bam40dh9343ma@4ax.com> References: <1155783551.689026.273260@m73g2000cwd.googlegroups.com> <s4s7e2tovtl41nnik6ij8bam40dh9343ma@4ax.com> Message-ID: <1155791636.154923.134690@m79g2000cwm.googlegroups.com> Dennis Lee Bieber wrote: > c.execute("insert into %s (%s) values (%s)" > % ("statecode", > ", ".join(data.keys() ), > ", ".join(["%s"] * len(data.keys() ) ) ), > data.values() ) > # NOTE: only works if data.keys() and data.values() are > # in the same order. > It is guaranteed, provided you don't mutate the dictionary between times. In any case, it's a bit hard to imagine under what circumstances there would be different traversal orders to obtain keys and values :-) From peter.maas at somewhere.com Wed Aug 23 16:13:07 2006 From: peter.maas at somewhere.com (Peter Maas) Date: Wed, 23 Aug 2006 22:13:07 +0200 Subject: What do you want in a new web framework? In-Reply-To: <1hkgnbt.ebn4o1111ftp0N%aleax@mac.com> References: <1156100331.329889.216340@p79g2000cwp.googlegroups.com> <pan.2006.08.20.19.48.34.996227@gmx.net> <1156156636.515678.118210@75g2000cwc.googlegroups.com> <4jele2pe011di99c5dnq4olclglrkieggc@4ax.com> <1hkgnbt.ebn4o1111ftp0N%aleax@mac.com> Message-ID: <ecicsj$91v$1@online.de> Alex Martelli wrote: > Indeed, it has been truthfully observed that Python's the only language > with more web frameworks than keywords. > > I have already suggested to the BDFL that he can remedy this situation > in Py3k: all he has to do, of course, is to add a LOT more keywords. Here is another remedy: he adds one of the frameworks to the standard library :) Peter Maas, Aachen From siona at chiark.greenend.org.uk Wed Aug 23 06:54:08 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 23 Aug 2006 11:54:08 +0100 (BST) Subject: key not found in dictionary References: <1156272596.613723.219280@h48g2000cwc.googlegroups.com> <44EB5632.3060505@hotmail.com> Message-ID: <uVx*0ZWor@news.chiark.greenend.org.uk> Chaz Ginger <cginboston at hotmail.com> wrote: >KraftDiner wrote: >> desc = self.numericDict[k][2] >> KeyError: 589824 <---- This is the error that is being produced, >As stated you can wrap the access in the try - except - else statement, >as in > >try: > foo['bar'] >except : > # Handle the error. Bare "except" is generally a bad idea. Here, it could be letting through whole truckloads of other errors. Suppose the OP typos: try: desc = self.numericDict[j][2] except: # handle missing key but the except isn't handling a KeyError, it's got a NameError (assuming j doesn't exist). Or what if self.numericDict[k] exists but self.numericDict[k][2] gives a TypeError or IndexError? It really needs to be: except KeyError: -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From UrsusMaximus at gmail.com Mon Aug 21 14:06:14 2006 From: UrsusMaximus at gmail.com (UrsusMaximus at gmail.com) Date: 21 Aug 2006 11:06:14 -0700 Subject: What do you want in a new web framework? In-Reply-To: <1156173509.767030.255710@b28g2000cwb.googlegroups.com> References: <1156100331.329889.216340@p79g2000cwp.googlegroups.com> <pan.2006.08.20.19.48.34.996227@gmx.net> <1156156636.515678.118210@75g2000cwc.googlegroups.com> <1156173509.767030.255710@b28g2000cwb.googlegroups.com> Message-ID: <1156183574.781794.11340@p79g2000cwp.googlegroups.com> hardemr wrote: > I've just read all of the answers. Most of yours said that there are > many web frameworks ,so it is nonsense to make a new web framework in > python. Hardemr, I like Ajacksu's answer, with a twist. Please concnentrate on writing a Visual Studio-like gui designer, and make it possible to add your Visual Studio like gui designer to Django (and TurboGears, et al). Leverage the hard work of others and the installed base; add your functionality on top. Don't re-create the wheel, build your internal combustion engine powered vehicle on top of the 4 wheels that already exist! ;-)) Please... Ron Stephens From pmartin at snakecard.com Thu Aug 3 16:58:26 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Thu, 03 Aug 2006 15:58:26 -0500 Subject: [Linux] What toolkit for a good grid/spreadsheet widget? References: <6fo4d2h0lnq2qcgi8jknh0ddmphhdgaulj@4ax.com> Message-ID: <XutAg.4400$W93.3598@dukeread05> Vincent Delporte wrote: > Hello > > I'd like to use Python under Linux to write a business application, > and I'll need a good grid/spreadsheet editable widget, maybe not on > par with eg. ComponentOne's excellent VSFlexGrid > (http://www.componentone.com/newimages/flexgrid_02_lg.gif), but > somewhat professional-grade. > > Any recommendation? GTK doesn't seem to have one that is good enough > (GTKSheet http://gtkextra.sourceforge.net/ looks like a basic table), > so I was wondering about QT/PyQt and wxWidgets/wxPython. Any > recommendation? > > Thank you > VD. http://www.wxpython.org/ Search for "Grid" here: http://www.wxpython.org/onlinedocs.php Regards, Philippe From antroy at gmail.com Mon Aug 7 06:54:15 2006 From: antroy at gmail.com (Ant) Date: 7 Aug 2006 03:54:15 -0700 Subject: How to get hours and minutes from 'datetime.timedelta' object? In-Reply-To: <1154942169.530491.150390@h48g2000cwc.googlegroups.com> References: <1154940942.707530.291130@m79g2000cwm.googlegroups.com> <1154942169.530491.150390@h48g2000cwc.googlegroups.com> Message-ID: <1154948054.987468.202100@i3g2000cwc.googlegroups.com> John Machin wrote: > Lad wrote: > > Hello, > > what is the best /easest way how to get number of hours and minutes > > from a timedelta object? ... > >>> diff.days > 0 > >>> diff.seconds > 52662 > >>> diff.microseconds > 922000 > >>> minutes = (diff.seconds + diff.microseconds / 1000000.0) / 60.0 > >>> minutes > 877.71536666666668 I suspect what Lad wanted was something more like: >>> def secs_mins_hours(timed): ... total_secs = timed.seconds ... secs = total_secs % 60 ... total_mins = total_secs / 60 ... mins = total_mins % 60 ... hours = total_mins / 60 ... return (secs, mins, hours) >>> aa=datetime.datetime(2006, 7, 29, 16, 13, 56, 609000) >>> bb=datetime.datetime(2006, 8, 3, 17, 59, 36, 46000) >>> td = aa - bb >>> secs_mins_hours(td) (39, 45, 1) I'm surprised that the timedelta class hasn't got secs, mins and hours properties - they could be generated on the fly in a similar way. From Iljya.Kalai at gmail.com Wed Aug 16 11:11:20 2006 From: Iljya.Kalai at gmail.com (Iljya) Date: 16 Aug 2006 08:11:20 -0700 Subject: Error with: pickle.dumps(numpy.float32) In-Reply-To: <1155670034.655485.214360@i3g2000cwc.googlegroups.com> References: <1155670034.655485.214360@i3g2000cwc.googlegroups.com> Message-ID: <1155741080.438315.192040@b28g2000cwb.googlegroups.com> I have reproduced the error with Numpy 1.0b1 The output with v.1.0b1 reads: PicklingError: Can't pickle <type 'float32scalar'>: it's not found as __builtin__.float32scalar Has anyone else encountered this? Thanks, Iljya Iljya wrote: > Hello, > > I need to pickle the type numpy.float32 but encounter an error when I > try to do so. I am able to pickle the array itself, it is specifically > the type that I cannot pickle. > > I am using: > Numpy version: 0.9.4 > Python version: 2.4.3 > Windows XP > > Here is the code that reproduces the error: > ______________________________________ > import numpy > import pickle > > pickle.dumps(numpy.float32) > > Output: > PicklingError: Can't pickle <type 'float32_arrtype'>: it's not found as > __builtin__.float32_arrtype > ______________________________________ > > Any suggestions would be much appreciated. > > Thanks, > > Iljya Kalai From david_wahler at bic.ky Thu Aug 3 12:55:43 2006 From: david_wahler at bic.ky (david_wahler at bic.ky) Date: 3 Aug 2006 11:55:43 -0500 Subject: [ANN] The argparse module Message-ID: <20060803165543.23046.qmail@BICSRV1011.bic.ky> I'll be out of the office until approximately August 20th. If you have any questions, please email support at bic.ky. -- David Wahler From stanc at al.com.au Fri Aug 18 17:53:28 2006 From: stanc at al.com.au (Astan Chee) Date: Sat, 19 Aug 2006 07:53:28 +1000 Subject: urllib2, proxies and https Message-ID: <44E636D8.2030205@al.com.au> Hi again, According to https://demo.launchpad.net/products/python/+bug/56872 or more specifically, the example of its working code: http://librarian.demo.launchpad.net/3507227/urllib2_proxy_auth.py I can use urllib2 via proxy to access a https site(specifically hooking it up to libgmail). The problem is that the proxy that is accessible to me is http/port8080 only. Is it possible to use urllib2 with this proxy to access a https site? (im guessing no, but im sure there are ways around it). I've tried modifying the code to point to a https site (https://mail.google.com/mail/) without changing the http proxy and it produces a HTTP timeout error. Despite this, if I manually use a web browser to access these sites it prompts me with the proxy login and lets me through. So im also puzzled here why my browser lets this happen but urllib2 doesnt. Thanks again for all your help. Cheers Astan From pmartin at snakecard.com Fri Aug 4 10:38:27 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Fri, 04 Aug 2006 09:38:27 -0500 Subject: [Linux] What toolkit for a good grid/spreadsheet widget? References: <6fo4d2h0lnq2qcgi8jknh0ddmphhdgaulj@4ax.com> <mailman.8938.1154639225.27775.python-list@python.org> <ma85d2lg1l260fmgg6k14kcqu6al2ift3c@4ax.com> <44d2eebb$0$7764$7a628cd7@news.club-internet.fr> Message-ID: <51JAg.4426$W93.2804@dukeread05> jean-michel bain-cornu wrote: > Hi, >> Thx for the two pointers. Are those widgets more than just tables, ie. >> can I edit the contents, including displaying a combo box, can items >> be grouped or hierarchized, or are they just basic, read-only tables >> to display results? >> >> I need this kind of widget to build a 2+ column interface to let users >> type entries into the application as an alternative to MS Access-style >> complicated entry masks. > > Wx have got an excellent one. I was succesful to use it with editable > cells and to include a choice in a cell. However, it was pretty hard to > reach that, ie to extract a working sample from the demo. Once done > that, no more problems with it. > What I suggest you is to have a look on the demo, in the chapter "Core > Windows/Controls -> Grid -> wx.Grid showing Editors and Renderers". > Rgds, > jm Yes, I can also select which cell can be edited on the cell level. From pavlovevidence at gmail.com Fri Aug 25 18:51:25 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 25 Aug 2006 15:51:25 -0700 Subject: When is a subclass not right? In-Reply-To: <1156533153.847764.311990@75g2000cwc.googlegroups.com> References: <1156387621.568779.191420@m73g2000cwd.googlegroups.com> <1156393371.550249.138930@75g2000cwc.googlegroups.com> <1156394781.155152.313080@i3g2000cwc.googlegroups.com> <Xns98293000DF07castleamber@130.133.1.4> <44ede9b8$0$8925$88260bb3@free.teranews.com> <Xns982990962CE4castleamber@130.133.1.4> <w0nHg.2718$HW1.1810@trndny03> <1156452136.196964.193620@i42g2000cwa.googlegroups.com> <1156533153.847764.311990@75g2000cwc.googlegroups.com> Message-ID: <1156546285.463116.174860@i42g2000cwa.googlegroups.com> David Ells wrote: > Carl Banks wrote: > > The classical advice in choosing whether to subclass or or use > > attribute is whether its more an an "is a" or "has a" relationship. If > > it's more natural to say B is an A, then subclass. If it's more > > natural to say B has an A, then use an attribute. But that's only a > > rule of thumb. > > > > I personally find another question helpful. If it's reasonable that B > > could have more than one of A, regardless if it actually does, use an > > attribute. If it's unreasonable, subclass. Again, rule of thumb. > > This is not always the defining line between when to use inheritance > vs. when to use composition. I really don't think a defining line exists. Some situatations exist where either will do, and as I've said I've often switched between them as my code develops. Sometimes the best choice is due to some technicality. "is a" vs "has a" is only a guideline, in situations where it isn't obvious, to hopefully but not certainly avoid a future switch. Same thing for other guideline I posted. If the guideline turns out to pick the wrong way, big deal, you fix it when refactoring. You're not afraid of refactoring, are you? :) Carl Banks From chris at kateandchris.net Tue Aug 8 15:05:18 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Tue, 8 Aug 2006 15:05:18 -0400 Subject: Extending/Embedding Confusion In-Reply-To: <1154717474.528297.285240@i42g2000cwa.googlegroups.com> References: <1154717474.528297.285240@i42g2000cwa.googlegroups.com> Message-ID: <20060808190518.GB12723@kateandchris.net> Depending on what you are trying to do you might be better off to start by using Pyrex, Boost::Python or Swig. http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/ http://www.boost.org/libs/python/doc/ http://www.swig.org/ -Chris On Fri, Aug 04, 2006 at 11:51:14AM -0700, jeremito wrote: > I am trying to learn how to extend and/or embed Python. I have looked > at the document "Extending and Embedding the Python Interpreter" and > also "Python/C API Reference Manual. In the examples shown in > "Extending..." there are some things I ma not familiar with so I turn > to the index in the Reference Manual, but they are not listed. For > example, PyEval_CallObject and PyDict_GetAttrString. My question is > this: Is the documentation out of date or is the index not complete? > Where can I get information about these things? > > Secondly, I am really struggling with understanding how to Extend/Embed > Python. The examples given in the documentation are not as helpful as > I would hope. Does anyone know of additional examples on the web that > will shed some light on this issue? I have tried Google, but haven't > yet been successful in finding additional examples that help. > Thanks, > Jeremy > > -- > http://mail.python.org/mailman/listinfo/python-list From bignose+hates-spam at benfinney.id.au Thu Aug 24 17:34:36 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 25 Aug 2006 07:34:36 +1000 Subject: blindness and top vs. bottom posting References: <1156387621.568779.191420@m73g2000cwd.googlegroups.com> <1156393371.550249.138930@75g2000cwc.googlegroups.com> <1156394781.155152.313080@i3g2000cwc.googlegroups.com> <Xns98293000DF07castleamber@130.133.1.4> <44ede9b8$0$8925$88260bb3@free.teranews.com> <44EDFCE6.9060800@tim.thechases.com> Message-ID: <877j0xx1g3.fsf@benfinney.id.au> Tim Chase <python.list at tim.thechases.com> writes: > > I am a member of another list that has at least one member who has > > lost his vision, and reads his news with a speech generator. It > > is terribly inconvenient for him to follow a thread full of > > 'bottom postings', as he is then forced to sit through the > > previous message contents again and again in search of the new > > content. > > I'm involved on the Blind Linux users (Blinux) list, and they seem > to have no problem bottom-posting. > > There are a variety of tools for converting bottom-posting into more > readable formats. If you want to suppress comments, a quality MUA > can suppress them. The parent poster is complaining about a straw man. As they point out, "bottom posting" is almost as bad as top posting. Both practices leave the entire content of quoted material intact, regardless of which parts are relevant. The correct solution to both top posting *and* bottom posting is "interleaved posting", but more importantly to trim away everything except the quoted material necessary for giving context to one's response. This is of even greater assistance to the blind, who then have just the necessary context to understand the current message. <URL:http://en.wikipedia.org/wiki/Top_posting> -- \ "We are not gonna be great; we are not gonna be amazing; we are | `\ gonna be *amazingly* amazing!" -- Zaphod Beeblebrox, _The | _o__) Hitch-Hiker's Guide To The Galaxy_, Douglas Adams | Ben Finney From eugene at boardkulture.com Mon Aug 14 09:22:26 2006 From: eugene at boardkulture.com (3KWA) Date: 14 Aug 2006 06:22:26 -0700 Subject: sending mailing list with smtplib Message-ID: <1155561746.812918.128770@h48g2000cwc.googlegroups.com> Hi all, I tried to send a small mailing list using python today (2036 emails). For that purpose I looked in the doc for some code examples (I had never done it before). And I ended up writing and running this little script: # list.txt is a text file container an email per line fp=open('list.txt','r') list=fp.readlines() fp.close() # message.txt is the plaine text message to send textfile='message.txt' subject='[xsbar] alive and kicking' me='eugene at xsbar.com' # rom and example in the doc import smtplib from email.MIMEText import MIMEText fp = open(textfile, 'rb') msg = MIMEText(fp.read()) fp.close() # ... but the actual message sending in a loop to send one email each (didn't work) for line in list: you=line[:-1] msg['Subject'] = subject msg['From'] = me msg['To'] = you s = smtplib.SMTP() s.connect() s.sendmail(me, [you], msg.as_string()) s.close() but it copied all the recipients in the header (To:) which I don't understand? Can someone help me understand what I did wrong? Thanks, EuGeNe From thn at mail.utexas.edu Mon Aug 14 16:50:31 2006 From: thn at mail.utexas.edu (Thomas Nelson) Date: 14 Aug 2006 13:50:31 -0700 Subject: Memory problem In-Reply-To: <mailman.9325.1155587201.27775.python-list@python.org> References: <mailman.9320.1155580347.27775.python-list@python.org> <85mdnb4jzcpTRH3ZnZ2dnUVZ_t6dnZ2d@comcast.com> <mailman.9325.1155587201.27775.python-list@python.org> Message-ID: <1155588631.739903.94160@h48g2000cwc.googlegroups.com> Yi Xing wrote: > On a related question: how do I initialize a list or an array with a > pre-specified number of elements, something like > int p[100] in C? I can do append() for 100 times but this looks silly... > > Thanks. > > Yi Xing Use [0]*100 for a list. THN From fredrik at pythonware.com Thu Aug 24 12:24:19 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Aug 2006 18:24:19 +0200 Subject: sum and strings In-Reply-To: <44EDCFDE.9060604@tim.thechases.com> References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <slrneeatf3.nbt.sybrenUSE@schuimige.stuvel.eu> <1155922208.930580.135080@m79g2000cwm.googlegroups.com> <mailman.9516.1155930431.27775.python-list@python.org> <1156365271.487489.62640@m73g2000cwd.googlegroups.com> <44ECC789.1010202@tim.thechases.com> <ecjga9$558$1@sea.gmane.org> <44EDCFDE.9060604@tim.thechases.com> Message-ID: <eckjri$cu$1@sea.gmane.org> Tim Chase wrote: > The interpreter is clearly smart enough to recognize when the > condition occurs such that it can throw the error...thus, why not > add a few more smarts and have it simply translate it into > "start+''.join(sequence)" to maintain predictable behavior > according to duck-typing? "join" doesn't use __add__ at all, so I'm not sure in what sense that would be more predictable. I'm probably missing something, but I cannot think of any core method that uses a radically different algorithm based on the *type* of one argument. besides, in all dictionaries I've consulted, the word "sum" means "adding numbers". are you sure it wouldn't be more predictable if "sum" converted strings to numbers ? (after all, questions about type errors like "cannot concatenate 'str' and 'int' objects" and "unsupported operand type(s) for +: 'int' and 'str'" are a *lot* more common than questions about sum() on string lists.) </F> From claudio.grondi at freenet.de Mon Aug 28 03:31:59 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Mon, 28 Aug 2006 09:31:59 +0200 Subject: Misleading error message when opening a file (on Windows XP SP 2) Message-ID: <ecu65e$12o$1@newsreader2.netcologne.de> Here an example of what I mean (Python 2.4.2, IDLE 1.1.2, Windows XP SP2, NTFS file system, 80 GByte large file): >>> f = file('veryBigFile.dat','r') >>> f = file('veryBigFile.dat','r+') Traceback (most recent call last): File "<pyshell#1>", line 1, in -toplevel- f = file('veryBigFile.dat','r+') IOError: [Errno 2] No such file or directory: 'veryBigFile.dat' Is it a BUG or a FEATURE? Claudio Grondi From f.braennstroem at gmx.de Tue Aug 8 01:42:17 2006 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Tue, 8 Aug 2006 07:42:17 +0200 Subject: email client like mutt References: <mailman.9013.1154800822.27775.python-list@python.org> <eb5ikc$2q2$1@panix1.panix.com> <mailman.9054.1154964178.27775.python-list@python.org> <eb8m68$jti$1@panix3.panix.com> <20060808021213.GD20884@turki.gavron.org> Message-ID: <eb987j$rpm$1@sea.gmane.org> Hi to both, * cga2000 <cga2000 at optonline.net> wrote: > On Mon, Aug 07, 2006 at 08:34:16PM EDT, Aahz wrote: >> In article <mailman.9054.1154964178.27775.python-list at python.org>, >> cga2000 <cga2000 at optonline.net> wrote: >> >On Sun, Aug 06, 2006 at 04:15:08PM EDT, Aahz wrote: >> >> In article <mailman.9013.1154800822.27775.python-list at python.org>, >> >> Fabian Braennstroem <f.braennstroem at gmx.de> wrote: >> >>> >> >>>I am looking for a python email client for the terminal... something like >> >>>mutt; maybe, so powerfull ;-) >> >> >> >> What's wrong with mutt? >> > >> >Like he says it's not written in python. >> >> Yes, I see that, but that doesn't answer my question. Not every >> application in the world needs to be written in Python. (Note that I'm >> a mutt user myself.) > > Well.. I'm also curious why he wants it to be written in python, so I > thought we could join forces. > > Incidentally I've been looking for a general-purpose application written > in python/ncurses for some time and haven't found anything. > > Looks like no new terminal application was written in the last ten years > or so. I guess that would rule out python..? I like mutt a lot, but at work I have to use lotus notes and I thought that I could use an existing python mail client to read and write mail 'around ' the lotus environment... that probably does not work anyways!? The second idea, which is more a working together with mutt, was to send files from 'lfm' (last file manager), which is completely written in python. I want to open mutt from lfm and automatically attach the marked files to the email... Greetings! Fabian From diffuser78 at gmail.com Fri Aug 11 12:31:36 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 11 Aug 2006 09:31:36 -0700 Subject: How to write a Installer for a Python App in Linux In-Reply-To: <44db9939$0$6062$636a55ce@news.free.fr> References: <1155240625.157696.143230@i42g2000cwa.googlegroups.com> <44db9939$0$6062$636a55ce@news.free.fr> Message-ID: <1155313896.329325.115710@m73g2000cwd.googlegroups.com> I saw some examples and understood for most part how to write a setpu.py. Since I want to bundle python and wxPython along with my application...how can I do that. Any code gurus can throw some pointers. Every help is appreciated. Bruno Desthuilliers wrote: > Look for distutil and EasyInstall (-> Python Eggs) From duncan.booth at invalid.invalid Wed Aug 30 08:58:30 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 Aug 2006 12:58:30 GMT Subject: where or filter on list References: <1156939493.558819.8410@i42g2000cwa.googlegroups.com> <mailman.10108.1156940286.27775.python-list@python.org> Message-ID: <Xns982F8DAB3355Cduncanbooth@127.0.0.1> skip at pobox.com wrote: > Another way might be to sort by absolute value: > > intermed = [(abs(v), v) for v in foo] > intermed.sort() > intermed[0][1] It is slightly simpler if you use sorted (assuming a recent enough Python): intermed = sorted(foo, key=abs) print intermed[0] The sorted list is of course the best way if you want to find not just one value but a group, e.g. the n nearest to 0. For nearest to a non-zero value v the version with sorted becomes: intermed = sorted(foo, key=lambda x:abs(x-v)) From tim.golden at viacom-outdoor.co.uk Tue Aug 22 05:48:25 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 22 Aug 2006 10:48:25 +0100 Subject: How can I enumerate all windows services and disable some of them? Message-ID: <CCAC78D42E32184F8E26DC163DB98306C1B3B6@vogbs009.gb.vo.local> [Tim Golden] | [could.net at gmail.com] | | | I know that Module win32service has some functions on manipulating | | win32 services. | | But I still have 2 questions: | | 1. how to enumerate all services? | | 2. how to disable a certain one? | | You can use WMI to do this if you want. ... or I could actually read the question before answering. I don't know if you can actually *disable* a service from WMI. You can certainly stop it, but the status appears to be a read-only option. Sorry TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From fakeaddress at nowhere.org Sun Aug 27 11:10:04 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 27 Aug 2006 15:10:04 GMT Subject: avoiding file corruption In-Reply-To: <12f3bo1t1ccr858@corp.supernews.com> References: <1156664673.325201.271140@i42g2000cwa.googlegroups.com> <12f3bo1t1ccr858@corp.supernews.com> Message-ID: <gBiIg.3482$yO7.688@newssvr14.news.prodigy.com> Grant Edwards wrote: > Amir Michail wrote: > >> Trying to open a file for writing that is already open for writing >> should result in an exception. > > MS Windows seems to do something similar, and it pisses me off > no end. Trying to open a file and read it while somebody else > has it open for writing causes an exception. If I want to open > a file and read it while it's being writtent to, that's my > business. Windows is actually much more sophisticated. It does allows shared write access; see the FILE_SHARE_WRITE option for Win32's CreateFile. You can also lock specific byte ranges in a file. -- --Bryan From john106henry at hotmail.com Thu Aug 10 17:04:02 2006 From: john106henry at hotmail.com (John Henry) Date: 10 Aug 2006 14:04:02 -0700 Subject: using python to edit a word file? References: <aJKCg.2673$No6.52073@news.tufts.edu> Message-ID: <1155243842.247393.109250@p79g2000cwp.googlegroups.com> John Salerno wrote: > I figured my first step is to install the win32 extension, which I did, > but I can't seem to find any documentation for it. A couple of the links > on Mark Hammond's site don't seem to work. > > Anyway, all I need to do is search in the Word document for certain > strings and either delete them or replace them. Easy enough, if only I > knew which function, etc. to use. > > Hope someone can push me in the right direction. > > Thanks. The easiest way for me to do things like this is to do it in Word and record a VB Macro. For instance you will see something like this: Selection.Find.ClearFormatting Selection.Find.Replacement.ClearFormatting With Selection.Find .Text = "save it" .Replacement.Text = "dont save it" .Forward = True .Wrap = wdFindContinue .Format = False .MatchCase = False .MatchWholeWord = False .MatchByte = False .CorrectHangulEndings = False .MatchAllWordForms = False .MatchSoundsLike = False .MatchWildcards = False .MatchFuzzy = False End With Selection.Find.Execute Replace:=wdReplaceAll and then hand translate it to Win32 Python, like: wordApp = Dispatch("Word.Application") wordDoc=wordApp.Documents.Add(...some word file name...) wordRange=wordDoc.Range(0,0).Select() sel=wordApp.Selection sel.Find.ClearFormatting() sel.Find.Replacement.ClearFormatting() sel.Find.Text = "save it" sel.Find.Replacement.Text = "dont save it" sel.Find.Forward = True sel.Find.Wrap = constants.wdFindContinue sel.Find.Format = False sel.Find.MatchCase = False sel.Find.MatchWholeWord = False sel.Find.MatchByte = False sel.Find.CorrectHangulEndings = False sel.Find.MatchAllWordForms = False sel.Find.MatchSoundsLike = False sel.Find.MatchWildcards = False sel.Find.MatchFuzzy = False sel.Find.Find.Execute(Replace=constants.wdReplaceAll) wordDoc.SaveAs(...some word file name...) Can't say that this works as I typed because I haven't try it myself but should give you a good start. Make sure you run the makepy.py program in the \python23\lib\site-packages\win32com\client directory and install the "MS Word 11.0 Object Library (8.3)" (or something equivalent). On my computers, this is not installed automatically and I have to remember to do it myself or else things won't work. Good Luck. From bounces at foo.org Tue Aug 1 22:55:17 2006 From: bounces at foo.org (Dan) Date: Wed, 02 Aug 2006 02:55:17 GMT Subject: Windows vs. Linux In-Reply-To: <1154448131_10257@news-east.n> References: <mailman.8771.1154395556.27775.python-list@python.org> <1154448131_10257@news-east.n> Message-ID: <puUzg.25915$RI1.10140@trndny04> Edmond Dantes wrote: > Dan wrote: > >> But taken out of that context, I'll challenge it. I was first exposed >> to Python about five or six years ago--my boss asked me to consider it. >> What I found was that the current version of Python was V2.2, but newest >> version (that I could find) that ran on VMS was V1.4. I decided to >> stick with Perl, which provides excellent support for VMS. > > What, you couldn't just take the latest source for Python and compile it > under VMS? > > :-) > > I say that in jest, but I am surprised there were no Unix/Linux libraries > available for VMS, which would've made the port easier -- and more up to > date. > Well, I never looked into a port, but there were certainly Unix libraries available for VMS. (I believe VMS is POSIX-compliant, but don't quote me on that.) /Dan -- dedded att verizon dott net From sjmachin at lexicon.net Sat Aug 19 08:28:08 2006 From: sjmachin at lexicon.net (John Machin) Date: 19 Aug 2006 05:28:08 -0700 Subject: How to get the ascii code of Chinese characters? References: <1155986298.643983.157460@i3g2000cwc.googlegroups.com> Message-ID: <1155990488.395220.178810@74g2000cwt.googlegroups.com> many_years_after wrote: > Hi,everyone: > > Have you any ideas? > > Say whatever you know about this. > Perhaps you had better explain what you mean by "ascii code of Chinese characters". Chinese characters ("hanzi") can be represented in many ways on a computer, in Unicode as well as many different "legacy" encodings, such as GB, GBK, big5, two different 4-digit telegraph codes, etc etc. They can also be spelled out in "roman" letters with or without tone indications (digits or "accents") in the pinyin system -- is that what you mean by "ascii code"? Perhaps you might like to tell us what you want to do in Python with hanzi and "ascii codes", so that we can give you a specific answer. With examples, please -- like what are the "ascii codes" for the two characters in the common greeting that comes across in toneless pinyin as "ni hao"? Cheers, John From sjmachin at lexicon.net Wed Aug 16 19:55:55 2006 From: sjmachin at lexicon.net (John Machin) Date: 16 Aug 2006 16:55:55 -0700 Subject: python-dev and setting up setting up f2py on Windows XP In-Reply-To: <1155744270.092818.256290@i42g2000cwa.googlegroups.com> References: <1155744270.092818.256290@i42g2000cwa.googlegroups.com> Message-ID: <1155772555.802594.252590@74g2000cwt.googlegroups.com> Sile wrote: > Hi, > > I've been trying to get f2py working on Windows XP, I am using Python > 2.3. I'm new to python so I'm not too sure what I'm doing yet. I need > the python-dev package to run f2py. I have been told this is just the > header files and .dll and I need to put them somewhere my C compiler > can find them. I've searched the web and none of the python-dev > packages I've found are for windows. I was wondering is this > automatically part of the windows version and if so how I set it up so > my C compiler can find them. If it is not part of the standard package > does anyone know where I can find it??? > > Any help at all would be much appreciated. The concept of "python-dev package" is a Debian concept which doesn't apply to Windows. The standard installation on Windows provides the header and library files that you need for interfacing with C. Don't put things where your C compiler can find them; do a standard no-frills install of Python2.4 using the .msi installer and tell your C compiler where the goodies are. E.g. using the MinGW32 gcc, you'd need things like: gcc -I\python24\include -lpython24 -L\python24\libs [first is "i".upper(), second is "L".lower()] Which C compiler are you using? You will need to add "C:\Python24" to the path so that you can invoke python easily; that will also enable anything else finding python24.dll if you do a "me only" install of Python. So give that a whirl and if you have any dramas, come back with questions ... HTH, John From claudio.grondi at freenet.de Fri Aug 25 10:04:02 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Fri, 25 Aug 2006 16:04:02 +0200 Subject: random writing access to a file in Python Message-ID: <ecn00i$t2o$1@newsreader2.netcologne.de> I have a 250 Gbyte file (occupies the whole hard drive space) and want to change only eight bytes in this file at a given offset of appr. 200 Gbyte (all other data in that file should remain unchanged). How can I do that in Python? Claudio Grondi From fakeaddress at nowhere.org Sat Aug 5 04:01:21 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 05 Aug 2006 08:01:21 GMT Subject: Thread Question In-Reply-To: <1154690942.385855.41130@m79g2000cwm.googlegroups.com> References: <1153998422.670828.148360@m79g2000cwm.googlegroups.com> <1154019801.999805.150000@m73g2000cwd.googlegroups.com> <mailman.8857.1154541684.27775.python-list@python.org> <1154544553.990241.280030@i3g2000cwc.googlegroups.com> <1154590917.731457.106230@s13g2000cwa.googlegroups.com> <1154613366.350191.81880@m73g2000cwd.googlegroups.com> <1154676387.063576.100570@i42g2000cwa.googlegroups.com> <1154690942.385855.41130@m79g2000cwm.googlegroups.com> Message-ID: <lfYAg.3102$kO3.2277@newssvr12.news.prodigy.com> Carl Banks wrote: > Ritesh Raj Sarraf wrote: >> Carl Banks wrote: >>> Then change the zipping part of download_from_web to acquire and >>> release this lock; do zipfile operations only between them. >>> >>> ziplock.acquire() >>> try: >>> do_all_zipfile_stuff_here() >>> finally: >>> ziplock.release() >> >> I hope while one thread has acquired the lock, the other threads (which >> have done the downloading work and are ready to zip) would wait. > > Exactly. Only one thread can hold a lock at a time. In the code above, a form called a "critical section", we might think of a thread as holding the lock when it is between the acquire() and release(). But that's not really how Python's locks work. A lock, even in the locked state, is not held by any particular thread. > If a thread tries > to acquire a lock that some other thread has, it'll wait until the > other thread releases it. More accurate: If a thread tries to acquire a lock that is in the locked state, it will wait until some thread releases it. (Unless it set the blocking flag false.) If more that one thread is waiting to acquire the lock, it may be blocked longer. I think the doc for threading.Lock is good: http://docs.python.org/lib/lock-objects.html -- --Bryan From g.brandl-nospam at gmx.net Fri Aug 18 15:06:51 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Fri, 18 Aug 2006 21:06:51 +0200 Subject: sum and strings In-Reply-To: <1155921231.537033.159460@p79g2000cwp.googlegroups.com> References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <slrneeatf3.nbt.sybrenUSE@schuimige.stuvel.eu> <1155921231.537033.159460@p79g2000cwp.googlegroups.com> Message-ID: <ec534d$5dn$1@news.albasani.net> Paddy wrote: > Sybren Stuvel wrote: >> Paddy enlightened us with: >> > Well, after all the above, there is a question: >> > >> > Why not make sum work for strings too? >> >> Because of "there should only be one way to do it, and that way should >> be obvious". There are already the str.join and unicode.join methods, >> which are more powerful than sum. >> >> Sybren > I get where you are coming from, but in this case we have a function, > sum, that is not as geeral as it could be. sum is already here, and > works for some types but not for strings which seems an arbitrary > limitation that impede duck typing. Only that it isn't arbitrary. > - Pad. > > P.S. I can see why, and am used to the ''.join method. A newbie > introduced to sum for integers might naturally try and concatenate > strings using sum too. Yes, and he's immediately told what to do instead. Georg From rschroev_nospam_ml at fastmail.fm Fri Aug 4 11:11:52 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 04 Aug 2006 15:11:52 GMT Subject: Problem reading/writing files In-Reply-To: <1154703858.102580.322590@m79g2000cwm.googlegroups.com> References: <1154661460.803694.241220@s13g2000cwa.googlegroups.com> <1154663988.871166.112930@s13g2000cwa.googlegroups.com> <1154692797.329732.73290@75g2000cwc.googlegroups.com> <mvIAg.2906$I92.177295@phobos.telenet-ops.be> <1154703858.102580.322590@m79g2000cwm.googlegroups.com> Message-ID: <YsJAg.2990$%M4.71751@phobos.telenet-ops.be> smeenehan at hmc.edu schreef: > Well, now I tried running the script and it worked fine with the .gfx > file. Originally I was working using the IDLE, which I wouldn't have > thought would make a difference, but when I ran the script on its own > it worked fine and when I ran it in the IDLE it didn't work unless the > data was in a text file. Weird. Weird indeed: I ran the script under IDLE too... -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From gelists at gmail.com Tue Aug 1 09:41:04 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Tue, 1 Aug 2006 10:41:04 -0300 Subject: Using Python for my web site References: <1154361480.915174.262720@b28g2000cwb.googlegroups.com> <1154409902.320511.114320@75g2000cwc.googlegroups.com> <1154416278.20290.183.camel@devilbox> Message-ID: <1hqlf4twmexrt$.dlg@gelists.gmail.com> On 2006-08-01 04:11:18, Cliff Wells wrote: > You say that you haven't tried Django or any other Python framework. > Perhaps you should. You seem to have at least the start of the right > idea about web application organization, so I think you'd be pleasantly > surprised with what you'll find already done for you by the major Python > frameworks and how much time you'll stop wasting on code that isn't part > of your application. I've checked it out quickly, and it seems that it is not possible to install e.g. TurboGears on a typical shared host -- as a normal user. You seem to run a shared hosts farm (IIRC). What's your point of view of hosting TurboGears or Django on a shared host? Is that (reasonably) possible? Thanks, Gerhard From g.brandl-nospam at gmx.net Tue Aug 22 06:31:16 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Tue, 22 Aug 2006 12:31:16 +0200 Subject: Problem of function calls from map() In-Reply-To: <LHkGg.20826$ph.8213@tornado.texas.rr.com> References: <mailman.9606.1156169593.27775.python-list@python.org> <LHkGg.20826$ph.8213@tornado.texas.rr.com> Message-ID: <ecemdl$qd5$1@news.albasani.net> Paul McGuire wrote: > "Dasn" <dasn at bluebottle.com> wrote in message > news:mailman.9606.1156169593.27775.python-list at python.org... >> >> Hi, there. >> >> 'lines' is a large list of strings each of which is seperated by '\t' >> >>> lines = ['bla\tbla\tblah', 'bh\tb\tb', ... ] >> >> I wanna split each string into a list. For speed, using map() instead >> of 'for' loop. > > Try this. Not sure how it stacks up for speed, though. (As others have > suggested, if 'for' loop is giving you speed heartburn, use a list > comprehension.) > > In this case, splitUsing is called only once, to create the embedded > function tmp. tmp is the function that split will call once per list item, > using whatever characters were specified in the call to splitUsing. > > -- Paul > > > > data = [ > "sldjflsdfj\tlsjdlj\tlkjsdlkfj", > "lsdjflsjd\tlsjdlfdj\tlskjdflkj", > "lskdjfl\tlskdjflj\tlskdlfkjsd", > ] > > def splitUsing(chars): > def tmp(s): > return s.split(chars) > return tmp > > for d in map(splitUsing('\t'), data): > print d And why is this better than map(lambda t: t.split('\t'), data) ? Georg From struggleyb at gmail.com Thu Aug 24 03:45:32 2006 From: struggleyb at gmail.com (Bo Yang) Date: 24 Aug 2006 00:45:32 -0700 Subject: How to download a web page just like a web browser do ? In-Reply-To: <1156346414.384352.298520@b28g2000cwb.googlegroups.com> References: <1156343685.281636.285100@p79g2000cwp.googlegroups.com> <1156346414.384352.298520@b28g2000cwb.googlegroups.com> Message-ID: <1156405532.083431.144960@75g2000cwc.googlegroups.com> Thank you , Max ! I think HarvestMan is just what I need ! Thanks again ! From sjdevnull at yahoo.com Thu Aug 31 03:33:51 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 31 Aug 2006 00:33:51 -0700 Subject: Allowing ref counting to close file items bad style? In-Reply-To: <7xlkp5mx22.fsf@ruckus.brouhaha.com> References: <9U6Jg.951$Xw6.283@trndny02><7x4pvvylrh.fsf@ruckus.brouhaha.com> <1156910432.917443.259720@p79g2000cwp.googlegroups.com> <7xmz9mkgnv.fsf@ruckus.brouhaha.com> <1156921226.069647.233550@p79g2000cwp.googlegroups.com> <7xodu2ekb6.fsf@ruckus.brouhaha.com> <1156957638.345092.169460@m73g2000cwd.googlegroups.com> <7xlkp5mx22.fsf@ruckus.brouhaha.com> Message-ID: <1157009631.302342.10760@m73g2000cwd.googlegroups.com> Paul Rubin wrote: > "sjdevnull at yahoo.com" <sjdevnull at yahoo.com> writes: > > I disagree strongly with this assertion. It's not as efficient overall > > as other GC implementations, but it's not a case of "less efficient to > > do the same task". Reference counting buys you deterministic GC in the > > pretty common case where you do not have circular references--and > > determinism is very valuable to programmers. Other GCs be faster, but > > they don't actually accomplish the same task. > > GC is supposed to create the illusion that all objects stay around > forever. It releases unreachable objects since the application can't > tell whether those objects are gone or not. No, that's not true of all GC implementations. Refcounting implementations give much nicer deterministic guarantees. From paul at boddie.org.uk Tue Aug 1 04:27:03 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 1 Aug 2006 01:27:03 -0700 Subject: Using Python for my web site References: <1154361480.915174.262720@b28g2000cwb.googlegroups.com> <1154416936.743642.50900@i42g2000cwa.googlegroups.com> Message-ID: <1154420823.138580.84070@i3g2000cwc.googlegroups.com> bryanjugglercryptographer at yahoo.com wrote: > northband wrote: > > [Specifications] > > I am trying to have the fastest page loads, averaging 100 items per > > result page. I have read about using Apache's mod_python so I could > > use PSP. Any help or tips are appreciated. > > So if I'm reading this correctly: you have a system that's > working, and the main purpose of the re-write is faster page > responses to users. Do I have that right? Performance is clearly important, but later on the questioner says... Q> Currently our site is built with a closed source hypertext Q> preprocessor much like PHP. That sounds like a good enough reason for migration, depending on how unportable, unsustainable or unmaintainable the technology platform has proven itself to be. Still, at least the questioner isn't seeking performance by wanting to rewrite everything in C++... Paul From lebougeant at 3douest.com Mon Aug 28 05:17:42 2006 From: lebougeant at 3douest.com (Jérôme Le Bougeant) Date: Mon, 28 Aug 2006 11:17:42 +0200 Subject: DirectPython Message-ID: <44f2b4b1$0$5108$ba4acef3@news.orange.fr> Hello, I have DirectPython 0.5 (http://directpython.sourceforge.net/) and python2.4 (directx9.0C installed). Samples do not work, I have this error : "RuntimeError: Failed to create a device" For example with sampleBasic.py : Traceback (most recent call last): File "sampleBasic.py", line 147, in ? mainloop() File "sampleBasic.py", line 75, in mainloop d3d.createDevice(title, u"textures/x.ico", window[2], window[3], False, CREATE.HARDWARE) RuntimeError: Failed to create a device Why ? please help me... any help would be appreciated. Thanks From alistair.king at helsinki.fi Fri Aug 4 06:37:35 2006 From: alistair.king at helsinki.fi (Alistair King) Date: Fri, 04 Aug 2006 13:37:35 +0300 Subject: help - iter & dict In-Reply-To: <loom.20060804T121653-822@post.gmane.org> References: <1154641320.44d26da8d8605@www1.helsinki.fi> <loom.20060804T121653-822@post.gmane.org> Message-ID: <44D3236F.7000302@helsinki.fi> taleinat wrote: > <aking <at> mappi.helsinki.fi> writes: > > >> CDSitdict = {28.473823598317392: "'2.4869999999999832'", 40.06163037274758: >> "'0.2910000000000002'", 27.756248559438422: "'2.8349999999999964'", >> 33.2299196586726: "'1.1249999999999962'", 29.989685187220061: >> "'1.9139999999999677'", 31.502319473614037: "'1.490999999999983'", >> 28.487341570327612: "'2.480999999999983'", 30.017763818271245: >> "'1.9049999999999681'", 32.943466663842266: "'1.1789999999999943'", >> 30.520103712886584: "'1.7519999999999736'", 31.453205956498341: >> "'1.5029999999999826'", 29.484222697359598: "'2.084999999999968'", >> 28.413513489228706: "'2.5139999999999842'", 28.314852455260802: >> "'2.558999999999986'", 28.652931545003508: "'2.4089999999999803'"} >> >> heres the error i get after entering Cpcb >> >> Traceback (most recent call last): >> File "elementalDS.py", line 156, in ? >> CDS = findClosest(CDSitdict, Cpcb) >> File "elementalDS.py", line 142, in findClosest >> distance = (target - v) ** 2 >> TypeError: unsupported operand type(s) for -: 'float' and 'str' >> alicat <at> linux:~/Desktop> >> > > The Python interpreter is being friendly and explaining exactly what the problem > is and where it occured. It's telling you that it can't subtract a string from a > float, in line 142 of your code (in the findClosest function). So the problem is > that 'target' is a float while 'v' is a string. > > 'v' should be a float as well, but it's a string since the values in your > dictionary are strings instead of numbers. Try removing the quotes around the > values in your dict (both the double-quotes and the single-quotes). > > > yes i now the key and values are swapped and the solutions work fine, i cant let the numerical key be involved in the iteration as in some cases there may be an exvalue below 3. the only solution i could come up with is to put single quotes round it but unfortunately i couldnt even to that thanks a -- Dr. Alistair King Research Chemist, Laboratory of Organic Chemistry, Department of Chemistry, Faculty of Science P.O. Box 55 (A.I. Virtasen aukio 1) FIN-00014 University of Helsinki Tel. +358 9 191 50429, Mobile +358 (0)50 5279446 Fax +358 9 191 50366 From emrahayanoglu at gmail.com Mon Aug 21 11:18:29 2006 From: emrahayanoglu at gmail.com (hardemr) Date: 21 Aug 2006 08:18:29 -0700 Subject: What do you want in a new web framework? In-Reply-To: <1156156636.515678.118210@75g2000cwc.googlegroups.com> References: <1156100331.329889.216340@p79g2000cwp.googlegroups.com> <pan.2006.08.20.19.48.34.996227@gmx.net> <1156156636.515678.118210@75g2000cwc.googlegroups.com> Message-ID: <1156173509.767030.255710@b28g2000cwb.googlegroups.com> Hello Everyone, I've just read all of the answers. Most of yours said that there are many web frameworks ,so it is nonsense to make a new web framework in python. Now I'm using and testing all of the frameworks in python also asp.net, jsp and java servlet, perl web frameworks and ruby on rails. Some of them have good positive points like that asp.net have gridviews to show data records, ruby on rails have ajax support, etc... The framework that i'll make, includes most of the positive points of the other frameworks. Maybe, it's a mix of web frameworks. I want to use dojo toolkit for javascript in my framework, and make a gui designer like Visual Studio and Sun Creator, etc... After that, may be you'll change your mind. And i want to listen your advices. Please feel free to say everything to me about framework. I'm waiting your answers. Best Regards, Emrah Ankara/Turkey From aahz at pythoncraft.com Sat Aug 12 09:56:36 2006 From: aahz at pythoncraft.com (Aahz) Date: 12 Aug 2006 06:56:36 -0700 Subject: long(Decimal) performance References: <1155349097.946873.279970@b28g2000cwb.googlegroups.com> Message-ID: <ebkmmk$2jn$1@panix3.panix.com> In article <1155349097.946873.279970 at b28g2000cwb.googlegroups.com>, ajaksu <ajaksu at gmail.com> wrote: > >Running long(Decimal) is pretty slow, and the conversion is based on >strings. I'm trying to figure out whether there is a good reason for >using strings like in decimal.py (that reason would be bound to bite me >down the road). I'm not sure why it's coded that, but it's somewhat irrelevant: right now, work is being done to convert decimal.py to C code, which will almost certainly be much faster than your code. Generally speaking, you should not be using Decimal now with any expectation of speed. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." --Brian W. Kernighan From thunderfoot at gmail.com Thu Aug 17 10:20:16 2006 From: thunderfoot at gmail.com (thunderfoot at gmail.com) Date: 17 Aug 2006 07:20:16 -0700 Subject: List match In-Reply-To: <1155823451.766317.7640@74g2000cwt.googlegroups.com> References: <1155823451.766317.7640@74g2000cwt.googlegroups.com> Message-ID: <1155824416.169604.108760@74g2000cwt.googlegroups.com> OriginalBrownster wrote: > Hi there: > > I know this probably is a very easy thing to do in python, but i wanted > to compare 2 lists and generate a new list that does not copy similar > entries. An example below > > list= ["apple", "banana", "grape"] > list2=["orange","banana", "pear"] > > now I want to compare these lits and generate a third list after > comparison > > list3 would be ["apple", "banana","grape","orange", "pear"] > > hence the double entry would not show up? > > Is there a way to do this?? > > Stephen How about: list3 = list1 + [item for item in list2 if item not in list1] print list3: ['apple', 'banana', 'grape', 'orange', 'pear'] From thn at mail.utexas.edu Thu Aug 10 09:57:53 2006 From: thn at mail.utexas.edu (Thomas Nelson) Date: 10 Aug 2006 06:57:53 -0700 Subject: Two Classes In Two Files In-Reply-To: <1155151480.848276.52650@75g2000cwc.googlegroups.com> References: <1155151480.848276.52650@75g2000cwc.googlegroups.com> Message-ID: <1155218273.894440.265560@m73g2000cwd.googlegroups.com> Perhaps __init__.py has what you're looking for? THN dhable at gmail.com wrote: > I just started working with Python and ran into an annoyance. Is there > a way to avoid having to use the "from xxx import yyy" syntax from > files in the same directory? I'm sure it's been asked a million times, > but I can't seem to find the answer. > > For example, I have two classes stored in separate files as such. > > File: one.py > ======== > class One: > def methodA(self): > print "class One" > def methodB(self): > print "class One" > > > File two.py > ======== > from one import One > > class Two(One): > def methodA(self): > print "class Two" > > if __name__ == "__main__": > x = Two() > x.methodA() > x.methodB() > > When I run the Two.py file, I get the expected output but I'd like to > eliminate the from line in two.py. From rupole at hotmail.com Tue Aug 29 21:15:57 2006 From: rupole at hotmail.com (Roger Upole) Date: Tue, 29 Aug 2006 21:15:57 -0400 Subject: Questoin about outlook calendar References: <mailman.10065.1156877114.27775.python-list@python.org> Message-ID: <1156900010_14781@sp6iad.superfeed.net> "Gallagher, Tim (NE)" wrote : > import win32com.client > import time > import datetime > > outlook = win32com.client.Dispatch("Outlook.Application") > namespace = outlook.GetNamespace("MAPI") > appointments = namespace.GetDefaultFolder(9).Items > > #print appointments.count > x = 4 # This is a number for one of the calendar entries > print appointments[x] > print appointments[x].start > print appointments[x].end > print appointments[x].RecurrenceState > print appointments[x].EntryID > print appointments[x].IsRecurring > recItem = appointments[x].GetRecurrencePattern GetRecurrencePattern is a method, so at this point recItem is a reference to the method itself, rather than the result of calling it. You'll need to add parens to actually call it. Roger From larry.bates at websafe.com Thu Aug 24 19:22:50 2006 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 24 Aug 2006 18:22:50 -0500 Subject: List problem In-Reply-To: <1156458544.544455.192330@m73g2000cwd.googlegroups.com> References: <1156458544.544455.192330@m73g2000cwd.googlegroups.com> Message-ID: <44EE34CA.3090407@websafe.com> kevndcks at aol.com wrote: > For example i write the following code in the Python command line; > >>>> list = ['One,Two,Three,Four'] > > Then enter this command, which will then return the following; > > ['One,Two,Three,Four'] > > > Now the problem, reading through the Python tutorial's, it describe's > that list's can sliced, concatenated and so on etc > > So i write the following > >>>> list[1:] + ['Five'] > > Then the error returned is that 'str' and 'list' could not be > concatenated which is where it baffles me. I'm understanding that this > mean's that the string 'Five' could not be joined onto the list, as i > havn't defined it in the array. Viewing the Python tutrial they have > the following, and working code; > >>>> a[:2] + ['bacon', 2*2] > ['spam', 'eggs', 'bacon', 4] > > How can they have the string 'bacon' and have it returned with no > error? > Your error message doesn't match your command. Now if you typed: list[0]+['Five'] that gives you the error you showed. What you meant to type was: l = ['One','Two','Three','Four'] This is a list of four strings, what you entered was a list of one string. NOTE never call a variable 'list' as it will mask the built-in list method (same goes for str, tuple, int, float, etc). -Larry Bates From onurb at xiludom.gro Wed Aug 2 03:35:16 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 02 Aug 2006 09:35:16 +0200 Subject: Finding the name of a class In-Reply-To: <7e2vc25eeapi9gvhdc8rqdn05v2ahbqogi@4ax.com> References: <q684q3xmd11.ln2@news.conpoint.com> <44cf7538$0$29435$626a54ce@news.free.fr> <mva4q3xb731.ln2@news.conpoint.com> <7e2vc25eeapi9gvhdc8rqdn05v2ahbqogi@4ax.com> Message-ID: <44d055b6$0$17404$636a55ce@news.free.fr> Dennis Lee Bieber wrote: > On Tue, 01 Aug 2006 11:09:57 -0500, Kirk Strauser <kirk at strauser.com> > declaimed the following in comp.lang.python: > >> Actually, I meant 'b = foo' in this case - I want to find the name of the >> class that b references, but the name of an instance (which may have zero >> or many references to it). >> > Pardon... That gives the class object another name, neither of which > has any precedence over the other. Not quite exactly. The 'b = foo' statement binds together name b and the object foo - which in this case happens to be a class. OTOH, class objects do have a __name__ attribute, which is not impacted by the binding. >>>>> b = Foo.bar >>>>> dir(b) >> ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'im_class', 'im_func', 'im_self'] >>>>> b.__class__ >> <type 'instancemethod'> >>>>> b.__class__.__name__ >> 'instancemethod' >> >> I was sort of hoping that it would print 'Foo'. > > But... you've just pulled the method "out" of the class > definition... Without supplying an instance, there is no linkage to a > class. Yes there is. Method objects have an im_class attribute, that is a reference to the class they were 'pulled out' from. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From rmuschall at tecont.de Wed Aug 2 17:10:06 2006 From: rmuschall at tecont.de (Ralf Muschall) Date: Wed, 02 Aug 2006 23:10:06 +0200 Subject: Railroad track syntax diagrams In-Reply-To: <1154459109.126048.35320@p79g2000cwp.googlegroups.com> References: <PzLzg.29035$rp4.24346@tornado.texas.rr.com> <1154459109.126048.35320@p79g2000cwp.googlegroups.com> Message-ID: <fug7q3-i6c.ln1@prcm.tecont.de> Paddy wrote: > I googlled and got these: > http://www.informatik.uni-freiburg.de/~thiemann/haskell/ebnf2ps/ > http://www.antlr.org/share/1107033888258/SDG2-1.5.zip There is another beast, also called ebnf2ps, but in elisp (runs inside the editor). It requires no additional software (i.e. no ghc) and is simpler to use (no questions about inexistent .afm files etc.) Ralf From david_wahler at bic.ky Tue Aug 8 03:16:58 2006 From: david_wahler at bic.ky (david_wahler at bic.ky) Date: 8 Aug 2006 02:16:58 -0500 Subject: =?utf-8?Q?Re:_Leipzig_Python_User_Group_=2D_Meeting, _August_16, _2006, _8:00pm?= Message-ID: <20060808071658.7293.qmail@BICSRV1011.bic.ky> I'll be out of the office until approximately August 20th. If you have any questions, please email support at bic.ky. -- David Wahler From spam at me.please Wed Aug 30 07:43:39 2006 From: spam at me.please (Skink) Date: Wed, 30 Aug 2006 13:43:39 +0200 Subject: models & editors in PyQt4 Message-ID: <ed3tl3$1oi8$1@news2.ipartners.pl> Hi, I created simple property classes with editing option, but since i'm not too much experienced in PyQt4 i'd like to ask if i handle ColorProperty changing right. Any other Property has its own editor and their control flow is imho ok. Hovewer i'm not sure about ColorProperty. What i do is: in createEditor(self, parent, option, index) i call QtGui.QColorDialog.getColor() and return None What do you think? Is it Ok? thanks, skink #-------------------------------------------- import sys from PyQt4 import QtGui, QtCore class PropertyDelegate(QtGui.QItemDelegate): def __init__(self, model): QtGui.QItemDelegate.__init__(self, None) self.model = model def createEditor(self, parent, option, index): if index.column() == 0: return None item = self.model.getItem(index) return item.createEditor(parent, option, index) def setEditorData(self, editor, index): item = self.model.getItem(index) item.setEditorData(editor, index) def setModelData(self, editor, model, index): item = self.model.getItem(index) item.setModelData(editor, model, index) # def updateEditorGeometry(self, editor, option, index): # editor.setGeometry(option.rect) def paint(self, painter, option, index): item = self.model.getItem(index) if isinstance(item, ColorProperty) and index.column() == 1: item.paint(painter, option, index) return QtGui.QItemDelegate.paint(self, painter, option, index) class SimpleModelItem: def __init__(self, parent=0): self._index = [] self._children = [] self._parent = parent if parent: parent._children.append(self) self._parent = parent def parent(self): return self._parent def children(self): return self._children def addIndex(self, index): self._index.append(index) def childId(self, child): return id(self._children[child]) def index(self, column=0): return self._index[column] class Property(SimpleModelItem): def __init__(self, parent=0, name="", data=[]): SimpleModelItem.__init__(self, parent) self._data = data self._name = name def data(self, index): return self._data[index.column()] def name(self): return self._name def createEditor(self, parent, option, index): return None def setEditorData(self, editor, index): return def setModelData(self, editor, model, index): return class StringProperty(Property): def __init__(self, parent, name, t): Property.__init__(self, parent, name, [t, ""]) def createEditor(self, parent, option, index): editor = QtGui.QLineEdit(parent) return editor def setEditorData(self, editor, index): value = index.model().getObjectData(self.name()) editor.setText(value) def setModelData(self, editor, model, index): index.model().setObjectData(self.name(), editor.text()) def data(self, index): if index.column() == 0: return self._data[0] else: return str(index.model().getObjectData(self.name())) class IntegerProperty(Property): def __init__(self, parent, name, t): Property.__init__(self, parent, name, [t, ""]) def createEditor(self, parent, option, index): editor = QtGui.QSpinBox(parent) editor.setMaximum(256*256) return editor def setEditorData(self, editor, index): value = index.model().getObjectData(self.name()) editor.setValue(value) def setModelData(self, editor, model, index): index.model().setObjectData(self.name(), editor.value()) def data(self, index): if index.column() == 0: return self._data[0] else: return str(index.model().getObjectData(self.name())) class SizeProperty(Property): def __init__(self, parent, name, t): Property.__init__(self, parent, name, [t, ""]) self.items = [] self.items.append(IntegerProperty(self, name+":x", "x")) self.items.append(IntegerProperty(self, name+":y", "y")) self.items.append(IntegerProperty(self, name+":w", "width")) self.items.append(IntegerProperty(self, name+":h", "height")) class ColorProperty(Property): def __init__(self, parent, name, t): Property.__init__(self, parent, name, [t, ""]) def createEditor(self, parent, option, index): color = QtGui.QColorDialog.getColor() if color.isValid(): index.model().setObjectData(self.name(), color) return None def paint(self, painter, option, index): r = option.rect if option.state & QtGui.QStyle.State_Selected: painter.fillRect(r, option.palette.highlight()) color = index.model().getObjectData(self.name()) colorStr = color.name() tr = painter.boundingRect(r, QtCore.Qt.AlignLeft, colorStr) w = tr.width() + 4 painter.fillRect(r.x() + 1, r.y() + 1, r.width() - 3 - w, r.height() - 3, QtGui.QBrush(color)) painter.setPen(QtCore.Qt.black) painter.drawRect(r.x() + 1, r.y() + 1, r.width() - 3 - w, r.height() - 3) r.setLeft(r.x() + r.width() + 1 - w) painter.drawText(r, QtCore.Qt.AlignLeft, colorStr) class EnumProperty(Property): def __init__(self, parent, name, t, te): Property.__init__(self, parent, name, [t, ""]) self.te = te def createEditor(self, parent, option, index): editor = QtGui.QComboBox(parent) i = 0 for item in self.te: editor.addItem(item, QtCore.QVariant(i)) i += 1 return editor def setEditorData(self, editor, index): index = index.model().getObjectData(self.name()) editor.setCurrentIndex(index) def setModelData(self, editor, model, index): index.model().setObjectData(self.name(), editor.currentIndex()) def data(self, index): if index.column() == 0: return self._data[0] else: index = index.model().getObjectData(self.name()) return self.te[index] class BooleanProperty(EnumProperty): def __init__(self, parent, name, t): EnumProperty.__init__(self, parent, name, t, ["False", "True"]) #----------------------------------------------------------------------- class SimpleModel(QtCore.QAbstractItemModel): def __init__(self, root, parent=None): QtCore.QAbstractItemModel.__init__(self, parent) self.ids = {} self.root = root self.root.addIndex(QtCore.QModelIndex()) self.ids[id(self.root)] = self.root self.walk(root) def walk(self, parent): row = 0 for child in parent.children(): _id = id(child) self.ids[_id] = child child.addIndex(self.createIndex(row, 0, _id)) child.addIndex(self.createIndex(row, 1, _id)) self.walk(child) row += 1 def getItem(self, index): if not index.isValid(): return self.root else: return self.ids[index.internalId()] #----------------------------------------------------------------------- def setObject(self, obj): self.obj = obj self.reset() def getObjectData(self, name): #print "getObjectData", name, self.obj[name] return self.obj[name] def setObjectData(self, name, value): #print "setObjectData", name, value self.obj[name] = value #----------------------------------------------------------------------- def index(self, row, column, parent): parentItem = self.getItem(parent) childItem = self.ids[parentItem.childId(row)] return childItem.index(column) def parent(self, index): childItem = self.getItem(index) parentItem = childItem.parent() return parentItem.index() def rowCount(self, parent): parentItem = self.getItem(parent) return len(parentItem.children()) def columnCount(self, parent): return 2 def data(self, index, role): if not index.isValid() or role != QtCore.Qt.DisplayRole: return QtCore.QVariant() item = self.getItem(index) return QtCore.QVariant(item.data(index)) def flags(self, index): if not index.isValid(): return QtCore.Qt.ItemIsEnabled else: return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable def headerData(self, section, orientation, role): if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole: if section == 0: return QtCore.QVariant("Name") else: return QtCore.QVariant("Value") return QtCore.QVariant() objAData = { "width": 6, "size:x": 10, "size:y": 15, "size:w": 20, "size:h": 25, "frameType": 0, "visible": 1, "color": QtGui.QColor(QtCore.Qt.red), "name": "foobar A" } objBData = { "width": 66, "size:x": 100, "size:y": 150, "size:w": 200, "size:h": 250, "frameType": 1, "visible": 0, "color": QtGui.QColor(QtCore.Qt.green), "name": "foobar B" } objCData = { "width": 666, "size:x": 1000, "size:y": 1500, "size:w": 2000, "size:h": 2500, "frameType": 2, "visible": 1, "color": QtGui.QColor(QtCore.Qt.blue), "name": "foobar C" } root = Property() newItem = StringProperty(root, "name", "Name") newItem = IntegerProperty(root, "width", "Item Width") newItem = ColorProperty(root, "color", "Background Color") newItem = SizeProperty(root, "size", "Item Size") newItem = EnumProperty(root, "frameType", "Frame Type", ["Solid", "Dashed", "None"]) newItem = BooleanProperty(root, "visible", "Visibility") class Widget(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) mainLayout = QtGui.QVBoxLayout() self.treeView = QtGui.QTreeView() self.treeView.setEditTriggers(QtGui.QAbstractItemView.SelectedClicked) self.model = SimpleModel(root) self.delegate = PropertyDelegate(self.model) self.treeView.setItemDelegate(self.delegate) self.model.setObject(objAData) self.treeView.setModel(self.model) mainLayout.addWidget(self.treeView) b1 = QtGui.QPushButton("Object A") self.connect(b1, QtCore.SIGNAL("clicked()"), self.objAClicked) mainLayout.addWidget(b1) b2 = QtGui.QPushButton("Object B") self.connect(b2, QtCore.SIGNAL("clicked()"), self.objBClicked) mainLayout.addWidget(b2) b3 = QtGui.QPushButton("Object C") self.connect(b3, QtCore.SIGNAL("clicked()"), self.objCClicked) mainLayout.addWidget(b3) self.setLayout(mainLayout) def objAClicked(self): self.model.setObject(objAData) def objBClicked(self): self.model.setObject(objBData) def objCClicked(self): self.model.setObject(objCData) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) widget = Widget() widget.show() sys.exit(app.exec_()) #-------------------------------------------- From s_rowse at hotmail.com Sat Aug 12 09:57:33 2006 From: s_rowse at hotmail.com (Sam) Date: 12 Aug 2006 06:57:33 -0700 Subject: matplotlib, wxPanel inside a wxPanel Message-ID: <1155391052.938133.284080@b28g2000cwb.googlegroups.com> Hello, I'm currently creating a GUI, which consists of a main frame that contains a menu bar,a toolbar and an empty panel, let's call it main_panel. Ideally, I'd like the following functionality: upon choosing an item from the menu bar, a particular graph will be displayed inside main_panel. Now I've taken a look at the 'embedding_in_wx' example files that come with matplotlib. Using this example, I can place a graph in a panel (let's call it graph_panel), and display this in a frame. I can also get NavigationToolbar2 to work completely. On the other hand, when i create graph_panel and put this inside of main_panel, NavigationToolbar2 does not work. The graph and toolbar are both displayed, but none of the buttons on the toolbar do anything. I'm beginning to think that what i'm trying to do isn't actually possible, and that i'll need to put it in a frame instead, which is a pity. Can anyone please advise if what i'm trying to do is possible and if so, provide a small example? I'm running windows XP, python 2.4, wxpython 2.6. From kbk at shore.net Wed Aug 2 01:49:06 2006 From: kbk at shore.net (Kurt B. Kaiser) Date: Wed, 2 Aug 2006 01:49:06 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200608020549.k725n6cP029299@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 396 open ( -5) / 3354 closed (+12) / 3750 total ( +7) Bugs : 864 open (-32) / 6087 closed (+52) / 6951 total (+20) RFE : 226 open ( +2) / 234 closed ( +1) / 460 total ( +3) New / Reopened Patches ______________________ Move firewall warning to "about" menu (2006-07-26) http://python.org/sf/1529018 opened by Tal Einat Allowing multiple instances of IDLE with sub-processes (2006-07-26) http://python.org/sf/1529142 opened by Tal Einat Squeezer - squeeze large output in the interpreter (2006-07-27) http://python.org/sf/1529353 opened by Tal Einat More openbsd targets for ctypes (2006-07-27) CLOSED http://python.org/sf/1529514 opened by Thomas Heller test_defaultdict not integrated into test sute (2006-07-27) CLOSED http://python.org/sf/1529686 opened by ?iga Seilnacht misleading info about tarfile.py's "r|*" mode (2006-07-27) CLOSED http://python.org/sf/1529811 opened by Lars Gust?bel pydoc render_doc (2006-07-28) http://python.org/sf/1530482 opened by ganges master test_email_codecs not integrated into test sute (2006-07-27) CLOSED http://python.org/sf/1529686 reopened by zseil Fix __index__() clipping really big numbers (2006-07-29) http://python.org/sf/1530738 opened by Nick Coghlan "a + (2006-07-29) CLOSED http://python.org/sf/1531113 opened by Christopher Tur Lesniewski-Laas Tracing and profiling functions can cause hangs in threads (2006-07-31) http://python.org/sf/1531859 opened by Matt Fleming Support for case-insensitivity in string.Template (2006-07-25) CLOSED http://python.org/sf/1528167 reopened by whit537 Patches Closed ______________ Expose case-insensitivity of string.Template (2006-07-25) http://python.org/sf/1528167 closed by bwarsaw Fix for #1513611 and #1511497; xml.sax imports (2006-07-10) http://python.org/sf/1519796 closed by zseil More openbsd targets for ctypes (2006-07-27) http://python.org/sf/1529514 closed by theller test_defaultdict not integrated into test sute (2006-07-27) http://python.org/sf/1529686 closed by gbrandl misleading info about tarfile.py's "r|*" mode (2006-07-27) http://python.org/sf/1529811 closed by akuchling Support for PyGetSetDefs in pydoc, inspect, and types (2006-07-10) http://python.org/sf/1520294 closed by bwarsaw Fix socketmodule compile on NetBSD (2006-07-21) http://python.org/sf/1526460 closed by splitscreen test_email_codecs not integrated into test sute (2006-07-27) http://python.org/sf/1529686 closed by gbrandl Describe Py_DEBUG and friends... (2006-05-18) http://python.org/sf/1490989 closed by akuchling os.path.exists returns False if no permission (2004-11-17) http://python.org/sf/1068277 closed by akuchling "a + (2006-07-29) http://python.org/sf/1531113 closed by nnorwitz Fix zip file header format in zipfile.py (2003-07-30) http://python.org/sf/780595 closed by gbrandl Don't produce core file in test_subprocess.py (2006-07-11) http://python.org/sf/1520905 closed by akuchling New / Reopened Bugs ___________________ readline module description should mention raw_input() (2006-07-26) CLOSED http://python.org/sf/1529157 opened by Thom Harp possible bug in mystrtol.c with recent gcc (2006-07-13) CLOSED http://python.org/sf/1521947 reopened by nnorwitz unrelated variable messing up doctests (2006-07-26) CLOSED http://python.org/sf/1529297 reopened by macquigg BROWSER path with capital letters (2006-07-28) http://python.org/sf/1529655 opened by Ken McGaugh doc string of read-only properties (2006-07-27) CLOSED http://python.org/sf/1529717 opened by Michael Amrhein distutils regression related to Distribution.run_command (2006-07-27) CLOSED http://python.org/sf/1529871 opened by Collin Winter bz2 lib missing from source distribution (2006-07-27) CLOSED http://python.org/sf/1529998 opened by james yoo Mac Universal Build of Python confuses distutils (2006-07-28) http://python.org/sf/1530142 opened by Richard Jones ssl object documentation lacks a couple of methods (2006-07-28) CLOSED http://python.org/sf/1530382 opened by Lawrence Oluyede file.seek() influelce write() when opened with a+ mode (2006-07-12) http://python.org/sf/1521491 reopened by rudnik_lior ctypes build fails on Solaris 10 (2006-07-28) http://python.org/sf/1530448 opened by Skip Montanaro struct.pack raises TypeError where it used to convert (2006-07-28) http://python.org/sf/1530559 opened by Joe Wreschnig distutils doesn't notice --with-pydebug (2006-07-29) http://python.org/sf/1530959 opened by Collin Winter __weaklist__ in typeobject.c (2006-07-29) http://python.org/sf/1531003 opened by Fred L. Drake, Jr. Comman not allowed at the end of argument list for **argumen (2006-07-29) http://python.org/sf/1531016 opened by Roman Suzi Reflected (swapped) operations overridden by subclasses (2006-07-31) CLOSED http://python.org/sf/1531349 opened by Andrei Polushin format_exception raises if str(exception) raises (2006-07-30) http://python.org/sf/1531405 opened by Jp Calderone parsetok.c emits warnings by writing to stderr (2006-07-30) http://python.org/sf/1531415 opened by Jp Calderone Build fails on MacOSX with missing symbol (2006-07-31) http://python.org/sf/1531662 opened by gideon may HTTPSConnection request hangs (2006-07-31) http://python.org/sf/1531775 opened by Noam Taich subprocess.Popen(cmd, stdout=sys.stdout) fails (2006-07-31) http://python.org/sf/1531862 opened by John A Meinel SocketServer.TCPServer returns different ports (2006-07-31) http://python.org/sf/1531963 opened by hakker.de the csv module writes files that Excel sees as SYLK files (2006-08-01) http://python.org/sf/1532483 opened by Vincent Povirk incorrect behaviour of PyUnicode_EncodeMBCS? (2006-08-01) http://python.org/sf/1532726 opened by Jan-Willem Bugs Closed ___________ Build fails on OS X with case sensitive fs (2006-07-19) http://python.org/sf/1525447 closed by ronaldoussoren readline module description should mention raw_input() (2006-07-26) http://python.org/sf/1529157 closed by akuchling possible bug in mystrtol.c with recent gcc (2006-07-13) http://python.org/sf/1521947 closed by nnorwitz xml.sax.ParseException weirdness in python 2.5b1 (2006-06-27) http://python.org/sf/1513611 closed by fdrake Python 2.4c1 test_univnewlines.py fails within IDLE IDE (2004-11-19) http://python.org/sf/1069433 closed by kbk unrelated variable messing up doctests (2006-07-26) http://python.org/sf/1529297 closed by nnorwitz unrelated variable messing up doctests (2006-07-26) http://python.org/sf/1529297 closed by tim_one wrong handling of character buffers in stringobject (2006-07-01) http://python.org/sf/1515471 closed by nnorwitz xml.sax.expatreader is missing (2006-06-23) http://python.org/sf/1511497 closed by fdrake FTP modue functions are not re-entrant,give odd exceptions (2006-04-13) http://python.org/sf/1469557 closed by gbrandl turtle.py Docs still incomplete (2006-07-09) http://python.org/sf/1519571 closed by akuchling doc string of read-only properties (2006-07-27) http://python.org/sf/1529717 closed by gbrandl distutils regression related to Distribution.run_command (2006-07-27) http://python.org/sf/1529871 closed by pje bz2 lib missing from source distribution (2006-07-27) http://python.org/sf/1529998 closed by nnorwitz missing module names in email package (2005-12-27) http://python.org/sf/1391608 closed by bwarsaw mimetools message's To field can't be changed (2006-06-28) http://python.org/sf/1513913 closed by bwarsaw Docs on import of email.MIMExxx classes wrong (2006-05-04) http://python.org/sf/1481650 closed by bwarsaw email.Utils.py: UnicodeError in RFC2322 header (2006-01-24) http://python.org/sf/1414018 closed by bwarsaw ssl object documentation lacks a couple of methods (2006-07-28) http://python.org/sf/1530382 closed by akuchling new.function() docs out of date (2003-11-03) http://python.org/sf/835255 closed by gbrandl compiler module loses docstrings (2006-03-02) http://python.org/sf/1441397 closed by gbrandl inconsistency in help(set) (2006-01-25) http://python.org/sf/1414697 closed by akuchling xmlcore needs to be documented (2006-06-11) http://python.org/sf/1504456 closed by fdrake urllib2 data argument (2006-07-25) http://python.org/sf/1528258 closed by akuchling Finish PEP 343 terminology cleanup (2006-04-26) http://python.org/sf/1476845 closed by ncoghlan set documentation deficiencies (2006-02-10) http://python.org/sf/1429053 closed by akuchling Weakref types documentation bugs (2005-05-02) http://python.org/sf/1193966 closed by fdrake suspect documentation of operator.isNumberType (2004-01-17) http://python.org/sf/878908 closed by gbrandl Wrong documentation of __radd__ etc. (2004-08-03) http://python.org/sf/1002453 closed by gbrandl Documented grammar for List displays incorrect (testlist) (2004-11-22) http://python.org/sf/1071248 closed by gbrandl os.path.sameopenfile documentation wrong. (2004-08-03) http://python.org/sf/1002398 closed by gbrandl mode 't' not documented as posssible mode for file built-in (2005-12-15) http://python.org/sf/1381717 closed by gbrandl Strange os.path.exists() results with invalid chars (2005-04-30) http://python.org/sf/1193180 closed by gbrandl popen3 on windows loses environment variables (2005-01-13) http://python.org/sf/1101667 closed by gbrandl Reflected (swapped) operations overridden by subclasses (2006-07-30) http://python.org/sf/1531349 closed by gbrandl String Methods 2.3.6.1 not in TOC (2006-06-29) http://python.org/sf/1514540 closed by akuchling PEP 307 pickle extensions not documented (2004-07-04) http://python.org/sf/984952 closed by akuchling 4.2.6 (re) Examples: float regexp exponential on failure (2003-11-24) http://python.org/sf/848556 closed by akuchling pydoc fails on package in ZIP archive (2006-06-15) http://python.org/sf/1506951 closed by gbrandl Installing 2.3b2 on to non-system disk fails (2003-07-03) http://python.org/sf/764975 closed by ronaldoussoren New / Reopened RFE __________________ distutils 'register' command and windows home directories (2006-07-30) http://python.org/sf/1531505 opened by Josiah Carlson RFE Closed __________ No simple example for pickle (2006-03-01) http://python.org/sf/1441072 closed by gbrandl From listserver at tdw.net Wed Aug 9 19:08:37 2006 From: listserver at tdw.net (Tim Williams) Date: Thu, 10 Aug 2006 00:08:37 +0100 Subject: timeout calling local sendmail In-Reply-To: <W49235293.825.54341.1@mx-extra> References: <1154963394.878933.80540@h48g2000cwc.googlegroups.com> <W49235293.825.54341.1@mx-extra> Message-ID: <9afea2ac0608091608y2e496bf9g4d6fcf50a6040db7@mail.gmail.com> On 9 Aug 2006 08:22:03 -0700, fluxent at gmail.com <fluxent at gmail.com> wrote: > that's > "timeout calling local sendmail" > not > "timeout calling local se" > > > fluxent at gmail.com wrote: > > (Environment: RedHat Linux recent, Python 2.3.5) > > > > We have a batch processing script that on occasion needs to send out an > > email. We have a sendmail running locally. > > > > Sometimes we get a socket timeout on sending that email. Increasing the > > timeout to 30sec reduced but did not eliminate it. > > > > It seems to happen more often when sending to some addresses in the UK, > > but it's definitely not limited to that. > > > > And, while we sometimes send a number of messages in a short period of > > time, (a) it's all single-threaded, and (b) the failure is often but > > not always the 1st message in the batch. > > > > Any ideas on what's going on? I don't know much about the > > thread/process model of sendmail to have any clue why this is > > happening. > RFC 1123 http://www.freesoft.org/CIE/RFC/1123/109.htm I find that a timeout of 120 seconds is the bare minimum. If the timeout is too short you get a condition where the email is received succesfully but appears to the sending server to have failed and a retry may occur - so the recipient gets multiple copies. HTH :) From paddy3118 at netscape.net Sun Aug 6 02:41:29 2006 From: paddy3118 at netscape.net (Paddy) Date: 5 Aug 2006 23:41:29 -0700 Subject: More int and float attributes In-Reply-To: <1154810987.818618.110350@h48g2000cwc.googlegroups.com> References: <1154780600.348169.158150@i42g2000cwa.googlegroups.com> <1154807223.104418.230270@i3g2000cwc.googlegroups.com> <1154810987.818618.110350@h48g2000cwc.googlegroups.com> Message-ID: <1154846489.880041.120280@m79g2000cwm.googlegroups.com> bearophileHUGS at lycos.com wrote: > Paddy: > > Or do you mean the ability to choose between hardware supported float > > s? e.g. float and double precision? > > No, I mean just having the ability to ask the float (his attribute) > what are the max and min values it can represent, etc. > > stop = float.max > ... > > I don't know any simple way to know that values now. And importing sys > to know the max int looks stupid. > > maxi = int.max > mini = int.min > ... > > Such attributes can be given to the Decimal values too, if you want. > > Bye, > bearophile Hi bearophille, decimals have their context; maybe floats could have your read-only 'context' values made available somehow. I don't know if their is an issue with making this (static) data available from all float instances, so maybe it should go in sys. Maybe people, (me included), don't pay enough attention to the trade-offs inherent in floating point arithmatic. I was taught about difference equations, and rounding errors. I regularly compute answers in programs without regard to floating point precision because the defaults chosen work for most of my cases, but if I needed to be more precise then I too would need some of the info you suggest. Question: do the scientific packages supported by Python supply this data in a regular manner? - Paddy. P.S. My appologies to any professional 'counters of currencies' out their who may have been offended by my earlier use of the term 'bean counters' - You probably earn much more than me - don't call in my loans - I have babes in arms to feed.... :-) From karmadharma at gmail.com Wed Aug 30 17:32:26 2006 From: karmadharma at gmail.com (karmadharma at gmail.com) Date: 30 Aug 2006 14:32:26 -0700 Subject: Debugging reference counts in python/C Message-ID: <1156973546.887759.206530@m73g2000cwd.googlegroups.com> Hello everybody I am trying to make sure that my (non trivial) C module is cleaning up properly after itself, and consequently I've built python with --py-debug which, besides allowing me to use certain functions, it also prints the reference count at the end. I am finding, however, that the reference count on exit seems to increase by 1 every time I create one of my objects, poring over the output of the debugging functions seems to imply that the only thing that changes is the refcount of [somenumber] '<dummy key>' where somenumber seems proportional to the number of objects I create, if I create n+1 objects, somenumber increases by 1. Looking at the docs this seems related to empty dictionaries, but I'm really stumped at the moment. Out of curiosity I also did this stupid test thinking it would return the same refcount, but evidently it doesn't: Type "help", "copyright", "credits" or "license" for more information. >>> a=1 [17214 refs] >>> (ctrl-D) [17214 refs] [6606 refs] Type "help", "copyright", "credits" or "license" for more information. >>> a=1 [17214 refs] >>> b=2 [17217 refs] >>> (ctrl-D) [17217 refs] [6608 refs] as you can see just assigning another variable causes the refcount to remain higher when python exits. Is this something I should be worried about at all? I am new to writing python C extensions, and that's why I never really worried about all this before; apologies if my question is obvious and/or trivial... From jscrerar at compuserve.com Sat Aug 19 18:01:39 2006 From: jscrerar at compuserve.com (Jim) Date: 19 Aug 2006 15:01:39 -0700 Subject: trouble using "\" as a string References: <1156023013.462640.165970@i42g2000cwa.googlegroups.com> Message-ID: <1156024899.431752.326710@i42g2000cwa.googlegroups.com> Try using: tempname = "\\" Jim OriginalBrownster wrote: > Hi there... > > I'm still pretty new to turbogears. but i have gotten pretty familiar > with it > > i'm just trying to clear something up, i'm having a difficult time > using \ when declaring a string expression > > such as tempname="\"..it says that the line is single qouted. > > i want this because using python I am pulling in filenames from a > mac..thus they are "/" in the pathways..and i want to .split it at the > "/" to obtain the filename at the end...but its proving diffucult with > this obstacle in the way. > > Why is this happening?? From cliff at develix.com Wed Aug 2 21:17:38 2006 From: cliff at develix.com (Cliff Wells) Date: Wed, 02 Aug 2006 18:17:38 -0700 Subject: Using Python for my web site In-Reply-To: <19zmaoel1tn3$.dlg@gelists.gmail.com> References: <1154361480.915174.262720@b28g2000cwb.googlegroups.com> <44ce3a5c$0$18952$626a54ce@news.free.fr> <1154367359.931684.106650@m73g2000cwd.googlegroups.com> <44ce4530$0$28242$626a54ce@news.free.fr> <mailman.8748.1154376811.27775.python-list@python.org> <pan.2006.08.02.00.04.19.775720@nothanks.org> <mailman.8827.1154485587.27775.python-list@python.org> <pan.2006.08.02.03.51.40.717506@nothanks.org> <19zmaoel1tn3$.dlg@gelists.gmail.com> Message-ID: <1154567858.20290.324.camel@devilbox> On Wed, 2006-08-02 at 10:46 -0300, Gerhard Fiedler wrote: > On 2006-08-02 00:51:28, Conrad wrote: > > > Which begins "A few years ago" > > Exactly. Isn't this a good start for honesty? It doesn't claim to state > anything up to date. > > It continues "I did some research", "some" being a very clear indicator > that I didn't consider this a thorough research. From the stated results of > this research it should be clear to any reasonable reader what kind of > research that was. "Claimed to have", "seemed to have" are not really > expressions that try to claim more than they are. I think the communication breakdown here is two-fold: 1) PostgreSQL fans are perhaps a bit paranoid about claims of MySQL being better. There used to be a tiny bit of truth in this claim for certain applications (mostly relating to performance and ease of use). This makes them tend to read statements such as yours as an attack and so you get defensive responses. Also, comparing MySQL to PostgreSQL is a bit like comparing PHP to Python: not even in the same class. PostgreSQL users probably consider the whole comparison is a bit insulting to begin with, then to suggest that MySQL *might* be better is practically a slap in the face ;-) 2) When you qualify statements with modifiers such as "some", "seemed", etc, you are almost bound to be misinterpreted, since those modifiers are apparently invisible on the net. I suspect most people scan messages, taking away the main point but discarding all the nice words the writer was so careful to write. For future reference, if you don't know and intend to convey that you don't, it's probably best to end your statement (no matter how carefully qualified) with a clear statement that you are fishing for informative responses. For instance, were I to say (on this list): "I've heard that Python is slow compared to PHP, and that many people recommend PHP because it's hard to find hosting for Python apps anyway.", I'd probably get a nice mix of both helpful replies and extremely irritable ones, despite the fact I clearly qualified my statements. Both of those statements were at least somewhat true at one point and as such tend to invoke more passionate responses from Python proponents. On the other hand, had I appended "So I'd like some other opinions because I don't know." to the end, it would probably cut the irritation down considerably (or at least be in a much more defensible position if it didn't). Regards, Cliff -- From diffuser78 at gmail.com Tue Aug 1 16:45:30 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 1 Aug 2006 13:45:30 -0700 Subject: Network Game in Python Message-ID: <1154465130.099412.101270@h48g2000cwc.googlegroups.com> I have to create a small and simple GUI app in Python which is similar to a netwrok game. Let me expalain you. I need some suggestions. I might use wxPython for GUI because that is the only GUI oolkit I know. There are 6 players in the game. They are all connected though a LAN (possible an internal network). There is one main supervirsor who starts the game and other 5 are players. Once the supervisor starts the game, a move goes randomly to any player out of the 5 players. Once a player gets a move he has to act. Based on his action next move will be generated by supervisor and sent to some other player in the network. This process goes on untill the simulation time ends. Winners and Loosers are decided by some point system which supervisor keeps track of. Some questions I have are: 1. How can I manage network messages among the players. Should multicast be used or Actor should send the message to Supervisor and he sends to all. ? What python modules can be handy in these things. 2. How can I manage moves among players. What move a player makes is visible to all others in real time, so essentially all players have the same consistent view of the game. Only the person with access can actually make a move or carry out action. Any suggestion how to carry out this thing. 3. Shold I use a flat file or some database in mySQL to measure points etc ? I want to have a repository which keep tracks of all the mvoes in the system and who played what move etc..? Any suggestions on this. 4. If you have any other input, it will be greatly appreciated. Thanks From jzgoda at o2.usun.pl Mon Aug 7 08:37:27 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Mon, 07 Aug 2006 14:37:27 +0200 Subject: VisualStudio2005 supported in distutils In-Reply-To: <44D72B46.2060802@v.loewis.de> References: <mailman.8844.1154526783.27775.python-list@python.org> <44D11BC3.40802@v.loewis.de> <ear76g$d30$1@nemesis.news.tpi.pl> <44D72B46.2060802@v.loewis.de> Message-ID: <eb7c70$rpv$1@atlantis.news.tpi.pl> Martin v. L?wis napisa?(a): >>Sure, but what if I succesfully compile Python with VS 2005? Hier ist >>der Hund begraben, distutils cann't handle this compiler so I'll be >>unable to compile any extension for my home-baken Python. > > It sure can. Just open a "Visual Studio Command Prompt" (or whatever > its name), and make sure MSSdk and DISTUTILS_USE_SDK are both set. > Then distutils will use the compiler from PATH, rather than the > pre-configured one. Thanks, didn't know that. -- Jarek Zgoda http://jpa.berlios.de/ From michiel at thingmajig.org Fri Aug 25 12:21:10 2006 From: michiel at thingmajig.org (Michiel Sikma) Date: Fri, 25 Aug 2006 18:21:10 +0200 Subject: time.clock() going backwards?? In-Reply-To: <vkFHg.82529$_J1.759243@twister2.libero.it> References: <vkFHg.82529$_J1.759243@twister2.libero.it> Message-ID: <A134A80A-540E-467E-B19A-7E76B8CC5300@thingmajig.org> Op 25-aug-2006, om 16:13 heeft Giovanni Bajo het volgende geschreven: > Hello, > > Is it possible this to be a bug in Python itself > (maybe, shooting at the moon, in the conversion between the 64bit > performance > counter and the floating point representation returned by time.clock > ()), or > could it be a bug in Windows itself or the mother board drivers > (buf if so, > wouldn't other application start going mad)? > -- > Giovanni Bajo Very interesting! While I couldn't possibly know the answer to this, I do wonder which version of Python you were using. Is it the bleeding edge 2.5 release candidate? Michiel From rogue_pedro at yahoo.com Fri Aug 18 22:16:43 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 18 Aug 2006 19:16:43 -0700 Subject: text editor suggestion? In-Reply-To: <44e66724$0$2363$c3e8da3@news.astraweb.com> References: <44e66724$0$2363$c3e8da3@news.astraweb.com> Message-ID: <1155953803.525289.64490@h48g2000cwc.googlegroups.com> John Salerno wrote: > Ok, I know it's been asked a million times, but I have a more specific > question so hopefully this won't be just the same old post. I've tried a > few different editors, and I really like UltraEdit, but it's > Windows-only and I'm working more on Linux nowadays. > > Here are my criteria: > > 1. syntax highlighting (highly customizable) > 2. auto/smart indenting > 3. ability to run script > 4. light-weight text editor, not an IDE > 5. cross-platform (not really necessary, but nice) > > That's pretty much all I need. It's nice when you can customize a bunch > of other stuff too, but those are the most important. > > I've tried vim, but I really don't feel like taking the time to learn > how to use it, given that I just like to casually program (not to > mention that I prefer to use the mouse when navigating a document > sometimes). > > I also just started using Scite, and I really like it, except I find its > syntax highlighting to be very inflexible. You aren't able to define > your own groups of words -- you have to use what's given, basically. One > thing I like about UltraEdit is that you simply define as many groups of > keywords as you want and then assign a style to each one. Scite has a > very strange and rigid method of highlighting. > > So hopefully some of you might have some suggestions. My requirements > are minimal, but I'm still not happy with the syntax highlighting I'm > seeing in a lot of editors out there. Have you tried IDLE? It ships with python, meets your 5 criteria(*), can be customized (highlighting colors and command keys and more), and includes a usable GUI debugger. It's got some warts, but I like it a lot, it's pretty much all I use for my python coding. http://www.python.org/idle/ (* It *is* an IDE, but a very lightweight one. :) ) From john106henry at hotmail.com Fri Aug 4 22:57:28 2006 From: john106henry at hotmail.com (John Henry) Date: 4 Aug 2006 19:57:28 -0700 Subject: Pywin32 Excel question Message-ID: <1154746648.811259.111460@h48g2000cwc.googlegroups.com> I posted the following message to the Pywin32 list but if anybody here can help, it would be appreciated very much. ============================ Hi list, I have a need to copy 3 rows of data from the top of my Excel spreadsheet to another location. I would have throught that this should be very straightforward since I've done a fair amount of Excel/Python programming. Unforturnately, I am stuck on this one. The VB Macro says I need to: Range("1:1,2:2,3:3").Select Range("A3").Activate Selection.Copy Rows("20:20").Select ActiveSheet.Paste So, I figure the Python code would be something like: <xlApp determined already> 1) xlSheet=xlApp.ActiveWorkbook.ActiveSheet 2) xlSel=xlSheet.Range("1:1,2:2,3:3").Select() 3) #xlSel=xlSheet.Range("A3").Activate() 4) xlSel.Copy() 5) xlSheet.Rows("20:20").Select() 6) xlSheet.Paste() Unfortunately, this doesn't work. After line 2, xlSel becomes "True" - not a "Selection" and so the code fails at line 4). I am not sure why I have to do the "Activate" on line 3 but it didn't matter, the code still fails at line 4. What am I doing wrong? Any help is greatly appreciated. Regards, From sjmachin at lexicon.net Tue Aug 15 22:49:17 2006 From: sjmachin at lexicon.net (John Machin) Date: 15 Aug 2006 19:49:17 -0700 Subject: Printing n elements per line in a list In-Reply-To: <pan.2006.08.16.01.46.00.372218@REMOVEME.cybersource.com.au> References: <1155685889.626881.37040@m73g2000cwd.googlegroups.com> <pan.2006.08.16.01.46.00.372218@REMOVEME.cybersource.com.au> Message-ID: <1155696557.538330.70800@m73g2000cwd.googlegroups.com> Steven D'Aprano wrote: > I think it's possible to > > hack it up using while loops and some ugly slicing, but hopefully I'm > > missing something > > I don't see why you think that's an ugly hack. > > def printitems(sequence, count=5): > """Print count items of sequence per line.""" > numrows = len(sequence)//count > if len(sequence)%count != 0: numrows += 1 > for start in range(0, numrows): > items = sequence[start*count:(start+1)*count] > for item in items: > print item, > print Ugliness is in the eye of the beholder. It is more blessed to add than to multiply. Gaze upon this alternative: def printitems2(sequence, count=5): """Print count items of sequence per line.""" for pos in range(0, len(sequence), count): for item in sequence[pos:pos+count]: print item, print Cheers, John From pavlovevidence at gmail.com Thu Aug 3 09:56:06 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 3 Aug 2006 06:56:06 -0700 Subject: Thread Question References: <1153998422.670828.148360@m79g2000cwm.googlegroups.com> <1154019801.999805.150000@m73g2000cwd.googlegroups.com> <mailman.8857.1154541684.27775.python-list@python.org> <1154544553.990241.280030@i3g2000cwc.googlegroups.com> <1154590917.731457.106230@s13g2000cwa.googlegroups.com> Message-ID: <1154613366.350191.81880@m73g2000cwd.googlegroups.com> Ritesh Raj Sarraf wrote: > Simon Forman wrote: > > > One other question I had, > > > If my user passes the --zip option, download_from_web() internally (when the > > > download is successful) zips the downloaded data to a zip file. Since in case > > > of threading there'll be multiple threads, and say if one of the thread > > > completes 2 seconds before others and is doing the zipping work: > > > What will the other thread, at that moment do, if it completes while the > > > previous thread is doing the zipping work ? > > > > The other threads will just take the next request from the Queue and > > process it. They won't "care" what the one thread is doing, > > downloading, zipping, whatever. > > > > > > The thread will be marked as complete only when the function that it > executed exits. Right ? > > download_from_web() internally calls a funtion to zip the file. So it > doesn't return before zipping. Till then this thread is not complete > and therefore is busy working (i.e. zipping). > > during the same time if another thread (which is also calling > download_from_web) completes the download, the download function will > again call the zip code. At that particular situtation, will it wait > for the previous thread to complete the zipping and release the file so > that it can zip more data to it or will it just panic and quit ? If you have multiple threads trying to access the same ZIP file at the same time, whether or not they use the same ZipFile object, you'll have trouble. You'd have to change download_from_web to protect against simultaneous use. A simple lock should suffice. Create the lock in the main thread, like so: ziplock = threading.Lock() Then change the zipping part of download_from_web to acquire and release this lock; do zipfile operations only between them. ziplock.acquire() try: do_all_zipfile_stuff_here() finally: ziplock.release() If you can't change download_from_web, you might have no choice but to download sequentially. OTOH, if each thread uses a different ZIP file (and a different ZipFile object), you wouldn't have to use a lock. It doesn't sound like you're doing that, though. It shouldn't be a problem if one thread is zipping at the same time another is downloading, unless there's some common data between them for some reason. Carl Banks From michiel at thingmajig.org Fri Aug 4 08:50:02 2006 From: michiel at thingmajig.org (Michiel Sikma) Date: Fri, 4 Aug 2006 14:50:02 +0200 Subject: Pydev with Eclipse on OSX Q Message-ID: <186128F8-803B-43BA-BC7F-40A282B7EB34@thingmajig.org> Hey guys. I'm trying to run Pydev on Eclipse on OSX, but I've got a problem that prevents me from making new projects in it. It seems that I cannot add my Python interpreter to the list of interpreters (it seems to do _something_ when I select it, but then ends up not adding it to the list). Are any of you guys familiar with this? Is there something I need to do before I can add my interpreter to that list? I'm on a G5 iMac and have the latest version of both programs. Thanks, Michiel From m.sloyko at gmail.com Wed Aug 30 03:42:38 2006 From: m.sloyko at gmail.com (Maxim Sloyko) Date: 30 Aug 2006 00:42:38 -0700 Subject: What do you want in a new web framework? References: <1156100330.768482.326760@h48g2000cwc.googlegroups.com> <ecbrm1$l0h$1@upsn250.cri.u-psud.fr> Message-ID: <1156923758.526608.251530@b28g2000cwb.googlegroups.com> Laurent Pointal wrote: > > Look at http://wiki.python.org/moin/WebFrameworks > > Do you *really* need to develop a *new* framework (maybe a scholl > exercise - it that case, KISS)? Isn't the main reason why there are so many of them is that all of them suck badly? From mail at microcorp.co.za Fri Aug 25 04:53:27 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 25 Aug 2006 10:53:27 +0200 Subject: Fw: Is this a good idea or a waste of time? Message-ID: <003c01c6c823$efe7e340$03000080@hendrik> "Simon Forman" <rogue_pedro at yahoo.com> wrote: 8<------------------------------------------------------------- | BTW, speaking of "strictness", "more stricter" is invalid English, | just "stricter" is the "correct" form. ;-) or alternatively the construct "more strict" is also acceptable - Hendrik From apardon at forel.vub.ac.be Tue Aug 29 03:07:53 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 29 Aug 2006 07:07:53 GMT Subject: Don't use __slots__ (was Re: performance of dictionary lookup vs. object attributes) References: <mailman.9853.1156495094.27775.python-list@python.org> <1156621904.481215.243080@m73g2000cwd.googlegroups.com> <mailman.9927.1156624141.27775.python-list@python.org> <1156625365.346825.18630@74g2000cwt.googlegroups.com> <ectbls$ofa$1@gide.ita.chalmers.se> Message-ID: <slrnef7pu9.4tu.apardon@rcpc42.vub.ac.be> On 2006-08-27, Jacob Hallen <jacob at cd.chalmers.se> wrote: > In article <1156625365.346825.18630 at 74g2000cwt.googlegroups.com>, > Patrick Maupin <pmaupin at gmail.com> wrote: > > Unfortunately there is a side effect to slots. They change the behaviour of > the objects that have slots in a way that can be abused by control freaks > and static typing weenies. This is bad, because the contol freaks should > be abusing the metaclasses and the static typing weenies should be abusing > decorators, since in Python,there should be only one obvious way of doing something. Your emphasis is wrong. In Python there should be one obvious way of doing something. Preferably this is the only obvious way. -- Antoon Pardon From bill.pursell at gmail.com Sun Aug 13 07:35:44 2006 From: bill.pursell at gmail.com (Bill Pursell) Date: 13 Aug 2006 04:35:44 -0700 Subject: Using a dictionary to pass data to/from embedded python functions In-Reply-To: <1hjy7rx.1sxrihq1jtyy68N%aleax@mac.com> References: <44dcf055@dnews.tpgi.com.au> <1hjy7rx.1sxrihq1jtyy68N%aleax@mac.com> Message-ID: <1155468943.915701.109980@m79g2000cwm.googlegroups.com> Alex Martelli wrote: > > I wrote the following file za.c: <sample code snipped> > and proceeded to compile and execute as follows: [[Note: it does not > matter that I'm using 2.5, the code is just as fine with previous > versions -- it just happens that 2.5 is what I'm using right now in > order to help out with 2.5's beta testing]]: > > brain:~/pyex alex$ gcc -c za.c -I/usr/local/include/python2.5 > brain:~/pyex alex$ gcc -o za za.o -L/usr/local/lib/python2.5/config/ > -lpython2.5 > brain:~/pyex alex$ ./za I needed to include a lot more flags to make the example compile. In particular: -L /usr/local/lib/python2.4/config/ -lpython2.4 -lrt -lm -ldl -lutil Why did you not need them? Is this a misconfiguration on my box, or something entirely different? I've seen this type of thing come up a lot, and I can't tell if it is simply the author omitting flags for the sake of brevity, or if I'm actually missing something. -- Bill Pursell From gagsl-py at yahoo.com.ar Mon Aug 14 17:50:32 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 14 Aug 2006 18:50:32 -0300 Subject: sending mailing list with smtplib In-Reply-To: <1155561746.812918.128770@h48g2000cwc.googlegroups.com> References: <1155561746.812918.128770@h48g2000cwc.googlegroups.com> Message-ID: <7.0.1.0.0.20060814184754.03a71df8@yahoo.com.ar> At Monday 14/8/2006 10:22, 3KWA wrote: ># ... but the actual message sending in a loop to send one email each >(didn't work) Specify "didn't work" at least... see http://www.catb.org/~esr/faqs/smart-questions.html Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From onurb at xiludom.gro Mon Aug 7 10:23:43 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 07 Aug 2006 16:23:43 +0200 Subject: is it possible to dividing up a class in multiple files? In-Reply-To: <eb7ftn$t15$1@news.lrz-muenchen.de> References: <eb7ftn$t15$1@news.lrz-muenchen.de> Message-ID: <44d74cf0$0$21145$7a628cd7@news.club-internet.fr> Martin H?fling wrote: > Hi there, > > is it possible to put the methods of a class in different files? I just > want to order them and try to keep the files small. Technically, yes - but in a somewhat hackish way. But you *really* should not have such a need at first. Smells like a design (or coding) problem to me - FWIW, very few of my source files are > 1 KLOC, and they usually contains many classes, functions and other definitions. From fredcdobbs127 at yahoo.com Sat Aug 26 15:12:27 2006 From: fredcdobbs127 at yahoo.com (Fred C. Dobbs) Date: 26 Aug 2006 12:12:27 -0700 Subject: Dive into Python question Message-ID: <1156619547.658725.276750@p79g2000cwp.googlegroups.com> I feel like an idiot. I'm going thru "Dive Into Python" and running the first program - odbchelper.py My output is "pwd=secret;database=master;uid=sa;server=mpilgrim" which has all the substrings reversed from the output documented in the book. I've run the downloaded code in Komodo, PythonWin and the command line and get the same results. Have I set some switch on my python install that reverses everything? From paul at boddie.org.uk Thu Aug 17 18:15:43 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 17 Aug 2006 15:15:43 -0700 Subject: hide python code ! References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155300852.497741.73230@74g2000cwt.googlegroups.com> <1155301468.870340.82920@b28g2000cwb.googlegroups.com> <1155307415.855555.124760@i3g2000cwc.googlegroups.com> <1155309563.898182.195950@p79g2000cwp.googlegroups.com> <1155313092.743230.33950@m73g2000cwd.googlegroups.com> <1155320948.142524.124990@p79g2000cwp.googlegroups.com> <1155564295.361980.279350@m73g2000cwd.googlegroups.com> <1155570126.905733.137850@m79g2000cwm.googlegroups.com> <1155657616.103285.40040@75g2000cwc.googlegroups.com> <pan.2006.08.16.04.51.27.33734@REMOVEME.cybersource.com.au> <1155760750.172859.172920@h48g2000cwc.googlegroups.com> <1155813593.559451.84740@p79g2000cwp.googlegroups.com> <1155842866.720030.284840@i42g2000cwa.googlegroups.com> Message-ID: <1155852943.809364.18770@74g2000cwt.googlegroups.com> danielx wrote: > [The suggestion that works apparently given away unconditionally become part of common culture.] > Extremely interesting point! This should really motivate people to > answer the question I posed earlier: Does an author of software forfeit > his rights to the code if he shares his program (ie, reliquishes > _complete_ protection over the code)? Well, although some software may be used without the user being particularly aware of the licence, licences such as the GPL are defined in terms of distribution. The authors of that licence perhaps realised that grounding such an agreement in terms of the usage or performance of a work may be susceptible to the misunderstandings which seem to have plagued the music industry. Listening to music over the radio is in practice an involuntary act, whereas recording and redistributing the music is something that one actively has to do. The apparent difference between broadcast popular music and software is that software typically arrives with a licence (or one is typically forced to view such a licence before downloading it), and that redistributing software is an act where any later argument that one was not aware of the licence would be a less credible defence. Of course, copyright laws may state that a work without a licence is "strongly owned" by the author in that redistribution is prohibited, but as I noted earlier this seems to have been perceived as counter-intuitive, especially where the work is widely "performed" for free. > Let's say this happens: I want to sell some software, but I'm affraid > people will just copy it. So I prototype it in Python (or whatever > programming language) and never release the program. Based on that, I > design a chip (I know this is nearly impossible, but we are doing a > mental experiment), which does exactly the same thing. I don't think it's an unreasonable suggestion. > First of all, the chip can be reverse engineered (of course, with MUCH > greater difficulty than the equivalent code). Should I still be worried > that my invention will be copied? It used to be said that the first people to buy the latest games console were the competition. > A second point to consider: The chip is patentable (I think this is the > case legally, as well as in the court of public opinion), so what about > the equivalent code? This is why people are very worried about the scope of patents gradually expanding from areas where companies have sought some kind of incentive for investment in manufacturing, for example, to areas where patents have actually been forbidden in the past, such as in computer software. Sadly, there's a kind of misguided attitude amongst law-makers (particularly certain "visionaries" in the European Union) who think they're encouraging innovation when unquestioningly accepting arguments that if technology A is patentable and if technology B is like technology A, then technology B should be patentable, rather than considering that patents on technology A should also be forbidden. Paul From dale at riverhall.nospam.co.uk Fri Aug 4 23:47:09 2006 From: dale at riverhall.nospam.co.uk (Dale Strickland-Clark) Date: Sat, 05 Aug 2006 04:47:09 +0100 Subject: Design Patterns in Python References: <mailman.9004.1154746181.27775.python-list@python.org> Message-ID: <4xUAg.71189$Ni5.12466@fe49.usenetserver.com> Gabriel Genellina wrote: > Hello > > Most authors talk about Java/C++, and describe patterns used as a > workaround to their static class model; the dynamic nature of Python > allows for trivial implementations in some cases. > I've seen some design patterns examples on the ActiveState site, and > some discussions some time ago on this list. > But does anyone know of a complete discussion/analysis of patterns in > Python? Books, articles, web pages... > Unfortunately the pattern-SIG is now defunct... > > > Gabriel Genellina > Softlab SRL > Something like this? http://tinyurl.com/q7uyt (www.amazon.co.uk) -- Dale Strickland-Clark Riverhall Systems - www.riverhall.co.uk From python.list at tim.thechases.com Fri Aug 25 17:54:55 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 25 Aug 2006 16:54:55 -0500 Subject: random writing access to a file in Python In-Reply-To: <ecno4v$h11$1@newsreader2.netcologne.de> References: <ecn00i$t2o$1@newsreader2.netcologne.de> <mailman.9872.1156515341.27775.python-list@python.org> <ecn22h$3o5$1@newsreader2.netcologne.de> <5a9ue2lrjh214ecmme09fsodhm3ico1ntm@4ax.com> <ecno4v$h11$1@newsreader2.netcologne.de> Message-ID: <44EF71AF.5010604@tim.thechases.com> > Is there a ready to use (free, best Open Source) tool able to sort lines > (each line appr. 20 bytes long) of a XXX GByte large text file (i.e. in > place) taking full advantage of available memory to speed up the process > as much as possible? Sounds like an occasion to use a merge-sort. The pseudo-code would be: break up the file into bite-sized chunks (maybe a couple megs each). Sort each of them linewise. Write them out to intermediate files Once you have these pieces, open each file read the first line of each one. [here] Find the "earliest" of each of those lines according to your sort-order. write it to your output file read the next line from that particular file return to [here] There are some optimizations that can be had on this as well...you can find the "earliest" *and* the "next earliest" of those lines/files, and just read from the "earliest" file until the current line of it passes "next earliest"...lather, rinse, repeat shifting "next earliest" to be the "earliest" and then find the new "next earliest". I don't know if the GNU "sort" utility does this, but I've thrown some rather large files at it and haven't choked it yet. -tkc From fredrik at pythonware.com Sun Aug 27 06:11:29 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 27 Aug 2006 12:11:29 +0200 Subject: Avoiding if..elsif statements In-Reply-To: <1156665361.369767.277380@b28g2000cwb.googlegroups.com> References: <1156545375.962486.49540@h48g2000cwc.googlegroups.com> <1156547346.647480.187910@b28g2000cwb.googlegroups.com> <mailman.9908.1156548808.27775.python-list@python.org> <1156665361.369767.277380@b28g2000cwb.googlegroups.com> Message-ID: <ecrr4g$jg0$2@sea.gmane.org> Tal Einat wrote: > This will work great if all of your functions recieve the same > argument(s). I assumed "every single function would be passing the same variables" meant exactly that, of course. </F> From bdesth.quelquechose at free.quelquepart.fr Sun Aug 6 07:09:36 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 06 Aug 2006 13:09:36 +0200 Subject: Is there an obvious way to do this in python? In-Reply-To: <mailman.8972.1154690979.27775.python-list@python.org> References: <mailman.8853.1154537129.27775.python-list@python.org><44d128e5$0$13484$636a55ce@news.free.fr><mailman.8884.1154590374.27775.python-list@python.org><1154602887.279222.37980@75g2000cwc.googlegroups.com><mailman.8925.1154627441.27775.python-list@python.org> <lci5d2tt124lqf2qr6br3a7eaidv534r5b@4ax.com> <mailman.8972.1154690979.27775.python-list@python.org> Message-ID: <44d5cbda$0$4767$626a54ce@news.free.fr> H J van Rooyen a ?crit : > "Dennis Lee Bieber" <wlfraed at ix.netcom.com> wrote: > (snip) > | If you go the web application route, each "login" would use a cookie > | to control session, so the application server can determine what > | functions to present to the user. You might even be able to use > | something like Plone to build the application server; it already has > | capability to present different views based upon login. > > Know squat about Plone - another thing to add to my list of reading *sigh* Well, actually, I would not bother too much reading about Plone here - Plone is (fairly complex and somewhat slow) CMS built on top of Zope, which is itself a web application server that's not easy to get started with and is (IMHO) definitively much more suited to CMS than to accounting apps. From jgodoy at gmail.com Sat Aug 19 13:59:25 2006 From: jgodoy at gmail.com (Jorge Godoy) Date: Sat, 19 Aug 2006 14:59:25 -0300 Subject: How to catch these kind of bugs in Python? References: <1156009543.993046.76720@75g2000cwc.googlegroups.com> Message-ID: <87mza0bo8y.fsf@gmail.com> "asincero" <asincero at gmail.com> writes: > In the above example, message should be set to 'Some obscure condition > occured.' if some_obscure_condition is True. But due to a lack of > sleep, and possibly even being drunk, the programmer has mistyped > message. These types of bugs would easily be caught in languages that > have a specific keyword or syntax for declaring variables before use. > I'm still fairly new to using Python on a more than casual basis, so I > don't know if Python has anyway to help me out here. Unit testing, running pylint, pychecker, etc. -- Jorge Godoy <jgodoy at gmail.com> From bugnthecode at gmail.com Tue Aug 29 15:14:42 2006 From: bugnthecode at gmail.com (bugnthecode) Date: 29 Aug 2006 12:14:42 -0700 Subject: Desktop Notification/Alerts In Python In-Reply-To: <1156872739.394427.111790@74g2000cwt.googlegroups.com> References: <1156781259.354526.142680@m79g2000cwm.googlegroups.com> <1156839399.221845.238200@p79g2000cwp.googlegroups.com> <1156872739.394427.111790@74g2000cwt.googlegroups.com> Message-ID: <1156878882.471707.145040@i42g2000cwa.googlegroups.com> Chaos wrote: > alex23 wrote: > > Chaos wrote: > > > I am looking for ways to have a Desktop Alert, like the one most IM > > > Messengers have (MSN, AIM) at the lower right above the taskbar. Can > > > anyone point me to the right resources to use? I get these alerts from gmail-notify. It's for linux, but a quick look over the source shows that it uses gtk which I believe to be a cross platform library (though may be a little ugly on windows) I wouldn't imagine it to be too hard to modify this to your needs. Project home page: http://gmail-notify.sourceforge.net/ HTH, Will From keegan.csmith at gmail.com Sun Aug 27 17:48:05 2006 From: keegan.csmith at gmail.com (keegan.csmith at gmail.com) Date: 27 Aug 2006 14:48:05 -0700 Subject: Persistent Session in CGI Message-ID: <1156715285.717012.91300@i42g2000cwa.googlegroups.com> Hi, I have started a new small web project, and was wondering if there are any good guides on how to do Persistent Sessions and Authentication using python and CGI. I don't really want too use Zope, because It's probably overkill for my tiny project. From fredrik at pythonware.com Wed Aug 23 14:58:06 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Aug 2006 20:58:06 +0200 Subject: how do you get the name of a dictionary? In-Reply-To: <1156350580.363393.256730@74g2000cwt.googlegroups.com> References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <pan.2006.08.21.03.33.27.84160@REMOVEME.cybersource.com.au> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> <mailman.9631.1156227418.27775.python-list@python.org> <1156264475.968894.221710@p79g2000cwp.googlegroups.com> <1156266720.205126.284050@i3g2000cwc.googlegroups.com> <1156268752.574983.123520@75g2000cwc.googlegroups.com> <pan.2006.08.22.20.05.58.528777@gmx.net> <1156281268.865624.302070@b28g2000cwb.googlegroups.com> <mailman.9666.1156281679.27775.python-list@python.org> <1156283135.985893.186500@m73g2000cwd.googlegroups.com> <mailman.9668.1156283600.27775.python-list@python.org> <1156284812.469380.274370@b28g2000cwb.googlegroups.com> <mailman.9686.1156315895.27775.python-list@python.org> <1156350580.363393.256730@74g2000cwt.googlegroups.com> Message-ID: <eci8ft$tml$1@sea.gmane.org> jojoba wrote: >> the fact that despite all attempts to explain how things work, you're >> still haven't realized that if you want the names of things, you should >> pass *namespaces* to your object viewer, not individual objects. > > And what im saying is that isnt it silly that we need pass an entire > namespace namespaces are objects too, you know. passing "an entire namespace" is no harder than passing any other object. </F> From larry.bates at websafe.com Fri Aug 4 20:15:55 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 04 Aug 2006 19:15:55 -0500 Subject: paramter passing question In-Reply-To: <1154724382.726685.258220@i3g2000cwc.googlegroups.com> References: <1154724382.726685.258220@i3g2000cwc.googlegroups.com> Message-ID: <44D3E33B.8040200@websafe.com> diffuser78 at gmail.com wrote: > I wrote a small app in wxPython using wxGlade as designer tool. wxGlade > brings and writes a lot of code by itself and thats where my confusion > started. Its about parameter passing. Here is my little confusion. > > ***************CODE BEGINS************************************ > class MyFrame1(wx.Frame): > def __init__(self, *args, **kwds): > ..... > ..... > def OnEdit(self, event): > sim_name = 'some_string' > win = MyFrame2(self, -1, "") > win.Show(True) > ******************************************************************** > > class MyFrame2(wx.Frame): > def __init__(self, *args, **kwds): > ..... > ..... > def onLaunch(self, event): > ## This function needs to use the parameter sim_name which is > in class MyFrame1-->OnEdit > ***************CODE ENDS************************************ > > I want to pass sim_name parameter to MyFrame2 in def OnEdit function > but I don't know how to do it. I tried couple of things but always got > some error. I have done some parameter passing in normal Python code > but *args and **kwds is a little confusing. > > Could you please tell me how to send parameter "sim_name" from > MyFrame1(in OnEdit function) and how to recieve it in MyFrame2 so that > I can use that parameter in MyFrame2 namespace. > > Every help is appreciated. > > Thanks > How about using the keyword args to pass it: class MyFrame1(wx.Frame): def __init__(self, *args, **kwds): ..... ..... def OnEdit(self, event): sim_name = 'some_string' win = MyFrame2(self, -1, "", sim_name=sim_name) win.Show(True) ******************************************************************** class MyFrame2(wx.Frame): def __init__(self, *args, **kwds): ..... ..... self.sim_name=kwds.get('sim_name', 'default sim_name') def onLaunch(self, event): ## This function needs to use the parameter sim_name which is ## self.sim_name can be used here -Larry Bates From skip at pobox.com Wed Aug 9 21:06:30 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 9 Aug 2006 20:06:30 -0500 Subject: Easy image rendering? In-Reply-To: <1155166070.085423.37420@b28g2000cwb.googlegroups.com> References: <1155166070.085423.37420@b28g2000cwb.googlegroups.com> Message-ID: <17626.34454.608358.315439@montanaro.dyndns.org> import PIL.Image img = PIL.Image.open(open("someimage.png", "rb")) img.show() No need for the extra open. Sorry... Skip From jyoti.chhabra at gmail.com Thu Aug 3 03:00:03 2006 From: jyoti.chhabra at gmail.com (JyotiC) Date: 3 Aug 2006 00:00:03 -0700 Subject: can this b done Message-ID: <1154588403.626530.72450@b28g2000cwb.googlegroups.com> hi, i hv a var of type IntVar, ca i get the name of this variable eg:- class someclass: def somefun(...): self.var=IntVar() .... def someotherfun(...): in this fun can i get the name of var. as in, can i get name var as a string 'var' Thanx From fredcdobbs127 at yahoo.com Sat Aug 26 16:06:07 2006 From: fredcdobbs127 at yahoo.com (Fred C. Dobbs) Date: 26 Aug 2006 13:06:07 -0700 Subject: Dive into Python question In-Reply-To: <1156620429.978438.317860@h48g2000cwc.googlegroups.com> References: <1156619547.658725.276750@p79g2000cwp.googlegroups.com> <1156620429.978438.317860@h48g2000cwc.googlegroups.com> Message-ID: <1156622767.072933.253320@i42g2000cwa.googlegroups.com> Thanks, after I looked into it I realized that the output order can change arbitarily. It just seems kind of strange that the first example is one where your output might not match what the author tells you it should be - and yet there's no mention of this in the book (at least at that point.) From meyer at acm.org Tue Aug 15 12:31:08 2006 From: meyer at acm.org (Andre Meyer) Date: Tue, 15 Aug 2006 18:31:08 +0200 Subject: Best IDE for Python In-Reply-To: <1155657824.729616.161420@b28g2000cwb.googlegroups.com> References: <1155541849.350392.31190@h48g2000cwc.googlegroups.com> <mailman.9297.1155545620.27775.python-list@python.org> <ebqc2f$3e3$1@news-int.gatech.edu> <1155657824.729616.161420@b28g2000cwb.googlegroups.com> Message-ID: <7008329d0608150931g3f4a0834x481a6e177984f49f@mail.gmail.com> PyDev is really nice. I use it a lot and it works great. It's just a bit heavy and why should one need a Java IDE for Python development ;-) Another "issue" is the lack of integration with a UML tool (code generation and reverse engineering), though an ArgoUML plugin is in the making (not for eclipse). btw What Web/XML plugins are you using with eclipse? regards Andre On 15 Aug 2006 09:03:44 -0700, akameswaran at gmail.com <akameswaran at gmail.com> wrote: > > I've had a similar experience and tried about everything. Personally - > eclipse with PyDev has been the winner for me. I also still do a bunch > of Java coding - so there is an added benefit of one tool across > languages. The final thing I really like with eclipse is the svn > plugins - making life very easy. Also, if your doing web/xml and other > stuff - there is a plugin for eclipse for it ;) Not all the plugins > work as seemlessly together (i abandon eclipse for the majority of > plone/zope stuff - most of it isn't python - and setting up eclipse to > be happy with the output of archgen has not been worth the bother - I'm > sure it's possible) > > PyLint can kind of be a pain if your on a low powered box, but tweaking > the settings (and I had to do a bit of tweaking) can alleviate the > problems, but still let you reap the benefits. > > Anand > > Yu-Xi Lim wrote: > > Michiel Sikma wrote: > > > By FOS, do you mean FOSS (Free and Open Source Software)? I've never > > > seen the acronym FOS used. > > > > Maybe he was trying for "Free Open Source IDE" without the > > semi-redundant "Software" > > > > > I personally use Eclipse with PyDev. > > > http://www.eclipse.org/ > > > http://pydev.sourceforge.net/ > > > > Eclipse+PyDev has the advantage over emacs when it comes to big > > projects, IMO. It has features like refactoring, better project > > management, code coverage. emacs has the advantage of being faster and > > smaller, and if all you need is a syntax-aware (smart indentation, > > syntax highlighting) editor and integrated debugger, emacs is more than > > enough. > > > > I've tried the other free IDEs like IDLE, SPE, eric3, TruStudio (for > > Eclipse), Boa, Komodo, WingIDE. I have various issues with them, > > including instability, poor automatic indentation, bad GUI (too many > > subwindows or uncustomizable), costly, no refactoring, and no project > > management. > > > > It's strangely ironic. I consider Eclipse to be a lousy Java IDE > > especially compared to commercial offerings and yet that's what the > > project started out as. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Dr. Andre P. Meyer http://python.openspace.nl/meyer TNO Defence, Security and Safety http://www.tno.nl/ Delft Cooperation on Intelligent Systems http://www.decis.nl/ Ah, this is obviously some strange usage of the word 'safe' that I wasn't previously aware of. - Douglas Adams -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060815/177f7f8a/attachment.html> From sjmachin at lexicon.net Wed Aug 9 19:56:34 2006 From: sjmachin at lexicon.net (John Machin) Date: 9 Aug 2006 16:56:34 -0700 Subject: technique to enter text using a mobile phone keypad (T9 dictionary-based disambiguation) In-Reply-To: <1155166420.058201.81630@n13g2000cwa.googlegroups.com> References: <mailman.9116.1155077147.27775.python-list@python.org> <1155095477.440347.149350@m79g2000cwm.googlegroups.com> <1155154447.409931.55750@p79g2000cwp.googlegroups.com> <1155156341.298792.188280@75g2000cwc.googlegroups.com> <1155164070.665244.193080@b28g2000cwb.googlegroups.com> <1155166420.058201.81630@n13g2000cwa.googlegroups.com> Message-ID: <1155167794.239636.202050@n13g2000cwa.googlegroups.com> bearophileHUGS at lycos.com wrote: > John Machin: > > 2. All responses so far seem to have missed a major point in the > > research paper quoted by the OP: each word has a *frequency* associated > > with it. When there are multiple choices (e.g. "43" -> ["he", "if", > > "id", ...]), the user is presented with the choices in descending > > frequency order. > > I haven't missed it; if you use the instrumeted PAQ compressor > approach, you gain the frequency information and more :-) > I didn't comment on that before because: (1) I thought it sounded like a tool in search of a problem -- the problem being to produce a user interface that meets conflicting goals (few keystrokes and few mistakes and minimal hurl-the-device-out-of-the-window frustrations); compression of the dictionary is of course desirable but I wouldn't have thought that that should have been foremost in the design process. (2) Googling for instrumen?ted PAQ compress(or|ion) yielded nothing that seemed relevant -- can you supply a link or two? Cheers, John From ms at cerenity.org Fri Aug 11 07:39:51 2006 From: ms at cerenity.org (Michael) Date: Fri, 11 Aug 2006 12:39:51 +0100 Subject: Component framework References: <1155286650.177024.284770@i42g2000cwa.googlegroups.com> Message-ID: <44dc6b4c$0$18509$ed2e19e4@ptn-nntp-reader04.plus.net> Jan Svec wrote: > Hi all, > some time ago I've seen an interesting component framework for Python > but I don't remember the name. I remember only one example. There were > two components: Wheel and Car, Wheel were then inserted four times into > Car and so on. This framework has had lazy instantiation of child > components. > > Does anybody know the name of this framework? PEAK - http://peak.telecommunity.com/Articles/WhatisPEAK.html """PEAK is the "Python Enterprise Application Kit". If you develop "enterprise" applications with Python, or indeed almost any sort of application with Python, PEAK may help you do it faster, easier, on a larger scale, and with fewer defects than ever before. The key is component-based development, on a reliable infrastructure.""" FWIW, I don't use it, but I'm aware of it. I use a component framework I develop for work & fun called Kamaelia - but PEAK is what you're thinking of. BTW, since it might be helpful, from your request I punched the following search terms into google - which links to the tutorial mentioning cars and wheels: * Search terms: wheel car component lazy python :-) Best Regards, Michael. -- Michael Sparks, Kamaelia Project Lead http://kamaelia.sourceforge.net/Home http://yeoldeclue.com/blog From Iljya.Kalai at gmail.com Tue Aug 15 15:27:14 2006 From: Iljya.Kalai at gmail.com (Iljya) Date: 15 Aug 2006 12:27:14 -0700 Subject: Error with: pickle.dumps(numpy.float32) Message-ID: <1155670034.655485.214360@i3g2000cwc.googlegroups.com> Hello, I need to pickle the type numpy.float32 but encounter an error when I try to do so. I am able to pickle the array itself, it is specifically the type that I cannot pickle. I am using: Numpy version: 0.9.4 Python version: 2.4.3 Windows XP Here is the code that reproduces the error: ______________________________________ import numpy import pickle pickle.dumps(numpy.float32) Output: PicklingError: Can't pickle <type 'float32_arrtype'>: it's not found as __builtin__.float32_arrtype ______________________________________ Any suggestions would be much appreciated. Thanks, Iljya Kalai From python at hope.cz Tue Aug 22 07:06:58 2006 From: python at hope.cz (Lad) Date: 22 Aug 2006 04:06:58 -0700 Subject: How to decode a string In-Reply-To: <mailman.9632.1156233052.27775.python-list@python.org> References: <1156170296.076521.174180@i3g2000cwc.googlegroups.com> <mailman.9610.1156171864.27775.python-list@python.org> <1156175385.580508.302330@m73g2000cwd.googlegroups.com> <pan.2006.08.21.17.10.16.104915@gmx.net> <1156229239.418473.248090@i3g2000cwc.googlegroups.com> <mailman.9632.1156233052.27775.python-list@python.org> Message-ID: <1156244818.061709.115190@m73g2000cwd.googlegroups.com> Fredrik Lundh wrote: > Lad wrote: > > > for > > print repr(RealName) command > > I will get > > > > P?ibylov\xe1 Ludmila > > where instead of ? should be also a character > > that's not very likely; repr() always includes quotes, always escapes > non-ASCII characters, and optionally includes a Unicode prefix. > > please try this > > print "*", repr(RealName), type(RealName), "*" > > and post the entire output; that is, *everything* between the asterisks. > The result of print "*", repr(RealName), type(RealName), "*" is * 'Fritschov\xe1 Laura' <type 'str'> * Best regards, L From mail at microcorp.co.za Thu Aug 3 01:53:33 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Thu, 3 Aug 2006 07:53:33 +0200 Subject: Is there an obvious way to do this in python? References: <mailman.8853.1154537129.27775.python-list@python.org> <1154547404.749534.320700@m79g2000cwm.googlegroups.com> Message-ID: <016d01c6b6cd$2e6ec4c0$03000080@hendrik> "Nick Vatamaniuc" <vatamane at gmail.com> wrote: | HJ, | | As someone already posted, the backend sounds very much like a | database, so why not use a database: transactions, specific views for | different users, limited access and so on = database! | Give PostgresSQL a try... *nods* - looks like I am going to have to do this.... | As far as presenting a different GUI to users, you can also do it based | on the database. In other words have a common login screen and if the | usertype from the database is returned as 'restricted' draw one | interface, if it is returned as 'full' draw the full interface. Even if | the restricted user will get the full interface up it won' t be | functional because the database would restrict writes to certain | tables/columns. This is the guts of my question - if I dont know all the types now, how do I make the front end so that I can easily update it as time reveals new requirements - a la banking style terminals - see my reply to Simon please | Remote update of code is also possible, but you'll have to implement | some kind of update server to which you can periodically send Python | files, those files will be installed on the machine by the update | server. You can try playing with Twisted to handle the networking. Or | just write a simple script to send stuff over scp/ssh -- that's what I | would do (start the ssh server, install public keys and then just scp | stuff over to the machines assuming they are online most of the | time...). This kind of addresses getting the stuff on to the server on the site for me - I would like the front end to be more dynamic... | | The problem will be if something goes wrong in the updated file or with | the update server then the whole system will be down (an off-by-one | error in the GUI db client code and all of the sudden all your users | will be writing bad data to the database... all at the same time). So | you will need to do frequent backups of the database, but you probably | know this already... | | Hope this helps, | Nick Vatamaniuc *grin* yes and it scares the s**t out of me - this is why I like the "do one thing at a time to completion " approach - much easier to recover when things go wrong... - Hendrik From cga2000 at optonline.net Wed Aug 16 02:27:43 2006 From: cga2000 at optonline.net (cga2000) Date: Wed, 16 Aug 2006 02:27:43 -0400 Subject: using python at the bash shell? In-Reply-To: <1155681933.117671.54450@i3g2000cwc.googlegroups.com> References: <44d7e364$0$24980$c3e8da3@news.astraweb.com> <mailman.9071.1155002101.27775.python-list@python.org> <R31Cg.2645$No6.51906@news.tufts.edu> <1155054162.683298.21760@m73g2000cwd.googlegroups.com> <mailman.9383.1155674099.27775.python-list@python.org> <1155681933.117671.54450@i3g2000cwc.googlegroups.com> Message-ID: <20060816062743.GL12939@turki.gavron.org> On Tue, Aug 15, 2006 at 06:45:33PM EDT, Simon Forman wrote: > cga2000 wrote: [..] > Why do you write "most commands" .. what type of command might not be > > run by "putting '!' before them?" > > Well, I wrote that just to hedge my bets, but here's an example: I set > up lesspipe and source-highlight to add syntax highlighting to various > file types when viewed through less. But using "!less neat.py" in > Ipython doesn't work because (I'm guessing here) Ipython doesn't handle > the color escape codes. It winds up looking like this: > > ESC[31m#!/usr/local/bin/python2.5ESC[m > ESC[01;34mfromESC[m random ESC[01;34mimportESC[m random as f > > > ESC[01;34mdefESC[m > ESC[01;30mgESC[mESC[31m(ESC[mESC[31m)ESC[mESC[31m:ESC[m > n1 ESC[31m=ESC[m ESC[01;30mfESC[mESC[31m(ESC[mESC[31m)ESC[m > ESC[01;34mwhileESC[m TrueESC[31m:ESC[m > n2 ESC[31m=ESC[m ESC[01;30mfESC[mESC[31m(ESC[mESC[31m)ESC[m > yield n1 ESC[31m-ESC[m n2 > n1 ESC[31m=ESC[m n2 > > Ew. > > So in this case I'd have to "!bash" then "less neat.py"... you could use "vim -R" -- or its alter ego "view" .. "!view neat.py" I tried that just now under ipython and I end up with the exact same syntax highlighting that I have when I run vim from the bash prompt. The problems I am having are mainly due to my bash customization -- aliases, functions .. all that stuff is no longer being recognized .. and also some bash built-ins such as "cd" do not do anything .. maybe ipython starts a subprocess that switches and then immediately exits .. so when I get the prompt back I'm back where I started. I guess reading the ipython manual and trying to understand what I'm doing before going any further wouldn't hurt.. :-) > > > In the linux world it would be rather interesting if a distro was > > available that uses nothing but python. > > > > The installer .. the startup scripts .. utilities .. etc. > > > > Maybe there is such a thing and I'm just not aware of it? > > IMHO it would be neat, but it'd be kind of a "stunt". There's a ton > of excellent code in most any linux distro *not* written in python. > quite a large project, I would imagine. > > Since it would be byt-code being executed it would be faster than > > regular shell stuff and a lot easier to customize/maintain. > > Mmmm... I bet it'd be hard to beat, say, grep... Or any of the > small, custom-purpose C-coded tools. (then there's make... gcc... > not easy to rewrite those.. just off the top of my head...) > Sorry .. couldn't think of a better word .. but by "utilities" I meant all those shell scripts in /usr/bin that come with gnu/linux distros and mostly appear to front-end "real" programs. I guess a python "system shell" could invoke all the C-coded stuff the same way bash does, no..? 'nuff [OT] for now.. Thanks, cga From tim at tdw.net Sun Aug 13 19:36:16 2006 From: tim at tdw.net (Tim Williams) Date: Mon, 14 Aug 2006 00:36:16 +0100 Subject: Nested if and expected an indent block In-Reply-To: <G49609990.86.24345.1@mx-extra> References: <G49609990.86.24345.1@mx-extra> Message-ID: <9afea2ac0608131636p3db93f9eo1062c2f7104bffba@mail.gmail.com> On 13 Aug 2006 16:28:45 -0700, kagard at gmail.com <RentInGhent at gmail.com> wrote: > Greetings: > > I'm brand new to Python and decided to write a syllogism solver for a > class I'm taking. At the start of the program, I define a function that > classifies the type of each statement in the syllogism. Python tells me > that it is expecting an indented block at the s in "some". I can see > what I'm doing wrong. Here's the code: > > def class_stmt(q,c): > """ > This function classifies a statement according to the rules of > categorical syllogisms and returns A, E, I, O to identify the > statement type. > """ > if q.lower() == "all": > if "not" in c: > stmt_type = "E" > else: > stmt_type = "A" > elif q.lower() == "some" # s in some is highlighted > if "not" in c: > stmt_type = "O" > else: > stmt_type = "I" It might be the missing colon after "some" If that's a typo on your email rather than in your script you should post the full traceback of the error. HTH :) From g.brandl-nospam at gmx.net Tue Aug 22 12:12:36 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Tue, 22 Aug 2006 18:12:36 +0200 Subject: CONSTRUCT - Module Attributes and Execution Environment In-Reply-To: <FbydnandyMuUtHbZnZ2dnUVZ_smdnZ2d@comcast.com> References: <1156253227.092971.36510@74g2000cwt.googlegroups.com> <FbydnandyMuUtHbZnZ2dnUVZ_smdnZ2d@comcast.com> Message-ID: <ecfadm$gh0$1@news.albasani.net> Larry Bates wrote: > lazaridis_com wrote: >> I would like to change the construct: >> >> if __name__ == '__main__': >> >> to something like: >> >> if exec.isMain(): >> >> My (OO thought) is to place a class in an separate code module and to >> instantiate an singleton instance which would keep th something like >> this: >> >> class ExecutionEnv: >> def isMain(self) >> if CALLING_MODULE.__name__ == '__main__': >> return true >> else >> return false >> >> exec = ExecutionEnv() >> >> How to I get access to the CALLING_MODULE ? >> >> - >> >> Are ther alternative constructs/mechanism available, which could be >> used to add this functionality possiby directly to a code-module? >> > Two thoughts: > > 1) Don't call a class instance exec, it will mask the built-in > exec statement. He won't be able to ;) Georg From blue99 at interia.pl Mon Aug 21 06:59:22 2006 From: blue99 at interia.pl (Rob Wolfe) Date: 21 Aug 2006 03:59:22 -0700 Subject: Regular Expression question In-Reply-To: <1156156724.165790.208880@b28g2000cwb.googlegroups.com> References: <1156153916.849933.178790@75g2000cwc.googlegroups.com> <1156154876.874272.283160@i3g2000cwc.googlegroups.com> <1156156724.165790.208880@b28g2000cwb.googlegroups.com> Message-ID: <1156157962.192238.116160@74g2000cwt.googlegroups.com> stevebread at yahoo.com wrote: > Thanks, i just tried it but I got the same result. > > I've been thinking about it for a few hours now and the problem with > this approach is that the .*? before the (?=tag2) may have matched a > tag1 and i don't know how to detect it. Maybe like this: 'tag1.+?name="(.+?)".*?(?:<)(?=tag2).*?="adj__(.*?)__' HTH, Rob From bdesth.quelquechose at free.quelquepart.fr Sun Aug 27 16:18:57 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 27 Aug 2006 22:18:57 +0200 Subject: Job Jar In-Reply-To: <1156271103.398243.45870@b28g2000cwb.googlegroups.com> References: <1156271103.398243.45870@b28g2000cwb.googlegroups.com> Message-ID: <44f1fb7e$0$9026$626a54ce@news.free.fr> D a ?crit : > Hello, I apologize in advance for the vague description, but as of now > I only have an idea of what I'd like to do, and need some guidance as > to if it is feasible, and where to begin. Basically, I'd like to > create a web-based "job jar", that users in my office can access in > order to view, and "take ownership" of, misc. office tasks. One idea I > had was that when users select a task (i.e. by selecting a check box > and clicking an UPDATE button), tasks are automatically put in an In > Progress list (which identifies the task and the user who took > ownership of it) - then, when the action is complete, the user updates > it again which puts it in a Completed list (again, with the task > description and the user who completed it). However, only certain > users should be able to add and modify task descriptions. http://trac.edgewall.org/ From claird at lairds.us Fri Aug 18 07:36:53 2006 From: claird at lairds.us (Cameron Laird) Date: Fri, 18 Aug 2006 11:36:53 +0000 Subject: Subprocess confusion: how file-like must stdin be? References: <9sker3-7g8.ln1@lairds.us> <8skae2l0or9g5d53jdj9g4bafandib75qa@4ax.com> <slrneeassv.c4m.nick@irishsea.home.craig-wood.com> Message-ID: <lblgr3-r48.ln1@lairds.us> In article <slrneeassv.c4m.nick at irishsea.home.craig-wood.com>, Nick Craig-Wood <nick at craig-wood.com> wrote: >Dennis Lee Bieber <wlfraed at ix.netcom.com> wrote: >> On Thu, 17 Aug 2006 17:16:25 +0000, claird at lairds.us (Cameron Laird) >> declaimed the following in comp.lang.python: >> >> > Question: >> > import subprocess, StringIO >> > >> > input = StringIO.StringIO("abcdefgh\nabc\n") >> >> Here you override the builtin function "input()" >> > # I don't know of a compact, evocative, and >> > # cross-platform way to exhibit this behavior. >> > # For now, depend on cat(1). >> > p = subprocess.Popen(["cat"], stdout = subprocess.PIPE, >> > stdin = response) >> >> Here you specify the non-existant "response" > >Assume the OP meant to write this > >>>> import subprocess, StringIO >>>> inp = StringIO.StringIO("abcdefgh\nabc\n") >>>> p = subprocess.Popen(["cat"], stdout = subprocess.PIPE, stdin = inp) >Traceback (most recent call last): > File "<stdin>", line 1, in ? > File "/usr/lib/python2.4/subprocess.py", line 534, in __init__ > (p2cread, p2cwrite, > File "/usr/lib/python2.4/subprocess.py", line 830, in _get_handles > p2cread = stdin.fileno() >AttributeError: StringIO instance has no attribute 'fileno' >>>> . . . Yes; my apologies for the confusion I introduced by "editing for publication", and doing it badly. Your interactive session does indeed exhibit the behavior that puzzles me. My expectation was that StringIO and the std* parameters to Popen() were made for each other; certainly there are many cases where stdout and stderr can be redirected *to* a StringIO. Is it simply the case that stdin demands a more file-like object? While that disappoints me, I certainly can program around it. My question, then: does stdin effectively require something really in the filesystem, or perhaps the stdout of a previous subprocess? Is there no built-in way to feed it an in-memory construct? From sjmachin at lexicon.net Wed Aug 16 01:38:13 2006 From: sjmachin at lexicon.net (John Machin) Date: 15 Aug 2006 22:38:13 -0700 Subject: Printing n elements per line in a list In-Reply-To: <m2wt992xl6.fsf@unique.fqdn> References: <1155685889.626881.37040@m73g2000cwd.googlegroups.com> <m21wrh4ily.fsf@unique.fqdn> <1155692031.569092.290900@m73g2000cwd.googlegroups.com> <m2wt992xl6.fsf@unique.fqdn> Message-ID: <1155706693.557242.249340@75g2000cwc.googlegroups.com> Dan Sommers wrote: > On 15 Aug 2006 18:33:51 -0700, > "John Machin" <sjmachin at lexicon.net> wrote: > > ... ctr = (ctr + 1) % n > > I'm old enough to remember the days when we avoided division like the > plague. Remember those zippy 1MHz (yes, that's an M and not a G) CPUs > with less than a handful of 8-bit registers? Old habits die hard. ;-) > How did you avoid division when testing for leap year? From pmaupin at gmail.com Sun Aug 27 20:52:26 2006 From: pmaupin at gmail.com (Patrick Maupin) Date: 27 Aug 2006 17:52:26 -0700 Subject: Don't use __slots__ (was Re: performance of dictionary lookup vs. object attributes) In-Reply-To: <ectbls$ofa$1@gide.ita.chalmers.se> References: <mailman.9853.1156495094.27775.python-list@python.org> <1156621904.481215.243080@m73g2000cwd.googlegroups.com> <mailman.9927.1156624141.27775.python-list@python.org> <1156625365.346825.18630@74g2000cwt.googlegroups.com> <ectbls$ofa$1@gide.ita.chalmers.se> Message-ID: <1156726346.818481.107280@i3g2000cwc.googlegroups.com> Jacob Hallen wrote: > Patrick Maupin <pmaupin at gmail.com> wrote: > >Also, as I noted, I _do_ use them on occasion, so if there really _are_ > >potential pitfalls there, I would like to understand exactly what they > >are, so my ears perk up whenever I notice a __slots__ discussion, but > >so far I have been repeatedly disappointed, in that I always see > >someone saying "don't do that" but I have never seen a cogent technical > >argument about how my scripts which __slots__ are going to suddenly, > >irretrievably break one day. > > The proper use of__slots__is to save space in objects. Instead of having > a dynamic dict that allows adding attributes to objects at anytime, > there is a static structure which does not allow additions after creation. > This saves the overheadof one dict for every object that uses slots. > While this is sometimes a useful optimisation, it would be completely > unnecessary if the Python interpreter was dynamic enough so that it would > only require the dict when there actually were additions to the object. > > Unfortunately there is a side effect to slots. They change the behaviour of > the objects that have slots in a way that can be abused by control freaks > and static typing weenies. This is bad, because the contol freaks should > be abusing the metaclasses and the static typing weenies should be abusing > decorators, since in Python,there should be only one obvious way of doing something. > > Making CPython smart enough to handle saving space without __slots__ is a a major > undertaking, which is probably why it is not on the list of changes for P3k (yet). > > Jacob Hall?n Thanks, Jacob! Saving space is exactly why I use __slots__, so I can sleep better now :) Regards, Pat From grahn+nntp at snipabacken.dyndns.org Sun Aug 20 18:01:32 2006 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 20 Aug 2006 22:01:32 GMT Subject: Permission Denied References: <mailman.9557.1156032685.27775.python-list@python.org> <1156038847.616137.61800@m79g2000cwm.googlegroups.com> <cPRFg.1547$dB.1365@read2.cgocable.net> <ec98pb$l01$2@lust.ihug.co.nz> <dbWFg.1314$sM1.1270@read1.cgocable.net> <ec9gci$1sk1$1@ulysses.news.tiscali.de> <87lkpjv8bg.fsf@gmail.com> Message-ID: <slrneehk7f.39c.grahn+nntp@frailea.sa.invalid> On Sun, 20 Aug 2006 10:35:31 -0300, Jorge Godoy <jgodoy at gmail.com> wrote: > Stargaming <stargaming at gmail.com> writes: > >> In the most cases, PATH is preconfigured to include "." (. is the current >> directory as .. is the parent one). > > I most cases on Unix boxes it isn't configured to include ".". Indeed -- but "Stargaming" might have missed a negation somewhere, because he went on to say [rearranged from the above] >> You can use ./yourpythonscript in this >> case. which is precisely what you /don't/ need to type if you have placed . in your $PATH. > The solution of creating a directory and adding it to PATH is the best one, > IMHO. Having a "~/bin" is also common for Linux and some distributions of it > already ship with it in /etc/skel and in the PATH, so just put a link there or > copy your scripts there. > >> The most "advanced" way would be expanding PATH with >> /home/youraccount/python/learning (use PATH=$PATH:/path/here..). > > Yes. This is the best. I wouldn't want random scripts under development ending up in my $PATH, not even my own. When you're just playing with/developing scripts, it's better to execute them by path (./foo.py etc). When you think they work and you have a long-term use for them, you install them globally, or copy, move or link them into your ~/bin/. /Jorgen -- // Jorgen Grahn <grahn@ Ph'nglui mglw'nafh Cthulhu \X/ snipabacken.dyndns.org> R'lyeh wgah'nagl fhtagn! From you at cogeco.ca Mon Aug 14 11:43:45 2006 From: you at cogeco.ca (AlbaClause) Date: Mon, 14 Aug 2006 11:43:45 -0400 Subject: looking for a simple way to load a program from another python program.. References: <1155498660.285772.144140@m73g2000cwd.googlegroups.com> Message-ID: <eP0Eg.103881$hp.37017@read2.cgocable.net> Eric_Dexter at msn.com wrote: > I was looking for a simple way to load a simple python program from > another python program. > > I tried > > os.system(cabel) > > The file name is cabel.py a csound instrument editor.. > > The error I am getting is > > Traceback (most recent call last): > File "C:\Python24\Lib\site-packages\boa-constructor\test of > snake\Frame1.py", line 212, in OnCabelItems0Menu > os.system(cabel) > NameError: global name 'cabel' is not defined > Localisation of messages is disabled, using default language. > time resolution is 279.365 ns > > This is with cabel in the current directory. I have managed to use > import to run it but it will only do it once. I may be able to use the > exec commands but I don't want to exit the program I am using only to > run other programs and then exit. I would also perfer that cabel is in > it's own directory. > > thanks in advance for any help > > http://www.stormpages.com/edexter/csound.html I am new to Python coding myself, but I've found that the easiest way to start another script from within a script, is to use the execfile('filename.py') command. There may be better ways of loading other Python scripts -- better ways that I'm not yet aware of -- but execfile() works for me. -- -- There are several things that I will never be: * I will never be attracted to females. * I will never enjoy the company of others. Exactly how these realities bode for my enemy, is not of my concern. From jfunk at funktronics.ca Thu Aug 31 13:21:14 2006 From: jfunk at funktronics.ca (James Oakley) Date: Thu, 31 Aug 2006 14:21:14 -0300 Subject: Need Python for Linux (Suse 10.1) In-Reply-To: <7.0.1.0.2.20060831020826.05688418@rcblue.com> References: <7.0.1.0.2.20060831020826.05688418@rcblue.com> Message-ID: <200608311421.14272.jfunk@funktronics.ca> On Thursday 31 August 2006 6:16 am, Dick Moores wrote: > I've got a friend interested in trying out Python. I sent him to > http://www.python.org/download/linux/ but he's uncertain as to what to > download. He's rather get a new download than use what was on his Suse > disk. His box is an x86. > > Any chance Python 2.4.3 compressed source tarball would be suitable for > him? He already has it. Python is installed by default on most Linux distributions, including SUSE. If he wants Python IDEs, libraries, and tools, he should open up YaST, select "Software Management", select the search filter, and enter python in the search box. There's a ton of Python stuff on SUSE, and there's even more in my YaST-compatible repo at http://repos.opensuse.org/home:/jimfunk/ . -- James Oakley jfunk at funktronics.ca From eyal.lotem at gmail.com Sat Aug 19 09:34:44 2006 From: eyal.lotem at gmail.com (Eyal Lotem) Date: Sat, 19 Aug 2006 16:34:44 +0300 Subject: timezones and time_t References: <1155931981.943667.214910@m73g2000cwd.googlegroups.com> Message-ID: <ec741k$8s1$1@news2.netvision.net.il> MrBlueSky wrote: > Hi, > I've got a Python application that (as well as lots of other stuff!) > has to translate time_t values into strings in the TZ of the users > choice. Looking at the Python Library Reference, I can see no platform > independent way of setting the TZ that time.localtime() returns - > tzset() is marked as only available on Unix and that is indeed the > case. > > Is there really nothing "shipped as standard"? I'm using Python 2.4.3 > on Windows XP. > > If not, what's the de-facto standard... pytz? > > Ta! > > John All of the timezone stuff in the standard C/Python libraries is very badly named and the use of implicit 'TZ' variables in various functions without a hint in their __doc__ is also annoying. Basically, I recommend just doing your own TZ translation: time.asctime(time.gmtime(time.time() + TZOFFSET)) My name recommendations for alternative time interface (t=float-time_t, tt=timetuple, local_ prefix=function converts via tz parameters): time.time -> time.gmt Return the current GMT as a float time_t time.local_t -> time. Return the current Local Time as a float time_t If argument is given, convert it to local format. time.asctime -> time.str Return the given time_t as a string. No conversions done. time.ctime -> time.local_str Remove in favor of: time.str(time.local_t) time.mktime -> time.t_of_tt time.gmtime -> time.tt_of_t time.localtime -> Remove in favor of: time.tt_of_t(time.local_t) These functions above will prevent a lot of confusion, because you are forced to either use: time.local_t or time.gmt, and thus you are aware of what the time_t you are using means. When you use time.str no implicit conversion takes place as in time.ctime, and confusion is avoided. Do you think this is worth a PEP? From steve at holdenweb.com Wed Aug 23 22:04:59 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 24 Aug 2006 03:04:59 +0100 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Aug 23) In-Reply-To: <wm2Hg.2709$No6.52718@news.tufts.edu> References: <eci8bf$nql$1@lairds.us> <wm2Hg.2709$No6.52718@news.tufts.edu> Message-ID: <ecj1ff$579$1@sea.gmane.org> John Salerno wrote: > Jack Diederich wrote: > > >> David Wahler is no longer out of the office. >> http://groups.google.com/groups/search?q=David+Wahler+out+of+office > > > LOL. That's the best part this week! :) Can anyone remember when David Wahler got back? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From boris.dusek at gmail.com Mon Aug 28 11:25:05 2006 From: boris.dusek at gmail.com (=?iso-8859-1?B?Qm9yaXMgRHWaZWs=?=) Date: 28 Aug 2006 08:25:05 -0700 Subject: Truly platform-independent DB access in Python? In-Reply-To: <44f2bade$0$13039$626a54ce@news.free.fr> References: <1156748466.739709.117850@h48g2000cwc.googlegroups.com> <44f2bade$0$13039$626a54ce@news.free.fr> Message-ID: <1156778705.807852.140510@75g2000cwc.googlegroups.com> Bruno Desthuilliers wrote: > bobrik wrote: > > Hello, > > > > I am using the Python DB API for access to MySQL. But it is not > > platform-independent > > It is. You don't have to change your Python code according to the OS or > CPU. > What I mean is that wiht platform-independent access, I should be able to not care on which operating system is the web server accessing my scripts where I use MySQLdb which I have to install (and therfore platform-dependently) compile myself. The important point is that MySQLdb is installed as an extra module. So you have to compile it manually, but what if the OS with server accessing the site that is on shared area changes? From johnjsal at NOSPAMgmail.com Sun Aug 13 17:27:59 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 13 Aug 2006 17:27:59 -0400 Subject: outputting a command to the terminal? Message-ID: <44df99f7$0$25025$c3e8da3@news.astraweb.com> Here's my new project: I want to write a little script that I can type at the terminal like this: $ scriptname package1 [package2, ...] where scriptname is my module name and any subsequent arguments are the names of Linux packages to install. Running the script as above will create this line: sudo aptitude install package1 package2 ... It will run that line at the terminal so the package(s) will be installed. Now, the extra functionality I want to add (otherwise I would just install them normally!) is to save the package names to a text file so I can now the names of programs I've manually installed, if I ever want to check the list or remove packages. So creating the proper bash command (sudo aptitude install ...) is easy, and writing the names to a file is easy. But I have two questions: 1. First of all, does Linux keep track of the packages you manually install? If so, then I won't have to do this at all. 2. Assuming I write this, how do output the bash command to the terminal? Is there a particular module that Python uses to interact with the terminal window that I can use to send the install command to the terminal? Thanks. From fpemberton133 at yahoo.com Thu Aug 10 14:39:41 2006 From: fpemberton133 at yahoo.com (f pemberton) Date: 10 Aug 2006 11:39:41 -0700 Subject: easy string formating question Message-ID: <1155235180.871436.22480@75g2000cwc.googlegroups.com> I have kind of an interesting string, it looks like a couple hundred letters bunched together with no spaces. Anyway, i'm trying to put a "?" and a (\n) newline after every 100th character of the string and then write that string to a file. How would I go about doing that? Any help would be much appreciated. From vyzasatya at gmail.com Thu Aug 24 00:39:25 2006 From: vyzasatya at gmail.com (Vyz) Date: 23 Aug 2006 21:39:25 -0700 Subject: Translating Javascript programs to python. In-Reply-To: <mailman.9754.1156384924.27775.python-list@python.org> References: <1156264202.542785.172270@74g2000cwt.googlegroups.com> <1156371324.186510.273930@75g2000cwc.googlegroups.com> <mailman.9754.1156384924.27775.python-list@python.org> Message-ID: <1156394365.753871.216460@75g2000cwc.googlegroups.com> Yes, this is a trimmed down version of padma, a generic indic transliteration tool Thanks for comments though. Terry Reedy wrote: > "Vyz" <vyzasatya at gmail.com> wrote in message > news:1156371324.186510.273930 at 75g2000cwc.googlegroups.com... > > Its a module to transliterate from telugu language written in roman > > script into native unicode. right now its running in a browser window > > at www.lekhini.org I Intend to translate it into python so that I can > > integrate into other tools I have. I am able to pass arguments and get > > output from the script also would be OK. or how about ways to wrap > > these javascript functions with python. > > Leaving aside the code the manipulated the display and user interaction, > the code should be pretty straightforward logic (if-else statements) and > table lookups, so translation to Python should be straightforward also. > > I checked parser.js. I don't know javascript but it looks to me like a > mixture of C and Python. The for loop headers have to be rewritten, and > the switch changed to if-elif. What looks different is the attachment as > attributes of method functions to functions rather than classes. > > As for 'wrapping': can you get a standard javascript interpreter? If so, > you could possibly adjust the js so you can pipe a roman string to the js > program and have it pipe back the telegu unicode version. > > >> > I have a script with hundreds of lines of javascript spread accross 7 > >> > files. Is there any tool out there to automatically or > >> > semi-automatically translate the code into python. > > unicode.js is mostly a few hundred verbose lines like > > Unicode.codePoints[Padma.lang_TELUGU].letter_PHA = "\u0C2B"; > > that setup the translation dict. Because the object model is different, I > suspect that these all need to be changed, but, I also suspect, in a > mechanical way. > > If one were starting in Python, one might either just define a dict more > compactly like > TEL_uni = {letter_PHA:"\u0C2B", ...} > *or* probably better, use the builtin unicodedata module as much as > possible. > > >>> import unicodedata as u > >>> pha = u.name(u'\u0c2b') > >>> pha > 'TELUGU LETTER PHA' > >>> u.lookup(pha) > u'\u0c2b' > > I don't know what you do with js statement like this: > Unicode.toPadma[Unicode.codePoints[Padma.lang_TELUGU].misc_VIRAMA + > Unicode.codePoints[Padma.lang_TELUGU].letter_KA] = Padma.vattu_KA; > where a constant seems to be assigned to a sum. But whatever these do > might correspond to the u.normalize function. > > This appears to be based on a generic Indian-script transliteration program > (Padma), so there may be functions not really needed for Telegu. (I am > familiar with Devanagri but know nothing of Telegu and its script except > that it is Dravidian rather than Indo-European-Sanskritic.) > > Good luck. > > Terry Jan Reedy From skip at pobox.com Fri Aug 25 20:10:05 2006 From: skip at pobox.com (skip at pobox.com) Date: Fri, 25 Aug 2006 19:10:05 -0500 Subject: time.clock() going backwards?? In-Reply-To: <ecnolv$h11$2@newsreader2.netcologne.de> References: <vkFHg.82529$_J1.759243@twister2.libero.it> <mailman.9888.1156536471.27775.python-list@python.org> <ecnolv$h11$2@newsreader2.netcologne.de> Message-ID: <17647.37213.864011.459859@montanaro.dyndns.org> >> I seem to remember this being mentioned before on the list, perhaps by Tim >> Peters. Perhaps he will chime in. Claudio> If I remember it right, the cause of such a problem is updating Claudio> the clock by accessing a time server over a network. Just any Claudio> such access results in adjusting the time a bit and leads Claudio> eventually to such problems. Wouldn't that affect time.time (time since the start of the Epoch), not time.clock (cpu time used by the current process)? Skip From lcazarre at gmail.com Thu Aug 10 08:45:53 2006 From: lcazarre at gmail.com (lcazarre at gmail.com) Date: 10 Aug 2006 05:45:53 -0700 Subject: Absolute beginner - is this feasible? Message-ID: <1155213953.799292.207930@p79g2000cwp.googlegroups.com> I am by no means a serious programmer (which will become evident as you read this very message), except that I use VBA almost daily to automate Excel spreadsheets. I do enjoy programming however and the only thing that prevented me from learning a language other than VBA is the lack of a project. Until today, I was not sure what I would do if I knew how to program in a language such as Python. I now feel the need to develop a small program for myself. I have a free subscription to Factiva (www.factiva.com), which gives me online access to virtually all newspapers, magazines, etc. using a normal internet browser. The bad thing is that I can only access the articles one by one. I wish I could write a program that would: - prompt me to choose a publication (let's say The Economist), - find the latest publication, - download automatically all the articles in that edition and finally - combine and format the articles in a single Word document. This way, I will be able to print the magazine and read it on my way to the office. Now my questions: - is it legal? (I do have a subscription to Factiva. I do not intend to distribute the printouts) - If so, can I use Python to automate this task? Thank you. From deets at nospam.web.de Thu Aug 24 14:37:10 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 24 Aug 2006 20:37:10 +0200 Subject: telnetlib thread-safe? In-Reply-To: <1156441749.350442.101520@i42g2000cwa.googlegroups.com> References: <1156434867.163326.42160@i42g2000cwa.googlegroups.com> <mailman.9794.1156436433.27775.python-list@python.org> <1156441749.350442.101520@i42g2000cwa.googlegroups.com> Message-ID: <4l69unFfa0kU1@uni-berlin.de> Jerry schrieb: > Fredrik Lundh wrote: >> define thread-safe. how do you plan to use it? > > I would like to write a program that spawns ~10 threads. Each thread > would get a host to connect to from a Queue object and run then do it's > thing (i.e. connecting to the host, running some commands, returning > back a success or fail based on the results). > > I just want to make sure that telnetlib is safe for this. Usually, OO-style libs that don't share state between objects are pretty safe - and I'd presume that this holds for telnetlib, too. There is of course no way except looking into the source to _know_ that for sure. So - try it out. Diez From nicogrubert at gmail.com Thu Aug 31 12:36:34 2006 From: nicogrubert at gmail.com (Nico Grubert) Date: Thu, 31 Aug 2006 18:36:34 +0200 Subject: Searching a string and extract all occurancies of a substring In-Reply-To: <44F70DB5.30302@gmail.com> References: <44F703C8.3080504@gmail.com> <7.0.1.0.0.20060831130033.05175028@yahoo.com.ar> <44F70DB5.30302@gmail.com> Message-ID: <44F71012.80502@gmail.com> > This works as long as there are no other <paramter> Tags in the content > that I parse. Got it. I forgot to handle the 'attrs' parameter in handle_starttag(). Changed it to: def handle_starttag(self, tag, attrs): if tag == 'parameter': if attrs == [('key', 'infobox_path')]: self.readingpaths = 1 This works so far. From fuzzyman at gmail.com Fri Aug 11 08:56:32 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 11 Aug 2006 05:56:32 -0700 Subject: hide python code ! In-Reply-To: <1155300831.873732.303770@p79g2000cwp.googlegroups.com> References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155253821.570487.165400@b28g2000cwb.googlegroups.com> <1155254631.617208.299550@m73g2000cwd.googlegroups.com> <pan.2006.08.11.00.21.06.658272@REMOVEME.cybersource.com.au> <654tq3-epj.ln1@lairds.us> <1155300831.873732.303770@p79g2000cwp.googlegroups.com> Message-ID: <1155300992.436922.61830@m73g2000cwd.googlegroups.com> Paul Boddie wrote: [snip..] > I've previously mentioned a very interesting paper which not only > described the reverse engineering of the Skype protocol and software > but also described how to make interoperating Skype clients. Given that > the well-financed developers spent a lot of time introducing various > protection measures (encryption, verification, etc.) and yet someone > can write the aforementioned stuff up in a paper, I'd recommend an > upgrade to any business plan which relies on obfuscation to prevent > "unauthorised" use or modification. Indeed, I'd recommend that any such > entrepreneur think twice about starting a traditional proprietary > software business in this day and age. > How many users did skype have before that happened... Several orders of magnitude above what is required to earn a living from selling a few programs I suspect. Fuzzyman http://www.voidspace.org.uk/python/index.shtml > Paul From fanglicheng at gmail.com Mon Aug 21 02:52:16 2006 From: fanglicheng at gmail.com (Licheng Fang) Date: 20 Aug 2006 23:52:16 -0700 Subject: Python and STL efficiency Message-ID: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> Hi, I'm learning STL and I wrote some simple code to compare the efficiency of python and STL. //C++ #include <iostream> #include <string> #include <vector> #include <set> #include <algorithm> using namespace std; int main(){ vector<string> a; for (long int i=0; i<10000 ; ++i){ a.push_back("What do you know?"); a.push_back("so long..."); a.push_back("chicken crosses road"); a.push_back("fool"); } set<string> b(a.begin(), a.end()); unique_copy(b.begin(), b.end(), ostream_iterator<string>(cout, "\n")); } #python def f(): a = [] for i in range(10000): a.append('What do you know') a.append('so long...') a.append('chicken crosses road') a.append('fool') b = set(a) for s in b: print s I was using VC++.net and IDLE, respectively. I had expected C++ to be way faster. However, while the python code gave the result almost instantly, the C++ code took several seconds to run! Can somebody explain this to me? Or is there something wrong with my code? From ask at me Sat Aug 12 09:16:29 2006 From: ask at me (alf) Date: Sat, 12 Aug 2006 09:16:29 -0400 Subject: iterator wrapper In-Reply-To: <1155351613.395862.211900@74g2000cwt.googlegroups.com> References: <8cednRaDbu_RkkDZnZ2dnUVZ_sKdnZ2d@comcast.com> <1155339879.395139.182050@m73g2000cwd.googlegroups.com> <1155340917.733325.74780@i3g2000cwc.googlegroups.com> <bL6dnUMbj9yfvkDZnZ2dnUVZ_qednZ2d@comcast.com> <1155351613.395862.211900@74g2000cwt.googlegroups.com> Message-ID: <V8mdnaVfKIJ_fUDZnZ2dnUVZ_rSdnZ2d@comcast.com> Simon Forman wrote: >> >>>|>> I = ([n] for n in i) >> >>This is nice but I am iterating thru hude objects (like MBs) so you know ... >> > > No, I don't know... :-) potentially my source lists are huge - so wanted to avoid unnecessary memory allocation > My friend, I think you've misunderstood. Observe: > > |>> L = [n for n in range(3)] > |>> G = (n for n in range(3)) > |>> L > [0, 1, 2] > |>> G > <generator object at 0xb7d982ec> well, I am in the python 2.3 word where generator comprehensions seem not to work. So I just took it a preallocated list comprehention. still wonder if there would be a difference between: G = (n for n in range(300000000)) - this creates the huge list there G = (n for n in xrange(300000000)) - this (at least to my understanding) does not > > List comprehensions [] create lists, generator comprehensions () create > generators. > > Generator comprehensions work "just-in-time", pulling items from > whatever they're iterating over as they themselves are iterated over, > as I hope this example makes clear: > >[...] got it now ... thx or the lesson.... A. From gagsl-py at yahoo.com.ar Mon Aug 28 20:56:55 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 28 Aug 2006 21:56:55 -0300 Subject: newbe question about removing items from one file to another file In-Reply-To: <1156714534.318183.326220@i3g2000cwc.googlegroups.com> References: <1156714534.318183.326220@i3g2000cwc.googlegroups.com> Message-ID: <7.0.1.0.0.20060828214356.03875ce0@yahoo.com.ar> At Sunday 27/8/2006 18:35, Eric_Dexter at msn.com wrote: (This code don't even compile...!) >def simplecsdtoorc(filename): > file = open(filename,"r") file is not a good name - hides the builtin type of the same name. Same for dict, list... > alllines = file.read_until("</CsInstruments>") read_until??? > pattern1 = re.compile("</") > orcfilename = filename[-3:] + "orc" perhaps you want filename[:-3]+"orc"? > for line in alllines: > if not pattern1 if not pattern1.search(line): > print >>orcfilename, line Open the output file before the loop, and use its write() method here >I am pretty sure my code isn't close to what I want. I need to be able >to skip html like commands from <defined> to <undefined> and to key on >another word in adition to </CsInstruments> to end the routine Good job for Beautiful Soup: http://www.crummy.com/software/BeautifulSoup/ Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From fredrik at pythonware.com Tue Aug 29 13:37:46 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 29 Aug 2006 19:37:46 +0200 Subject: distributing modules to machines In-Reply-To: <1156870835.222638.58120@m73g2000cwd.googlegroups.com> References: <1156870835.222638.58120@m73g2000cwd.googlegroups.com> Message-ID: <ed1u1a$h9m$1@sea.gmane.org> r1pp3r wrote: > What I would like to do is have the system update itself on demand. In > other words, pass pickled objects (the code comprising the server) down > the pipeline to the server, have them copied to the right place, and > then restart the server which can then invoke the new code. should work (assuming you trust the various systems involved, and your own ability to avoid deploying broken code) but using a custom protocol for this sounds like a slight overkill, though. I would probably use rsync (over ssh) at regular intervals, or, if we're only talking about small amounts of code, a bootstrap script that fetches the current version over http(s) every time the server starts. (in the http case, you can use etag/if-modified-since to avoid downloading things if they haven't changed, but if you're on a fast network, that probably won't matter much). </F> From danielmarkhot at gmail.com Fri Aug 25 10:33:34 2006 From: danielmarkhot at gmail.com (Daniel Mark) Date: 25 Aug 2006 07:33:34 -0700 Subject: How to handle wrong input in getopt package in Python? Message-ID: <1156516414.702940.50940@74g2000cwt.googlegroups.com> Hello all: I am using getopt package in Python and found a problem that I can not figure out an easy to do . // Correct input D:\>python AddArrowOnImage.py --imageDir=c:/ // Incorrect input D:\>python AddArrowOnImage.py --imageDi Traceback (most recent call last): File "AddArrowOnImage.py", line 113, in ? File "AddArrowOnImage.py", line 88, in main File "getopt.pyc", line 89, in getopt File "getopt.pyc", line 157, in do_longs getopt.GetoptError: option --imageDir requires argument Is there any method in getopt or Python that I could easily check the validity of each command line input parameter? Thank you -Daniel FYI: My code that deals with getopt is as follows: o, a = getopt.getopt(sys.argv[1:], 'h', ['imageDir=']) opts = {} for k,v in o: if k in ['--imageDir'] and len(v) == 0: usage(); sys.exit("Insufficient input parameters!") opts[k] = v if opts.has_key('-h'): usage(); sys.exit(0) if not len(opts['--imageDir']): usage(); sys.exit("Insufficient input parameters!") From rogue_pedro at yahoo.com Fri Aug 18 23:16:23 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 18 Aug 2006 20:16:23 -0700 Subject: text editor suggestion? In-Reply-To: <7xveopfo6d.fsf@ruckus.brouhaha.com> References: <44e66724$0$2363$c3e8da3@news.astraweb.com> <1155953803.525289.64490@h48g2000cwc.googlegroups.com> <7xveopfo6d.fsf@ruckus.brouhaha.com> Message-ID: <1155957383.567734.11480@b28g2000cwb.googlegroups.com> Paul Rubin wrote: > "Simon Forman" <rogue_pedro at yahoo.com> writes: > > Have you tried IDLE? It ships with python, meets your 5 criteria(*), > > can be customized (highlighting colors and command keys and more), and > > includes a usable GUI debugger. It's got some warts, but I like it a > > lot, it's pretty much all I use for my python coding. > > I use it too, but have never gotten the debugger to work reliably. I'm curious about what you mean? It doesn't do all I'd wish for, but I've never had any real problem with it. (It's bicyclerepairman I haven't been able to get working. lol) Peace, ~Simon From fredrik at pythonware.com Tue Aug 22 10:50:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Aug 2006 16:50:39 +0200 Subject: Problem of function calls from map() References: <200608211350.k7LDoBJb032411@fe12.bluebottle.com><mailman.9628.1156210759.27775.python-list@python.org> <2Gf*MkSor@news.chiark.greenend.org.uk> Message-ID: <ecf5jv$18n$1@sea.gmane.org> Sion Arrowsmith wrote: > I think there's something weird going on -- sp4 should be making > 154563 calls to str.split. So no wonder it goes faster -- it's not doing > any work. of course it does: >>> lines = ["line\tone", "line\ttwo"] >>> [s.split("\t") for s in lines] [['line', 'one'], ['line', 'two']] >>> map(str.split, lines) [['line', 'one'], ['line', 'two']] the problem is that he's using a Python-level profiler to benchmark things written in C. (you cannot really use "profile" to *benchmark* things written in Python either; the profiler tells you where a given program spends the time, not how fast it is in com- parision with other programs) </F> From bignose+hates-spam at benfinney.id.au Sat Aug 19 22:58:51 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 20 Aug 2006 12:58:51 +1000 Subject: How to get the ascii code of Chinese characters? References: <1155986298.643983.157460@i3g2000cwc.googlegroups.com> <1155990488.395220.178810@74g2000cwt.googlegroups.com> <1155999554.486951.303480@i42g2000cwa.googlegroups.com> <1156021926.365938.220900@75g2000cwc.googlegroups.com> <1156039938.770189.200070@b28g2000cwb.googlegroups.com> Message-ID: <873bbsyuxg.fsf@benfinney.id.au> "many_years_after" <shuanyu at gmail.com> writes: > Well, people may input from keyboard. They input some Chinese > characters, then, I want to create a number. The same number will be > created if they input the same Chinese characters. You seem to be looking for a hash. <URL:http://docs.python.org/lib/module-md5> <URL:http://docs.python.org/lib/module-sha> If not, please tell us what your *purpose* is. It's not at all clear from your questions what you are trying to achieve. -- \ "I was in a bar the other night, hopping from barstool to | `\ barstool, trying to get lucky, but there wasn't any gum under | _o__) any of them." -- Emo Philips | Ben Finney From bj_666 at gmx.net Sun Aug 20 09:05:12 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 20 Aug 2006 15:05:12 +0200 Subject: sum and strings References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <slrneeatf3.nbt.sybrenUSE@schuimige.stuvel.eu> <7xr6zel2r2.fsf@ruckus.brouhaha.com> <ec4b27$7lr$1@news.albasani.net> <1155971485.709068.255140@b28g2000cwb.googlegroups.com> <1156038134.216383.80960@h48g2000cwc.googlegroups.com> <1156067043.386056.129320@i42g2000cwa.googlegroups.com> <1156069124.744004.118670@i3g2000cwc.googlegroups.com> <mailman.9571.1156078160.27775.python-list@python.org> Message-ID: <pan.2006.08.20.13.05.11.167426@gmx.net> In <mailman.9571.1156078160.27775.python-list at python.org>, Gerhard Fiedler wrote: > On 2006-08-20 07:18:44, Rhamphoryncus wrote: > >>> shallow = [] >>> [shallow.extend(i) for i in deep] >> >> I'm sure this has been mentioned before, but listcomps are for when you >> want to store the list and use it for further things, not for when you >> want a side effect. TOOWTDI. > > Can you please explain what you mean with this, and maybe why? You should not abuse list comps just to have a one liner. Only use them if you really want to build a list and not just for side effects. The above one-liner builds a list of `None`\s of length ``len(deep)`` for no reason just to throw them away. Ciao, Marc 'BlackJack' Rintsch From jmdeschamps at gmail.com Sat Aug 19 19:24:01 2006 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 19 Aug 2006 16:24:01 -0700 Subject: tkinter btn visual state with tkMessageBox In-Reply-To: <mailman.9548.1156003386.27775.python-list@python.org> References: <1155995811.278433.87560@75g2000cwc.googlegroups.com> <mailman.9548.1156003386.27775.python-list@python.org> Message-ID: <1156029841.889543.172890@p79g2000cwp.googlegroups.com> Hendrik van Rooyen wrote: > <jmdeschamps at gmail.com> wrote: > > To: <python-list at python.org> > > > | why is the button sunken when called through a bind method, and not > | with the command attribute? > | Thank you! > | > | > | ## Cut'nPaste example > | from Tkinter import * > | import tkMessageBox > | > | class Vue(object): > | def __init__(self): > | self.root=Tk() > | self.root.title("test button visual state") > | self.b1=Button(self.root,text="tkMessageBox.showinfo with bind > | :-(") #,command=self.showMsg) > | self.b1.bind("<Button>",self.showMsg) > > 8<--------------------------------------------------------------------------- > > change this to : > > self.b1.bind("<ButtonRelease>",self.showMsg) > > Problem is that a button "sinks in" when you press it and "springs back" when > you release it... > > and the "Button" leaves it sunken.... - because when you release, the control is > no longer there > > - Hendrik Thanks Hendrik - is the command attribute connected to the bindable events? jm From rogue_pedro at yahoo.com Tue Aug 29 01:46:27 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 28 Aug 2006 22:46:27 -0700 Subject: Is this a good idea or a waste of time? In-Reply-To: <slrnef7gj7.4tu.apardon@rcpc42.vub.ac.be> References: <1156449402.022781.292840@p79g2000cwp.googlegroups.com> <1156485945.967160.238790@m73g2000cwd.googlegroups.com> <slrnef5hep.4tu.apardon@rcpc42.vub.ac.be> <44f322cd$1@nntp0.pdx.net> <slrnef6o2j.4tu.apardon@rcpc42.vub.ac.be> <1156802762.331853.80000@75g2000cwc.googlegroups.com> <slrnef7gj7.4tu.apardon@rcpc42.vub.ac.be> Message-ID: <1156830387.226840.39070@b28g2000cwb.googlegroups.com> Antoon Pardon wrote: > On 2006-08-28, sjdevnull at yahoo.com <sjdevnull at yahoo.com> wrote: > > Antoon Pardon wrote: > >> There seem to be enough problems that work with ints but not with > >> floats. In such a case enforcing that the number you work with > >> is indeed an int seems fully appropiate. > > > > I've _never_ seen a case where enforcing types in the manner of the OP > > is appropriate. > > > > It fails with trivial wrappers like > > > > class myInt(int): > > def printFormatted(self): > > .......... > > > > Even looser checking with isinstance is rarely right. You may want to > > exclude floats, but that doesn't mean you want to exclude int-like > > objects that don't inherit from int. > > That may be true. But one may wonder if this is a failing of the > programmer or a failing of the language that doesn't support > such things. What the hell are you talking about? I'm curious: what is the meaning, to you, of the word "this" in your sentence above? > > -- > Antoon Pardon From stylecomputers at gmail.com Mon Aug 14 03:50:49 2006 From: stylecomputers at gmail.com (stylecomputers at gmail.com) Date: 14 Aug 2006 00:50:49 -0700 Subject: Best IDE for Python Message-ID: <1155541849.350392.31190@h48g2000cwc.googlegroups.com> Hi All, What do you find the best IDE for creating web applications in Python is? Preferably FOS IDE. Cheers From ds4ff1 at yahoo.com Wed Aug 9 15:06:33 2006 From: ds4ff1 at yahoo.com (ds4ff1z) Date: 9 Aug 2006 12:06:33 -0700 Subject: (easy question) Find and replace multiple items In-Reply-To: <mailman.9114.1155070968.27775.python-list@python.org> References: <1155069659.347944.111010@m79g2000cwm.googlegroups.com> <mailman.9114.1155070968.27775.python-list@python.org> Message-ID: <1155150393.325411.153780@m73g2000cwd.googlegroups.com> Tim Chase wrote: > > Hello, i'm looking to find and replace multiple characters in a text > > file (test1). I have a bunch of random numbers and i want to replace > > each number with a letter (such as replace a 7 with an f and 6 with a > > d). I would like a suggestion on an a way to do this. Thanks > > Well, the canonical way would be to use a tool designed to do > transformations: > > tr '76' 'fd' < test1.txt > out.txt > > However, if it's python you want: > > >>> mapping = {'7': 'f', '6': 'd'} > >>> s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" > >>> ''.join([mapping.get(c, c) for c in s]) > 'ABCDEFGHIJKLMNOPQRSTUVWXYZ12345df890' > > will transform all the items found in "s" according to the > defined mapping. > > Or, depending on your string length and the number of items > you're replacing: > > >>> for k,v in mapping.items(): s = s.replace(k,v) > > may be a better choice. Or maybe they're both lousy choices. :) > Time it and choose accordingly. > > -tkc Thanks for the solutions! From paddy3118 at netscape.net Fri Aug 18 21:59:05 2006 From: paddy3118 at netscape.net (Paddy) Date: 18 Aug 2006 18:59:05 -0700 Subject: sum and strings In-Reply-To: <ec534d$5dn$1@news.albasani.net> References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <slrneeatf3.nbt.sybrenUSE@schuimige.stuvel.eu> <1155921231.537033.159460@p79g2000cwp.googlegroups.com> <ec534d$5dn$1@news.albasani.net> Message-ID: <1155952745.939653.7130@m73g2000cwd.googlegroups.com> Georg Brandl wrote: > Paddy wrote: <<SNIP>> > > I get where you are coming from, but in this case we have a function, > > sum, that is not as geeral as it could be. sum is already here, and > > works for some types but not for strings which seems an arbitrary > > limitation that impede duck typing. > > Only that it isn't arbitrary. Hi Georg, I said it *seemed* arbitrary. I doubt that it is arbitrary, and thought someone would say why the restriction is necessary. > > > - Pad. > > > > P.S. I can see why, and am used to the ''.join method. A newbie > > introduced to sum for integers might naturally try and concatenate > > strings using sum too. > > Yes, and he's immediately told what to do instead. Yep, thats the what. Now as to the why? - paddy. From jjl at pobox.com Mon Aug 21 15:27:48 2006 From: jjl at pobox.com (John J. Lee) Date: Mon, 21 Aug 2006 19:27:48 GMT Subject: Python Editor with Autocorrection References: <mailman.9594.1156146191.27775.python-list@python.org> Message-ID: <87sljp51or.fsf@pobox.com> Laurentiu <laurstorage at yahoo.com> writes: > i am searching for a free python editor with > autocorrection capabillities. > > for example:" the wrong setfocus() call to become > SetFocus(), etc." Perhaps not quite what you were looking for, but emacs' dabbrev-expand works well for avoiding mistyped Python names (not to mention typing less). It searches through all buffers for a "word" matching the first few characters you typed. So, to type the first "dabbrev-expand" in this sentence, I just typed 'da', then hit F4 (which I have bound to dabbrev-expand). If there are multiple matches, you can carry on hitting F4 until the expansion you want is found, or type a few more characters and try again. The capitalization behaviour is controlled by the variable dabbrev-case-replace. I think other editors can do something similar, but it works well with the emacs way of working (one emacs process open, lots of files loaded into buffers in that process). John From ajaksu at gmail.com Thu Aug 17 10:35:24 2006 From: ajaksu at gmail.com (ajaksu) Date: 17 Aug 2006 07:35:24 -0700 Subject: "wxmsw26uh_vc.dll not found" when using wxAgg backend References: <1155707756.522298.11930@75g2000cwc.googlegroups.com> Message-ID: <1155825324.556855.154020@h48g2000cwc.googlegroups.com> Hi Sam, Sam wrote: > I've installed matplotlib recently because I want to add graphing > functionality to a GUI that i'm making. Have you considered wxmpl? I'm leaning towards using it, " Painless matplotlib embedding in wxPython" sounds good (and it even works). More information and downloads at http://agni.phys.iit.edu/~kmcivor/wxmpl/ > - the following error box pops up: "This application has failed to > start because wxmsw26uh_vc.dll was not found. Reinstalling the > application may fix this problem." Matplotlib mailing list should give you better answers on this, but I'll try my best :) I have wx-2.6-msw-ansi and my DLL is wxmsw26h_vc.dll, so it seems wxmsw26Uh_vc.dll means the Unicode version. Matplotlib examples do work here and including "# -*- coding: utf-8 -*-" in the demo source causes no problem. Have you ever installed a Unicode version of wxPython? The file wx.pth in Lib/site-packages/ should point to your default wx version (a single line with the directory name), does it? The configuration file matplotlibrc (in Lib\site-packages\matplotlib\mpl-data\ and somewhere in your profile) might have something weird causing this, worth a check IMHO. If these don't solve the problem, installing an older wxPython might work around any version conflicts that could exist. Hoping this helps, Daniel From phinsxiii at gmail.com Mon Aug 21 14:40:30 2006 From: phinsxiii at gmail.com (Bucco) Date: 21 Aug 2006 11:40:30 -0700 Subject: More List Comparison Help Message-ID: <1156185630.491504.145530@i3g2000cwc.googlegroups.com> I have taken into advice what was mentioned earlier, but I have run into a snag in which I am getting the wrong output from my class. > python matchlist.py ./test ./test/list.txt output: ['list.txt', 'test1.txt', 'test2.txt'] set(['test1']) ['', '/', 't', 'e', 's', 't'] The first line of output correctly displays the list of file names in the argv[1] directory. The second line of output correctly displays the set list from readlines on list.txt. The third line of out put should be the same as the 1st line minus the extenxions in the file names. Here is the code: import os from sys import argv class MatchList: def __init__(self, dirList, fileList): self.dirList = os.listdir(dirList) self.fileList = set(open(fileList, 'r').readlines()) self.matchList = [] self.retList = [] self.rut = [] def match(self): for item in dirList: rut = os.path.splitext(item)[0] self.matchList.append(rut) print self.matchList def testPrint(self): print self.dirList print self.fileList self.match() if __name__ == '__main__': if len(argv) == 3: dirList = argv[1] fileListName = argv[2] match = MatchList(dirList, fileListName) match.testPrint() What I want to happen is produce a list of the filenames minus the extensions so that I can set that list. Once that list is set, I can subtract the set list from the readlines function and then use the difference list to determine what files are missing form the directory. Thanks in advance:) SA P.S. Is there a special way to include code in my postings so that it looks different from the rest of the text in the posting? From bjourne at gmail.com Thu Aug 31 21:10:16 2006 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Fri, 1 Sep 2006 03:10:16 +0200 Subject: Pros/Cons of Turbogears/Rails? In-Reply-To: <1157061525.31869.54.camel@devilbox> References: <WXmIg.20772$gY6.18513@newssvr11.news.prodigy.com> <1157034321.926854.123520@m79g2000cwm.googlegroups.com> <1157037862.804249.81290@b28g2000cwb.googlegroups.com> <32822fe60608311112u7ad04f1bhb998351fb15d682@mail.gmail.com> <740c3aec0608311431q1fdd21a6x496957508135504d@mail.gmail.com> <1157061525.31869.54.camel@devilbox> Message-ID: <740c3aec0608311810u56c1ad65h853ac55ce7524059@mail.gmail.com> > > > Someone ones said on the mailing list TG is the Ubuntu of web > > > frameworks, and I think I'll add and you can strip down the kernel and > > > it wont break :) > > > > But that is not really true. If you use Cheetah instead of Kid, you > > lose out: No widgets, > > Untrue. Even though I don't use widgets much myself, I wanted to make > sure they *could* be used with TurboStan, so I did a quick test with > Kevin's autocomplete widget. Worked fine. I can't see why Cheetah > would be any different. Maybe I stand corrected then. But the definition of the AutoCompleteField widget is here: http://trac.turbogears.org/turbogears/browser/trunk/turbogears/widgets/big_widgets.py#L88 I really don't understand how a completely different non-xml based templating engine, with a completely different syntax, would be able to grok that. > > If you use SQLAlchemy instead of SQLObject, no identity framework, > Completely false. Yes, I'm sorry. Last time I used it, it didn't work. But now it seem to have 100% compatibility. > > no administrative tools (tg-admin sql, > > True. > > > CatWalk etc > > True. > > > ) and no documentation. > > Partially true. The documentation exists but some of it is out-of-date > and it was never very complete to begin with. Of course, like many OSS > projects, the mailing list is your best resource and SQLAlchemy itself > has quite good documentation. SQLAlchemy does, yes. > > If you use prototype instead of MochiKit... I have no idea what > > happens > > You get Prototype instead of MochiKit. ... And the docs showing you how to integrate TurboGears with AJAXy stuff ofcourse no longer applies. > Personally I've chosen to go a different route on a couple things and > leave the rest intact. I expect most people are the same. With most > frameworks, there's typically one or two things most people don't like > and it's nice to be able to replace those things without a lot of fuss. > I don't see how that's a liability. I disagree, most frameworks do not let you replace its components. They are a "take it or leave it" kind of deal. I like that. The more adaptable you try to make a piece of code, the more complex it becomes. Obviously, it is easier to make code that supports one templating engine than to make it that supports everyone. You then most solve that additional complexity. Both in the code AND in the documentation and you must ensure that the additional complexity doesn't "leak" and make users life miserable. I think Jorge claimed that TurboGears was very pluggable and I claimed that it wasn't so. My point is that making the code pluggable is not enough. All the stuff around it also need to support the pluggability, not the least the docs. > That's odd, because I've actually used both and found TurboGears far > easier to get started with (no mucking about with Apache and mod_python > for one thing, no need to setup explicit url regexes just to get "hello, > world" on a page). > > Judging from your above comments it sounds to me like you're mostly > speculating about TurboGears. Not so. During 3 months a few months ago I've built a pretty big web application using TurboGears. The easy of use of a framework isn't writing "hello, world" applications, it is finding out how to do things, doing them and how fast you can do it. > > In the future both Rails and TurboGears will probably be great. But > > since someone mentioned Rails moving to YARV, and TurboGears moving to > > SQLAlchemy and Markup, it seems to me that they are both in a state of > > flux and not quite ready yet. > > TurboGears is certainly in a state of flux although from an outside > (i.e. API) standpoint it's not nearly as bad as you might think from the > changes that have gone on under the hood. There's been only a few > breaking changes up til now (I converted a site I'd built on 0.8 to the > latest SVN last night and most of the issues I encountered were with my > own changes to TurboStan). You must have been luckier than me then or maybe you didn't use much advanced functionality? I converted a site from SVN head somewhere at 0.9 to 1.1 and there were lots of breakages. Anyway, I think we have different definitions for "not quite ready." Lets say you have to build and maintain a site or web application together with two other developers who (like most web developers) doesn't know Python. Would you then choose TurboGears? -- mvh Bj?rn From jojoba12 at hotmail.com Tue Aug 22 18:13:32 2006 From: jojoba12 at hotmail.com (jojoba) Date: 22 Aug 2006 15:13:32 -0700 Subject: how do you get the name of a dictionary? In-Reply-To: <mailman.9668.1156283600.27775.python-list@python.org> References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <pan.2006.08.21.03.33.27.84160@REMOVEME.cybersource.com.au> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> <mailman.9631.1156227418.27775.python-list@python.org> <1156264475.968894.221710@p79g2000cwp.googlegroups.com> <1156266720.205126.284050@i3g2000cwc.googlegroups.com> <1156268752.574983.123520@75g2000cwc.googlegroups.com> <pan.2006.08.22.20.05.58.528777@gmx.net> <1156281268.865624.302070@b28g2000cwb.googlegroups.com> <mailman.9666.1156281679.27775.python-list@python.org> <1156283135.985893.186500@m73g2000cwd.googlegroups.com> <mailman.9668.1156283600.27775.python-list@python.org> Message-ID: <1156284812.469380.274370@b28g2000cwb.googlegroups.com> > > Wow Fredrick! Are you serious? > > yes. > </F> Thank you for the clear answer. > >> no, you're just wasting a lot of bandwidth making it clear that you just > >> cannot be bothered to learn how things actually work. By the way, what exactly led you to this conclusion? jojoba From larry.bates at websafe.com Wed Aug 30 09:09:12 2006 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 30 Aug 2006 08:09:12 -0500 Subject: where or filter on list In-Reply-To: <1156939493.558819.8410@i42g2000cwa.googlegroups.com> References: <1156939493.558819.8410@i42g2000cwa.googlegroups.com> Message-ID: <44F58DF8.7000308@websafe.com> charles.hebert at gmail.com wrote: > Hi, > > Can anybody tell me how to to find the nearest value to zero in a list > ? > > To do that, i'm using list comprenhension : > >>>> foo = [-5,-1,2,3] # nearest value to zero ? >>>> [value for value in foo if math.fabs(value) == min([int(math.fabs(x)) for x in foo])] > [-1] > > Something simpler ? > How to extend this function to any given value ? > > Thanks, > > CH. > One of I'm sure many ways: import sys def closest(value, list): m=None mdistance=sys.maxint for entry in list: distance=abs(value-entry) if distance < mdistance: m=entry mdistance=distance return m if __name__ == "__main__": foo = [-5,-1,2,3] print closest(0, foo) Note: If you know that the list is ordered you can break out of the loop you can optimize the loop by breaking out when you start getting further away from value or you might be able to use the bisect module to find it faster. If the lists are small it probably isn't worth the extra effort. If they are large and sorted look at bisect. Question: what if two values are equidistant? -Larry bATES From i3x9mdw at j9n35c.invalid Sat Aug 12 01:37:09 2006 From: i3x9mdw at j9n35c.invalid (Alan Connor) Date: Sat, 12 Aug 2006 05:37:09 GMT Subject: [OT] John Salerno (was: and i thought windows made a mess of files...) References: <44dd3a65$0$2381$c3e8da3@news.astraweb.com> Message-ID: <slrnedqpef.18n.i3x9mdw@b29x3m.invalid> On alt.os.linux, in <44dd3a65$0$2381$c3e8da3 at news.astraweb.com>, "John Salerno" wrote: > Path: text.usenetserver.com!atl-c01.usenetserver.com!news.usenetserver.com!atl-c03.usenetserver.com!news.usenetserver.com!news.glorb.com!news.astraweb.com!router2.astraweb.com!not-for-mail > Date: Fri, 11 Aug 2006 22:19:06 -0400 > From: John Salerno <johnjsal at NOSPAMgmail.com> http://groups.google.com/advanced_group_search John Salerno Results 1 - 100 of 1,650 posts in the last year 2 alt.cellular.sprintpcs 1 alt.games.morrowind 2 alt.games.neverwinter-nights 11 alt.html 25 alt.music.dave-matthews 2 alt.os.linux 4 comp.editors 1 comp.lang.javascript 44 comp.lang.python 1 macromedia.dreamweaver 7 microsoft.public.dotnet.languages.csharp Are all of those yours, or did you steal someone's alias? Either way, I don't see many posts on Linux groups. Looks like you don't know anything about Linux. And that your problems are your fault. > User-Agent: Thunderbird 1.5.0.5 (X11/20060728) Maybe. Maybe you just copied that from someone else's headers. It looks remarkably like your Windows User-Agent header too (see copied headers below). > MIME-Version: 1.0 > Newsgroups: alt.os.linux > Subject: and i thought windows made a mess of files... > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > Content-Transfer-Encoding: 7bit > Lines: 19 > Message-ID: <44dd3a65$0$2381$c3e8da3 at news.astraweb.com> > Organization: Unlimited download news at news.astraweb.com > NNTP-Posting-Host: 60df7692.news.astraweb.com > X-Trace: DXC=\AE;PX=>0<HPn_2M35M[hOL?0kYOcDh at JT=47B=V8C_DY=jS5X8o9RN0VYgRJ?2k^Oln`hjW77lSFZkYSc1bWQlE > Xref: usenetserver.com alt.os.linux:422359 > X-Received-Date: Fri, 11 Aug 2006 22:19:14 EDT (text.usenetserver.com) No posting IP. What a surprise. <article not downloaded: http://slrn.sourceforge.net/docs/README.offline> Your only other post on any linux group was here and you were using a completely different newsserver and Windows. # Path: text.usenetserver.com!atl-c01.usenetserver.com!news.usenetserver.com!atl-c05.usenetserver.com!news.usenetserver.com!postnews.google.com!news4.google.com!border1.nntp.dca.giganews.com!nntp.giganews.com!local02.nntp.dca.giganews.com!nntp.rcn.net!news.rcn.net.POSTED!not-for-mail # NNTP-Posting-Date: Sat, 05 Aug 2006 17:46:49 -0500 # Date: Sat, 05 Aug 2006 18:44:32 -0400 # From: John Salerno <johnjsal at NOSPAMgmail.com> # User-Agent: Thunderbird 1.5.0.4 (Windows/20060516) # MIME-Version: 1.0 # Newsgroups: alt.os.linux # Subject: should the root partition be a primary partition? # Content-Type: text/plain; charset=ISO-8859-1; format=flowed # Content-Transfer-Encoding: 7bit # Message-ID: <6s2dnctHFPFEgkjZnZ2dnUVZ_oydnZ2d at rcn.net> # Lines: 14 # NNTP-Posting-Host: 209.6.130.27 Almost certainly bogus. I wouldn't believe anything in this fellow's headers or articles. # X-Trace: sv3-qhiskzmd0+yq2C/ol14t8YRbXZ1SJjjLsvy6mDFGsrGVCOJevDD+CHmcpbqOvh/3Cbh2xj35Ck yCu9w!CFnCWRzTvsRwip4yXzppHgVtS9ha+HYUZU1Jx0lCRvkBf0qEXLMVZXH32ON4dUNiSDLaQ3duWtvd # X-Complaints-To: abuse at rcn.net # X-DMCA-Complaints-To: abuse at rcn.net # X-Abuse-and-DMCA-Info: Please be sure to forward a copy of ALL headers # X-Abuse-and-DMCA-Info: Otherwise we will be unable to process your complaint # properly # X-Postfilter: 1.3.32 # Xref: usenetserver.com alt.os.linux:422211 # X-Received-Date: Sat, 05 Aug 2006 18:46:49 EDT (text.usenetserver.com) And here we have you on comp.editors using yet another newsserver: # Path: text.usenetserver.com!atl-c01.usenetserver.com!news.usenetserver.com!atl-c02.usenetserver.com!news.usenetserver.com!newscon06.news.prodigy.com!prodigy.net!newsfeed-00.mathworks.com!NNTP.WPI.EDU!news.tufts.edu!not-for-mail # From: John Salerno <johnjsal at NOSPAMgmail.com> # Organization: Tufts University # User-Agent: Thunderbird 1.5 (Windows/20051201) # MIME-Version: 1.0 # Newsgroups: comp.editors # Subject: newbie to vim, question about moving to end of line # Content-Type: text/plain; charset=ISO-8859-1; format=flowed # Content-Transfer-Encoding: 7bit # Lines: 24 # Message-ID: <ewsyg.2597$No6.50993 at news.tufts.edu> # Date: Fri, 28 Jul 2006 18:16:42 GMT # NNTP-Posting-Host: 130.64.67.227 # X-Complaints-To: news at tufts.edu # X-Trace: news.tufts.edu 1154110602 130.64.67.227 (Fri, 28 Jul 2006 14:16:42 EDT) # NNTP-Posting-Date: Fri, 28 Jul 2006 14:16:42 EDT # Xref: usenetserver.com comp.editors:161026 # X-Received-Date: Fri, 28 Jul 2006 14:16:43 EDT (text.usenetserver.com) TROLL. I don't help trolls. And I don't think you could run Linux if your life depended on it. You'd actually have to take a break from running your mouth on hundreds of groups under dozens of aliases to do some homework. Phuk off (again). Done. Note: I won't be downloading any articles on this thread. Alan -- Challenge-Response Systems are the best garbage-mail blockers in the world. Spammers and trolls can't beat them and you don't need to be a geek to use them. A brief introduction: http://home.earthlink.net/~alanconnor/cr.html From g_windfall at yahoo.com Fri Aug 18 14:20:47 2006 From: g_windfall at yahoo.com (g_windfall at yahoo.com) Date: 18 Aug 2006 11:20:47 -0700 Subject: it is this easy $$$$$ Message-ID: <1155925247.624482.268440@b28g2000cwb.googlegroups.com> Fast and easy money from your home$$$$ -------------------------------------------------------------------------------- This has been proven to work on Oprah, 20/20, Wall Street Journal - a legitimate method of gaining money. Please read on and take it seriously. It really works! Do you need extra income quickly and legally? Do you have a PayPal account? If not, the set up takes 10-15 minutes. You could make up to $50,000 in one month's time with more money coming in every month thereafter! $50,000 in PayPal? That's Right! $50,000 dollars in your PayPal account! IT WAS PROVEN ON OPRAH AND THIS SYSTEM IS COMPLETELY LEGAL!!! You may have heard of this program (or one like it) on 20/20 or even in the Wall Street Journal. $10 that's all it takes. I'll try to keep it short and sweet. To get started just copy this whole page and paste it to edit it. Simply follow the instructions below and in 2 to 3 weeks, you will have as much as $50,000 dollars in your PayPal account or even more. Most people respond to this program because of the low investment ($10 dollars) and the high profit potential. There is no limit to the income you can generate from this (you can do it over and over). If you follow the instructions, you will reach thousands of people! Honesty, Faith, and Integrity make this system work. I think everyone has heard of PayPal. Anyone with an e-mail address can join for FREE! If you're not already a PayPal user, the first thing you need to do is sign up. Sign-up for paypal here www.paypal.com It's really easy to set up and it's FREE!!! Just make sure you have a Business or Premier account or you may be subjected to a monthly income limitation which may slow this program down. Send $5 to the first person on the list by using the Paypal send money feature, and include in the email: "Please add me to your list." This keeps the program legal. Then send another $5 to the 5th person on the list, with an email that says, "Thank you. I've joined." Remove the 1st e-mail address and place your address at the bottom. This moves the 2nd to 1st, 3rd to 2nd, 4th to 3rd, and the 5th place into 4th. DO NOT TRY TO PLACE YOURSELF IN THE FIRST PLACE. IT WILL ONLY REACH THE PEOPLE YOU SEND IT TO, AND THEN YOUR NAME WILL BE REMOVED FROM THE LIST! If you do this the way it was designed, it will reach thousands by the time your name gets to the top. REMEMBER TO SEND a $5.00 dollar donation to the 1st e-mail address and the message "PLEASE ADD ME TO YOUR LIST," and send an email with the words 'THANK YOU. I'VE JOINED" and the other $5.00 donation to the 5th person. This helps the 5th person keep track of progress of the letter and continue to send out more emails. Here is the list: 1. dukkey74 at yahoo.com 2. hhkaufman78 at yahoo.com 3. bly at mac.com 4. tturner81 at yahoo.com 5. g_windfall at yahoo.com (Make sure it's the same e-mail address that you used to open your PayPal account. This is the way you will receive payment) Now that you have paid the 1st person and 5th person and sent them both an email, a note, and placed your e-mail address in the 5th place, then what you need to do is post your letter. You can post on craigslist.org, message boards and newsgroups (there are thousands!), and you can even send in an email to your email list. IT IS YOUR JOB AS THE 5TH PERSON ON THE LIST TO ENSURE THERE ARE AT LEAST 20 "THANK YOU. I'VE JOINED" replies. The fifth person is the guardian of the system! If there are not at least 20 replies then the fifth person will keep sending/posting the letter until there is. MAKE SURE YOU SEND $5 DOLLARS TO THE FIRST PERSON TO THANK THEM FOR WHEN THEY WERE THE GUARDIAN OF THE LETTER AND $5 DOLLARS TO THE FIFTH PERSON SO MORE EMAILS CONTINUE TO GO OUT! Now the fun happens.we reap what we sow. Other people will see your posting and do the exact same thing, bringing you lots and lots of dollars!! Seriously, its common sense.you do it and 25 or more people see and do the same thingso on and so fortheveryone wins! You will receive thanks AND THE SAME BLESSING. When your name is on the 1st slot, 8,000 to 15,000 people will send you 5 dollars! Keep in mind the most you spent is $10 DOLLARS! (Remember this: what goes around comes around!) ************************************************************* TESTIMONIALS: Mary Gatters, Columbus, SC: I only have one thing to say to you: OH MY GOD! I sent out 142 copies total before 20 replied, like the instructions said. Then I went on a short vacation. When I got back my account had over $32,000 dollars in it already and the money was still coming! I'm still floating on air (especially with my new car). I thought the guardian system sounded cheesy, but now I realize it is the formula that makes this letter really work! THANKS! Richard Barrie, Boulder, CO: I was shocked when I saw how much money came flooding into my PayPal account. Within 3 weeks my account balance has ballooned to $22,449. At first I thought there had been some sort of error with my account!" **A note from the last person to try this: I called information on these two names, and the people do actually exist.** Here are the step-by-step directions again: Step 1. Set up your PayPal account, if you don't already have one, and send the top name (1st person) $5.00 dollars. DON'T FORGET to include "Please add me to your list." This is important as it keeps the program legal. Step 2. Send the other $5.00 dollars and an e-mail stating "Thank you. I've Joined." to the 5th name on the list. Step 3. Remove the top name, bump the other 4 names up one place each. Place your name in the bottom slot and you will receive a minimum of $100.00 or more from your efforts. Step 4. Keep sending/posting the letter until you get 20 "Thank you. I've joined" replies in your mailbox. That's it. It's that simple! Please give it an honest effort, you will not be disappointed and will be very glad you did when it starts to work. Remember, all you are going to be out of pocket is about the cost of a couple of coffees with the opportunity of banking thousands of dollars into your PayPal account! Take the smallest risk of your life. Take 10-20 minutes to work on this small project and reap the rewards! GOOD FORTUNE!! (If you need to email me, you can.) From cginboston at hotmail.com Fri Aug 25 19:02:24 2006 From: cginboston at hotmail.com (Chaz Ginger) Date: Fri, 25 Aug 2006 23:02:24 GMT Subject: Avoiding if..elsif statements In-Reply-To: <1156545375.962486.49540@h48g2000cwc.googlegroups.com> References: <1156545375.962486.49540@h48g2000cwc.googlegroups.com> Message-ID: <44EF8180.2010809@hotmail.com> unexpected wrote: > I have a program where based on a specific value from a dictionary, I > call a different function. Currently, I've implemented a bunch of > if..elsif statements to do this, but it's gotten to be over 30 right > now and has gotten rather tedious. Is there a more efficient way to do > this? > > Code: > > value = self.dictionary.get(keyword)[0] > > if value == "something": > somethingClass.func() > elsif value == "somethingElse": > somethingElseClass.func() > elsif value == "anotherthing": > anotherthingClass.func() > elsif value == "yetanotherthing": > yetanotherthingClass.func() > > Is it possible to store these function calls in a dictionary so that I > could just call the dictionary value? > Why not do it this way? foo = {'something':somethingClass.func,'somethingelse':somethingelseClass.func) if foo.has_key(value) : foo[value]() else : raise OMG, "%s isn't known" % value From riko at despammed.com Thu Aug 24 11:20:17 2006 From: riko at despammed.com (Mc Osten) Date: Thu, 24 Aug 2006 17:20:17 +0200 Subject: Python and STL efficiency References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <eccb9u$kjs$1@gemini.csx.cam.ac.uk> <1hkh28d.xscw4v1y4v9a6N%riko@despammed.com> <mailman.9640.1156247569.27775.python-list@python.org> <1hkh6lb.6dsnh51lj8z96N%riko@despammed.com> <1156252193.524186.107520@b28g2000cwb.googlegroups.com> <1hkhexv.18m65rl61swqyN%riko@despammed.com> <1156265848.875774.251640@i42g2000cwa.googlegroups.com> <1156290607.269119.88710@b28g2000cwb.googlegroups.com> <1hkil6j.xm4l6y1kwo13dN%riko@despammed.com> <1156317315.946762.215690@p79g2000cwp.googlegroups.com> <1hkioxy.42be4c1lg0jq5N%riko@despammed.com> <1156320792.011620.141030@m79g2000cwm.googlegroups.com> <1hkitqt.c17kl5o30nr4N%riko@despammed.com> <1156340217.774595.282950@75g2000cwc.googlegroups.com> <1156343260.399048.182310@m73g2000cwd.googlegroups.com> <1hkjdnl.1pw8bkv892pxcN%riko@despammed.com> <slrneer7g7.1is.horpner@FIAD06.norwich.edu> Message-ID: <1hkl458.s0lbzc1bbfkh1N%riko@despammed.com> Neil Cerutti <horpner at yahoo.com> wrote: > Those of you experiencing a temporary obsession with this topic > are encouraged to study The Great Language Shootout, until the > obsession goes away. ;) I think that everybody knows GLS. However, when I have results different from what I expected, I try to understand where I did the wrong assumption. But a recent post kind of explains what the problem is. -- blog: http://www.akropolix.net/rik0/blogs | Uccidete i filosofi, site: http://www.akropolix.net/rik0/ | tenetevi riso e forum: http://www.akropolix.net/forum/ | bacchette per voi. From thomasbartkus at comcast.net Tue Aug 8 17:33:30 2006 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Tue, 8 Aug 2006 16:33:30 -0500 Subject: Open file handles? Message-ID: <PvmdnW7gW8hCn0TZnZ2dnUVZ_oSdnZ2d@telcove.net> This may be more of a Linux question, but I'm doing this from Python. ..... How can I know if anything (I don't care who or what!) is in the middle of using a particular file? This comes in context of needing to copy a file BUT only if I can verify that something else doesn't have an open write handle to that file. IOW - I need to decline the operation if something else hasn't finished writing to the file. How can I know? Thomas Bartkus From rogue_pedro at yahoo.com Tue Aug 8 20:13:40 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 8 Aug 2006 17:13:40 -0700 Subject: How to reverse tuples in a list? References: <1155081671.728757.228050@p79g2000cwp.googlegroups.com> Message-ID: <1155082420.665109.301000@75g2000cwc.googlegroups.com> Noah wrote: > I have a list of tuples > [('a', 1.0), ('b', 2.0), ('c', 3.0)] > I want to reverse the order of the elements inside the tuples. > [(1.0,'a'), (2.0, 'b'), (3.0, 'c')] > > I know I could do this long-form: > q = [] > y = [('a', 1.0), ('b', 2.0), ('c', 3.0)] > for i in y: > t=list(t) > t.reverse() > q.append(tuple(t)) > y = q > > But it seems like there should be a clever way to do this with > a list comprehensions. Problem is I can't see how to apply > reverse() to each tuple in the list because reverse() a > list method (not a tuple method) and because it operates > in-place (does not return a value). This kind of wrecks doing > it in a list comprehension. What I'd like to say is something like > this: > y = [t.reverse() for t in y] > Even if reverse worked on tuples, it wouldn't work inside a > list comprehension. > > Yours, > Noah If your tuples are all two items, you can do it like this: y = [(b, a) for a, b in y] if not, then: y = [tuple(reversed(t)) for t in y] :-D Peace, ~Simon From ziga.seilnacht at gmail.com Sat Aug 19 03:00:38 2006 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 19 Aug 2006 00:00:38 -0700 Subject: efficient memoize decorator? References: <1155931932.349283.27700@h48g2000cwc.googlegroups.com> Message-ID: <1155970838.837378.304560@74g2000cwt.googlegroups.com> thattommyhallll at gmail.com wrote: > im plugging away at the problems at > http://www.mathschallenge.net/index.php?section=project > im trying to use them as a motivator to get into advanced topics in > python. > one thing that Structure And Interpretation Of Computer Programs > teaches is that memoisation is good. > all of the memoize decorators at the python cookbook seem to make my > code slower. > is using a decorator a lazy and inefficient way of doing memoization? > can anyone point me to where would explain how to do it quickly. or is > my function at fault? Your problem is that you are mixing psyco and memoize decorators; psyco cannot accelerate inner functions that use nested scopes (see http://psyco.sourceforge.net/psycoguide/unsupported.html ). You could try using the memoize decorator from: http://wiki.python.org/moin/PythonDecoratorLibrary , which doesn't use functions with closures, or use Fredrik Lundh's solution which puts memoization directly into the function. Ziga From bdesth.quelquechose at free.quelquepart.fr Sun Aug 27 16:21:48 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 27 Aug 2006 22:21:48 +0200 Subject: callable to disappear? In-Reply-To: <ecmesm$4d6$1@news.albasani.net> References: <slrneeopqs.a7l.apardon@rcpc42.vub.ac.be> <ecmesm$4d6$1@news.albasani.net> Message-ID: <44f1fc29$0$9026$626a54ce@news.free.fr> Georg Brandl a ?crit : > Antoon Pardon wrote: > >> I have been reading http://www.python.org/dev/peps/pep-3100/ >> en there is written: >> >> To be removed: >> ... >> >> callable(): just call the object and catch the exception >> ... > > > >> Is there a chance this will be reconsidered? >> > > There was some discussion on python-dev, which concluded that callable() > in its current form is not very useful, I use it quite frequently. From fredrik at pythonware.com Thu Aug 24 15:02:51 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Aug 2006 21:02:51 +0200 Subject: String formatting with nested dictionaries In-Reply-To: <1156436560.040352.162580@b28g2000cwb.googlegroups.com> References: <1156436560.040352.162580@b28g2000cwb.googlegroups.com> Message-ID: <eckt4q$2br$2@sea.gmane.org> linnorm at gmail.com wrote: > I've got a bit of code which has a dictionary nested within another > dictionary. I'm trying to print out specific values from the inner > dict in a formatted string and I'm running into a roadblock. I can't > figure out how to get a value from the inner dict into the string. To > make this even more complicated this is being compiled into a large > string including other parts of the outer dict. > > mydict = {'inner_dict':{'Value1':1, 'Value2':2}, 'foo':'bar', > 'Hammer':'nails'} > > print "foo is set to %(foo)s - Value One is: %(inner_dict['Value1'])s > and Value Two is: %(inner_dict['Value2'])s -- Hammers are used to pound > in %(Hammer)s" % mydict > > The above fails looking for a key named 'inner_dict['Value1']' which > doesn't exist. the % operator treats the keys as plain keys, not expressions. if you trust the template provider, you can use a custom wrapper to evaluate the key expressions: mydict = {'inner_dict':{'Value1':1, 'Value2':2}, 'foo':'bar', 'Hammer':'nails'} class wrapper: def __init__(self, dict): self.dict = dict def __getitem__(self, key): try: return self.dict[key] except KeyError: return eval(key, self.dict) print "foo is set to %(foo)s - Value One is: %(inner_dict['Value1'])s and Value Two is: %(inner_dict['Value2'])s -- Hammers are used to pound in %(Hammer)s" % wrapper(mydict) foo is set to bar - Value One is: 1 and Value Two is: 2 -- Hammers are used to pound in nails </F> From onlyafly at gmail.com Thu Aug 3 10:55:07 2006 From: onlyafly at gmail.com (Kkaa) Date: 3 Aug 2006 07:55:07 -0700 Subject: Hiding Console Output In-Reply-To: <1154565299.429228.149140@b28g2000cwb.googlegroups.com> References: <1154549874.490652.106980@m73g2000cwd.googlegroups.com> <1154565299.429228.149140@b28g2000cwb.googlegroups.com> Message-ID: <1154616907.925182.217970@i42g2000cwa.googlegroups.com> This seems like the right thing to do, but it runs the program in the background, and I need my program to wait until the x.exe has finished. I tried using this code: p = subprocess.Popen("x.exe",shell=True,stdout=subprocess.PIPE,stdin=subprocess.PIPE, stderr=subprocess.PIPE) sts = os.waitpid(p.pid, 0) But I get the error: "No child process". Any ideas? placid wrote: > Kkaa wrote: > > I'm using the os.system command in a python script on Windows to run a > > batch file like this: > > > > os.system('x.exe') > > > > The third-party program x.exe outputs some text to the console that I > > want to prevent from being displayed. Is there a way to prevent the > > output of x.exe from python? > > using the subprocess module to create a subprocess and piping the > stdout,stdin and stderr so you wont see any ouput from the process > unless you read from the PIPE's. > > > import subprocess > p = subprocess.Popen("x.exe", shell=True, > stdout=subprocess.PIPE,stdin=subprocess.PIPE, stderr=subprocess.PIPE) > > > > Cheers > > - > http://bulkan.googlepages.com/python/ From guotie.9 at gmail.com Tue Aug 29 05:06:35 2006 From: guotie.9 at gmail.com (=?utf-8?B?5Y+u5Y+u5b2T5b2T?=) Date: 29 Aug 2006 02:06:35 -0700 Subject: The lib email parse problem... In-Reply-To: <1156841950.866776.66400@b28g2000cwb.googlegroups.com> References: <1156837260.222395.305960@b28g2000cwb.googlegroups.com> <1156841437.692537.68200@i42g2000cwa.googlegroups.com> <1156841950.866776.66400@b28g2000cwb.googlegroups.com> Message-ID: <1156842395.855885.183330@p79g2000cwp.googlegroups.com> supose a email part like this: Content-Type: Multipart/Alternative; boundary="Boundary-=_iTIraXJMjfQvFKkvZlqprUgHZWDm" --Boundary-=_iTIraXJMjfQvFKkvZlqprUgHZWDm Content-Type: text/plain; charset="gb2312" Content-Transfer-Encoding: 7bit abcd. --Boundary-=_iTIraXJMjfQvFKkvZlqprUgHZWDm Content-Type: text/html; charset="gb2312" Content-Transfer-Encoding: quoted-printable ................. --Boundary-=_iTIraXJMjfQvFKkvZlqprUgHZWDm-- the plain text is abcd, and the alternative content type is text/html, i should prefer explain the html content, and i must not explaint the two part ,so i want to get the boundary end. thanks all. From david_wahler at bic.ky Wed Aug 2 04:14:01 2006 From: david_wahler at bic.ky (david_wahler at bic.ky) Date: 2 Aug 2006 03:14:01 -0500 Subject: =?utf-8?Q?Re:_Dr._Dobb's_Python=2DURL=21_=2D_weekly_Python_news_and_links_=28Aug__2=29?= Message-ID: <20060802081401.8095.qmail@BICSRV1011.bic.ky> I'll be out of the office until approximately August 20th. If you have any questions, please email support at bic.ky. -- David Wahler From moverx at gmail.com Tue Aug 29 13:54:18 2006 From: moverx at gmail.com (Yusnel Rojas) Date: Tue, 29 Aug 2006 10:54:18 -0700 Subject: SOAP web services Message-ID: <28b127080608291054n23792597j6cf524762bf5d3b8@mail.gmail.com> I'm trying to make the wsdl asociated with this sample but I cannot make it work import SOAPpy def doUpper(word): return word.upper() server = SOAPpy.SOAPServer(("", 8000)) server.registerFunction(doUpper) server.registerFunction(who) server.serve_forever() can anyone tell me how to do this? anyone who nkows something about SOAPpy.wstools.WSDL? thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060829/4750d89d/attachment.html> From faulkner612 at comcast.net Mon Aug 14 14:23:30 2006 From: faulkner612 at comcast.net (faulkner) Date: 14 Aug 2006 11:23:30 -0700 Subject: TypeError: 'module' object is not callable (newby question) In-Reply-To: <yp2Eg.1858$VQ.825@trndny05> References: <yp2Eg.1858$VQ.825@trndny05> Message-ID: <1155579810.782217.225560@b28g2000cwb.googlegroups.com> works for me. do you do anything in your script besides that? Charles Russell wrote: > Why does this work from the python prompt, but fail from a script? > How does one make it work from a script? > > #! /usr/bin/python > import glob > # following line works from python prompt; why not in script? > files=glob.glob('*.py') > print files > > Traceback (most recent call last): > File "./glob.py", line 2, in ? > import glob > File "/home/cdr/python/glob.py", line 5, in ? > files=glob.glob('*.py') > TypeError: 'module' object is not callable From timr at probo.com Mon Aug 28 00:54:05 2006 From: timr at probo.com (Tim Roberts) Date: Mon, 28 Aug 2006 04:54:05 GMT Subject: time.clock() going backwards?? References: <vkFHg.82529$_J1.759243@twister2.libero.it> <ecnla4$fv2$1@sea.gmane.org> <mailman.9894.1156540900.27775.python-list@python.org> Message-ID: <dht4f25nlkc4outso2o30mpug033umdh8b@4ax.com> "Tim Peters" <tim.peters at gmail.com> wrote: >[Giovanni Bajo[ >>> I experimented something very strange, a few days ago. I was debugging an >>> application at a customer's site, and the problem turned out to be that >>> time.clock() was going "backwards", that is it was sometimes >>> (randomically) returning a floating point value which was "less than" the >>> value returned by the previous invokation. The computer was a pretty fast >>> one (P4 3Ghz I think, running Windows XP), and this happened only between >>> very close invokations of time.clock(). > >[Terry Reed] >> I seem to remember this being mentioned before on the list, perhaps by Tim >> Peters. Perhaps he will chime in. > >No real need ;-) BIOS or HAL bug on a multiprocessor (or maybe even >hyperthreaded) box is by far the most likely cause (and the only cause >ever identified for sure by people who followed up). Python's C code >slinging QueryPerformanceCounter is exceedingly simple, and isn't a >suspect because of that. It's on the edge of vague possibility that >Microsoft's compiler generates non-monotonic code for converting >64-bit integer to double: It is much simpler than that. With a multiprocessor HAL, including on a dual-core or hyperthreaded system, QueryPerformanceCounter returns the raw cycle counter (RDTSC). However, on Windows XP, the operating system does not synchronize the cycle counters on multiple processors, and they can be actually be millions of cycles apart. This was a change from previous systems. On NT4 and Win2000, the operating actually rewrote the cycle counters on the second (and beyond) processors to align them to the first processor, so the delta was usually only a dozen or two cycles. XP does not appear to do that. I think that is a huge mistake, since it renders QueryPerformanceCounter non-monotonic. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From sjmachin at lexicon.net Sat Aug 26 17:56:08 2006 From: sjmachin at lexicon.net (John Machin) Date: 26 Aug 2006 14:56:08 -0700 Subject: f2py on windows XP - "Unknown Switch"?? In-Reply-To: <1156177095.867153.327380@h48g2000cwc.googlegroups.com> References: <1156177095.867153.327380@h48g2000cwc.googlegroups.com> Message-ID: <1156629368.463878.138620@h48g2000cwc.googlegroups.com> Sile wrote: > Hello, > I'm trying to get f2py working from the command line on windows XP. I > have mingw32 as my C complier (after some advice on a previous thread) > and Compaq Visual Fortran 6.5. Changing my C complier reduced my errors > but I'm still having trouble. I think I have all the correct paths set > but I'm not sure. F2PY gets further when I specifically tell it what my > compilers are as follows................. > [snip] Sile, I'd suggest that if you haven't got this sorted yet, you try the f2py mailing list, or e-mail direct to the package author. Cheers, John [who's been away from the net for a week] From dominic.fox at gmail.com Wed Aug 30 09:06:35 2006 From: dominic.fox at gmail.com (Dominic Fox) Date: Wed, 30 Aug 2006 14:06:35 +0100 Subject: xml.sax.writer Message-ID: <f278b2130608300606m63d082cdl448353890ac29c64@mail.gmail.com> Hi, xml.sax.writer doesn't appear in the global module documentation, and googling for it doesn't tell you all that much either. Is it actually in the standard libraries, or is it an interloper from something else (the libxml bindings, say) that just happens to have taken up residence in the xml.sax namespace? Dominic -- Shall we be pure or impure? Today we shall be very pure. It must always be possible to contain impurities in a pure way. --Tarmo Uustalu and Varmo Vene From riko at despammed.com Wed Aug 23 03:59:14 2006 From: riko at despammed.com (Mc Osten) Date: Wed, 23 Aug 2006 09:59:14 +0200 Subject: Python and STL efficiency References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <eccb9u$kjs$1@gemini.csx.cam.ac.uk> <1hkh28d.xscw4v1y4v9a6N%riko@despammed.com> <mailman.9640.1156247569.27775.python-list@python.org> <1hkh6lb.6dsnh51lj8z96N%riko@despammed.com> <1156252193.524186.107520@b28g2000cwb.googlegroups.com> <1156299389.336939.211670@i42g2000cwa.googlegroups.com> <1hkildy.73vcuzyxlsgeN%riko@despammed.com> <1156319484.165195.80540@p79g2000cwp.googlegroups.com> Message-ID: <1hkip1o.2dnx1h1nafe8zN%riko@despammed.com> GHUM <haraldarminmassa at gmail.com> wrote: > Proofed @ EuroPython > 2006 in CERN, near the LHC Beta, in the same room many Nobel laurates > gave their presentations before. Have you some link? I suppose it's kind of a joke they did or something like that... -- blog: http://www.akropolix.net/rik0/blogs | Uccidete i filosofi, site: http://www.akropolix.net/rik0/ | tenetevi riso e forum: http://www.akropolix.net/forum/ | bacchette per voi. From vasudevram at gmail.com Tue Aug 8 10:41:44 2006 From: vasudevram at gmail.com (vasudevram) Date: 8 Aug 2006 07:41:44 -0700 Subject: Info on continuations? Message-ID: <1155048104.107797.220630@b28g2000cwb.googlegroups.com> Hi, I am Googling and will do more, found some stuff, but interested to get viewpoints of list members on: Continuations in Python. Saw a few URLs which had some info, some of which I understood. But like I said, personal viewpoints are good to have. Thanks Vasudev ------------------------------------------------------------------------------------------------------------------------- Software consulting and training http://www.dancingbison.com PDF conversion toolkit: http://sourceforge.net/projects/xtopdf (stable version 1.0, supports plain text and DBF conversions to PDF) ------------------------------------------------------------------------------------------------------------------------- From neokosmos at gmail.com Wed Aug 16 02:39:09 2006 From: neokosmos at gmail.com (neokosmos at gmail.com) Date: 15 Aug 2006 23:39:09 -0700 Subject: Memory usage of an 'empty' python interpreter Message-ID: <1155710349.127768.17280@h48g2000cwc.googlegroups.com> I was wondering what the approximate amount of memory needed to load a Python interpreter (only, no objects, no scripts, no nothing else) in a Linux 2.6 environment. According to ps, it appears to be 3312 bytes, which seems absurdly low to me. However, when I check the size of my Python executable, it looks like it is only about 5600 bytes in size, so maybe this is reasonable? Right now, I currently have one bare Python interpreter running and no other Python programs. Here is the output of ps -aux | grep python (headers added for readability): USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND paul 17561 0.1 0.6 14616 3312 pts/2 S+ 02:33 0:00 python paul 17569 0.0 0.1 2600 520 pts/3 R+ 02:34 0:00 grep python If I am reading this right, it says the Python interpreter itself is using 3312 bytes of memory, but has 14616 bytes of shared memory it can access (which, i assume, is mostly shared libraries). Here's my ls -l /usr/bin/python2.4: -rwxr-xr-x 1 root root 5424 Jul 21 08:02 /usr/bin/python2.4 Am I interpreting this stuff more or less correctly? Thanks! From oliphant.travis at ieee.org Sat Aug 26 05:44:34 2006 From: oliphant.travis at ieee.org (Travis E. Oliphant) Date: Sat, 26 Aug 2006 03:44:34 -0600 Subject: [ANN] NumPy 1.0b4 now available Message-ID: <44F01802.8050505@ieee.org> The 4th beta release of NumPy 1.0 has just been made available. NumPy 1.0 represents the culmination of over 18 months of work to unify the Numeric and Numarray array packages into a single best-of-breed array package for Python. NumPy supports all the features of Numeric and Numarray with a healthy dose of it's own improved features. It's time to start porting your applications to use NumPy as Numeric is no longer maintained and Numarray will only be maintained for a few more months. Porting is not difficult especially using the compatibility layers numpy.oldnumeric and numpy.numarray and the alter_code1.py modules in those packages. The full C-API of Numeric is supported as is the C-API of Numarray. More information is available at http://numpy.scipy.org NumPy Developers From bdesth.quelquechose at free.quelquepart.fr Mon Aug 28 16:39:36 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 28 Aug 2006 22:39:36 +0200 Subject: how to get the os file icon for a given content-type? In-Reply-To: <44f31e50$0$17268$9b622d9e@news.freenet.de> References: <1156753983.080547.306100@h48g2000cwc.googlegroups.com> <44f2b8cc$0$11818$636a55ce@news.free.fr> <1156759387.819060.266380@m73g2000cwd.googlegroups.com> <1156770929.202576.298640@m79g2000cwm.googlegroups.com> <44f31e50$0$17268$9b622d9e@news.freenet.de> Message-ID: <44f351cd$0$6709$636a55ce@news.free.fr> Martin v. L?wis a ?crit : > Paul Boddie schrieb: > >>neoedmund wrote: >> >>[File icons for a given content type] >> >> >>>So what? Java 5.0 has the method, why python has not? >> >>I'd be generally surprised if whichever Java API responsible for this >>managed to work it out correctly for the different free desktop >>environments (KDE, GNOME, etc.) > > > Just because nobody said it so far (although it's probably obvious > to everybody): I doubt neoedmund is talking about free desktop > environments... Which bring us back to my first answer : this is OS-specific. > Regards, > Martin From onurb at xiludom.gro Mon Aug 28 06:09:59 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 28 Aug 2006 12:09:59 +0200 Subject: Pros/Cons of Turbogears/Rails? In-Reply-To: <WXmIg.20772$gY6.18513@newssvr11.news.prodigy.com> References: <WXmIg.20772$gY6.18513@newssvr11.news.prodigy.com> Message-ID: <44f2c0f7$0$12824$626a54ce@news.free.fr> kenneth.m.mcdonald at sbcglobal.net wrote: > First, I don't intend this to be a flame war, please. Then avoid crossposting to both c.l.ruby and c.l.python !-) (BTW, fu2 c.l.python). > Python > and Ruby are the only two languages I'd willingly work in > (at least amongst common languages), and TurboGears and > Rails seem roughly equivalent. > > I'm much more knowledgable about Python, but that's a minor > issue--I've been intending to learn more Ruby anyway. > > Here are the pros and cons that I'm aware of and consider > important: > > Turbogears: > + SqlObject allows working with the DB tables without > using SQL itself. I personnaly don't like SqlObject. SqlAlchemy looks like a much better solution IMHO. And FWIW, Ruby has it's own ORM too. (snip) > I was initially leaning towards Rails due to maturity, > but the most recent version of TurboGears seem to have > fixed a lot of the "ad hoc" feeling I got from previous > versions. But I'm still very much up in the air. Then take a few days to play with both Rails and TG and go with the one that better fits your brain. FWIW, you may also want to check Pylons (another Python Web-MVC framework). My 2 cents -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From onlyafly at gmail.com Wed Aug 2 16:17:54 2006 From: onlyafly at gmail.com (Kkaa) Date: 2 Aug 2006 13:17:54 -0700 Subject: Hiding Console Output Message-ID: <1154549874.490652.106980@m73g2000cwd.googlegroups.com> I'm using the os.system command in a python script on Windows to run a batch file like this: os.system('x.exe') The third-party program x.exe outputs some text to the console that I want to prevent from being displayed. Is there a way to prevent the output of x.exe from python? From crystalattice at gmail.com Fri Aug 25 21:36:55 2006 From: crystalattice at gmail.com (crystalattice) Date: 25 Aug 2006 18:36:55 -0700 Subject: wxGlade and __init__ Message-ID: <1156556215.769634.322240@h48g2000cwc.googlegroups.com> I'm making a GUI for a console-based program I just wrote. I figured it would be mostly straight forward to convert it over in wxPython but now I'm confused. In my console program, I have __init__ making the dictionaries et al. and then my methods will populate them. However, when I use wxGlade under SPE to make the GUI, wxGlade makes it's own __init__. I know not to add anything to this section because it's written over everytime I make changes in wxGlade. How do I reconcile having the auto created __init__ from wxGlade and the __init__ I want to use from my console version? Here's an example of my console program: def __init__(self): """Constructor to initialize each data member to zero.""" #---Attribute info self.attrib = 0 self.attrib_dict = self.default_attribs.copy() #instance version self.setAttribute("str") self.setAttribute("intel") self.setAttribute("build") self.setAttribute("char") self.setAttribute("will") self.setAttribute("throw") self.setAttribute("mass") self.setAttribute("load") self.setAttribute("dex") self.coreInitiative = 0 #---Create attributes--- def setAttribute(self, attr): """Generate value for an attribute, between 2 and 20.""" #---Get secondary attributes if attr == "throw": self.attrib_dict[attr] = self.attrib_dict["str"] * 2 #meters elif attr == "mass": self.attrib_dict[attr] = (self.attrib_dict["build"] * 5) + 15 #kg elif attr == "load": self.attrib_dict[attr] = (self.attrib_dict["str"] + self.attrib_dict["build"]) #kg #---Get core attributes else: self.attrib_dict[attr] = multiDie(2, 2) #2d10 Here's the code created by wxGlade: class Attributes(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: Attributes.__init__ kwds["style"] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) self.panel_2 = wx.Panel(self, -1) self.btnAttributes = wx.Button(self.panel_2, -1, "Get Attributes") self.lblAge = wx.StaticText(self.panel_2, -1, "Age:") self.txtAge = wx.TextCtrl(self.panel_2, -1, "") self.lblChar = wx.StaticText(self.panel_2, -1, "Charisma:") self.txtChar = wx.TextCtrl(self.panel_2, -1, "") self.lblStr = wx.StaticText(self.panel_2, -1, "Strength:") self.txtStr = wx.TextCtrl(self.panel_2, -1, "") self.lblBuild = wx.StaticText(self.panel_2, -1, "Build:") self.txtBuild = wx.TextCtrl(self.panel_2, -1, "") self.lblIntel = wx.StaticText(self.panel_2, -1, "Intelligence:") self.txtIntel = wx.TextCtrl(self.panel_2, -1, "") self.lblThrow = wx.StaticText(self.panel_2, -1, "Throw Range:") self.txtThrow = wx.TextCtrl(self.panel_2, -1, "") self.lblWill = wx.StaticText(self.panel_2, -1, "Willpower:") self.txtWill = wx.TextCtrl(self.panel_2, -1, "") self.lblMass = wx.StaticText(self.panel_2, -1, "Mass:") self.txtMass = wx.TextCtrl(self.panel_2, -1, "") self.lblDex = wx.StaticText(self.panel_2, -1, "Dexterity:") self.txtDex = wx.TextCtrl(self.panel_2, -1, "") self.lblLoad = wx.StaticText(self.panel_2, -1, "Load:") self.txtLoad = wx.TextCtrl(self.panel_2, -1, "") self.lblHP = wx.StaticText(self.panel_2, -1, "Hit Points") self.lblHead = wx.StaticText(self.panel_2, -1, "Head:") self.txtHead = wx.TextCtrl(self.panel_2, -1, "") self.lblTorso = wx.StaticText(self.panel_2, -1, "Torso:") self.txtTorso = wx.TextCtrl(self.panel_2, -1, "") self.lblRArm = wx.StaticText(self.panel_2, -1, "Right Arm:") self.txtRArm = wx.TextCtrl(self.panel_2, -1, "") self.lblLArm = wx.StaticText(self.panel_2, -1, "Left Arm:") self.txtLArm = wx.TextCtrl(self.panel_2, -1, "") self.lblRLeg = wx.StaticText(self.panel_2, -1, "Right Leg:") self.txtRLeg = wx.TextCtrl(self.panel_2, -1, "") self.lblLLeg = wx.StaticText(self.panel_2, -1, "Left Leg:") self.text_ctrl_18 = wx.TextCtrl(self.panel_2, -1, "") self.btnNext2 = wx.Button(self.panel_2, -1, "Next Page") self.__set_properties() self.__do_layout() # end wxGlade From fredrik at pythonware.com Thu Aug 17 03:08:55 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 17 Aug 2006 09:08:55 +0200 Subject: PySequence_SetItem In-Reply-To: <20060817004911.GF5772@performancedrivers.com> References: <1155754847.392950.266180@h48g2000cwc.googlegroups.com> <1155755905.233229.93440@74g2000cwt.googlegroups.com> <1155761144.583994.260150@m73g2000cwd.googlegroups.com> <mailman.9442.1155763376.27775.python-list@python.org> <1155764364.775366.76070@i3g2000cwc.googlegroups.com> <mailman.9443.1155765750.27775.python-list@python.org> <1155767139.084992.133200@i42g2000cwa.googlegroups.com> <mailman.9448.1155772454.27775.python-list@python.org> <1155773602.991452.12450@74g2000cwt.googlegroups.com> <20060817004911.GF5772@performancedrivers.com> Message-ID: <ec14lt$gq5$1@sea.gmane.org> Jack Diederich wrote: >> For avoidance of doubt: the change is to use Py_XDECREF, yes/no? > > Yes. not necessarily: the bug is that you're using an uninitialized object in a context that expects an initialized object. might be a better idea to raise a SystemError exception. </F> From shekhar.kaushik at gmail.com Fri Aug 25 02:17:16 2006 From: shekhar.kaushik at gmail.com (Chandrashekhar Kaushik) Date: Fri, 25 Aug 2006 11:47:16 +0530 Subject: pickling and endianess In-Reply-To: <1f7befae0608242304p3ad8cffdh123f3577daa78dca@mail.gmail.com> References: <c56a14170608242219t764fa281x74e1eb4725a1ac68@mail.gmail.com> <1f7befae0608242304p3ad8cffdh123f3577daa78dca@mail.gmail.com> Message-ID: <c56a14170608242317p10facdadl5beef9b6d2aa0130@mail.gmail.com> Thank you for the information. A request though. I am actually looking to implement serialization routines in C++. An am facing the problem of how to tackle endianess and sizeof issues. Could you give me a overview of how pickling is done in python ? Reading pickle.py is obviously the option , but its getting daunting as i am not that proficient in python :( . On 8/25/06, Tim Peters <tim.peters at gmail.com> wrote: > > [Chandrashekhar kaushik] > > Can an object pickled and saved on a little-endian machine be unpickled > > on a big-endian machine ? > > Yes. The pickle format is platform-independent (native endianness > doesn't matter, and neither do the native sizes of C's various integer > types). > > > Does python handle this in some manner , by say having a flag to > indicate > > the endianess of the machine on which the object was pickled ? And then > > using this flag to decide how that data will be unpickled ? > > Not a flag, no, the pickle format is the same on all platforms. If > you need to know details, read pickle.py. > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- shekhar -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060825/5d7344fa/attachment.html> From moriwaka at gmail.com Mon Aug 21 04:24:15 2006 From: moriwaka at gmail.com (moriwaka) Date: 21 Aug 2006 01:24:15 -0700 Subject: redemo.py with named groups Message-ID: <1156148655.708800.129880@m79g2000cwm.googlegroups.com> Hi, I wrote an easy patch for redemo.py to print named groups. For example, regexp: (?P<spam>.*) string: foobar shows following groups. Groups: 0: 'foobar' 1: 'foobar' 'spam': 'foobar' I don't know how/where to commit this patch.. any suggestions? --- Tools/scripts/redemo.py 2004-02-13 02:35:32.000000000 +0900 +++ redemo.py 2006-08-21 01:11:11.000000000 +0900 @@ -148,6 +148,10 @@ for i in range(len(groups)): g = "%2d: %r" % (i, groups[i]) self.grouplist.insert(END, g) + groupdict = m.groupdict() + for key in groupdict: + g = "%r: %r" % (key, groupdict[key]) + self.grouplist.insert(END, g) nmatches = nmatches + 1 if self.showvar.get() == "first": break From fredrik at pythonware.com Mon Aug 21 08:34:03 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Aug 2006 14:34:03 +0200 Subject: Python and STL efficiency In-Reply-To: <1156162237.274636.17850@i3g2000cwc.googlegroups.com> References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <mailman.9595.1156153010.27775.python-list@python.org> <1156162237.274636.17850@i3g2000cwc.googlegroups.com> Message-ID: <ecc97r$mfb$1@sea.gmane.org> Ray wrote: >> in the C++ example, you're creating 40000 string objects. > > In which case, Licheng, you should try using the /GF switch. This will > tell Microsoft C++ compiler to pool identical string literals together. in what way does that change the implementation of C++'s string type ? </F> From gelists at gmail.com Tue Aug 1 13:47:59 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Tue, 1 Aug 2006 14:47:59 -0300 Subject: Windows vs. Linux References: <1154301694.445639.99580@m79g2000cwm.googlegroups.com> <44cddfb3$0$7761$7a628cd7@news.club-internet.fr> <e%szg.3$gY6.1@newssvr11.news.prodigy.com> <slrnecustl.dsk.sybrenUSE@schuimige.stuvel.eu> Message-ID: <1kvrregnapopd.dlg@gelists.gmail.com> On 2006-08-01 12:31:01, Sybren Stuvel wrote: > Ehm... replace that with "the latter with bonk on every OS except > Microsoft Windows". Windows is the weird one in OS-land, because they > are the only one that use the most widely used escape-character (the > backslash) as path separator. Is that really true? From what I know, it's more like this: - Unix-type systems: '/' - Windows-type systems: '\' - Mac OS: ':' - OpenVMS: '.' - ... Maybe someone else can fill in some of the missing OSes. It doesn't seem to look like Windows is the odd man out; it rather seems that every type of OS uses its own separator. (URLs probably use the slash because the internet protocols have been developed largely on Unix-type systems for use with Unix-type systems?) Gerhard From fizbin at gmail.com Thu Aug 31 18:47:20 2006 From: fizbin at gmail.com (fizbin at gmail.com) Date: 31 Aug 2006 15:47:20 -0700 Subject: Duck typing alows true polymorfisim References: <1156532721.879808.40990@i3g2000cwc.googlegroups.com> <1156533807.630662.12330@i42g2000cwa.googlegroups.com> <12fblk87ppk7ief@corp.supernews.com> <9l9hs3-64h.ln1@sirius.tg00suus7038.net> Message-ID: <1157064440.222224.138960@i42g2000cwa.googlegroups.com> Just a quick note in the midst of this: The Ghost In The Machine wrote: > Dynamic type creation. I don't know if Java has this or not. > One can of course attempt bytecode synthesis -- I think that's > what BCEL uses -- but that's a bit of a hack. Since no one has pointed this out, I should mention the oft-neglected class java.lang.reflect.Proxy, which allows you to create at runtime a class that implements a given set of interfaces and a single instance of that class. Methods are all handled in a manner similar to ruby's method_missing - that is, a single method is passed the method (as a Method object) and arguments (as Object[]). Beanshell (http://www.beanshell.org/) uses this to allow dynamic, scripted objects (created at runtime) to implement arbitrary Java interfaces. Reportedly, this greatly simplifies swing and AWT programming, since one can ignore methods that are specified as part of the interface but aren't actually used through the course of the program. From rogue_pedro at yahoo.com Thu Aug 10 22:03:17 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 10 Aug 2006 19:03:17 -0700 Subject: hide python code ! In-Reply-To: <1155254631.617208.299550@m73g2000cwd.googlegroups.com> References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155253821.570487.165400@b28g2000cwb.googlegroups.com> <1155254631.617208.299550@m73g2000cwd.googlegroups.com> Message-ID: <1155261797.751312.249460@74g2000cwt.googlegroups.com> Bayazee wrote: > hi > in compiled languages when we compile a code to an executable file it > convert to a machine code so now we cant access to source ... It can still be disassembled and reverse engineered. > but in python we easily open the program executable(ascii) file and > read source .... > i meen than any way to protect my code or convert it to executable > witch can not be decompiled (python code).... How do you reconcile this desire with being part of "First Iranian Open Source Community"? I am not hostile, just curious. BTW, John Machin's suggestion of presenting your code as a web service is a good one. Peace, ~Simon From rogue_pedro at yahoo.com Wed Aug 16 15:38:09 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 16 Aug 2006 12:38:09 -0700 Subject: getting database column names from query In-Reply-To: <mailman.9439.1155756537.27775.python-list@python.org> References: <mailman.9439.1155756537.27775.python-list@python.org> Message-ID: <1155757089.830700.168060@m79g2000cwm.googlegroups.com> Jason Nordwick wrote: > I'm using MySQLdb and can connect and issue queries that return result sets, but I how do I get the column names for those result sets? > > >>> c = MySQLdb.connect(*creds) > >>> k = c.cursor() > >>> k.execute("select * from account") > 3L > >>> k.fetchall() > ((1L, 'test', -1L), (2L, 'Test', -1L), (3L, 'Test2', -1L)) > > > -j k.description See also http://www.python.org/dev/peps/pep-0249/ HTH, ~Simon From skip at pobox.com Tue Aug 8 14:07:05 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 8 Aug 2006 13:07:05 -0500 Subject: Newbie question: what's with "self"? In-Reply-To: <1155054411.511813.203270@i42g2000cwa.googlegroups.com> References: <1155054411.511813.203270@i42g2000cwa.googlegroups.com> Message-ID: <17624.53961.30110.220418@montanaro.dyndns.org> donkeyboy> This is probably a really basic question, but anyway ... I'm donkeyboy> new to both Python and OO programming. From looking at a donkeyboy> number of code examples, the word "self" is used a lot when donkeyboy> referring to classes. As such, what does "self" mean and/or donkeyboy> do? "self" is a name refering to the particular instance whose method is being called. If I have class C: def __init__(self): self.x = 7 def printx(self): print self.x a = C() b = C() If I call a.printx(), self will be bound to the same object a is bound to. If I call b.printx(), it will be bound to the object b references. The precise use of the name "self" is indeed simply a convention. You could call it "barney" if that makes you feel better. ;-) Skip From danielwong at berkeley.edu Sun Aug 6 12:34:41 2006 From: danielwong at berkeley.edu (danielx) Date: 6 Aug 2006 09:34:41 -0700 Subject: Why do I require an "elif" statement here? References: <1154712731.375032.203570@m79g2000cwm.googlegroups.com> <mailman.8999.1154714505.27775.python-list@python.org> <1154812783.619385.293820@n13g2000cwa.googlegroups.com> <mailman.9018.1154813589.27775.python-list@python.org> <1154824177.621769.311390@m73g2000cwd.googlegroups.com> Message-ID: <1154882081.470315.279350@h48g2000cwc.googlegroups.com> I'm surprised no one has mentioned neat-er, more pythonic ways of doing this. I'm also surprised no one mentioned regular expressions. Regular expressions are really powerful for searching and manipulating text. Here is where I learned most of the stuff I know about regular expressions: http://www.amk.ca/python/howto/regex/ I think this howto does a pretty good job, and doesn't take too long to read. Anyway, here's my solution, which does Not use regular expressions: def reindent(line): ## we use slicing, because we don't know how long line is head = line[:OLD_INDENT] tail = line[OLD_INDENT:] ## if line starts with Exactly so many spaces... if head == whitespace*OLD_INDENT and not tail.startswith(' '): return whitespace*NEW_INDENT + tail else: return line # our default emptyString = "" lines = input.readlines() reindented = [reindent(ln) for ln in lines] output.write( emptyString.join(reindented) ) I'll bet you could put that all on one line using lambda instead of a def, but this is Python, and we like clarity ;). A regular expression could have taken the place of our reindent function, but I'll leave that up to you to explore ;). Jim wrote: > Good stuff! > Since I'm only interested in spaces being my only whitespace it makes > sense for me to use "line.lstrip(whitespace)" in my script, thus > eliminating the "elif char == '\n':" statement. > Thanks, > Jim > > Tim Chase wrote: > > > Hard to believe that lstrip() produces an empty string on lines with > > > just spaces and doesn't remove the '\n' with lines that have > > > characters. > > > > It's easy to understand that lstrip() is doing exactly what it's > > supposed to. It evaluates from the left of your string, > > discarding whitespace (spaces, tabs, and cr/lf characters) until > > it hits a non-whitespace character or the end of the string. > > When there's no non-whitespace, it returns an empty string. > > > > If you wanted to remove the \n from the right of lines, there was > > an earlier discussion on the list where someone (Bruno?) and I > > went back and forth and I think we finally decided that the > > "best" solution was > > > > s.rstrip('\n') > > > > which had the fewest side-effects. > > > > However, when you use the output.write() method, you'd then have > > to add the \n back in to make sure it ended up in the output stream. > > > > If you wanted to continue to use lstrip(), you could also just > > ensure that you're only stripping spaces (chr(0x20)) by using > > > > s.lstrip(' ') > > > > This would leave \t and \n characters unmolested. > > > > More info can be found at > > > > >>> help("".lstrip) > > >>> help("".rstrip) > > >>> help("".strip) > > > > Hope this helps, > > > > -tkc From rdiaz02 at gmail.com Mon Aug 21 20:37:25 2006 From: rdiaz02 at gmail.com (Ramon Diaz-Uriarte) Date: Tue, 22 Aug 2006 02:37:25 +0200 Subject: idutils and Python Message-ID: <624934630608211737x5e74abb9l291f334b31c22cfe@mail.gmail.com> Dear All, Has anybody tried to use ID Utils (http://www.gnu.org/software/idutils/46) with Python? I've googled, searched the mailing list, and have found nothing. A silly, simple use of IDUtils with Python code does work, using a language map that says *.py files are text files. But I am wondering if someone has done something more sophisticated. (For instance, I get matches to commented out functions, which I'd rather not, lots of extra stuff is indexed which probably shouldn't, etc). Thanks, R. P.D. ID utils is somewhat like [ce]tags, and has support under Emacs (see section 5.2 of the ID utils manual: http://www.gnu.org/software/idutils/manual/idutils.html#Emacs-gid-interface47 ). One nice feature is that, when searching for matches, it shows the results in a compilation buffer, so you can see where, in each file, the identifier is used, and visit that if you want. I like this a lot better than "tags-search". -- Ramon Diaz-Uriarte Bioinformatics Unit Spanish National Cancer Centre (CNIO) http://ligarto.org/rdiaz From chris at kateandchris.net Tue Aug 8 15:13:58 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Tue, 8 Aug 2006 15:13:58 -0400 Subject: Backup GMAIL Messages with Python In-Reply-To: <312cfe2b0608051743y5183827r240f096c83fff1b0@mail.gmail.com> References: <mailman.9017.1154805163.27775.python-list@python.org> <feaBg.7256$rP1.5423@news-server.bigpond.net.au> <312cfe2b0608051743y5183827r240f096c83fff1b0@mail.gmail.com> Message-ID: <20060808191357.GC12723@kateandchris.net> fetchmail worked for me. You have to be patient though because it takes a while for all of your mail to become available for pop download. -Chris On Sat, Aug 05, 2006 at 08:43:32PM -0400, Gregory Pi?ero wrote: > On 8/5/06, Neil Hodgson <nyamatongwe+thunder at gmail.com> wrote: > > While you can write a script, its quite easy to turn on POP and run > > a client side mail client like Thunderbird. > > Good point, Neil. This is a very tempting option, I just wanted to > include it in a backup script rather than having to open up > Thunderbird once a day. > > -Greg > -- > http://mail.python.org/mailman/listinfo/python-list From pavlovevidence at gmail.com Mon Aug 21 12:54:41 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 21 Aug 2006 09:54:41 -0700 Subject: sum and strings In-Reply-To: <pan.2006.08.21.09.36.20.956098@REMOVEME.cybersource.com.au> References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <slrneeatf3.nbt.sybrenUSE@schuimige.stuvel.eu> <1155922208.930580.135080@m79g2000cwm.googlegroups.com> <mailman.9516.1155930431.27775.python-list@python.org> <1155952305.848495.7060@i3g2000cwc.googlegroups.com> <7x4pw9h3yy.fsf@ruckus.brouhaha.com> <pan.2006.08.21.09.36.20.956098@REMOVEME.cybersource.com.au> Message-ID: <1156179281.249531.188460@b28g2000cwb.googlegroups.com> Steven D'Aprano wrote: >But I think it is a shame that sum() does a > special type-check to avoid something which is only sometimes slow. It > doesn't protect against O(n**2) performance; it merely protects against > just one of an infinite number of possible "traps for the unwary". I'm not so sure special casing was a good idea myself, but... If you allow for a small number of special cases in the language to protect against the most harmful and prone traps, this case would be one of the top ones, IMHO. Carl Banks and, you know, if you really want to concatenate strings with sum, you can class noopadd(object): def __add__(self,other): return other sum(["abc","def","ghi"],noopadd()) From bedouglas at earthlink.net Thu Aug 10 21:45:54 2006 From: bedouglas at earthlink.net (bruce) Date: Thu, 10 Aug 2006 18:45:54 -0700 Subject: python/mysql/list question... In-Reply-To: <278e01c6bce6$b1bbe960$0301a8c0@Mesa.com> Message-ID: <279001c6bce7$e340f470$0301a8c0@Mesa.com> never mind... doh!!! executemany as opposed to execute!!! thanks -----Original Message----- From: python-list-bounces+bedouglas=earthlink.net at python.org [mailto:python-list-bounces+bedouglas=earthlink.net at python.org]On Behalf Of bruce Sent: Thursday, August 10, 2006 6:37 PM To: python-list at python.org Subject: python/mysql/list question... hi. i have the following sample code. i'm trying to figure out if there's a way to use a 'list of lists' in a mysql execute... i've tried a variety of combinations but i get an error: Error 1241: Operand should contain 1 column(s) the test code is: insertSQL = """insert into appTBL (appName, universityID) values(%s,%s)""" a = [] b = [] a.append('qqa') a.append(222) b.append(a) a=[] a.append('bbb') a.append(66) b.append(a) try: c.execute(insertSQL, (b[0],b[1])) <<<<<<<<<<<<<<<<<<< except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) print b sys.exit (1) i've tried to use b, (b), etc... using b[0] works for the 1st row... any thoughts/comments... thanks -- http://mail.python.org/mailman/listinfo/python-list From steve at holdenweb.com Mon Aug 14 22:22:40 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 15 Aug 2006 03:22:40 +0100 Subject: How to fill a form In-Reply-To: <20060815034051.89ef7e18.sulsa@gazeta.pl> References: <20060815034051.89ef7e18.sulsa@gazeta.pl> Message-ID: <ebrb4q$gec$1@sea.gmane.org> Sulsa wrote: > I need to fill form from web site, the code for this form looks like > this: > > <form action="login.php" method="post" target="_top"> > > <input type="text" name="username" size="25" maxlength="40" > class="post" /> > <input type="password" name="password" size="25" maxlength="25" > class="post" /> > > <input type="hidden" name="redirect" > value="" /> > <input type="submit" name="login" class="mainoption" > value="Login" /> > > </form> > > I can of course connect to a web site and download the form, i do it > like this: > > import urllib2 > www = urllib2.urlopen("http://www.site.com/login.php") > form_data= stronka.read() > > or using httplib: > > import httplib > conn = httplib.HTTPConnection("www.site.com") > conn.request("GET", "/login.php") > data1 = conn.getresponse().read() > > > but i can't fill and send this form is there some simple way to do it? I'd recommend you take a look at mechanize, see http://wwwsearch.sourceforge.net/mechanize/ and specifically at ClientForm, see http://wwwsearch.sourceforge.net/ClientForm/ These make it easy to perform browser-like accesses to forms-based web applications. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From rogue_pedro at yahoo.com Mon Aug 28 16:58:03 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 28 Aug 2006 13:58:03 -0700 Subject: Twisted server and protocol question In-Reply-To: <1156793369.290812.247200@m73g2000cwd.googlegroups.com> References: <1156793369.290812.247200@m73g2000cwd.googlegroups.com> Message-ID: <1156798683.820174.60840@m79g2000cwm.googlegroups.com> Benry wrote: > Hi guys. I hope I can discuss Twisted here. If not, direct me to the > correct place please. Twisted mailing list: http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python ;-) ~Simon From faruk.nur at mynet.com Wed Aug 9 06:05:22 2006 From: faruk.nur at mynet.com (faruk.nur at mynet.com) Date: 9 Aug 2006 03:05:22 -0700 Subject: ALLAH Message-ID: <1155117922.061942.100370@n13g2000cwa.googlegroups.com> Kader; soru:madem,her?ey bir kader defterinde yaz?l? ve her?ey ona g?re oluyor.o halde insanlar ni?in cehenneme gidiyor? cevap:evet her?ey bir kader defterinde yaz?l? ve her?ey ona g?re oluyor.ama,defterde yaz?l? oldu?u i?in o ?ey olmuyor. mesela;meteroloji uzman?,uydudan gelen foto?raflara bakarak gelece?i g?rebilmektedir.bir insan ne kadar y?kse?e ??karsa hem g?r?? alan? geni?ler hemde gelece?i g?rebilir. uzman, uydudan g?r?yor ki,T?rkiye"nin bat?s?ndan ya?mur bulutlar? geliyor.bulutlar?n h?z?n? ve y?n?n? hesapl?yarak,hemen defterine ?unlar? yaz?yor,"yar?n t?rkiye bulutlu ve ya???l? olacak".bulutlar?n gelmesine bir g?n var.bir g?n sonra t?rkiye bulutlu ve ya???l? olsa;acaba meteroloji uzman? bir g?n ?nceden deftere,bu olay? yazd??? i?inmi olaylar oluyor?yoksa uzman olaylar? uydudan ?nceden g?rd?demi yazd?. do?ru cevap;g?rd?de yazd?.yazd??? i?in olaylar olmamakta,fakat olay?n ?yle olaca??n? ?nceden g?r?p yazm??t?r. Mesela;akl? ba??nda bir ki?iyi, siz s?rt?n?za alsan?z,nereye gitmek istersen seni oraya g?t?rece?im deseniz,diyelim ki iki yol var biri,tehlikeli yol, ?teki tehlikesiz yol.siz ba?tan o ki?iye uyar?da bulunarak her iki yolun durumunu anlatsan?z buna ra?men,o ki?i beni tehlikeli yoldan g?t?r dese,o tehlikeli yolda ba??na bir kaza gelse ,size diyebilirmi ki,bak senin y?z?nden ba??ma bu kaza geldi diyemez.??nk? kendi iradesiyle tehlikeli yolu se?mi?tir.g?t?ren de?il,isteyen su?ludur.G?? ve kuvvet yaln?z Allah"tand?r.bunu fel?li hastalar daha iyi bilir.G?t?ren Allah"t?r, fakat tehlikeli yolda gitmek isteyen,insan su?ludur. Hem insan ba??bo? b?rak?lm?? da de?ildir. C?z-i iradesinden ba?ka kendisine ait g?nahlar? ve bor?lar? vard?r.sevaptaki hissesi ise pek azd?r.Kimin ve neyin sayesinde sevap i?lemi?tir d???nmesi gerekir. Allah; birzaman gayet zengin bir ressam,sergi a?mak istemi?,fakat sahnenin gerisinde durmu? kendisini konuklara g?stermemi?.konuklara hert?rl? ikram? yapm??.sergiyi gezen misafirler,harika resimlere bakm??lar,ne kadar g?zel resimler diyerek aralar?nda konu?urlarken birisi, ressam? g?remedi?i i?in, acaba bu resimler nas?l olmu?tur diye bir soru ortaya atm??.bir k?s?m insanlar,bu resimler kendi kendine olmu?tur demi?ler.bir k?s?m insanlar resimleri tabiiyyat kanunlar?n?n yapt???n? iddia etmi?ler.bir k?s?m insanlar ise resimleri,resmi meydana getiren,boya,f?r?a, tablo birlikte bu resmi kafa kafaya vermi?ler meydana getirmi?tir demi?ler.bir k?s?m insanlar ise,harika resimleri ancak bir ressam taraf?ndan yap?labilece?ini s?yleyerek,kendilerine ikramda bulunan ressam? i?eriden,alk??lar ile davet edip,kendisiyle tan??m?? ve te?ekk?r etmi?ler.i?te biz,kainat?n tek yarat?c?s? olan, o ressama Allah diyoruz. ressamdan fark?, ger?ek ve canl? resimler yaratmas?d?r. Resim,ressam?n bir par?as? olmad??? gibi; ressam da, resmin bir par?as? de?ildir. Soru:Peki,Allah"? kim yaratm??t?r?sorusu(?eytan?n insanlar? kand?rmak i?in sordu?u sorudur) genellikle insanlar?n kafas?n?n kar??mas?na yol a?m??,bu soruda tak?l?p kalm??lard?r. ?nsanlar?n bu sorunun cevab?n? bulmaya ?al??mas?,nafiledir. Mesela; diyelimki bir saraya girmek i?in y?z kap? var,ama bir kap? kapal? ve saray?n sahibi ancak o kap?y? a?abilir ve anahtarda sadece ondad?r.D??ar?dan saraya girmeye ?al??an biri,a??k doksandokuz kap?n?n herhangi birinden i?eri girebilir.Fakat kapal? kap?n?n ?n?nde durup o kap?y? a?amay?nca,bu saraya girilemez diyemez,??nk? di?er doksandokuz kap? a??kt?r.Aynen ?ylede,Allah"? kim yaratm??t?r, sorusu farzedelim ki kapal? bir kap?d?r.O kap?n?n anahtar? sadece Allah"tad?r.Allah"a inanmak i?in doksandokuz kap? a??kt?r.Ama inat edip,kapal? kap?n?n ?n?nde durmak ve saray sahibini inkar etmek ve a??k kap?dan saraya girmemek ak?l kar? de?ildir. Peki Allah yoksa,bu kainat? kim yaratm??t?r? bu kainat nas?l olmu?tur?yani yukar?daki harika resimler nas?l olmu?tur? sorusunun cevab?n? inat edenlerin vermesi gerekir. ?lmin kap?s? Hz.Ali ??yle der,"Varsayal?m ki inanmayan inat edenlerin dedi?i gibi Allah,ahiret,cennet,hesap kitap, vs.yok.Ne inanana bir ?ey olur,nede inanmamakta inat edene.Ama ya varsa,"inanana yine bir ?ey olmaz ama inanmamakta inat eden; i?ini ?ansa b?rakm?? olur ki buda ak?l kar? de?ildir. Tevekk?l ve dua; bir ?if?i,evvela(?n?art);?r?n almak i?in,1-topra??n? nadasa koyacak,2-topra??n? s?recek,tohumu dikecek,3-sulayacak.vb.fiili dua edecek. Sonra; Allah"a ,?r?n vermesi i?in kavli(s?zl?) dua edecek.??nk? bir afet gelir ?r?n? al?p g?t?rebilir.Mesela;?ekirge ve sel afeti gibi.?artlardan birinin eksik olmas?,neticeye engeldir. Dua eden ki?i i?in o istedi?i, kendisi hakk?nda hay?rl? olup olmad???n? dua eden bilemez.O halde duam niye,ni?in kab?l edilmedi diye,?z?lmemelidir. Mesela;Bir anne ve baba hi?bir zaman ?ocu?unun k?t?l???n? istemedi?i i?in ,terbiyeye muhta? ?ocu?unun her istedi?ini de yapmaz .Bu imtihan d?nyas?nda,s?n?rl? ve kay?tl? oldu?umuz i?in her istedi?imizi elde edemeyiz,her istedi?imizi yapamay?z.Fakat her istedi?imizi elde edecek ve her istedi?imizi yapabilece?imiz bir yer vard?r ki o yere cennet derler. Her ?eye muhta? olan ki?inin , Samed olan Allah"?n kap?s?n? ?almas? do?ru bir ?eydir.Yanl?? olan, her?eye muhta? bir ki?inin, kendisini hi?bir?eye muhta? olmad???n? zannetmesi ve dua etmemesidir. ?eytan, ?eytan"?n asl? cin olup ate?ten yarat?lm??t?r.?nsan?n apa??k,bir d??man?d?r.Mahlukat?,Allah"a d??man etmek i?in f?rsat kollar. Bu hayat? insanlar i?in cehenneme ?evirmeye ?al???r. ?nsan, ?eytan"dan herbak?mdan ?st?nd?r.Fakat ?eytan"?da hafife almamak gerekir.??nk? Hz.Adem babam?z ile Hz.Havva annemizin cennetten ??kmas?na vesile olmu?tur.Biz ?eytan?n inad?na,bu d?nyay? cennete ?evirmek i?in ?al??mal?y?z. Sak?n sizi ?eytan, Allah afedicidir diye yan?ltmas?n.??nk?, Allah af edicidir ama, kul hakk? hari?tir. ?eytan,Allah"? inkar etmemektedir ama,O"na d??man oldu?u,iman etmedi?i i?in ezeli ve ebedi olarak cehennemden ??kamayacakt?r. ?nkar etmemek ayr?d?r,iman etmek ayr?d?r,hi? inanmamak ise,hi?mi hi? ak?l kar? de?ildir.?nsanlar korku ile ?mit aras?nda olmal?. Acaba cennetlikmiyim, yoksa cehennemlikmiyim sorusunu merak etmek yerine, en k?t? ihtimali g?z ?n?ne alarak, tedbirimizi almak; daha ak?ll?ca bir i? olsa gerektir.Allah'tan ancak O"na iman etmeyenler,?midini keser. Son nefese kadar,kimin ne olaca??,(?eytan hari?)bizce mechuldur.Cennet ucuz olmad??? gibi, cehennem dahi l?z?msuz de?ildir. Din, Her semavi hak dinler,medeniyetin ve insan?n maddeten ve manen y?kselmesini,daha iyiye ve ileri gitmesini savunur. ?slam,bir lokma bir h?rka felsefesine kar??d?r.Yar?n ?lecekmi? gibi, ahirete, hi? ?lmeyecekmi? gibi d?nyaya te?vik eder,?ki g?n? ayn? olan ziyandad?r,kom?usu a? iken, tok yatan bizden de?ildir, haks?z yere bir insan? ?ld?ren,t?m insanl??? ?ld?rm?? gibidir, d???ncesini savunur.Tek ilah vard?r. O ilah?n ad? Allah"d?r. Zerrece Allah"a iman? olan ve O"na d??man olmayan herkez, hesaptan sonra cennete girecektir. ?slam; Peygamberi Hz.Muhammed"tir,Kitab? Kuran-? Kerim"dir. Bir M?sl?man,hem ?ncile,hem Hz.?sa"ya, hem,Tevrata, hem Hz.Musa"ya yani t?m semavi kitap ve peygamberlere zaten inand??? i?in din de?i?tirmesi, hi?mi hi? ak?l kar? de?ildir. Namaz, Dininin dire?idir.Bir insan,Allah"?n benim namaz?ma ihtiyac? yoktur,demesi,hasta birinsinin,doktara "ey doktor senin ilaca ne ihtiyac?n var demesine benzer ki,Allah"?n bizim namaz?m?za elbetteki ihtiyac? yoktur,bizim namaza ihtiyac?m?z vard?r.Bedenin havaya ve suya ihtiyac? oldu?u gibi, ruhunda manevi g?daya ihtiyac? vard?r ki o g?dalardan biriside "Hu" kelimesidir.?nsanlar her nefes veri?te bilmeden,gayri ihtiyari "hu" derler.Hu ,Allah demektir.Asl?nda her ?ey Allah"? anmaktad?r.?nsan?n bu d?nyaya g?nderilmesinin sebebi ve hikmeti ,Allah"? tan?mak ,O"na dua ve ibadet etmektir. Hayat, Helal ?ekilde; ?al???n?z,kazan?n?z,yiyiniz,da??t?n?z,payla??n?z,ama israf etmeyiniz.Kara g?nler, ya?l?l???n?z ve ahiret i?inde,az?k ay?r?n?z. ?limin ,mal?n ve kuvvetin ?nemini fark ediniz.Bunlar? insanl???n hayr? i?in ve helal bir ?ekilde kullan?n?z. ?eytan?n,d?nyay? fesada veren ve insanlar i?in d?nyay? ?ehenneme ?eviren,sen ?al?? ben yiyeyim ve ben tok olay?m ba?kas? a?l?ktan ?ls?n bana ne d???ncesini ,ortadan kald?rmak ve sosyal dengeleri kurmak i?in ?al??mak insanl??a yap?lacak en b?y?k hay?rlardan biri olsa gerektir. ?lim, Bir zaman iki ayna var imi?,her iki aynada y?zlerini g?kteki g?ne?e ?evirmi?,aynalarda akseden,tecelli eden g?ne?i , insanlar?n y?zlerine her iki ayna da ?evirdi?inde, insanlar?n g?zlerini kama?t?rm??lar. Aynalardan biri gururlanarak ben insanlar?n g?zlerini kama?t?rd?m diye gururlanm?? ve kendisinde bir ?eyler oldu?unu tevehh?m, zan etmi?.Di?er ayna ise m?tevaz? bir?ekilde,asl?nda kendisinde bizatihi bir ?ey olmad???n?,g?kteki g?ne? olmasa hi?bir?eye yaramad???n?, ?nceki aynaya s?ylemi?. ??te gururlu ayna, sihir ve b?y? gibi zararl? ilimler ile ilgilenip insanlar? kendisinin etkiledi?ini zanneden ?eytan gibidir.Ama m?tevaz? ayna ise m?cize ve kerametin as?l sahibinin kendisi olmad???n? bilen ve faydal? ilimler ile ilgilenen bilge ki?idir.G?bta edilecek ki?i g?kteki g?ne?in ?s? ve ?????na mazhar olan kendisini g?ne? zannetmeyen ama g?ne?i g?steren, ki?idir.Bu aynalar?n en g?zelleri peygamberlere aittir.en k?t?leri ise ?eytan ve ?eytan gibilere aittir. ?eytan ve ?eytan gibi k?t? ki?ilerin ?errinden Allah"a s???nmak gerektir.??nk? insanlar? ve insanl??? tesirleri alt?na alabilmekte ve aldatabilmektedirler.Her insan kabiliyeti nispetinde g?ne?e mahzar olabilir ve olmal?d?rda. As?l olan aynay? insanl???n hayr?na kullanmak ve ayna oldu?unu hi?birzaman unutmamakt?r.Aynadan kas?t insan, g?ne?ten kas?t ise,Allah't?r. G?ne? bize ???k ve ?s?s? ile ?ok yak?nd?r,biz ise g?ne?e ?ok uza??z.Ama ayna vas?tas?yla,bir nebze g?ne?in ?zelliklerini anlayabiliriz. Veya uzay meki?i ile g?ne?in hakiki nuruna ve ?s?s?na yakla?abiliriz onu yak?ndan inceleyebiliriz ki,bunu mirac hadisesinde Hz.Muhammed bizzat refref'e binerek ?ok k?sa bir zaman zarf?nda yapm??t?r. Cenneti,cehennemi ve kainat?n yarat?c?s?n? g?rm??,gidipte g?renmi var veya gidipte d?nenmi var sorusunuda cevaps?z b?rakmam??t?r. Mesela, koca bir k?tlesi olan d?nyam?z?,vas?tas?z ve ?ok s?ratli bir?ekilde g?t?ren ve d?nd?ren, bir insan? elbette ve evleviyetle daha h?zl? ve k?sa bir s?rede g?t?rmeye ve geri getirmeye muktedirdir ve aynen ?ylede olmu?tur. ?nsanl??a faydal? bilgileri, tan?d?k,tan?mad?k,ba?kalar? ile de payla??n?z,yay?n?z. Ben bu bilgileri bilmiyordum,bana kimse ??retmedi diyen ki?inin hesab?; bilenden, bildi?i halde susandan ve hakikat? ve do?ruyu yaymayandan sorulacakt?r. Mal?n zekat? oldu?u gibi,ilminde zekat? ve kuvvetinde bir zekat? vard?r.Bilen ile bilmeyen bir de?ildir.?lim m?min"in yiti?idir, nerede olursa al?r.?lim ?in"dede olsa al?n?z.Hayatta,en hakiki mur?it ilimdir. Faydal? t?m ilimlerden istifade ediniz,ettiriniz. Be?ikten mezara kadar ilim ??reniniz. Okuyunuz,okutunuz.Ne demi? yunus emre,'?lim ilim bilmektir, ilim kendin bilmektir,sen kendini bilmez isen ilim nice okumakt?r.' Ruh nedir; Ruh insan?n asl?d?r,kendisidir.Mahiyeti,bir ?ekli sureti ve ?uuru olan bir kanundur, yer?ekimi kanunu gibi,ama yer?ekimi kanununun bir ?ekli, sureti ve ?uuru yoktur.Fakat d?nyadaki i?leri yapabilmesi i?in, ruh"un elbisesi,bine?i mahiyetinde olan bedene ihtiyac? vard?r.Ruh katiyen bakidir,yani ?l?ms?zd?r. Ey insanlar, baki bir aleme gideceksiniz,o halde haz?rl?kl? olun.?l?m,ruhun bedenden ??kmas? daha ?nce vefat etmi? olan sevgili anne ve baban?z?n ve dostlar?n?z?n yan?na gitmektir. Mesela ;bir ??f?r nas?l arac?ndan inince araba hi?bir i?e yaramaz ise,ruh"ta beden arac?ndan inince, beden hi?bir i?e yaramaz.Kabre konan bedendir.Siz ise ruhsunuz.Ruh berzah alemine gitmektedir. ?l?m yokluk ve hiclik de?ildir.Kim yok olmak isterki,Ezeli ve ebedi bir Allah"?n sevgili mahlukat?da ebedi olmal?d?r.Fakat mahlukat?n ebedili?i bizatihi de?il, Allah"?n dilemesiyledir. Ey insanlar ve cinler ezeli ve ebedi cennete girmek,ebedi ya?amak,her istedi?ini yapmak ve Allah'? g?rmek istemezmisiniz. Ey sevgili ruh,bunun i?in Allah'a ??kretmeli ve iman etmeli de?ilmisin. HULASA : Allah,birdir, hi?bir?eye ihtiyac? yoktur,ne birba?kas? O'nu yaratm??t?r nede O'nun bir ?ocu?u vard?r.O'nun e?i ve benzeri yoktur. From sjmachin at lexicon.net Thu Aug 17 00:11:15 2006 From: sjmachin at lexicon.net (John Machin) Date: 16 Aug 2006 21:11:15 -0700 Subject: Printing n elements per line in a list In-Reply-To: <1155784935.362159.241630@m79g2000cwm.googlegroups.com> References: <1155685889.626881.37040@m73g2000cwd.googlegroups.com> <1155769304.916282.183340@i3g2000cwc.googlegroups.com> <1155770893.267734.81400@h48g2000cwc.googlegroups.com> <1155784935.362159.241630@m79g2000cwm.googlegroups.com> Message-ID: <1155787875.112075.142630@i42g2000cwa.googlegroups.com> Matimus wrote: > Well, I have another at bat, so I will try to redeem myself... using > recursion: > > def printTable(l,c): > print(("%d "*len(l[:c]))%tuple(l[:c])) > if( len(l[:c]) > 0 ): > printTable(l[c:],c) > > printTable(range(1,101),5) Sorry. Recursion disqualified your batter before he got out of the dugout. Besides the %d restricts it to use wirh integers, and using "L".lower() as a variable name made the umpire barf through his facemask all over the catcher. Fortunately the ump didn't notice the weirdly-spaced and superfluous () in the if statement ... From bdesth.quelquechose at free.quelquepart.fr Mon Aug 28 16:21:45 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 28 Aug 2006 22:21:45 +0200 Subject: class problem In-Reply-To: <1156786617.162744.128870@h48g2000cwc.googlegroups.com> References: <1156786617.162744.128870@h48g2000cwc.googlegroups.com> Message-ID: <44f34d9d$0$6650$636a55ce@news.free.fr> fegge a ?crit : > when i declare a class, is there difference between the below: > class myClass(): > class myClass(threading.Thread) > If you don't know the answer to this, then it's time to read the fine manual. Please come back when done. From siona at chiark.greenend.org.uk Thu Aug 24 11:57:46 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 24 Aug 2006 16:57:46 +0100 (BST) Subject: Is there an elegant way to dir() module from inside? References: <1156429103.823271.204880@m73g2000cwd.googlegroups.com> Message-ID: <cGt*Em3or@news.chiark.greenend.org.uk> volcano <Mark.Geyzer at gmail.com> wrote: >I am looking for a way to discover which classes a module contains from >"inside". I am building a testing class that should, when instatntiated >within any module, locate certain classes within the containing module. globals().keys() -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From peter.maas at somewhere.com Sat Aug 19 15:54:36 2006 From: peter.maas at somewhere.com (Peter Maas) Date: Sat, 19 Aug 2006 21:54:36 +0200 Subject: How to get the ascii code of Chinese characters? In-Reply-To: <mailman.9552.1156006565.27775.python-list@python.org> References: <1155986298.643983.157460@i3g2000cwc.googlegroups.com> <1155990488.395220.178810@74g2000cwt.googlegroups.com> <1155999554.486951.303480@i42g2000cwa.googlegroups.com> <pan.2006.08.19.15.42.29.167353@gmx.net> <mailman.9552.1156006565.27775.python-list@python.org> Message-ID: <ec7qac$3ra$1@online.de> Gerhard Fiedler wrote: > Well, ASCII can represent the Unicode numerically -- if that is what the OP > wants. No. ASCII characters range is 0..127 while Unicode characters range is at least 0..65535. > For example, "U+81EC" (all ASCII) is one possible -- not very > readable though <g> -- representation of a Hanzi character (see > http://www.cojak.org/index.php?function=code_lookup&term=81EC). U+81EC means a Unicode character which is represented by the number 0x81EC. There are some encodings defined which map Unicode sequences to byte sequences: UTF-8 maps Unicode strings to sequences of bytes in the range 0..255, UTF-7 maps Unicode strings to sequences of bytes in the range 0..127. You *could* read the latter as ASCII sequences but this is not correct. How to do it in Python? Let chinesePhrase be a Unicode string with Chinese content. Then chinesePhrase_7bit = chinesePhrase.encode('utf-7') will produce a sequences of bytes in the range 0..127 representing chinesePhrase and *looking like* a (meaningless) ASCII sequence. chinesePhrase_16bit = chinesePhrase.encode('utf-16be') will produce a sequence with Unicode numbers packed in a byte string in big endian order. This is probably closest to what the OP wants. Peter Maas, Aachen From claird at lairds.us Mon Aug 7 13:46:53 2006 From: claird at lairds.us (Cameron Laird) Date: Mon, 7 Aug 2006 17:46:53 +0000 Subject: Static Variables in Python? References: <mailman.8746.1154373688.27775.python-list@python.org> <1154378719.157643.98340@p79g2000cwp.googlegroups.com> Message-ID: <dtakq3-r2b.ln1@lairds.us> In article <1154378719.157643.98340 at p79g2000cwp.googlegroups.com>, Paddy <paddy3118 at netscape.net> wrote: . [substantial thread with many serious alternatives] . . >You can do things with function attributes > >def foo(x): > foo.static += x > return foo.static >foo.static = 0 . . . My favorite variation is this: def accumulator(x): # On first execution, the attribute is not yet known. # This technique allows use of accumulator() as a # function without the "consumer" having to initialize # it. if not "static" in dir(accumulator): accumulator.static = 0 accumulator.static += x return accumulator.static print accumulator(3) print accumulator(5) From alexandre.guimond at siemens.com Tue Aug 15 04:05:55 2006 From: alexandre.guimond at siemens.com (Alexandre Guimond) Date: 15 Aug 2006 01:05:55 -0700 Subject: how to deepcopy a slice object? Message-ID: <1155629155.207232.50400@m79g2000cwm.googlegroups.com> Hi all, i'm trying to deepcopy a slice object but i get the following error. Does anyone know a workaround? ActivePython 2.4.3 Build 12 (ActiveState Software Inc.) based on Python 2.4.3 (#69, Apr 11 2006, 15:32:42) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import copy >>> copy.deepcopy( slice( 1, 10, 2 ) ) Traceback (most recent call last): File "<stdin>", line 1, in ? File "C:\Program Files\Python\lib\copy.py", line 204, in deepcopy y = _reconstruct(x, rv, 1, memo) File "C:\Program Files\Python\lib\copy.py", line 336, in _reconstruct y = callable(*args) File "C:\Program Files\Python\lib\copy_reg.py", line 92, in __newobj__ return cls.__new__(cls, *args) TypeError: slice expected at least 1 arguments, got 0 thx for any help. From bearophileHUGS at lycos.com Wed Aug 30 21:28:27 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 30 Aug 2006 18:28:27 -0700 Subject: python equivalent for fputc In-Reply-To: <1156986879.533017.241450@b28g2000cwb.googlegroups.com> References: <1156986879.533017.241450@b28g2000cwb.googlegroups.com> Message-ID: <1156987707.504941.307230@b28g2000cwb.googlegroups.com> Putty wrote: > I'm porting a program a friend wrote in C over to Python and I've run > into a little hang-up. The C program writes characters out to a file. > I'm 99% sure that a conversion is going on here as well. I know for a > fact that it's taking a number and turning it into a character. > So what kind of call can I make to do it in Python? There may be some ways. Here is the data: from random import randint vals = [randint(0, 255) for i in xrange(10)] This is probably the most common way: print "".join(chr(c) for c in vals) If you need to access the chars one after the other, this may be a (quite slower, but less memory consuming) alternative: import sys write = sys.stdout.write for c in vals: write(chr(c)) print In some cases a solution like this one can be useful too: import array print array.array("B", vals).tostring() Bye, bearophile From bearophileHUGS at lycos.com Sat Aug 26 13:32:53 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 26 Aug 2006 10:32:53 -0700 Subject: question about class, functions and scope In-Reply-To: <1156609028.269804.189220@74g2000cwt.googlegroups.com> References: <1156583602.302530.206630@74g2000cwt.googlegroups.com> <1156589657.706430.69650@74g2000cwt.googlegroups.com> <1156604233.729177.66440@i3g2000cwc.googlegroups.com> <1156609028.269804.189220@74g2000cwt.googlegroups.com> Message-ID: <1156613573.374812.165660@m79g2000cwm.googlegroups.com> nephish: > one more question. > the functions defined above the classes that the could be called from > within the classes, they do not need a 'self' declaration because they > are not part of a class, right? Class methods generally require the self as first parameter, functions don't need the self. So your original code was wrong (sorry, I haven't seen that before). You can also inject functions as methods inside a class, and in such case your function usually needs a self parameter too. Bye, bearophile From thomas at mindz-i.co.nz Wed Aug 2 22:22:15 2006 From: thomas at mindz-i.co.nz (Thomas Thomas) Date: Thu, 3 Aug 2006 14:22:15 +1200 Subject: python unicode how to Message-ID: <026201c6b6a3$a51c2f10$346ea8c0@tintz.co.nz> Hi all, I have a file with special characters such as "?" etc. I need to read the file into a list as unicode strings.. How can I do this.. I tried codecs import codecs filename='d:/poll/test.XST' metaHash={} infile = codecs.open(filename, "r", encoding='utf-16') text = infile.read().split('\n') print text I am getting the error Traceback (most recent call last): File "<stdin>", line 1, in ? File "c:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/python-1928Lij.py", line 9, in ? text = infile.read().split('\n') File "C:\Python23\lib\codecs.py", line 380, in read return self.reader.read(size) File "C:\Python23\lib\encodings\utf_16.py", line 48, in read raise UnicodeError,"UTF-16 stream does not start with BOM" UnicodeError: UTF-16 stream does not start with BOM also a sample file content will be string MetaDataPrompt = "Discovery No"; string MetaDataFieldName = "Discovery No"; string MetaDataType = "string"; string MetaDataValue = "?500"; } 3{ string MetaDataPrompt = "comments"; string MetaDataFieldName = "Comments"; string MetaDataType = "string"; string MetaDataValue = "Energy Scope ?500"; Thanks Thomas ----------------------------------------------------- Thomas Thomas thomas at mindz-i.co.nz Phone. +64 7 855 8478 Fax. +64 7 855 8871 -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060803/e8ccee7a/attachment.html> From sjmachin at lexicon.net Tue Aug 8 19:45:10 2006 From: sjmachin at lexicon.net (John Machin) Date: 8 Aug 2006 16:45:10 -0700 Subject: Class data being zapped by method In-Reply-To: <1155076971.519157.92540@i42g2000cwa.googlegroups.com> References: <1155065906.910642.77320@75g2000cwc.googlegroups.com> <mailman.9111.1155066643.27775.python-list@python.org> <1155076971.519157.92540@i42g2000cwa.googlegroups.com> Message-ID: <1155080710.437461.155300@m79g2000cwm.googlegroups.com> Kevin M wrote: > Figures. I'll try to complicate it sufficiently ;) > > > [edit] I was going to try to sum up what goes on, but I realized that I > was retyping what I already programmed in an effort to better > illustrate exactly what I'm doing. Pastebin it is. Don't fear, it's > only around 200 lines total. > > Class file -- http://pastebin.4programmers.net/640 Any *good* reason you have (a) split your solution in an arbitrary fashion [some in a class, some not] (b) put the class in a separate file? > Main file -- http://pastebin.4programmers.net/639 > > PLEASE don't worry about any file parsing stuff. That's all working > well. The problem is that I'm getting IndexError exceptions in my > _a_count and _b_count methods when they're called from analyze(). I > added some code to increase verbosity, and it turns that the count > methods within the Test class are operating on EMPTY lists ( [] ), so > naturally they can't index anything. This is the core of the problem, > especially considering that line 98 in main.py works as expected. > Line 98 is # print arrTests[2].data This doesn't show that *all* cases have non-empty lists. Data is appended *conditionally* around about line 92. <aside> The try/except adds another level of (totally unnecessary, AFAICT) complexity & stuffupability -- you should really do it the other way around: for line in arrLines: row = line.split()[offset:] for index, test in enumerate(arrTests): blah = row[index] if blah not in bad_vals: etc and *don't* ignore IndexError (with this rearrangement, any IndexError is a bug). </aside> To demonstrate that you have a real problem: (1) replace line 98 by: print [i, len(x.data), id(x) for i, x in enumerate(arrTests)] (2) after line 26 in your class file, insert print id(self), len(self.data) [The id() will tell you unequivocably which test object has the problem when/if the _a_sort method fails] HTH, John P.S. Next time, show your actual output. From rogue_pedro at yahoo.com Wed Aug 16 19:09:39 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 16 Aug 2006 16:09:39 -0700 Subject: Anyone have a link handy to an RFC 821 compliant email address regex for Python? In-Reply-To: <1155766985.974863.116360@p79g2000cwp.googlegroups.com> References: <1155766985.974863.116360@p79g2000cwp.googlegroups.com> Message-ID: <1155769779.041598.17970@m79g2000cwm.googlegroups.com> fuzzylollipop wrote: > I want to do email address format validations, without turning to ANTLR > or pyparsing, anyone know of a regex that is COMPLIANT with RFC 821. > Most of the ones I have found from google searches are not really as > robust as I need them to be. Would email.Utils.parseaddr() fit the bill? http://docs.python.org/lib/module-email.Utils.html#l2h-3944 HTH, ~Simon From gelists at gmail.com Tue Aug 15 09:39:35 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Tue, 15 Aug 2006 10:39:35 -0300 Subject: hide python code ! References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <ebs18e$3og$01$1@news.t-online.com> Message-ID: <1vi7vznv0flph$.dlg@gelists.gmail.com> On 2006-08-15 05:40:31, Armin Steinhoff wrote: >> First Iranian Open Source Community : www.python.ir > > Interesting ... but you are not a member of this community. Right? You know how to read a thread, right? :) Gerhard From mail at microcorp.co.za Fri Aug 4 11:23:02 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Fri, 4 Aug 2006 17:23:02 +0200 Subject: How to force a thread to stop References: <mailman.8475.1153762034.27775.python-list@python.org>mailman.8528.1153845034.27775.python-list@python.org>mailman.8572.1153932090.27775.python-list@python.org><1153942270.301732.99880@h48g2000cwc.googlegroups.com><mailman.8585.1153946003.27775.python-list@python.org><7xslkoum88.fsf@ruckus.brouhaha.com><44C7E7EC.4020301@mvista.com><1lwn8bs8qhg4c.dlg@gelists.gmail.com><mailman.8597.1153960691.27775.python-list@python.org><fangc2hg3d6rmcusjqqpk8ct8v3m8eqbd8@4ax.com><mailman.8615.1154004533.27775.python-list@python.org><3sphc25or7ir5keeithpvb1k3vog39botu@4ax.com><mailman.8644.1154070822.27775.python-list@python.org><7xwt9y8916.fsf@ruckus.brouhaha.com><mailman.8655.1154092222.27775.python-list@python.org><7xvephg7yq.fsf@ruckus.brouhaha.com><mailman.8693.1154164578.27775.python-list@python.org><1hjgrs7.w01xtjt192o1N%aleax@mac.com><00ae01c6b6e5$9996ca00$03000080@hendrik><zmj78svvh7nl.dlg@gelists.gmail.com><00d301c6b79d$f91fd800$03000080@hendrik> <1s2zfko9eippw.dlg@gelis ts.gmail.com> Message-ID: <006a01c6b7d9$e0e925c0$03000080@hendrik> "Gerhard Fiedler" <gelists at gmail.com> wrote: | On 2006-08-04 02:33:07, H J van Rooyen wrote: | | > The next step above the 555 is a PIC... then you can steal power from the | > RS-232 line - and its a small step from "PIC" to "PIG"... | | I see... you obviously know what to do, if you want to :) | | But I'm not sure such a device alone is of much help in a typical server. I | think it's probably just as common that only one service hangs. To make it | useful, the trigger process has to be carefully designed, so that it | actually has a chance of failing when you need it to fail. This probably | requires either code changes to the various services (so that they each | trigger their own watchdog) or some supervisor program that only triggers | the watchdog if it receives responses from all relevant services. | | Gerhard This is true - its trivial to just kill the whole machine like this, but its kind of like using a sledgehammer to crack a nut - and as you so rightly point out - if the process that tickles the watchdog to make it happy is not (very) tightly coupled to the thing you want to monitor - then it may not work at all - specially if interrupts are involved - in fact something like a state machine that looks for alternate occurrences of (at least) two things is required - the interrupt gives it a kick and sets a flag, the application sees the flag and gives it the alternate kick and clears the flag, and so on, with the internal tasks in the machine "passing the ball" in this (or some other) way - that way you are (relatively) sure the thing is still running... but it needs careful design or it will either kill the machine for no good reason, (when something like disk accesses slow the external (user) processes down ) , or it will fail to fire if it is something that is driven from a call back - the app may be crazy, but the OS may still be doing call-backs and timing stuff faithfully - you cant be too careful... - Hendrik From gagsl-py at yahoo.com.ar Wed Aug 23 10:56:19 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 23 Aug 2006 11:56:19 -0300 Subject: How to download a web page just like a web browser do ? In-Reply-To: <1156343685.281636.285100@p79g2000cwp.googlegroups.com> References: <1156343685.281636.285100@p79g2000cwp.googlegroups.com> Message-ID: <7.0.1.0.0.20060823115357.03e6e5b0@yahoo.com.ar> At Wednesday 23/8/2006 11:34, Bo Yang wrote: > Everyday , I receive a newsletter from NYTimes , but I >didn't want to read the news in evening the time the letter >came in . So , I am about to download the web page >contains the news and read them next morning ! I decide to >use python to write a tool , which should be feeded with a >URL , and then download the page to my disk . This >function just like the Browser's "save as..." function . I >know what shoud I do to accomplish that , I need to parse >the web page , and download all pages in the page , and >modify all the links to conrespond local disk links and ... This tool already exists: wget Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From pythonnews at nospam.jmbc.fr Sat Aug 12 13:38:00 2006 From: pythonnews at nospam.jmbc.fr (jean-michel bain-cornu) Date: Sat, 12 Aug 2006 19:38:00 +0200 Subject: wxPython ListBook Class, Label Position w/ ImageList In-Reply-To: <1155383930.411326.10150@h48g2000cwc.googlegroups.com> References: <1155383930.411326.10150@h48g2000cwc.googlegroups.com> Message-ID: <44de128b$0$21149$7a628cd7@news.club-internet.fr> Hi, > By default the label position of an image list is below the image. Is > there any way to change this? > If it exists, it's undocumented, and there is not a sample. Did you ask the wx forum ? It's probably a better place to have this kind of information. If they provide you a C sample, I could help you to convert it in python. Anyway, if you find out something, I'm interested... Regards, jm From amichail at gmail.com Sun Aug 27 06:00:23 2006 From: amichail at gmail.com (Amir Michail) Date: 27 Aug 2006 03:00:23 -0700 Subject: avoiding file corruption In-Reply-To: <mailman.9932.1156670558.27775.python-list@python.org> References: <1156664673.325201.271140@i42g2000cwa.googlegroups.com> <mailman.9932.1156670558.27775.python-list@python.org> Message-ID: <1156672823.166736.327670@i42g2000cwa.googlegroups.com> Paolo Pantaleo wrote: > 27 Aug 2006 00:44:33 -0700, Amir Michail <amichail at gmail.com>: > > Hi, > > > > Trying to open a file for writing that is already open for writing > > should result in an exception. > > > > It's all too easy to accidentally open a shelve for writing twice and > > this can lead to hard to track down database corruption errors. > > > > Amir > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > Even if it could be strange, the OS usually allow you to open a file > twice, that's up to the programmer to ensure the consistency of the > operations. > > PAolo > But if this is usually a serious bug, shouldn't an exception be raised? Amir > > > -- > if you have a minute to spend please visit my photogrphy site: > http://mypic.co.nr From rogue_pedro at yahoo.com Fri Aug 25 02:05:46 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 24 Aug 2006 23:05:46 -0700 Subject: Is this a good idea or a waste of time? References: <1156449402.022781.292840@p79g2000cwp.googlegroups.com> Message-ID: <1156485945.967160.238790@m73g2000cwd.googlegroups.com> asincero wrote: > Would it be considered good form to begin every method or function with > a bunch of asserts checking to see if the parameters are of the correct > type (in addition to seeing if they meet other kinds of precondition > constraints)? Like: > > def foo(a, b, c, d): > assert type(a) == str > assert type(b) == str > assert type(c) == int > assert type(d) == bool > # rest of function follows > > This is something I miss from working with more stricter languages like > C++, where the compiler will tell you if a parameter is the wrong type. > If anything, I think it goes a long way towards the code being more > self documenting. Or is this a waste of time and not really "the > Python way"? > > -- Arcadio Generally asserts should be used to "enforce" invariants of your code (as opposed to typechecking), or to check certain things while debugging. FWIW, if I saw code that that you presented here I'd assume the programmer who wrote it was either very new(-bie-ish) or just very very paranoid, so I guess I could say it's not pythonic... :-) BTW, speaking of "strictness", "more stricter" is invalid English, just "stricter" is the "correct" form. ;-) Peace, ~Simon From belred at gmail.com Sun Aug 20 11:37:04 2006 From: belred at gmail.com (Bryan) Date: Sun, 20 Aug 2006 08:37:04 -0700 Subject: PyThreadState_Swap(NULL) In-Reply-To: <ec5b3m$puo$1@sea.gmane.org> References: <ec5b3m$puo$1@sea.gmane.org> Message-ID: <44E881A0.5040605@gmail.com> let me try to ask the question again in a simpler more generic way. i thought that the following lines of code, could not fail even if another library in the same process initialized the python interpreter first. if (!Py_IsInitialized()) { Py_Initialize(); } PyEval_InitThreads(); interpreter = PyThreadState_Swap(NULL); what could another library do to make this fail? and is there anything i can do to make this work in all situations? thanks, bryan From jaysherby at gmail.com Tue Aug 8 16:31:05 2006 From: jaysherby at gmail.com (jaysherby at gmail.com) Date: 8 Aug 2006 13:31:05 -0700 Subject: newb question: file searching In-Reply-To: <1155068505.141479.5210@m79g2000cwm.googlegroups.com> References: <1155067111.892386.130610@n13g2000cwa.googlegroups.com> <1155068505.141479.5210@m79g2000cwm.googlegroups.com> Message-ID: <1155069065.129575.10650@i42g2000cwa.googlegroups.com> Mike Kent wrote: > What you want is os.walk(). > > http://www.python.org/doc/current/lib/os-file-dir.html I'm thinking os.walk() could definitely be a big part of my solution, but I need a little for info. If I'm reading this correctly, os.walk() just goes file by file and serves it up for your script to decide what to do with each one. Is that right? So, for each file it found, I'd have to decide if it met the criteria of the filetype I'm searching for and then add that info to whatever datatype I want to make a little list for myself? Am I being coherent? Something like: for files in os.walk(top, topdown=False): for name in files: (do whatever to decide if criteria is met, etc.) Does this look correct? From cowie.rob at gmail.com Fri Aug 18 10:45:51 2006 From: cowie.rob at gmail.com (Rob Cowie) Date: 18 Aug 2006 07:45:51 -0700 Subject: Documenting a package with Pydoc Message-ID: <1155912351.433504.265020@h48g2000cwc.googlegroups.com> I have searched this group and the wider net to find an answer to this, but I haven't been successful. Pydoc seems to be capable of writing documentation for all modules within a package by simply pointing it to the package on the command line... pydoc -w <packagename_without_/> Certainly, the method writedocs() appears to descend into a directory and create docs for each importable object. Perhaps I'm doing something wrong but when I do this, pydoc reports that no Python documentation can be found for each of the contents of the package. Of course, if I point pydoc directly to the modules, it succeeds. Am I doing something wrong? Cheers, Rob C From fakeaddress at nowhere.org Sat Aug 5 14:26:33 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 05 Aug 2006 18:26:33 GMT Subject: Thread Question In-Reply-To: <mailman.9014.1154801071.27775.python-list@python.org> References: <1153998422.670828.148360@m79g2000cwm.googlegroups.com> <1154019801.999805.150000@m73g2000cwd.googlegroups.com> <mailman.8857.1154541684.27775.python-list@python.org> <1154544553.990241.280030@i3g2000cwc.googlegroups.com> <1154590917.731457.106230@s13g2000cwa.googlegroups.com> <1154613366.350191.81880@m73g2000cwd.googlegroups.com> <1154676387.063576.100570@i42g2000cwa.googlegroups.com> <1154690942.385855.41130@m79g2000cwm.googlegroups.com> <lfYAg.3102$kO3.2277@newssvr12.news.prodigy.com> <mailman.9014.1154801071.27775.python-list@python.org> Message-ID: <tp5Bg.3519$9T3.1625@newssvr25.news.prodigy.net> Ritesh Raj Sarraf wrote: [...] > I noticed that even though while one thread acquires the lock, the other threads > don't respect the lock. In fact they just go ahead and execute the statements > within the lock acquire statement. With this behavior, I'm ending up having a > partially corrupted zip archive file. No, Carl's code was fine. I just found his explanation misleading. > def run(request, response, func=copy_first_match): > '''Get items from the request Queue, process them > with func(), put the results along with the > Thread's name into the response Queue. > > Stop running once an item is None.''' > > name = threading.currentThread().getName() > ziplock = threading.Lock() You don't want "ziplock = threading.Lock()" in the body of the function. It creates a new and different lock on every execution. Your threads are all acquiring different locks. To coordinate your threads, they need to be using the same lock. Try moving "ziplock = threading.Lock()" out of the function, so your code might read, in part: ziplock = threading.Lock() def run(request, response, func=copy_first_match): # And so on... -- --Bryan From jweida at gmail.com Thu Aug 24 13:49:09 2006 From: jweida at gmail.com (Jerry) Date: 24 Aug 2006 10:49:09 -0700 Subject: telnetlib thread-safe? In-Reply-To: <mailman.9794.1156436433.27775.python-list@python.org> References: <1156434867.163326.42160@i42g2000cwa.googlegroups.com> <mailman.9794.1156436433.27775.python-list@python.org> Message-ID: <1156441749.350442.101520@i42g2000cwa.googlegroups.com> Fredrik Lundh wrote: > define thread-safe. how do you plan to use it? I would like to write a program that spawns ~10 threads. Each thread would get a host to connect to from a Queue object and run then do it's thing (i.e. connecting to the host, running some commands, returning back a success or fail based on the results). I just want to make sure that telnetlib is safe for this. -- Jerry From enigmadude at rock.com Wed Aug 9 15:15:19 2006 From: enigmadude at rock.com (enigmadude at rock.com) Date: 9 Aug 2006 12:15:19 -0700 Subject: Nested function scope problem In-Reply-To: <1153526722.757378.144130@m73g2000cwd.googlegroups.com> References: <1153526722.757378.144130@m73g2000cwd.googlegroups.com> Message-ID: <1155150919.349080.301270@i3g2000cwc.googlegroups.com> I agree with the previous comments that this approach is "bad form". But if you absolutely *must* modify an enclosing function's variables with an inner function, all you need to do is remember that a Python function is an object too, so it can be assigned attributes. ;-) def outer(): outer.x = 1 print outer.x def inner(): outer.x = 2 inner() print outer.x Josiah Manson wrote: > I found that I was repeating the same couple of lines over and over in > a function and decided to split those lines into a nested function > after copying one too many minor changes all over. The only problem is > that my little helper function doesn't work! It claims that a variable > doesn't exist. If I move the variable declaration, it finds the > variable, but can't change it. Declaring the variable global in the > nested function doesn't work either. > > But, changing the variable in the containing scope is the whole purpose > of this helper function. > > I'm new to python, so there is probably some solution I haven't > encountered yet. Could you please suggest a nice clean solution? The > offending code is below. Thanks. > > def breakLine(s): > """Break a string into a list of words and symbols. > """ > def addTok(): > if len(tok) > 0: > ls.append(tok) > tok = '' > > ls = [] > tok = '' > splitters = '?()&|:~,' > whitespace = ' \t\n\r' > > for c in s: > if c in splitters: > addTok() > ls.append(c) > elif c in whitespace: > addTok() > else: > tok = tok + c > > addTok() > > return ls > > #some tests to make sure it works > print breakLine('carolina(Prada):cat(X,Y)') > print breakLine('trouble :bird (X ) &cat ( Y )') > print breakLine('?trouble') From amit.man at gmail.com Mon Aug 28 11:53:19 2006 From: amit.man at gmail.com (noro) Date: 28 Aug 2006 08:53:19 -0700 Subject: unit test for a printing method Message-ID: <1156780399.289589.58750@m73g2000cwd.googlegroups.com> What is the proper way to test (using unit test) a method that print information? for example: def A(s): print '---'+s+'---' and i want to check that A("bla") really print out "---bla---" thanks amit From sjmachin at lexicon.net Fri Aug 11 19:24:49 2006 From: sjmachin at lexicon.net (John Machin) Date: 11 Aug 2006 16:24:49 -0700 Subject: help with c <-> python buffer transfer References: <1155335511.379184.200570@75g2000cwc.googlegroups.com> Message-ID: <1155338689.873546.6930@i42g2000cwa.googlegroups.com> tkirke at gmail.com wrote: > How does one transfer a buffer object from python -> c and back again > (assuming the data gets modified)? > I can't seem to get this or anything else to work, but am clueless as > to what I'm doing wrong > > > using namespace boost::python; Looks like C++, not C. > > static PyObject * proc_buf(PyObject *self, PyObject *args) { [I'm not familiar with the boost gadget, but ...] Doesn't "static" mean that this function is *not* externally visible? > PyObject *resultobj; > char* output_samples; > int len; > if (!PyArg_ParseTuple(args,"s#|l",&output_samples, &len)) { You have made the length an optional argument, but not initialised the receiving variable "len". Nothing to do with your current problem, but highly dangerous. > return NULL; /* wrong arguments provided */ > } > for (int i=0;i<len;i++) { > output_samples[i] *= 2; // for example > } This is updating the internal representation of the input in situ. Not a very good idea at all. Take a copy. Return the updated copy. > resultobj = PyString_FromStringAndSize(output_samples, len); > return resultobj; > } > > > This compiles ok, but when in python I do > Put print repr(bufx), type(bufx) here so that we're all clued in on what you are talking about. You say "transfer a buffer object" but your C[++] is returning a string object. > buf = proc_buf( bufx, len(bufx) You are missing both a module name and a ")" here. It should look something like: buf = theextensionmodule.proc_buf( bufx, len(bufx)) Please *always* copy/paste the actual code that you executed. > len(buf) > > I get > len() of unsized object Please *always* copy/paste the actual error message & stack trace that you get. Try print repr(buf), type(buf) here; it might give you a clue as to what type of object you have that is unsized. On the surface this is a mystery, as (based on the info that you have supplied), "buf" should be a string. HTH .... alternatively come up a level or three and tell us what your basic requirement is; maybe it can be solved more easily in Python or Pyrex. Cheers, John From gdamjan at gmail.com Wed Aug 30 21:34:56 2006 From: gdamjan at gmail.com (Damjan) Date: Thu, 31 Aug 2006 03:34:56 +0200 Subject: Persistent Session in CGI References: <1156715285.717012.91300@i42g2000cwa.googlegroups.com> <44f636b5$0$75032$14726298@news.sunsite.dk> Message-ID: <44f63c50$0$75032$14726298@news.sunsite.dk> > But.. WSGI is the new CGI Let me give you a minimal example using RhubarbTart (it depends on Paste) from rhubarbtart import request, response, expose from rhubarbtart import TartRootController class Root(TartRootController): @expose def index(self, msg="Hello world!"): response.headers['Content-type'] = 'text/plain' return msg app = Root() # # Now to serve it as a CGI script, just: # from wsgiref.handlers import CGIHandler CGIHandler().run(app) # # or to server it in a long running python-based HTTP server # from paste import httpserver httpserver.serve(app) # END of example Now this is just the begining to show you that it's not hard. But when you see what EvalException can do for you, you'll beg for more :) Hint: from paste.evalexception.middleware import EvalException app = EvalException(app) # then serve the app in the paste httpserver ... # but make some error in your python code to see it's results -- damjan From webraviteja at gmail.com Sat Aug 19 18:07:54 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 19 Aug 2006 15:07:54 -0700 Subject: How to catch these kind of bugs in Python? In-Reply-To: <1156009543.993046.76720@75g2000cwc.googlegroups.com> References: <1156009543.993046.76720@75g2000cwc.googlegroups.com> Message-ID: <1156025274.035050.35130@i42g2000cwa.googlegroups.com> asincero wrote: > Is there anyway to catch the following type of bug in Python code: > > message = 'This is a message' > # some code > # some more code > if some_obscure_condition: > nessage = 'Some obscure condition occured.' > # yet more code > # still more code > print message > > > In the above example, message should be set to 'Some obscure condition > occured.' if some_obscure_condition is True. But due to a lack of > sleep, and possibly even being drunk, the programmer has mistyped > message. These types of bugs would easily be caught in languages that > have a specific keyword or syntax for declaring variables before use. > I'm still fairly new to using Python on a more than casual basis, so I > don't know if Python has anyway to help me out here. The keyword is "obscure condition". The solution is to use a coverage tool and create unit tests that give you 100% code coverage. From aleax at mac.com Wed Aug 2 21:13:39 2006 From: aleax at mac.com (Alex Martelli) Date: Wed, 2 Aug 2006 18:13:39 -0700 Subject: Windows vs. Linux References: <1154301694.445639.99580@m79g2000cwm.googlegroups.com> <44cddfb3$0$7761$7a628cd7@news.club-internet.fr> <e%szg.3$gY6.1@newssvr11.news.prodigy.com> <slrnecustl.dsk.sybrenUSE@schuimige.stuvel.eu> <mailman.8814.1154454507.27775.python-list@python.org> <slrnecvati.eia.sybrenUSE@schuimige.stuvel.eu> <mailman.8825.1154473236.27775.python-list@python.org> <1hjfow0.xza1lcpaytg8N%aleax@mac.com> <mailman.8864.1154547580.27775.python-list@python.org> Message-ID: <1hjgewt.9ha0su1r78e94N%aleax@mac.com> Gerhard Fiedler <gelists at gmail.com> wrote: ... > > Part of the CP/M compatibility did include the use of / as flag-indicator > > (the use of \r+\n as line ending also comes from CP/M -- in turn, CP/M > > had aped these traits from some DEC minicomputer operating systems). > > At the time, probably pretty good reasons for using the slash as command > line flag indicator. In DEC's case, the / was an essentially random choice -- nothing particularly stood either for or against it -- and there was no particularly good reason for CP/M to ape it later, either (Unix is even older than CP/M, _and_ ran on HW essentially identical to that used by some of said DEC OS's, yet, having good designers, it "broke" both these points of "compatibility"... yet didn't suffer in the least thereby). The \r+\n choice is different -- it did indeed have a good reason _at the time_ DEC chose it: for OSs without real device drivers (on machines with no power to spare for even the most trivial processing), sending a bunch of lines to a dumb teletype really needed the lines to be terminated by telling the tty both to return-carriage (the \r) AND to advance paper (the \n) -- and the former had to be first because the carriage-return operation was mechanically slower but could occur at the same time as the paper advance. But these issues did not apply by the '70s, when CP/M was born and Unix got its name (from the previous name, briefly used in the late '60s, of UNICS). Whether there's "a good reason" to embed the consequences of these mechanical issues in fileformats and protocols, destined no doubt to survive for many decades to come, 40 years after said issues had become essentially moot, is another issue... but backwards-incompatible changes ARE always hard (and yet, the original designers of successful systems are basically never as ambitious and visionary as to think of the effect their choices of today will have 40 or 80 years down the road -- systems designed with the mindset of thinking many-decades-ahead tend to fail in their struggle against quick-and-dirty ones, as bemoaned but lucidly analyzed in Gabriel's deservedly famous essay on "worse is better", e.g. at <http://www.jwz.org/doc/worse-is-better.html>). > And, as an aside, I'm sure that MS would have sold more of their Xenix if > the market had wanted it. But the market really wanted DOS... Yes, particularly considering the much higher HW demands of Xenix's entry point, compared to DOS's -- not only did Xenix always require a hard disk, but, for over 2 years, Xenix supported only Zilog Z8001 and later Motorola 68000... it took SCO, in late 1983, to release an 8086 version, and by that time DOS was well entrenched in the marketplace, also supporting floppy-only machines that remained a much more affordable entry point than hard-disk ones for further years. Basically, by the time PCs with hard disks were starting to become widespread, MS had lost interest in marketing Xenix, which only SCO was pushing, so it made sense in '87 for MS to sell SCO Xenix outright in exchange for a large slice of SCO's stock (20%, if I remember right). Alex From spam at me.please Sat Aug 26 03:44:04 2006 From: spam at me.please (Skink) Date: Sat, 26 Aug 2006 09:44:04 +0200 Subject: django's view.py as class not just methods In-Reply-To: <873bbk64b0.fsf@smsnet.pl> References: <ecmtfd$jjm$1@news2.ipartners.pl> <873bbk64b0.fsf@smsnet.pl> Message-ID: <ecou3v$1obd$1@news2.ipartners.pl> Rob Wolfe wrote: > > I didn't try it with django but maybe closure is the solution. > Try this: > > > index, detail and download functions can be mapped > in urls.py now. > Rob, thanks a lot. is gonna be good starting point skink From gabrielg_laburando at yahoo.com.ar Fri Aug 25 02:38:57 2006 From: gabrielg_laburando at yahoo.com.ar (Gabriel G) Date: Fri, 25 Aug 2006 03:38:57 -0300 Subject: lazy arithmetic In-Reply-To: <1156483096.397300.110210@75g2000cwc.googlegroups.com> References: <1156476992.102203.304450@p79g2000cwp.googlegroups.com> <mailman.9840.1156481380.27775.python-list@python.org> <1156483096.397300.110210@75g2000cwc.googlegroups.com> Message-ID: <7.0.1.0.0.20060825031701.044c6e68@yahoo.com.ar> At Friday 25/8/2006 02:18, pianomaestro at gmail.com wrote: > > x+y get translated to x.__add__(y) > >No that's not true at all. The self argument to __add__ ends >up being the Add instance, not the Item instance: > >z=x+y is translated to z.__add__(y) Well, I deleted my response after I noticed that Simon Forman has done it very well. Just a note: print z after this line and compare with self inside __init__ if you're still not convinced. Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From laurent.pointal at limsi.fr Wed Aug 16 04:47:47 2006 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Wed, 16 Aug 2006 10:47:47 +0200 Subject: Reference Variables In Python Like Those In PHP In-Reply-To: <1155651471.605912.46640@m73g2000cwd.googlegroups.com> References: <1155651471.605912.46640@m73g2000cwd.googlegroups.com> Message-ID: <ebum3l$94k$1@upsn250.cri.u-psud.fr> Chaos a ?crit : > Is It possible to have reference variables like in PHP > > ex. > > <?php > > $x = 1; > $y =& $x; > > $y += 1; > > echo $x; > echo "\n" > echo $y; > > ?> > > This would show > > 2 > 2 > > Is this available in python? See other replies (ie. in Python all variables are names refering to objects). You may achieve same result using an object as a namespace, like this: Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> class Dummy(object) : pass ... >>> x=Dummy() >>> x.val = 1 >>> y = x <-- here x and y refer to *same* Dummy object >>> y.val += 1 >>> x.val 2 >>> y.val 2 A+ Laurent. From fredrik at pythonware.com Wed Aug 23 15:01:12 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Aug 2006 21:01:12 +0200 Subject: how do you get the name of a dictionary? In-Reply-To: <ec5vth$8c2$1@sea.gmane.org> References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <mailman.9517.1155930607.27775.python-list@python.org> <dppFg.2704$No6.52662@news.tufts.edu> <ec5vth$8c2$1@sea.gmane.org> Message-ID: <eci8ln$tml$2@sea.gmane.org> Steve Holden wrote: > Right. Plus it's fun to imagine the effbot hitting itself as hard as > some people would obviously have liked to hit it in the past :-) you mean the guy who's spent the last six months downrating every single post I've made on this list over at googlegroups ? I'd say it's safe to ignore him; he's a certified nutcase. </F> From duncan.booth at invalid.invalid Tue Aug 1 09:52:24 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Aug 2006 13:52:24 GMT Subject: looking for a regular expression References: <4PMYYI$BLv@bbs.wretch.cc> Message-ID: <Xns9812975195DD7duncanbooth@127.0.0.1> ?????b?????????H wrote: > I want "justice" and the words between the 2 nearest commas, which is > > establish justice > > All I can come up with is > > r",(.*?justice.*?)," > > but the result is > > in order to form a more perfect union, establish justice > > Apreciate any help. ",([^,]*justice[^,]*)," But this is simpler if you don't use a regular expression: >>> s = "We the people of the United States, in order to form a more perfect union, establish justice, insure domestic tranquility,......" >>> [phrase for phrase in s.split(',') if 'justice' in phrase ] [' establish justice'] From NOXwebmasterX at XmbstevensX.com Wed Aug 2 17:36:38 2006 From: NOXwebmasterX at XmbstevensX.com (mbstevens) Date: Wed, 02 Aug 2006 21:36:38 GMT Subject: python under earthlink hosting? References: <pan.2006.08.01.07.11.44.579891@XmbstevensX.com> <44d09d56$0$4531$e4fe514c@news.xs4all.nl> Message-ID: <pan.2006.08.02.21.35.24.813213@XmbstevensX.com> On Wed, 02 Aug 2006 14:40:48 +0200, Martin P. Hellwig wrote: > Maybe they didn't symlink it, try /usr/local/bin/python2.4 Thanks, Martin. I went back to earthlink with this: _________________________ Me: "I understand that I am supposed to be able to write CGI scripts in any scripting language. I can't seem to find the Python interpreter on my server, and keep getting a 500 internal server error with the following shebang lines: #!/usr/local/bin/python #!/usr/bin/python #!/bin/python #!usr/local/bin/python2.4 #!/usr/bin/python2.4 #!/bin/python2.4 Is Python just not running on the server that hosts my site? If it is running -- where is it?" __ Daniel P: "I am sorry, EarthLink provides support only for CGI and Perl scripting." ______________________ It seemed like such a simple couple of questions for their support staff to answer. I'm beginning to think that if I want to write Python CGI scripts I'll have to move to a different service. From fakeaddress at nowhere.org Fri Aug 4 02:48:05 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 04 Aug 2006 06:48:05 GMT Subject: Windows vs. Linux In-Reply-To: <mailman.8870.1154557509.27775.python-list@python.org> References: <e%szg.3$gY6.1@newssvr11.news.prodigy.com> <slrnecustl.dsk.sybrenUSE@schuimige.stuvel.eu> <mailman.8814.1154454507.27775.python-list@python.org> <slrnecvati.eia.sybrenUSE@schuimige.stuvel.eu> <mailman.8825.1154473236.27775.python-list@python.org> <slrned0lr7.f6d.sybrenUSE@schuimige.stuvel.eu> <mailman.8845.1154526941.27775.python-list@python.org> <Pk2Ag.2623$No6.51588@news.tufts.edu> <slrned1dlu.gbe.sybrenUSE@schuimige.stuvel.eu> <1154531160.066733.71210@s13g2000cwa.googlegroups.com> <mailman.8870.1154557509.27775.python-list@python.org> Message-ID: <F4CAg.909$o27.589@newssvr21.news.prodigy.com> Christopher Weimann wrote: > On 08/02/2006-08:06AM, bryanjugglercryptographer at yahoo.com wrote: >> From a WinXP command prompt: >> >> C:\> >> C:\>cd /windows/system32 >> >> C:\WINDOWS\system32> >> >> > > > This doesn't work the way you think it does. > > C:\>cd /windows > > C:\WINDOWS>cd /system32 > > C:\WINDOWS\system32> > > C:\WINDOWS\system32>cd /windows > The system cannot find the path specified. > > It IGNORES a leading / char. Ah, yes, I see. As Gerhard Fiedler pointed out, they use '/' elsewhere on command lines to introduce options, so it could be ambiguous as the first character of a path name. -- --Bryan From paul at boddie.org.uk Mon Aug 21 06:37:16 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 21 Aug 2006 03:37:16 -0700 Subject: What do you want in a new web framework? References: <1156100331.329889.216340@p79g2000cwp.googlegroups.com> <pan.2006.08.20.19.48.34.996227@gmx.net> Message-ID: <1156156636.515678.118210@75g2000cwc.googlegroups.com> Marc 'BlackJack' Rintsch wrote: > emrahayanoglu wrote: > > > > Now i want to listen all of you. What do you want in that web > > framework(Easy use of Database, Easy use of XML, GUI Designer, etc...)? > > Don't think that yet another Python web framework is really needed. Why not? I know that some people are probably basking in the glory of supposedly having their favourite framework recently blessed by the BDFL, whilst others lament the almost unfair rejection of their own framework on possibly dubious grounds by the very same person (thus seeing their "winner takes all" strategy backfire totally), but open source and various other network-effect movements benefit from lots of people trying different things (the "scratch your own itch" observation) rather than everyone gathering together for one big strategy meeting. Certainly, I'd recommend against anyone starting out on such a project without having at least looked at the state of the Web frameworks scene [1] and Python Web programming in general [2] (a resource which I've recently updated in order to remove a degree of incoherency introduced over the years), but apart from some Zope-based tools, I haven't seen much GUI-designer-friendly stuff in the Python frameworks scene, for example, nor does XML (in its widest W3C sense) seem to be well-integrated into most frameworks (4Suite and some other less hyped frameworks aside). So it's not just a case of picking one of the more popular frameworks-du-jour, especially since many of them seem to have their own wheel-reinvention tendencies despite protests to the contrary. Paul [1] http://wiki.python.org/moin/WebFrameworks [2] http://wiki.python.org/moin/WebProgramming From sjdevnull at yahoo.com Tue Aug 1 14:45:16 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 1 Aug 2006 11:45:16 -0700 Subject: Jumping over in the class hierarchy In-Reply-To: <44cf7481$0$24888$9b4e6d93@newsread4.arcor-online.net> References: <44cf7481$0$24888$9b4e6d93@newsread4.arcor-online.net> Message-ID: <1154457916.260798.190770@m73g2000cwd.googlegroups.com> Pupeno wrote: > Hello, > I want to jump over a method in the class hierarchy, that is: If I have > class A(object), clas B(A), class C(B) and in C, I want a method to do > exactly what A does but not what B does in its reimplementation, would it > be correct to do: super(A, super(B, self)).method() in C ? > Thank you. There's no reason to mess with super. Explicitly call A.method() From ray223 at gmail.com Wed Aug 16 19:27:52 2006 From: ray223 at gmail.com (ray223 at gmail.com) Date: 16 Aug 2006 16:27:52 -0700 Subject: How to delete a directory tree in FTP References: <1155742012.987806.236060@75g2000cwc.googlegroups.com> Message-ID: <1155770872.609546.324240@75g2000cwc.googlegroups.com> T wrote: > I connect to a FTP server which can be either unix or windows server. > Once in the FTP session, I would like to delete a directory tree on the > server. Is there a command that will do this? If not, can someone > point me to a right direction? > > Thanks! Have a look at rmtree in ftputil. http://ftputil.sschwarzer.net/ Regards, Ray Smith http://RaymondSmith.com From neokosmos at gmail.com Thu Aug 10 10:50:05 2006 From: neokosmos at gmail.com (neokosmos at gmail.com) Date: 10 Aug 2006 07:50:05 -0700 Subject: (newbie) Float() and high precision In-Reply-To: <mailman.9207.1155220976.27775.python-list@python.org> References: <mailman.9207.1155220976.27775.python-list@python.org> Message-ID: <1155221405.469411.286570@m79g2000cwm.googlegroups.com> wirecom at wirelessmeasurement.com wrote: > What's the best way to do higher precision maths than the standard Float()? It depends exactly what your needs are. What sort of application are you thinking of? You may actually need a good numerical analyst and not necessarily a new datatype here. :-) From mail at microcorp.co.za Sat Aug 5 05:53:35 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Sat, 5 Aug 2006 11:53:35 +0200 Subject: Enhanced Listbox References: <1154645765.984577.122710@b28g2000cwb.googlegroups.com><mailman.8971.1154690963.27775.python-list@python.org> <1154733152.101965.324260@h48g2000cwc.googlegroups.com> Message-ID: <011e01c6b876$86535de0$03000080@hendrik> "drodrig" <drodrig at magicbrain.com> wrote: (top posting fixed) | H J van Rooyen wrote: | > "drodrig" <drodrig at magicbrain.com> | > | > | > | My apologies if this question has been asked an answered. | > | | > | I am looking for a tkinter grid control or enhanced listbox that can | > | act as a "receipt" for a cash register program. I would like the widget | > | to contain a visible grid of columns and rows. I've tried binding | > | multiple listboxes to a scrollbar. This works OK, but I am missing the | > | vertical lines dividing each row and I can't seem to figure out how to | > | set the height (or vertical margin) of each row in the listbox(es). If | > | I could do these things my current implementation might be OK. Or, I | > | could just use a pre-packaged solution, if I coud find one. | > | | > | Any help is appreciated. | > | | > - you could try making your columns different background colours if this is | > acceptable... | > | > - Hendrik | | Thanks for your reply. I have done this. It certainly helps. My biggest | concern right now is the vertical space between the fonts in each row. | I need more than the default and I'm not sure on how to go about | achieving this. Also, the vertical lines between each row would be | nice. | I also don't know how to do this - as far as I know the height and width parameters of the listbox widget refer to number of lines and characters respectively - I cant see anything that gives you control over the height of a line - but maybe I am looking in the wrong place - I know that if you use a bigger font the individual lines get bigger - but it looks proportional to me. - Hendrik From kylotan at gmail.com Thu Aug 24 08:27:08 2006 From: kylotan at gmail.com (Ben Sizer) Date: 24 Aug 2006 05:27:08 -0700 Subject: Pygame, mouse events and threads In-Reply-To: <1156421018.882740.166810@b28g2000cwb.googlegroups.com> References: <1156421018.882740.166810@b28g2000cwb.googlegroups.com> Message-ID: <1156422427.974304.272200@m79g2000cwm.googlegroups.com> jedi200581 at yahoo.co.uk wrote: > When I put the content of the run and input functions in the main > thread, it's working, why not in the thread? Because event handling needs to be done in the main thread. So does rendering. This is a limitation of the underlying system. As a general rule, try to keep all your PyGame functions in the main thread and push your other processing into background threads, if you really need them. -- Ben Sizer From stargaming at gmail.com Sun Aug 13 14:28:07 2006 From: stargaming at gmail.com (Stargaming) Date: Sun, 13 Aug 2006 20:28:07 +0200 Subject: yet another noob question In-Reply-To: <1155492110.659011.196280@75g2000cwc.googlegroups.com> References: <1155492110.659011.196280@75g2000cwc.googlegroups.com> Message-ID: <ebnqvr$263h$1@ulysses.news.tiscali.de> mike_wilson1333 schrieb: > I would like to generate every unique combination of numbers 1-5 in a 5 > digit number and follow each combo with a newline. So i'm looking at > generating combinations such as: (12345) , (12235), (55554) and so on. > What would be the best way to do this? So, basically i'm looking for a > list of all combinations of 1-5 in a 5 digit unique number. Also, when > I send the list to print there can't be any duplicates of the combos. > > > Thanks, > > Mike > Generally, it is range(11111, 55555) Sincerely, Stargaming -- From duncan.booth at invalid.invalid Tue Aug 29 09:18:24 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 29 Aug 2006 13:18:24 GMT Subject: Extending the dict class References: <1156852916.254032.172390@b28g2000cwb.googlegroups.com> <44f4313e$0$26985$626a54ce@news.free.fr> <1156854958.228815.107090@m73g2000cwd.googlegroups.com> <Xns982E8CDD96042duncanbooth@127.0.0.1> <1156856325.095181.303140@p79g2000cwp.googlegroups.com> Message-ID: <Xns982E918CA9DC2duncanbooth@127.0.0.1> chosechu wrote: > > Duncan Booth wrote: >> If the order of the argument names matters, then it seems to me that >> should be handled by the SOAP library, not pushed onto the end user >> whoch should just be calling the function with the named arguments in >> the most convenient order. >> >> Shouldn't SOAPpy be able to get this information out of the WSDL? > > Yes, SOAPpy could extract this from the WSDL specs. > SOAPpy could also find another way to pass call parameters, but I > kinda like > the named parameters (seems really Python-like). Microsoft could also > build SOAP services that parse XML without making ordering mandatory > where > nobody said it was. Indeed, the spec says that parameterOrder is a hint and may be safely ignored. > > ... but we are living in a different dimension, one where I can extend > the Python dict class but not touch 2 of its 3 constructors (of course > the most > useful ones). No, you weren't able to extend the builtin dict class nor touch any its constructor. All you did was to create a subclass with its own constructor and hide the name for the builtin dictionary type. The original type was still unchanged as you can see since anything which constructed a dictionary without using the name you had overwritten still got the original type. If you had looked at type(dict()) and type({}) after your subclassing, you would see that they are different types. From rogue_pedro at yahoo.com Wed Aug 16 15:24:42 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 16 Aug 2006 12:24:42 -0700 Subject: trouble understanding inheritance... In-Reply-To: <1155754767.694480.256200@h48g2000cwc.googlegroups.com> References: <1155753183.207393.116940@m79g2000cwm.googlegroups.com> <mailman.9435.1155753894.27775.python-list@python.org> <1155754767.694480.256200@h48g2000cwc.googlegroups.com> Message-ID: <1155756282.851876.46470@b28g2000cwb.googlegroups.com> KraftDiner wrote: > Fredrik Lundh wrote: > > KraftDiner wrote: > > > > > This is not working the way I think it should.... > > > it would appear that fromfile and getName are calling the baseClass > > > methods which are > > > simple passes.... What have I done wrong? > > > > > > class baseClass: > > > def __init__(self, type): > > > if type == 'A': > > > self = typeA() > > > else: > > > self = typeB() > > > > __init__ is not a constructor, and assigning to self doesn't change the > > type of the constructed object. > > > > looks like you need to get a better tutorial. > > > > </F> > > Well how does one select which class baseClass really is when you > contruct the object? > What am I missing? > > a = typeA() > b = typeB() > c = baseClass(a) a = typeA() b = typeB() You're done. Stop there. You can't "select which class baseClass really is"-- it really is baseClass. You "select" which class your object is by choosing which class to use to construct the object. HTH, ~Simon From yuxi at ece.gatech.edu Sun Aug 13 17:56:08 2006 From: yuxi at ece.gatech.edu (Yu-Xi Lim) Date: Sun, 13 Aug 2006 17:56:08 -0400 Subject: outputting a command to the terminal? In-Reply-To: <44df99f7$0$25025$c3e8da3@news.astraweb.com> References: <44df99f7$0$25025$c3e8da3@news.astraweb.com> Message-ID: <ebo75n$src$1@news-int2.gatech.edu> John Salerno wrote: > 1. First of all, does Linux keep track of the packages you manually > install? If so, then I won't have to do this at all. I assume you're using a Debian-based distro with aptitude as the front end. In which case, all dpkg operations should be logged in /var/log/dpkg.log Generally, after the initial installation, all subsequent operations are either updates of existing packages or packages you installed manually. Only rarely do you get new packages installed automatically as a result of an additional dependency from an original automatically installed package. If you know when you completed your initial installation, you can easily parse the log files to determine what else was installed after that. > 2. Assuming I write this, how do output the bash command to the > terminal? Is there a particular module that Python uses to interact with > the terminal window that I can use to send the install command to the > terminal? I'm wondering about the need to "output the bash command to the terminal". It would probably suffice if your Python script just spawned an instance of the shell with the necessary command line. Take a look at the subprocess module. But this really calls for a bash script: #!/bin/bash echo $@ >> /path/to/manual_install.log sudo aptitude install $@ Shorter than the equivalent Python code. You could probably declare this as a function in your bash initialization files too, if you know how to do this. From ddvlad at gmail.com Thu Aug 10 04:44:28 2006 From: ddvlad at gmail.com (Vlad Dogaru) Date: 10 Aug 2006 01:44:28 -0700 Subject: Session implementation for Python In-Reply-To: <44d9cb06$0$21148$7a628cd7@news.club-internet.fr> References: <Xns981A90874AA20ddvladgmailcom@81.174.50.80> <44d9cb06$0$21148$7a628cd7@news.club-internet.fr> Message-ID: <1155199468.537545.100460@m79g2000cwm.googlegroups.com> Bruno Desthuilliers wrote: > Vlad Dogaru wrote: > > Hello, > > > > is there any PHP-like implementation for sessions in Python? I fear > > that writing my own would be seriously insecure, besides I could > > actually learn a lot by inspecting the code. > > > > The reason I am asking is that I would like to implement simple scripts > > which require login with CGI (no mod_python or Django -- I want to > > learn CGI first). > > http://jonpy.sourceforge.net/ Exactly what I was looking for. Thanks a bunch. Vlad From pythonnews at nospam.jmbc.fr Fri Aug 18 11:04:30 2006 From: pythonnews at nospam.jmbc.fr (jean-michel bain-cornu) Date: Fri, 18 Aug 2006 17:04:30 +0200 Subject: crash in wx.TreeListCtrl SelectItem() In-Reply-To: <mailman.9502.1155893871.27775.python-list@python.org> References: <mailman.9502.1155893871.27775.python-list@python.org> Message-ID: <44e5d798$0$21146$7a628cd7@news.club-internet.fr> Hi, > I have a strange crash (segfault on FreeBSD) that I can not reliably reproduce > and therefore unfortunately can not provide a self contained test case at the > moment. > > Here is what I do (and what works almost always, but sometimes crashes): > > 1) find an item in a wx.TreeListCtrl by its pydata (code posted to this list) > 2) if the item is found: > a) call EnsureVisible(foundItem) > b) call SelectItem(foundItem) > > The call to EnsureVisible() always returns, but SelectItem() crashes python > sometimes. > > foundItem on a crash is something like this: > <wx._controls.TreeItemId; proxy of C++ wxTreeItemId instance at > _a0d0c708_p_wxTreeItemId> > > calling GetPyData(foundItem) returns the correct pydate. > > Any ideas what could be happening or how to further debug this? Try anyway to reproduce with a sample. The only way I know in this case is to split the code and see if it happens again. If so, split again, and again, and so on... It can be long, but the only way. Very often, you'll find yourself the buggy part. Once time you'll have a sample, post it, I can try on linux and windows. Also please give the versions of the softwares you use. rgds jm From mail at microcorp.co.za Mon Aug 28 04:28:38 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 28 Aug 2006 10:28:38 +0200 Subject: How to let a loop run for a while before checking for breakcondition? References: <ecrqe1$9j$1@newsreader2.netcologne.de><4ldfp0F1csmpU1@uni-berlin.de> <ecs2ck$egu$1@newsreader2.netcologne.de> Message-ID: <017c01c6ca80$ad4a7340$03000080@hendrik> "Claudio Grondi" <claudio.grondi at freenet.de> wrote: | Diez B. Roggisch wrote: | > Claudio Grondi schrieb: | > | >> | >> Sometimes it is known in advance, that the time spent in a loop will | >> be in order of minutes or even hours, so it makes sense to optimize | >> each element in the loop to make it run faster. | >> One of instructions which can sure be optimized away is the check for | >> the break condition, at least within the time where it is known that | >> the loop will not reach it. | >> | >> Any idea how to write such a loop? | >> | >> e.g. | >> | >> counter = 2*64 | >> | >> while counter(BUT DON'T CHECK IT THE FIRST ONE HOUR LONG): | > | > | > now = time.time() | > while time.time() - now < 3600.0 or some_other_condition: | > ... | > | > | > The short circuiting of the or will prevent the execution of | > some_other_condition. | > | >> ... do something ... # and decrease the counter | >> | >> Thanks for any hint, but in particular if related to timers on the | >> Windows 2000/XP system I am mainly working with. | >> | >> What do you think about this idea? Does it make sense? | > | > What idea? | This one you haven't probably got from what I have written. | I thought, that the introductory text gives enough context to be able to | see what I mean, but I was apparently wrong. | | The idea is to speed up a loop by using a timer interrupt interfering | with the loop, so that only after the timer interrupt would occur, the | loop will start to check its break condition in each iteration. | No checking of any kind in the loop should happen up to that time to | minimize the number of operations in each iteration within the loop | itself (i.e. the loop more or less won't know, that there is a timer on | its way to change the loops behavior at a later time). | | I hope this above helps to understand what I would like to achieve. | | Claudio Grondi I don't think this is usefully possible in python - the problem is that you will simply replace one check - The expiry of the counter - with another - to see if the interrupt has occurred already - That said - the way I would do it would be to do something like this (in horrible pseudo code): loop_start: do_something() jump loop_start if counter > end_value: break jump loop_start loop_end: Interrupt_routine: replace the first jump to loop_start with a bunch of no - ops return I don't think you can do this in python - it involves altering the running loop - but hey maybe I can learn something here... This example sort of exposes the break for what it is - a jump statement in disguise - "look you cant recognise me - I am wearing dark glasses" - and "continue" is exactly like that too - the only difference is that the one jumps to the end, and the other to the beginning of the loop... - Hendrik From cliff at develix.com Wed Aug 2 05:05:51 2006 From: cliff at develix.com (Cliff Wells) Date: Wed, 02 Aug 2006 02:05:51 -0700 Subject: Using Python for my web site In-Reply-To: <1685iz6tcrk26$.dlg@gelists.gmail.com> References: <1154361480.915174.262720@b28g2000cwb.googlegroups.com> <44ce3a5c$0$18952$626a54ce@news.free.fr> <1154367359.931684.106650@m73g2000cwd.googlegroups.com> <44ce4530$0$28242$626a54ce@news.free.fr> <mailman.8748.1154376811.27775.python-list@python.org> <pan.2006.08.02.00.04.19.775720@nothanks.org> <1685iz6tcrk26$.dlg@gelists.gmail.com> Message-ID: <1154509551.20290.290.camel@devilbox> On Tue, 2006-08-01 at 23:26 -0300, Gerhard Fiedler wrote: > Or is there something in PostgreSQL that makes its users acidic? :) Well, ACID is popular in PostgreSQL circles. Cliff -- From mail at microcorp.co.za Thu Aug 3 08:05:19 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Thu, 3 Aug 2006 14:05:19 +0200 Subject: Is there an obvious way to do this in python? References: <mailman.8853.1154537129.27775.python-list@python.org> <44d128e5$0$13484$636a55ce@news.free.fr><mailman.8884.1154590374.27775.python-list@python.org> <easbje$92d$1@news-int2.gatech.edu> Message-ID: <012001c6b6f5$e6428640$03000080@hendrik> "Yu-Xi Lim" <yuxi at ece.gatech.edu> wrote: | H J van Rooyen wrote: | > | | > |> And I would like to make this flexible, so that it becomes easy to introduce | > new | > |> transactions, without having to run around updating the code in all the user | > |> machines, with the concomitant version number hassles. | > | | > |Then you want a web front end. | > | > This seems to me to assume that the server does all the work | | Depends on what you mean by "all the work." What I mean by this is that the server does stuff that I think belongs on the client - like getting involved in the nitty gritty of what the client should display - I want the client to be smart enough to do the assembly of the elements of a transaction by itself, going back to the server for data only when its needed - remember this is essentially an accounting type data entry package - most of the stuff is typed in as text, when processing documents from the outside, while the locally produced docs like invoices would be generated by the system, to a large extent by making choices amongst alternatives known to the server - so I see the client interacting with the server quite a lot, eventually to be able do things like auto completion of things like stock codes and descriptions, customer details, etc. - but I don't want every keystroke flying over the LAN and being handled by the server... In a sense I want to build an architecture that assembles a record from a mix of user input and user choices out of alternatives (which unfortunately would have to be kept on the server) and that then ships this to the server to process, and to keep track of - such a record would be either accepted or rejected by the server, and it would be the responsibility of the client to ensure that the transaction is completed - like in a banking system, I envisage ways for the client to 'poll' the server to get the state of the last transaction, to make this possible. | | Operations such as filtering results are best done at the server unless | your have extremely high-bandwidth connections so that each client can | examine the entire data set and perform the operations themselves (with | minimal time of course, since your other clients may be waiting on that | transaction). | | Transactions, too, will have to be supported by the server, or else you | may be left with partial transactions if a client gets disconnected | somehow as well as the need to implement complex locking systems yourself. | | As for the other conditions, such as privilege and access control, I | think you'd find that centrally managed is the most manageable in the | long run. | | You won't regret making it server-centric. The experts have already done | the optimisations and have ways of getting around the possible | bottleneck of having a single server perform most of the operations. | | > |Yes, it's called a web frontend for a SQL DBMS. There's no shortage of | > |Python frameworks to do this kind of things. | > | | > | > I kind of wanted to avoid the web based stuff - the application data is so small | > and trivial, in a sense. | | You'd find that the python frameworks, especially those modeled after | Ruby on Rails, make creating trivial applications, such as the front-end | you describe, trivial. Go take a look at Django and TurboGears and the | others. Some have videos demonstrating stuff like how to make a | blog/wiki/other-database-app in 5 minutes. Most come with a built-in | webserver, though generally those aren't tested or guaranteed for | high-load environments. I get the feeling I am drinking out of a fire hose... I will look. | | All you need to add is a DB. Most recommend postgresql, and I'd | recommend that too, to provide the features you are looking for. Avoid | the lightweight DB systems such as Gadfly, sqlite, MS Jet/Access since | those don't have the necessary features. postgres seems the way to go - if there is anything that is coming across clear, it is this. Have you any ideas about the "code change on the fly" requirement? or is it a complete no no? thanks - Hendrik From rogue_pedro at yahoo.com Sun Aug 13 15:07:49 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 13 Aug 2006 12:07:49 -0700 Subject: yet another noob question References: <1155492110.659011.196280@75g2000cwc.googlegroups.com> <ebnqvr$263h$1@ulysses.news.tiscali.de> <ebnrht$266m$1@ulysses.news.tiscali.de> Message-ID: <1155496069.847013.45330@b28g2000cwb.googlegroups.com> Stargaming wrote: > Stargaming schrieb: > > mike_wilson1333 schrieb: > > > >> I would like to generate every unique combination of numbers 1-5 in a 5 > >> digit number and follow each combo with a newline. So i'm looking at > >> generating combinations such as: (12345) , (12235), (55554) and so on. > >> What would be the best way to do this? So, basically i'm looking for a > >> list of all combinations of 1-5 in a 5 digit unique number. Also, when > >> I send the list to print there can't be any duplicates of the combos. > >> > >> > >> Thanks, > >> > >> Mike > >> > > > > Generally, it is range(11111, 55555) > > > > Sincerely, > > Stargaming > > Whoops, I'm sorry. I think I was a little bit too enthusiastic and "wow > look 'print range' is fun!". You could do a list comprehension over the > range thingy. def stoopid_way(start, end): for n in xrange(start, end + 1): # Make a string. s = '%d' % n # Exclude 0's. if '0' in s: continue # Exclude 6-9's. try: int(s, 6) except ValueError: continue yield s Use it like so: # Get all the strings as a list.. data = list(stoopid_way(11111, 55555)) # ..or print the strings one-by-one.. for s in stoopid_way(11111, 55555): print s # ..or print one big string, joined by newlines. print '\n'.join(stoopid_way(11111, 55555)) I originally meant this as a joke and was going to say not to use it. But on my old, slow computer it only takes about a second or two. If that's fast enough for you then it won't do any harm to use it. (Just don't mention my name ;-) ) Peace, ~Simon From anthra.norell at tiscalinet.ch Thu Aug 24 02:52:40 2006 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Thu, 24 Aug 2006 08:52:40 +0200 Subject: Taking data from a text file to parse html page References: <1156378275.662140.214650@h48g2000cwc.googlegroups.com> Message-ID: <002501c6c749$e51163e0$0201a8c0@mcuf7> DH, Could you be more specific describing what you have and what you want? You are addressing people, many of whom are good at stripping useless junk once you tell them what 'useless junk' is. Also it helps to post some of you data that you need to process and a sample of the same data as it should look once it is processed. Frederic ----- Original Message ----- From: "DH" <dylanhughes at gmail.com> Newsgroups: comp.lang.python To: <python-list at python.org> Sent: Thursday, August 24, 2006 2:11 AM Subject: Taking data from a text file to parse html page > Hi, > > I'm trying to strip the html and other useless junk from a html page.. > Id like to create something like an automated text editor, where it > takes the keywords from a txt file and removes them from the html page > (replace the words in the html page with blank space) I'm new to python > and could use a little push in the right direction, any ideas on how to > implement this? > > Thanks! > > -- > http://mail.python.org/mailman/listinfo/python-list From jorge.vargas at gmail.com Mon Aug 28 23:36:42 2006 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Mon, 28 Aug 2006 23:36:42 -0400 Subject: Pros/Cons of Turbogears/Rails? In-Reply-To: <WXmIg.20772$gY6.18513@newssvr11.news.prodigy.com> References: <WXmIg.20772$gY6.18513@newssvr11.news.prodigy.com> Message-ID: <32822fe60608282036n594aa099r2a82e56779495dc2@mail.gmail.com> On 8/27/06, kenneth.m.mcdonald at sbcglobal.net <kenneth.m.mcdonald at sbcglobal.net> wrote: > First, I don't intend this to be a flame war, please. Python > and Ruby are the only two languages I'd willingly work in > (at least amongst common languages), and TurboGears and > Rails seem roughly equivalent. > > I'm much more knowledgable about Python, but that's a minor > issue--I've been intending to learn more Ruby anyway. > > Here are the pros and cons that I'm aware of and consider > important: > > Turbogears: > + SqlObject allows working with the DB tables without > using SQL itself. yes and SQLAlchemy lets you do more complex things, like working with an existing database. > + Likely to be faster because as far as I'm aware, Python > is significantly faster. no idea there. > + Easy access to other libraries (such as the Python > Imaging Library) that Ruby, being a relatively newer > language, doesn't have equivalents to. python's'lib is MUCH more bigger > + Built-in default SQLite makes it easier to set up? actually no you still have to install sqlite and the "build in" is just a config entry. > (as far as I can tell, Ruby requires MySql by default--don't > know how easy this is to change.) > + I find the templating system somewhat cleaner; code in > py: xml namespace allows pure .html templates, instead > of equivalent of .rhtml files. > > Ruby: > + More mature system. More stable? More features? not at all, you could say that in a TG vrs django or zope. > + Much better documented. This is a biggie. TG docs are lacking at the moment mainly due to a problem with the documentation engine, we have been bouncing between trac,docudo, xmls and now moinmoin. this will be settle soon, until this is fix there will be on 1.0 (which may be the reason why RoR is already out and TG isn't) > + Built-in Rubydoc system would make documenting the > system easier. (IMHO, developers almost always > underestimate the need for good documentation that > is written along withe the system.) Is there a > Python doc system that has received Guido's blessing > yet? D'oxygen would seem an obvious choice. huh? docstrings ... > + Better coordination with Javascript helper code? again huh, in TG you include a JS lib and it's done. if someone has made a widget for it all you have to do is install it (easy_install widget). > > I was initially leaning towards Rails due to maturity, > but the most recent version of TurboGears seem to have > fixed a lot of the "ad hoc" feeling I got from previous > versions. But I'm still very much up in the air. is that 0.5 and 0.8? almost everyone on TG runs the 0.9 alpha's there has been so much code in to them that is stable as a rock. > > Thanks, > Ken > > P.S. If I wanted to provide an image by streaming the > file data directly over the connection, rather than by > referring to an image file, how would I do that? I'd > like to build code that would allow images to be assembled > into a single-file photo album (zip or bsddb file), and > so can't refer to them as individual image files. if that's the case either is just overkill all you need is a simple httpserver and reading a bit about image encoding. > -- > http://mail.python.org/mailman/listinfo/python-list > From fredrik at pythonware.com Mon Aug 21 06:41:14 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Aug 2006 12:41:14 +0200 Subject: sum and strings In-Reply-To: <1hkda8w.iecnyb3w9mz9N%aleax@mac.com> References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <slrneeatf3.nbt.sybrenUSE@schuimige.stuvel.eu> <7xr6zel2r2.fsf@ruckus.brouhaha.com> <ec4b27$7lr$1@news.albasani.net> <1155971485.709068.255140@b28g2000cwb.googlegroups.com> <1156038134.216383.80960@h48g2000cwc.googlegroups.com> <1156067043.386056.129320@i42g2000cwa.googlegroups.com> <1156069124.744004.118670@i3g2000cwc.googlegroups.com> <1hkda8w.iecnyb3w9mz9N%aleax@mac.com> Message-ID: <ecc2kb$g1$1@sea.gmane.org> Alex Martelli wrote: > In terms of performance, however, the simple loop that you (rhamph) > posted is generally best -- e.g., with Python 2.5c1 on a MacbookPro: > > brain:~/downloads alex$ python -mtimeit -s'deep=[range(9)]*9' > 's=sum(deep,[])' > 100000 loops, best of 3: 11.2 usec per loop > > brain:~/downloads alex$ python -mtimeit -s'deep=[range(9)]*9' 's=[] >> for sublist in deep: s.extend(sublist)' > 100000 loops, best of 3: 6.92 usec per loop at least on this machine, map(s.extend) is slightly faster than the loop: timeit -s"deep=[range(9)]*9" "s=[]" "for sublist in deep: s.extend(sublist)" 100000 loops, best of 3: 5.59 usec per loop timeit -s"deep=[range(9)]*9" "s=[]" "map(s.extend, deep)" 100000 loops, best of 3: 5.26 usec per loop </F> From Avizoa at gmail.com Fri Aug 4 11:21:45 2006 From: Avizoa at gmail.com (Avizoa at gmail.com) Date: 4 Aug 2006 08:21:45 -0700 Subject: wxPython font color In-Reply-To: <1154701738.123713.137210@s13g2000cwa.googlegroups.com> References: <1154701738.123713.137210@s13g2000cwa.googlegroups.com> Message-ID: <1154704905.823619.282020@75g2000cwc.googlegroups.com> Fonts don't have colors. You need to either change the text color in whatever widget the test is going or change the wx.Brush in your Paint method. Kiran wrote: > hey everybody, > i cant seem to find a way to create a font with a non-default color > using the wx.Font constructor. anybody know how to change hte color? > > thanks From rogue_pedro at yahoo.com Wed Aug 30 03:34:48 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 30 Aug 2006 00:34:48 -0700 Subject: psycopg2 features In-Reply-To: <1156922127.882417.137920@i42g2000cwa.googlegroups.com> References: <1156922127.882417.137920@i42g2000cwa.googlegroups.com> Message-ID: <1156923288.115833.225180@h48g2000cwc.googlegroups.com> Maxim Sloyko wrote: > Hello, clp and all people reading it! > Recently I was porting my (small) app from psycopg to psycopg2 (they > got me with this "2"). > I read, that psycopg2 supports all features of psycopg and plus many > more, however, when I started to port, I discovered, that psycopg2 > lacks serialized connections and "commit on cursor" completely. Did I > miss something or psycopg2 just isn't mature enough yet? > > BTW, is there any postgresql engine, that can fake nested transactions > via savepoints feature? You should probably ask this in the psycopg mailing list: http://lists.initd.org/mailman/listinfo/psycopg Peace, ~Simon From martin at v.loewis.de Mon Aug 7 08:05:10 2006 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 07 Aug 2006 14:05:10 +0200 Subject: install python on cdrom In-Reply-To: <mailman.8929.1154631593.27775.python-list@python.org> References: <mailman.8702.1154190374.27775.python-list@python.org> <44CC7991.9000002@v.loewis.de> <mailman.8929.1154631593.27775.python-list@python.org> Message-ID: <44d72c76$0$24203$9b622d9e@news.freenet.de> Fabian Braennstroem schrieb: > Thanks, but unfortunately the administrative policy does not > allow such installation, but could it work, when I do such a > installation in my home directory, copy everything to a > cdrom/dvd and mount it in proper place? Yes, that should work as well. Python won't be able to create .pyc files, of course, but that shouldn't be a problem (plus you could make sure they are up-to-date when you copy them onto the CD-ROM). Regards, Martin From robinsiebler at 321.net Mon Aug 28 21:08:06 2006 From: robinsiebler at 321.net (robinsiebler) Date: 28 Aug 2006 18:08:06 -0700 Subject: Searching for text In-Reply-To: <1156811812.783788.92910@74g2000cwt.googlegroups.com> References: <1156809673.741444.110690@m73g2000cwd.googlegroups.com> <mailman.10014.1156811509.27775.python-list@python.org> <1156811812.783788.92910@74g2000cwt.googlegroups.com> Message-ID: <1156813686.151600.146170@75g2000cwc.googlegroups.com> The other thing I failed to mention is that I need to ensure that I find the fsType *before* I find the next FontName. From sjmachin at lexicon.net Fri Aug 18 21:21:17 2006 From: sjmachin at lexicon.net (John Machin) Date: 18 Aug 2006 18:21:17 -0700 Subject: couple more questions about sqlite In-Reply-To: <44e666f9$0$12542$c3e8da3@news.astraweb.com> References: <MqnFg.2703$No6.52653@news.tufts.edu> <1155930772.591854.53910@m79g2000cwm.googlegroups.com> <1rpFg.2705$No6.52662@news.tufts.edu> <1155943434.653053.232100@74g2000cwt.googlegroups.com> <44e666f9$0$12542$c3e8da3@news.astraweb.com> Message-ID: <1155950477.783716.177870@74g2000cwt.googlegroups.com> John Salerno wrote: > John Machin wrote: > > > Your confusion is quite understandable. I started looking at sqlite > > when the announcement that it would be included in Python 2.5 came out. > > Puzzlement reigned. I ended up with the following up the front of my > > experimental module: > > So does this mean that when 2.5 is released, all I need is the built-in > module sqlite3? Plus the command-line utility, which AFAICT is not included with Python 2.5. From hadaqada at gmail.com Mon Aug 7 11:37:39 2006 From: hadaqada at gmail.com (Uffe Wassmann) Date: Mon, 7 Aug 2006 17:37:39 +0200 Subject: need an alternative to getattr() In-Reply-To: <1154961041.067164.199520@i42g2000cwa.googlegroups.com> References: <1154961041.067164.199520@i42g2000cwa.googlegroups.com> Message-ID: <cc8d60f40608070837k55ef2384k11965a1f0c662449@mail.gmail.com> I think you would benefit from looking at the ConfigParser module. I haven't tried it yet, but it looks like a nice interface for writing and reading configuration files. -Uffe. On 7 Aug 2006 07:30:41 -0700, pranav.choudhary at gmail.com <pranav.choudhary at gmail.com> wrote: > Hi, > > AIM: I have a config file that contains configuration under headings > like this: > > heading1: > <configuration 1> > <configuration 2> > heading2: > <configuration 1> > <configuration 2> > ... > ... > > i parse this file to get heading1, heading2, etc and then i want to > call heading1.process(), heading2.process(), etc. > What i am trying to do is: (this is not the exact code, it just > represents what i am trying to do) > > import heading1 > import heading2 > While True: > heading = get_next_heading(file_ptr) # This func will return > "heading1", then "heading2"(on next call) > if heading = "": > break > getattr(heading, "process")(file_ptr) # The problem, as you would > have noticed, is that the first > # argument to getattr is a string!! > > Is there an alternatice to getattr() that will solve my problem, or is > there another way to do it. > > -pranav > > -- > http://mail.python.org/mailman/listinfo/python-list > From steve at holdenweb.com Mon Aug 14 23:41:36 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 15 Aug 2006 04:41:36 +0100 Subject: How to fill a form In-Reply-To: <20060815050733.10e14112.sulsa@gazeta.pl> References: <20060815034051.89ef7e18.sulsa@gazeta.pl> <mailman.9336.1155608567.27775.python-list@python.org> <20060815050733.10e14112.sulsa@gazeta.pl> Message-ID: <ebrfoq$rbu$1@sea.gmane.org> Sulsa wrote: > On Tue, 15 Aug 2006 03:22:40 +0100 > Steve Holden <steve at holdenweb.com> wrote: > > >>I'd recommend you take a look at mechanize, see >> >> http://wwwsearch.sourceforge.net/mechanize/ >> >>and specifically at ClientForm, see >> >> http://wwwsearch.sourceforge.net/ClientForm/ >> >>These make it easy to perform browser-like accesses to forms-based >>web applications. >> > > > I want to fill only one smiple form so i would like not to use any non > standard libraries. That's your choice, but frankly I'd be very surprised if it wasn't quicker to download and use mechanize/clientform than it was to put your own solution together. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From grante at visi.com Wed Aug 9 15:08:47 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 09 Aug 2006 19:08:47 -0000 Subject: Python share CPU time? References: <1155146500.063665.282430@p79g2000cwp.googlegroups.com> <mailman.9165.1155149712.27775.python-list@python.org> Message-ID: <12dkclvtkvoin13@corp.supernews.com> On 2006-08-09, Tim Chase <python.list at tim.thechases.com> wrote: >> Problem is that I would have to share the CPU between all the robots, >> and thus allocate a time period to each robot. However I couldn't find >> any way to start a thread (robot), and interrupt it after a given time >> period. >> Any suggestions on how to proceed? > >>> import thread, time > >>> def robot(name): > ... for i in xrange(5): > ... print "%s on pass %i" % (name, i) > ... time.sleep(0.01) >[...] I originally suggested the thread/sleep() scheme, but after thinking about it more, I really like the generator approach in the case where you want to explicity end each robot's "turn" using the CPU (which is what the sleep() call does). OTOH, if you want the robots to wait for events of some sort (e.g. from a queue) or data from an I/O device, then threading is probably the way to go. I guess it all depends on whether the robots' behavior is to be time-driven or event-driven. -- Grant Edwards grante Yow! Used staples are good at with SOY SAUCE! visi.com From blue99 at interia.pl Mon Aug 21 06:07:56 2006 From: blue99 at interia.pl (Rob Wolfe) Date: 21 Aug 2006 03:07:56 -0700 Subject: Regular Expression question In-Reply-To: <1156153916.849933.178790@75g2000cwc.googlegroups.com> References: <1156153916.849933.178790@75g2000cwc.googlegroups.com> Message-ID: <1156154876.874272.283160@i3g2000cwc.googlegroups.com> stevebread at yahoo.com wrote: > Hi, I am having some difficulty trying to create a regular expression. > > Consider: > > <tag1 name="john"/> <br/> <tag2 value="adj__tall__"/> > <tag1 name="joe"/> > <tag1 name="jack"/> > <tag2 value="adj__short__"/> > > Whenever a tag1 is followed by a tag 2, I want to retrieve the values > of the tag1:name and tag2:value attributes. So my end result here > should be > john, tall > jack, short > > My low quality regexp > re.compile('tag1.+?name="(.+?)".*?(?!tag1).*?="adj__(.*?)__', > re.DOTALL) > > cannot handle the case where there is a tag1 that is not followed by a > tag2. findall returns > john, tall > joe, short > > Ideas? Have you tried this: 'tag1.+?name="(.+?)".*?(?=tag2).*?="adj__(.*?)__' ? HTH, Rob From fredrik at pythonware.com Sat Aug 26 01:39:54 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 26 Aug 2006 07:39:54 +0200 Subject: Problem with List of List In-Reply-To: <1156569535.500196.7920@i3g2000cwc.googlegroups.com> References: <1156569535.500196.7920@i3g2000cwc.googlegroups.com> Message-ID: <ecomr9$ps1$1@sea.gmane.org> Kirt wrote: > I am a newbie and stuck over this for a week that's unfortunate. > I have a code > ==================CODE============= > List=[['1', 'a', '6'], ['1', 'b', '6'], ['1', 'c', '6'], > ['1', 'd', '6'],['2', 'a','6'], ['2', 'b', '6'], > ['2', 'c', '6'], ['2', 'd', '6'], ['3', 'a', '6'], > ['3','b', '6'], ['4', 'a', '6'], ['4', 'b', '6']] > > > for x in List: > temp=[] > print x > for y in List: > if x[0]==y[0]: > print y[0],y[1] > temp.append(y) > for z in temp: > List.remove(z) > print 'rem', z the for loop uses an internal index to fetch items from the list you're looping over, so if you remove items from it, you'll end up skipping over items. this is hinted at in the tutorial: http://docs.python.org/tut/node6.html#SECTION006200000000000000000 and explained in further detail in the language reference: http://docs.python.org/ref/for.html http://pyref.infogami.com/for </F> From bearophileHUGS at lycos.com Sun Aug 13 15:45:04 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 13 Aug 2006 12:45:04 -0700 Subject: yet another noob question In-Reply-To: <1155496069.847013.45330@b28g2000cwb.googlegroups.com> References: <1155492110.659011.196280@75g2000cwc.googlegroups.com> <ebnqvr$263h$1@ulysses.news.tiscali.de> <ebnrht$266m$1@ulysses.news.tiscali.de> <1155496069.847013.45330@b28g2000cwb.googlegroups.com> Message-ID: <1155498304.213833.114050@m73g2000cwd.googlegroups.com> Simon Forman: > I originally meant this as a joke and was going to say not to use it. > But on my old, slow computer it only takes about a second or two. Another possibility, still using a filter: nodig = set("06789") r = [i for i in xrange(11111, 55555+1) if not (set(`i`) & nodig)] Bye, bearophile From kylotan at gmail.com Wed Aug 2 09:55:26 2006 From: kylotan at gmail.com (Ben Sizer) Date: 2 Aug 2006 06:55:26 -0700 Subject: Network Game in Python In-Reply-To: <1154465130.099412.101270@h48g2000cwc.googlegroups.com> References: <1154465130.099412.101270@h48g2000cwc.googlegroups.com> Message-ID: <1154526926.548459.231220@75g2000cwc.googlegroups.com> diffuser78 at gmail.com wrote: > Some questions I have are: > 1. How can I manage network messages among the players. Should > multicast be used or Actor should send the message to Supervisor and he > sends to all. ? Send a message from one client to the supervisor, handle it, then get the supervisor to send messages back out to notify all clients of the change. That way, the supervisor always has the correct state, and knows which clients are aware of it. > What python modules can be handy in these things. The socket and select modules are all that you need. Perhaps there's a higher-level solution somewhere but I don't expect you'd need it. > 2. How can I manage moves among players. What move a player makes is > visible to all others in real time, so essentially all players have the > same consistent view of the game. Only the person with access can > actually make a move or carry out action. Any suggestion how to carry > out this thing. As above: inform the supervisor/server of the move, and the server informs all others of what is going on. Usually this is just a message telling the client to update certain values. The client will update those values and refresh the display. You may find it easiest to send whole objects using pickle or something like that. > 3. Shold I use a flat file or some database in mySQL to measure points > etc ? I want to have a repository which keep tracks of all the mvoes in > the system and who played what move etc..? Any suggestions on this. Use whichever is easiest for you. Why do you need to save the data to disk anyway? If you definitely need to do that, the shelve module is often a good choice for basic needs. But it depends on what you need to do with the information after you write it. -- Ben Sizer From jjl at pobox.com Tue Aug 22 21:26:56 2006 From: jjl at pobox.com (John J. Lee) Date: Wed, 23 Aug 2006 01:26:56 GMT Subject: What do you want in a new web framework? References: <1156100331.329889.216340@p79g2000cwp.googlegroups.com> <pan.2006.08.20.19.48.34.996227@gmx.net> <1156156636.515678.118210@75g2000cwc.googlegroups.com> <1156173509.767030.255710@b28g2000cwb.googlegroups.com> <1156183574.781794.11340@p79g2000cwp.googlegroups.com> Message-ID: <87wt905jj3.fsf@pobox.com> UrsusMaximus at gmail.com writes: > hardemr wrote: > > > I've just read all of the answers. Most of yours said that there are > > many web frameworks ,so it is nonsense to make a new web framework in > > python. > > Hardemr, I like Ajacksu's answer, with a twist. Please concnentrate on > writing a Visual Studio-like gui designer, and make it possible to add > your Visual Studio like gui designer to Django (and TurboGears, et al). > > > Leverage the hard work of others and the installed base; add your > functionality on top. Don't re-create the wheel, build your internal > combustion engine powered vehicle on top of the 4 wheels that already > exist! ;-)) pyjamas! http://pyjamas.pyworks.org/ Now would be a fantastic time to muck in and do as UrsusMaximus suggests -- nobody on the pyjamas project is yet talking about such things, but it's obviously an area that could make you very popular if done well ;-) John From fredrik at pythonware.com Mon Aug 28 11:59:33 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 28 Aug 2006 17:59:33 +0200 Subject: unit test for a printing method In-Reply-To: <1156780399.289589.58750@m73g2000cwd.googlegroups.com> References: <1156780399.289589.58750@m73g2000cwd.googlegroups.com> Message-ID: <ecv3t6$lmq$2@sea.gmane.org> noro wrote: > What is the proper way to test (using unit test) a method that print > information? > for example: > > def A(s): > print '---'+s+'---' > > and i want to check that A("bla") really print out "---bla---" http://docs.python.org/lib/module-doctest.html </F> From saad82 at gmail.com Tue Aug 8 17:28:27 2006 From: saad82 at gmail.com (wipit) Date: 8 Aug 2006 14:28:27 -0700 Subject: python - HTML processing - need tips References: <1154995128.118127.227840@i3g2000cwc.googlegroups.com> <mailman.9068.1154997799.27775.python-list@python.org> Message-ID: <1155072507.601107.38370@p79g2000cwp.googlegroups.com> I figured it out... Just turned the POST request into a GET to see what was getting appended to the URL - thanks Gabe! Gabriel Genellina wrote: > At Monday 7/8/2006 20:58, wipit wrote: > > >I need to process a HTML form in python. I'm using urllib2 and > >HTMLParser to handle the html. There are several steps I need to take > >to get to the specific page on the relevant site the first of which is > >to log in with a username/password. The html code that processes the > >login consists of 2 edit boxes (for User ID and Password) and a Submit > >button which uses ASP.net client side validation as follows (formatted > >for clarity): > > Another approach would be using HTTPDebugger > <http://www.softx.org/debugger.html> to see exactly what gets > submitted, and then build a compatible Request. > On many sites you don't even need to *get* the login page -nor parse > it-, just posting the right Request is enough to log in successfully. > > > > Gabriel Genellina > '@'.join(('gagsl-py','.'.join(('yahoo','com','ar')))) > > > > > > __________________________________________________ > Pregunt?. Respond?. Descubr?. > Todo lo que quer?as saber, y lo que ni imaginabas, > est? en Yahoo! Respuestas (Beta). > ?Probalo ya! > http://www.yahoo.com.ar/respuestas From richardjones at optushome.com.au Fri Aug 4 03:18:38 2006 From: richardjones at optushome.com.au (Richard Jones) Date: Fri, 04 Aug 2006 17:18:38 +1000 Subject: PyWeek #3 in September! Message-ID: <44d2f4ce$0$25276$afc38c87@news.optusnet.com.au> PyWeek 3 is coming up. I've scheduled it for the first week of September. The exact dates are 00:00UTC Sunday 3rd September to 00:00UTC Sunday 10th September. REGISTRATION IS NOW OPEN Visit the PyWeek website to sign up: http://www.pyweek.org/ THE PYWEEK CHALLENGE: - Invites all Python programmers to write a game in one week from scratch either as an individual or in a team, - Is intended to be challenging and fun, - Will hopefully increase the public body of python game tools, code and expertise, - Will let a lot of people actually finish a game, and - May inspire new projects (with ready made teams!) Entries must be developed during the challenge, and must incorporate some theme decided at the start of the challenge. The rules for the challenge are at: http://media.pyweek.org/static/rules.html Richard -- Visit the PyWeek website: http://www.pyweek.org/ From claudio.grondi at freenet.de Thu Aug 3 08:16:48 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Thu, 03 Aug 2006 14:16:48 +0200 Subject: opposite of import In-Reply-To: <1154605835.465468.97550@m79g2000cwm.googlegroups.com> References: <1154605835.465468.97550@m79g2000cwm.googlegroups.com> Message-ID: <easpff$smk$1@newsreader2.netcologne.de> pranav.choudhary at gmail.com wrote: > Hi > I am new to python. I wanted to know if there is an opposite of "import" > If you mean 'import' adds something, so you ask how to get rid of something? Here you are: Look at the 'del' statement if it is what you are looking for. Claudio Grondi From steve at holdenweb.com Wed Aug 23 22:12:09 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 24 Aug 2006 03:12:09 +0100 Subject: Accessing application data portably In-Reply-To: <20060823162056.GA4698@weber> References: <20060823162056.GA4698@weber> Message-ID: <44ED0AF9.6070603@holdenweb.com> Tom E H wrote: > My Python application includes some data files that need to be accessed by > modules I distribute with it. > > Where can I put them, and how should I arrange my code, so that it works > across platforms? > > On Linux, I could install the data to "/usr/lib/myprogram/datafile", and > on Windows to "datafile" relative to where the executable (made by > py2exe) is installed. Then I could detect the operating system, and choose > appropriately. > > To be that explicit seems undesirable. Any cleverer ideas? > > Tom > > (Please CC me on replies: I'm not subscribed. The From address is munged) > If you aren't ubscribed then the only person who is going to copy you on email is someone complaining about your presumptuousness in assuming they'd happily want to spend time trimming your email address just so you won't be bothered by the spam plagie. Sorry, the question seems to have completely gone out of my head ... regards Steeve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From theoryboy at my-deja.com Wed Aug 30 08:44:04 2006 From: theoryboy at my-deja.com (Peter Saffrey) Date: 30 Aug 2006 05:44:04 -0700 Subject: basename with extensions Message-ID: <1156941844.769114.247000@h48g2000cwc.googlegroups.com> I'd like to resurrect this subject: http://groups.google.com/group/comp.lang.python/browse_frm/thread/11146344b03e72b6/6b2a3b0c0e902114?lnk=gst&q=basename&rnum=2#6b2a3b0c0e902114 If I have a path like this: mypath = /some/long/path/file.xml and I want "file" I currently have to do: os.path.basename(os.path.splitext(mypath)[0]) or use the slightly convoluted string method detailed in the groups link above. An optional second argument to basename to remove a specified extension, as is available in other languages like PHP and in the shell version of basename, would seem pretty sensible. Or have I missed something? Peter From python at hope.cz Wed Aug 2 07:48:00 2006 From: python at hope.cz (Lad) Date: 2 Aug 2006 04:48:00 -0700 Subject: Datetime objects Message-ID: <1154519280.363058.224110@m73g2000cwd.googlegroups.com> How can I find days and minutes difference between two datetime objects? For example If I have b=datetime.datetime(2006, 8, 2, 8, 57, 28, 687000) a=datetime.datetime(2006, 8, 1, 18, 19, 45, 765000) Thank you for help L. From cginboston at hotmail.com Tue Aug 8 02:58:05 2006 From: cginboston at hotmail.com (Chaz Ginger) Date: Tue, 08 Aug 2006 06:58:05 GMT Subject: singleton decorator In-Reply-To: <1154994782.457129.291620@75g2000cwc.googlegroups.com> References: <mailman.9064.1154993614.27775.python-list@python.org> <1154994782.457129.291620@75g2000cwc.googlegroups.com> Message-ID: <44D835FD.4070900@hotmail.com> bearophileHUGS at lycos.com wrote: > Andre Meyer: >> What is the preferred pythonic way of implementing singleton elegantly? > > Maybe to just use a module. > > Bye, > bearophile > Here is some sample code for both singleton classes and named classes that I use: > class Singleton(type): > """ > This class will allow only one instance of a type > regardless of the initialization arguments. > """ > def __init__(self, *args, **kwargs): > """ > This is done when the class is defined. > """ > type.__init__(self, *args, **kwargs) > self._instance = None > > def __call__(self, *args, **kwargs): > """ > This is called when the class is instantiated. > """ > if not self._instance : self._instance = type.__call__(self,*args,**kwargs) > return self._instance > > class namedSingleton(type): > """ > This class will allow a different singleton per initialization > argument list. This implementation does not take into account > variations in the keyword args. > """ > def __init__(self, *args, **kwargs): > """ > This is executed when the class is first defined. > """ > type.__init__(self, *args, **kwargs) > self._instances = {} > > def __call__(self, *args, **kwargs): > """ > This is called when the class is instantiated. > """ > if not args in self._instances: > self._instances[args] = type.__call__(self, *args,**kwargs ) > return self._instances[args] From tim at zoominternet.net Sun Aug 27 10:51:23 2006 From: tim at zoominternet.net (Tim Scheidemantle) Date: Sun, 27 Aug 2006 10:51:23 -0400 Subject: avoiding file corruption In-Reply-To: <1156664673.325201.271140@i42g2000cwa.googlegroups.com> References: <1156664673.325201.271140@i42g2000cwa.googlegroups.com> Message-ID: <44F1B16B.6050204@zoominternet.net> Amir Michail wrote: > Hi, > > Trying to open a file for writing that is already open for writing > should result in an exception. Look at fcntl module, I use it in a class to control access from within my processes. I don't think this functionality should be inherent to python though. Keep in mind only my processes open the shelve db so your mileage may vary. get and set methods are just for convenience This works under linux, don't know about windows. #!/usr/bin/env python import fcntl, shelve, time, bsddb from os.path import exists class fLocked: def __init__(self, fname): if exists(fname): #verify it is not corrupt bsddb.db.DB().verify(fname) self.fname = fname self.have_lock = False self.db = shelve.open(self.fname) self.fileno = self.db.dict.db.fd() def __del__(self): try: self.db.close() except: pass def aquire_lock(self, timeout = 5): if self.have_lock: return True started = time.time() while not self.have_lock and (time.time() - started < timeout): try: fcntl.flock(self.fileno, fcntl.LOCK_EX + fcntl.LOCK_NB) self.have_lock = True except IOError: # wait for it to become available time.sleep(.5) return self.have_lock def release_lock(self): if self.have_lock: fcntl.flock(self.fileno, fcntl.LOCK_UN) self.have_lock = False return not self.have_lock def get(self, key, default = {}): if self.aquire_lock(): record = self.db.get(key, default) self.release_lock() else: raise IOError, "Unable to lock %s" % self.fname return record def set(self, key, value): if self.aquire_lock(): self.db[key] = value self.release_lock() else: raise IOError, "Unable to lock %s" % self.fname if __name__ == '__main__': fname = 'test.db' dbs = [] for i in range(2): dbs.append(fLocked(fname)) print dbs[0].aquire_lock() print dbs[1].aquire_lock(1) #should fail getting flock dbs[0].release_lock() print dbs[1].aquire_lock() #should be able to get lock --Tim From phil at riverbankcomputing.co.uk Fri Aug 4 07:58:22 2006 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Fri, 4 Aug 2006 12:58:22 +0100 Subject: Which KDE IDE for Python? In-Reply-To: <1154688723.966070.27590@b28g2000cwb.googlegroups.com> References: <1154682596.419636.70320@p79g2000cwp.googlegroups.com> <4jgj6qF7n43lU1@uni-berlin.de> <1154688723.966070.27590@b28g2000cwb.googlegroups.com> Message-ID: <200608041258.22687.phil@riverbankcomputing.co.uk> On Friday 04 August 2006 11:52 am, Bart Ogryczak wrote: > Diez B. Roggisch wrote: > > Bart Ogryczak schrieb: > > > Hi, > > > Rigth now I'm using two IDEs for Python, KDevelop and Eric. Both have > > > drawbacks. KDevelop is a multilanguage IDE, and doesn't really have > > > anything special for Python. There's no Python debugger, no PyDOC > > > integration, it's class browser doesn't display attributes. On the > > > other side there's Eric, which is made just for Python. But.. it > > > doesn't integrate with KDE, doesn't support remote files (fish://, > > > ftp:// etc.). Does anyone know a better IDE for Python, that'll > > > integrate nicely with KDE? > > > > I bet you can try and convince Detlev Offenbach (eric developer) to add > > that - he already has _some_ KDE-specific stuff in there, and I presume > > supporting IO-Slaves might not be too hard. > > Actually I doubt it. For example on question why doesn't Eric use > katepart as editor, he responded: > "Because it is actually written using PyQt and is meant to work on > Win... and Mac OS X as well. Therefore it must not depend on KDE (or > any other non-portable or non-ported toolkit)." There is a huge difference between depending on something and being able to use something if it is available. Eric can't depend on katepart, but it can use the KDE standard dialogs if they are available. Phil From crystalattice at gmail.com Thu Aug 24 17:42:15 2006 From: crystalattice at gmail.com (crystalattice) Date: 24 Aug 2006 14:42:15 -0700 Subject: wxPython default radiobox choice In-Reply-To: <mailman.9829.1156454254.27775.python-list@python.org> References: <1156451235.958752.101510@i42g2000cwa.googlegroups.com> <mailman.9829.1156454254.27775.python-list@python.org> Message-ID: <1156455735.057112.237480@m73g2000cwd.googlegroups.com> Laszlo Nagy wrote: > crystalattice ?rta: > > In my GUI app, I have a radio box allowing the user to pick his/her > > gender. When I click a button, I'd like the radio box to tell the > > program which choice is marked. I can get it to work when I manually > > pick a choice but I get an error when the choice is left at the default > > value, which is "Male". > > > > I have the radio box tied to an event to "see" when a choice is made, > > but how does it work if the person just leaves the default value? I've > > looked at the wxPython demo but the radio box actions only work for > > changing values. > > > > > I'm not sure if I understood your problem. You can call the > wxRadioBox.GetSelection method anytime to get the current value. > If you need that value very often (e.g. thousand times per sec) then you > can "shadow" the default value in an instance variable. > > Example (untested): > > > class MyClass(wx.Frame): > """In this frame, you can use the curchoice variable after > construction.""" > def __init__(self): > # ... create your frame here... > r =self.radio = wx.RadioBox(self,-1,choiches=['One','Two','Three']) > # Set default value > r.SetSelection(0) # This does not cause a > wxEVT_COMMAND_RADIOBOX_SELECTED event to get emitted. > self.curchoice = 0 > # Bind the event > r.Bind( > wx.EVT_COMMAND_RADIOBOX_SELECTED, > self.OnRadioChanged, > r > ) > > > def OnRadioChanged(self,event): > self.curchoice = self.radio.GetSelection() > # Do whatever you want here... > event.Skip() Thanks for the response. I got it working now. I was trying to bind the radio box to an event, rather than just calling GetSelection(). I thought I needed to bind it to make it work (based on the wxPython demo code). From hove at ntnu.no Sun Aug 13 07:31:50 2006 From: hove at ntnu.no (Joakim Hove) Date: Sun, 13 Aug 2006 13:31:50 +0200 Subject: __LINE__ and __FILE__ functionality in Python? Message-ID: <k0nac68na6x.fsf@metropolis.phys.ntnu.no> Hello, i have simple[1] function like this: def log_msg(msg , file , line): print "%s:%s %s" % (file,line,msg) the file and line arguments should be the filename and linenumber of the source file where the function is called. If this were C I would have used the __FILE__ and __LINE__ macros as: log_msg(msg , __FILE__ , __LINE__) Is there a way to emulate this behaviour in Python? Best Regards Joakim Hove [1]: It is not *that* simple, but you get the point. -- Joakim Hove hove AT ntnu.no / Tlf: +47 (73 5)9 34 27 / Stabburveien 18 Fax: ................. / N-5231 Paradis http://www.ift.uib.no/~hove/ / 55 91 28 18 / 92 68 57 04 From sjmachin at lexicon.net Thu Aug 10 19:50:21 2006 From: sjmachin at lexicon.net (John Machin) Date: 10 Aug 2006 16:50:21 -0700 Subject: hide python code ! In-Reply-To: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> Message-ID: <1155253821.570487.165400@b28g2000cwb.googlegroups.com> Bayazee wrote: > hi > can we hide a python code ? > if i want to write a commercial software can i hide my source code from ^^^^^^^^^^^^^^^^^^^^^^^^[1] > users access ? > we can conver it to pyc but this file can decompiled ... so ...!! > do you have any idea about this ...? > > --------------------------------------- > First Iranian Open Source Community : www.python.ir ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^[2] [1] and [2] don't seem to be compatible. Really the only way to keep your code secret is not to distribute it -- provide the functionality from a web server. If you want to distribute obfuscated code, consider writing it in perl :-) From webraviteja at gmail.com Mon Aug 21 23:05:34 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 21 Aug 2006 20:05:34 -0700 Subject: What would be the best way to run python client in the background In-Reply-To: <1156133211.300891.262650@m73g2000cwd.googlegroups.com> References: <1155625271.858914.175780@m73g2000cwd.googlegroups.com> <1156131192.693874.204390@b28g2000cwb.googlegroups.com> <1156133211.300891.262650@m73g2000cwd.googlegroups.com> Message-ID: <1156215934.499144.29190@i3g2000cwc.googlegroups.com> > The reason for the a seperate persistant check is because it will be > used to enable software to be installed in whole lab of PCs but only > allow a predifined number to run the software at any time one time. > And then when a user stop using the software a licence will become > available to for someone else on the same or another PC to use the > software. The reason that the process of the software being check is > not used is because it will be used for software written by other > people. I hope this makes what and why a little clearer. Let me know > if you think that I have misunderstoood you. Hmm... I don't have experience with such architecture personally. The software being managed must have some sort of dependency on the license manager if the manager is to be external. I don't know how you can reliably manage external programs that are decoupled from the license manager. You can however create a plug-in of sorts if the other authors would be willing to incorporate it without much work to them. I mostly explored license management in Delphi apps. Since Delphi is/was a Shareware favorite, it has quite a few open source / commercial components available to manage such licensing, usually with trivial effort from the component user. You could take a look at them (http://www.torry.net/quicksearchd.php?String=shareware&Title=No). Some of them might even compile on Lazarus to expose them to Python. By large, the culture of Python is open source and such expertise may not be common place here. You might want to subscribe to the mailing lists of "Association of Shareware Professionals" (http://www.asp-shareware.org/). I have not been on this path in 5 years and so am out of touch. From larry.bates at websafe.com Thu Aug 24 09:19:55 2006 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 24 Aug 2006 08:19:55 -0500 Subject: Taking data from a text file to parse html page In-Reply-To: <1156378275.662140.214650@h48g2000cwc.googlegroups.com> References: <1156378275.662140.214650@h48g2000cwc.googlegroups.com> Message-ID: <44EDA77B.3070408@websafe.com> DH wrote: > Hi, > > I'm trying to strip the html and other useless junk from a html page.. > Id like to create something like an automated text editor, where it > takes the keywords from a txt file and removes them from the html page > (replace the words in the html page with blank space) I'm new to python > and could use a little push in the right direction, any ideas on how to > implement this? > > Thanks! > See Beautiful Soup: http://www.crummy.com/software/BeautifulSoup/ it will parse even badly formed HTML and allow you to extract/change information as you wish. -Larry Bates From aries.shuaib at gmail.com Wed Aug 16 21:06:34 2006 From: aries.shuaib at gmail.com (Shuaib) Date: 16 Aug 2006 18:06:34 -0700 Subject: How do I catch ExpatError exception? References: <1155771384.487253.152630@i42g2000cwa.googlegroups.com> <mailman.9450.1155775196.27775.python-list@python.org> Message-ID: <1155776794.631173.38540@m73g2000cwd.googlegroups.com> Steve Holden wrote: > import xml.parsers.expat Thanks, that worked. > > def r(): > return 1/0 > > try: > print r() > except: > import sys > t, v, tb = sys.exc_info() > > print "exception on line", tb.tb_lineno How do I get the helpful text that is thrown with the exception? Like if the exception is " IOError: [Errno 2] No such file or directory: 'out.xml' " How do I get the the text after IOError: ? Thanks again. From deets at nospam.web.de Sat Aug 19 12:14:02 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 19 Aug 2006 18:14:02 +0200 Subject: write eof without closing In-Reply-To: <ec7b65$pfo$1@netlx020.civ.utwente.nl> References: <ec72ev$4e0$1@netlx020.civ.utwente.nl> <pan.2006.08.19.13.56.56.122014@gmx.net> <ec7b65$pfo$1@netlx020.civ.utwente.nl> Message-ID: <4kormaFcp9ucU1@uni-berlin.de> cage schrieb: > Marc 'BlackJack' Rintsch schreef: >> In <ec72ev$4e0$1 at netlx020.civ.utwente.nl>, cage wrote: >> >>> can i write a eof to a file descriptor without closing it? >>> like: >>> fd.write(EOF) >>> or something >> >> What do you expect this to to? Writing a byte to the file and you don't >> know which value this byte has? >> >> Ciao, >> Marc 'BlackJack' Rintsch > > ok let me explain this a bit more... > I want to use a program that has a 'pipe' mode, in which you can use > stdin to send commands to the program. I found out that, when in pipe > mode and you are using the keyboard as input source you can do Ctrl-D to > 'signal' the program that you have finished typing your command. The > program parses and then performs the command, and it doesn't quit. It > quits after 'Quit\n' + Ctrl-D > Now I want a python script to provide the input, how do i do that? I now > use popen to be able to write to the program's stdin (p_stdin) > I noticed that when i do a p_stdin.close() it acts as a 'ctrl-d' in that > the program recognizes the signal to process the command, but then I > cannot use p_stdin anymore to do p_stdin.write(...) According to wikipedia (german version, but I bet you can get that info using the english one, too) C-d sends EOT - end of transmission. Which is ascii 0x04. So I suggest you try writing "\x04" to the pipe. Maybe that works. Diez From amichail at gmail.com Sun Aug 27 03:44:33 2006 From: amichail at gmail.com (Amir Michail) Date: 27 Aug 2006 00:44:33 -0700 Subject: avoiding file corruption Message-ID: <1156664673.325201.271140@i42g2000cwa.googlegroups.com> Hi, Trying to open a file for writing that is already open for writing should result in an exception. It's all too easy to accidentally open a shelve for writing twice and this can lead to hard to track down database corruption errors. Amir From gagsl-py at yahoo.com.ar Fri Aug 18 21:44:51 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 18 Aug 2006 22:44:51 -0300 Subject: Http client to POST using multipart/form-data In-Reply-To: <a53f49fd0608172306n319478c3m53d6ae8d35458013@mail.gmail.co m> References: <a53f49fd0608172306n319478c3m53d6ae8d35458013@mail.gmail.com> Message-ID: <7.0.1.0.0.20060818223248.05ad1628@yahoo.com.ar> At Friday 18/8/2006 03:06, Bruno Dilly wrote: >I'm implementing a http client to POST using multipart/form-data. It >uses urllib2 module, and files are uploaded correctly. > >But I need to know how much has been uploaded at a given moment, to >inform the user the proportion of the file already uploaded. See httplib.HTTPConnection._send_request; after sending the headers: if body: self.send(body) You should inherit from HTTPConnection and provide your feedback there - that depends on your application. Then, inherit from urllib2.HTTPHandler, and override http_open to use your custom HTTPConnection. Pass your custom HTTPHandler to build_opener and it will use it. Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From ove.svensson at ericsson.com Thu Aug 24 08:47:33 2006 From: ove.svensson at ericsson.com (Ove Svensson) Date: Thu, 24 Aug 2006 14:47:33 +0200 Subject: setuid root References: <mailman.9781.1156421578.27775.python-list@python.org> Message-ID: <eczy7te8fmi.fsf@ericsson.com> "Tiago Sim?es Batista" <baitas at zmail.pt> writes: > > Any sugestions? > http://www.faqs.org/faqs/unix-faq/faq/part4/section-7.html From bdesth.quelquechose at free.quelquepart.fr Mon Aug 28 16:19:27 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 28 Aug 2006 22:19:27 +0200 Subject: looking for data on csv files In-Reply-To: <1156793860.723758.188800@74g2000cwt.googlegroups.com> References: <1156793860.723758.188800@74g2000cwt.googlegroups.com> Message-ID: <44f34d14$0$6650$636a55ce@news.free.fr> flit a ?crit : > Hi! > I am using the csv modules.. > > when I use the command: > > if nome in row[rowcsv]: > print "\n" > print row[rowcsv] + "\n ----> " + row[11] + "\n" > print > "################################################################" Python 2.4.1 (#1, Jul 23 2005, 00:37:37) [GCC 3.3.4 20040623 (Gentoo Linux 3.3.4-r1, ssp-3.3.2-2, pie-8.7.6)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> if nome in row[rowcsv]: ... print "\n" ... print row[rowcsv] + "\n ----> " + row[11] + "\n" ... print ... Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name 'nome' is not defined Not enough code to reproduce your problem. Please post the minimal snippet reproducing your problem. > there is this case: > > 1- data on file PUItarr > > If the user try to find for puitarr or PUITARR it doesn?t find. > > I tried the string.upper and .lower , but there is a a way to look far > all possible combinations? Probably. > And yes, i am a newbie.. Don't worry - we've all been newbies. From bearophileHUGS at lycos.com Thu Aug 17 16:23:00 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 17 Aug 2006 13:23:00 -0700 Subject: New to python In-Reply-To: <mailman.9477.1155841371.27775.python-list@python.org> References: <mailman.9477.1155841371.27775.python-list@python.org> Message-ID: <1155846180.515052.33210@m79g2000cwm.googlegroups.com> Tim Gallagher: > I am new to python and I have a few questions. I am an old Perl hacker > been using Perl for many years. I wanted to give python a try, I am > happy with it so far. In some places and jobs Perl is the only scripting language used still, but It seems there are other people like you that are slowly evaporating from the Perl community and trying Python and Ruby. Welcome, and feel free to ask what you need. Bye, bearophile From sjmachin at lexicon.net Thu Aug 10 18:08:23 2006 From: sjmachin at lexicon.net (John Machin) Date: 10 Aug 2006 15:08:23 -0700 Subject: What's the cleanest way to compare 2 dictionary? References: <1155147450.628625.20270@m79g2000cwm.googlegroups.com> <1155165349.766502.314760@n13g2000cwa.googlegroups.com> <1155240726.922672.279230@i3g2000cwc.googlegroups.com> Message-ID: <1155247703.127047.57670@m79g2000cwm.googlegroups.com> John Henry wrote: > John, > > Yes, there are several scenerios. > > a) Comparing keys only. > > That's been answered (although I haven't gotten it to work under 2.3 > yet) (1) What's the problem with getting it to work under 2.3? (2) Why not upgrade? > > b) Comparing records. You haven't got that far yet. The next problem is actually comparing two *collections* of records, and you need to decide whether for equality purposes the collections should be treated as an unordered list, an ordered list, a set, or something else. Then you need to consider how equality of records is to be defined e.g. case sensitive or not. > > Now it gets more fun - as you pointed out. I was assuming that there > is no short cut here. If the key exists on both set, and if I wish to > know if the records are the same, I would have to do record by record > comparsion. However, since there are only a handful of records per > key, this wouldn't be so bad. Maybe I just overload the compare > operator or something. > IMHO, "something" would be better than "overload the compare operator". In any case, you need to DEFINE what you mean by equality of a collection of records, *then* implement it. "only a handful":. Naturally 0 and 1 are special, but otherwise the number of records in the bag shoudn't really be a factor in your implementation. HTH, John From rogue_pedro at yahoo.com Wed Aug 30 19:47:27 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 30 Aug 2006 16:47:27 -0700 Subject: TNEF decoder References: <TbDIg.1431$4O4.1306@trnddc02> <1156901227.576728.203500@74g2000cwt.googlegroups.com> <mailman.10096.1156926566.27775.python-list@python.org> Message-ID: <1156981647.830215.229470@e3g2000cwe.googlegroups.com> Hendrik van Rooyen wrote: > "Simon Forman" <rogue_pedro at yahoo.com> wrote: > > 8<----------------------------- > > > | A place I once worked at had a project that included some TNEF > | handling. There was one developer assigned fulltime to it. He was the > | one who sat at his desk hurling curses at his workstation at the top of > | his lungs, later he developed a pretty severe drinking problem. > > > Should I take this to mean: " Don't go near TNEF because your underwear will > become carnivorous and consume your genitalia? " > > - Hendrik Hahahaha! In fairness, TNEF was only a small-ish part of what was slowly driving this poor guy crazy in front of our eyes. He was trying to make some sort of server that integrated with the Evolution "groupware" thingy. I don't know much more than that because I stayed the hell away from it. FWIW, our tnef, um, "parser" or whatever it was started with one of the brightest guys (in a shop of pretty bright guys, yours truly excepted ;P) spending *months* with outlook (or whatever) and a hex editor: change one thing, export tnef, see what changed in the binary data, repeat... Remarkably, he did not descend to drinking. I don't know the state of his genitals though.. Peace, ~Simon From michiel at thingmajig.org Thu Aug 10 04:27:31 2006 From: michiel at thingmajig.org (Michiel Sikma) Date: Thu, 10 Aug 2006 10:27:31 +0200 Subject: sys.platform documentation? Message-ID: <3ECB1846-9D95-4A7F-8CBA-33457B3A5068@thingmajig.org> Hello everybody, I was thinking about making a really insignificant addition to an online system that I'm making using Python: namely, I would like it to print the platform that it is running on in a human-readable manner. I was thinking of doing it like this: import sys platforms = { 'darwin': 'Darwin', 'win32': 'Microsoft Windows', 'freebsd6': 'FreeBSD 6.0' } def version(): return '%s, running on %s.' % (NAME, platforms[sys.platform]) However, in order to populate the list of platforms, I need to know which strings sys.platform can return. I haven't found any documentation on this, but I guess that I'm not looking in the right places! Do any of you know where I can find a list of possible return values from sys.platform? I'll settle for a Python C source code file, too, if it contains strings. Regards, Michiel From bearophileHUGS at lycos.com Mon Aug 14 07:38:00 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 14 Aug 2006 04:38:00 -0700 Subject: yet another noob question In-Reply-To: <1155553769.564374.227670@75g2000cwc.googlegroups.com> References: <1155492110.659011.196280@75g2000cwc.googlegroups.com> <1155553769.564374.227670@75g2000cwc.googlegroups.com> Message-ID: <1155555480.520626.56200@75g2000cwc.googlegroups.com> Gerard Flanagan: > mod5 = ['1','2','3','4','5'] > X = [ ''.join([a,b,c,d,e]) > for a in mod5 > for b in mod5 > for c in mod5 > for d in mod5 > for e in mod5 ] A modified version of your one is the faster so far: v = "12345" r = [a+b+c+d+e for a in v for b in v for c in v for d in v for e in v] Bye, bearophile From grover.uk at gmail.com Sat Aug 26 12:55:36 2006 From: grover.uk at gmail.com (groves) Date: 26 Aug 2006 09:55:36 -0700 Subject: rollover effect In-Reply-To: <1156611065.857764.129500@b28g2000cwb.googlegroups.com> References: <1156607403.741240.25000@74g2000cwt.googlegroups.com> <1156608042.466471.210270@m73g2000cwd.googlegroups.com> <1156608554.489516.243640@h48g2000cwc.googlegroups.com> <1156609000.477885.289150@h48g2000cwc.googlegroups.com> <1156609368.745082.324510@h48g2000cwc.googlegroups.com> <1156611065.857764.129500@b28g2000cwb.googlegroups.com> Message-ID: <1156611336.747834.76610@74g2000cwt.googlegroups.com> Simon Forman wrote: > groves wrote: > > Sorry, as I am new to python so couldn't understand what yu were > > asking. > > Now the problem is that i annot use pmw in my project..is thre anyother > > alternative by which I can have a rollover mouse effect on the canvas. > > thanks > > Not a problem. Although "IDE" and "GUI" are terms that are not > specific to python. But you still haven't answered my question? Are > you using Tkinter? wxWidgets? Gtk bindings? > > Assuming that you're using Tkinter, what prevents you from using Pmw? > > Peace, > ~Simon Yes I am using Tkinter... the thing is I I m new to Tkhave not used PMW bfore..Nd inter... So just though If there is any alternative,,,as i don't have much time From gagsl-py at yahoo.com.ar Wed Aug 9 22:43:54 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 09 Aug 2006 23:43:54 -0300 Subject: os.path.normpath In-Reply-To: <1155149144.453575.181870@m79g2000cwm.googlegroups.com> References: <1155149144.453575.181870@m79g2000cwm.googlegroups.com> Message-ID: <7.0.1.0.0.20060809233142.03aa7088@yahoo.com.ar> At Wednesday 9/8/2006 15:45, nathanbullock at gmail.com wrote: >I am using a windows box and passing a string like "../foo/../foo2" to >normpath which then returns "..\\foo2". But if this string is going >into a webpage link it should really be "../foo". You could just .replace('\\','/') on the resulting string. Or use the urlparse module. >Is there any way to tell os.path.normpath to act like we are an a unix >style box? The fact than '/' is used as a path separator both on unix and on HTTP URLs should be considered as a mere coincidence (in fact it isn't...) URLs dont necesarily point to a real file on a real file system (Zope is an example). Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From zeph_zhang at yahoo.co.uk Tue Aug 15 01:17:36 2006 From: zeph_zhang at yahoo.co.uk (Zeph) Date: Tue, 15 Aug 2006 01:17:36 -0400 Subject: Mega Newbie Questions: Probably FAQs In-Reply-To: <ebrg55$13r$1@news-int2.gatech.edu> References: <E64Eg.103891$hp.90053@read2.cgocable.net> <ebrg55$13r$1@news-int2.gatech.edu> Message-ID: <qNcEg.61$dB.36@read2.cgocable.net> Zeph wrote: >> 3) Can someone recommend a good framework that will enable me to keep >> things well sorted out, and easy to maintain as my apps grow? (I'm >> considering MVC, but have no idea how to apply it until I've gone >> beyond "Hello World"). Yu-Xi Lim wrote: > Framework for what kind of apps? Web, native GUI, client-server, etc? > MVC is an abstract architecture rather than a specific implementation. > Even so, many implementations rarely employ a purely MVC design. Native GUI with some client-server abilities. Basically, it's a database-inventory sort of thing with some pretty intense reporting. Call it a productivity app--no need for intense graphics or massive computation. Fundamentally, what I want is to be able to distribute a "regular app", mainly for the Windows market, but I also want to offer it to the Mac and Linux crowd--on one code base if possible. I have on a number of occasions downloaded apps that required that Visual Basic, or .Net or whatever runtimes be installed. I've never liked or trusted these kinds of apps. Regardless of the quality that the particular thing may have had, I didn't trust it and didn't like all of the extra clutter that went along with it. This is why I'd prefer to deliver some sort of stand alone solution--or at least something that appears as such. Fundamentally, I want to put out a solid, slick and professional product. Is Python still a good choice for me? Back to the question: When I speak of framework, maybe I should have used the term "methodology". I have excellent methods for coding my web-apps (I like Fusebox) but not having created anything significant in another language from scratch for over 10 years, I wouldn't know how to start organizing my stuff so that it's long-term maintainable. > The size of the Python community is huge compared to RealBasic. And > you'll benefit from that alone by better answers to your questions, > better documentation, and better 3rd party libraries. Excellent points. > Side note: You seem like you've researched a bit, but unfortunately been > affected by the swirl of buzzwords. While there are usually valid > reasons for particular technologies to have so much hype behind them, > you should not neglect the alternatives. They may be the answer you seek. Yes. That's the problem with being a newb: you don't know what you don't know, then when you do, it's obvious. I'm still seeing only the surface. One question that does come to my mind is that of the notion of decompiling or reverse engineering. Based on a comment someone made earlier, is this a significant concern that I should have, if I want to ship commercial software? The stage I'm at right now is that I'm on the fence between REALbasic and Python. Here's how I see it, relevant to my situation: REALbasic Pros: A fairly rich system, excellent GUI, spits out a binary executable for Win, Mac and Linux. One code base. Well documented, ever evolving. Relatively reasonably priced for commercial purposes. Cons: Closed source (what if they're bought out?) I'm not sure that I can trust my investment of time to last 10 years. The language and IDE is a tad strange to me. It has the word "Basic" (read: cheap, half-assed, not-a-real-app) in it, which is not a particularly good term to use in a pitch. Unknown: Learning curve? Long-term value? Level of support? Python Pros: Free. Open source. Deep. Flexible. Rich community and third party stuff. Well documented. Cons: Interpreted. Unknown: Secure (meaning not easily reverse engineered) code? Performance? Further thoughts? From tim.golden at viacom-outdoor.co.uk Tue Aug 15 03:58:23 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 15 Aug 2006 08:58:23 +0100 Subject: What would be the best way to run python client in the background Message-ID: <CCAC78D42E32184F8E26DC163DB98306C1B36D@vogbs009.gb.vo.local> [gel] | I have written a python client server app [...] | I want to run the client end of the app more or less invisibly | (no console) on the XP clients when ever a users logs on. You say "when[]ever a user logs on" but does this app need to be run on a per-user basis? Or could it run all the time -- ie as a Windows Service -- and do enough to determine which user is logged on when it needed to? The normal way is to run a Win32 service. There are several posts on the subject around the Python and Python-Win32 mailing lists / newsgroups. The alternative is to set something to run when any user logs in to run without a window. Again, there are posts on the subject, including one I seem to remember from Robin Becker, which tell how to do this kind of thing. Let us know if you can't find anything which seems to fit the bill. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From slianoglou at gmail.com Sun Aug 6 22:44:30 2006 From: slianoglou at gmail.com (Steve Lianoglou) Date: 6 Aug 2006 19:44:30 -0700 Subject: Question about using python as a scripting language References: <1154910518.506581.26470@b28g2000cwb.googlegroups.com> Message-ID: <1154918670.836910.17940@m79g2000cwm.googlegroups.com> Hi, > I was wondering how I can read > commands from the XML file and then execute them in the game. ... > I just need some way of > being able to read from the file what function the program needs to > call next. Any help is appreciated. One thing you could do is use the eval or compile methods. These functions let you run arbitray code passed into them as a string. So, for instance, you can write: my_list = eval('[1,2,3,4]') and my_list will then be assigned the list [1,2,3,4], moreover: eval("my_list.%s" % "reverse()") or ... even further .. :-) command = "reverse" eval("my_list.%s()" % "reverse") will reverse my_list Is that something like what you're looking for? -steve From saint.infidel at gmail.com Thu Aug 10 15:34:50 2006 From: saint.infidel at gmail.com (infidel) Date: 10 Aug 2006 12:34:50 -0700 Subject: converting a nested try/except statement into try/except/else In-Reply-To: <lsHCg.2671$No6.52074@news.tufts.edu> References: <s8qCg.2663$No6.52066@news.tufts.edu> <44da4329$0$702$626a54ce@news.free.fr> <44da5e3f$0$19111$626a54ce@news.free.fr> <lsHCg.2671$No6.52074@news.tufts.edu> Message-ID: <1155238490.718107.312720@b28g2000cwb.googlegroups.com> > > try: > > if int(text) <= 0: raise ValueError > > Hmm, I'm actually not so sure about this line now. It doesn't seem right > to raise a ValueError when the result of the expression is negative, > because even though it's a problem for my program, it isn't really a > "ValueError," right? It's an invalid value to your program, so yes, it is a ValueError. From manuhack at gmail.com Mon Aug 7 13:59:01 2006 From: manuhack at gmail.com (manuhack) Date: 7 Aug 2006 10:59:01 -0700 Subject: A problem from a Vim user Message-ID: <1154973541.450774.50090@75g2000cwc.googlegroups.com> When I use raw_input('Please type something.\n') in the python 2.4 command line windows, it doesn't have any problem. However, when I run the same command in vim 7 as :py raw_input('Please type something.\n'), there is an EOFError: EOF when reading a line. Is there a way to use that command within vim without raising errors? Thanks a lot. From tim.leeuwvander at nl.unisys.com Mon Aug 21 04:28:07 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 21 Aug 2006 01:28:07 -0700 Subject: Python and STL efficiency In-Reply-To: <pan.2006.08.21.07.48.24.455806@gmx.net> References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <pan.2006.08.21.07.48.24.455806@gmx.net> Message-ID: <1156148887.390281.77580@m73g2000cwd.googlegroups.com> Marc 'BlackJack' Rintsch wrote: > In <1156143136.020647.294290 at i42g2000cwa.googlegroups.com>, Licheng Fang > wrote: > > > Hi, I'm learning STL and I wrote some simple code to compare the > > efficiency of python and STL. > > [...] > > There's a difference in data structures at least. The Python `set` type > is implemented with a hash algorithm, so the equivalent STL type would be > `hash_set`. `set` in Python does not store its contents sorted. > The set should be only 4 items in size, according to my reading of the code, so set implementation differences shouldn't lead to drastic performance differences. > Ciao, > Marc 'BlackJack' Rintsch Cheers, --Tim From blue99 at interia.pl Thu Aug 31 08:09:46 2006 From: blue99 at interia.pl (Rob Wolfe) Date: 31 Aug 2006 05:09:46 -0700 Subject: wxNotebook color change In-Reply-To: <1157020467.883961.282800@p79g2000cwp.googlegroups.com> References: <1157020467.883961.282800@p79g2000cwp.googlegroups.com> Message-ID: <1157026185.987725.275010@e3g2000cwe.googlegroups.com> mardif wrote: > Hi ! > > this is my problem: > > I've a wxNotebook object, which contains 2 Panels. > On up, there is TAB section, I have 2 tabs. > I want to color the TAB section with ( for example ) red color. > > I've tried with SetBackgroundColour() for wxNotebook object and for 2 > panel inside, but it doesn't works. > why?? Presumably you forgot to refresh window. Try this: <code> import wx app = wx.PySimpleApp() frame = wx.Frame(None, -1, "Notebook") nb = wx.Notebook(frame, -1) form1 = wx.Panel(nb, -1) nb.AddPage(form1, "Form1") form2 = wx.Panel(nb, -1) form2.SetBackgroundColour(wx.RED) nb.AddPage(form2, "Form2") nb.SetSelection(1) frame.Refresh() frame.Show(True) app.MainLoop() </code> HTH, Rob From deets at nospam.web.de Sun Aug 27 08:42:52 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 27 Aug 2006 14:42:52 +0200 Subject: How to let a loop run for a while before checking for break condition? In-Reply-To: <ecs2ck$egu$1@newsreader2.netcologne.de> References: <ecrqe1$9j$1@newsreader2.netcologne.de> <4ldfp0F1csmpU1@uni-berlin.de> <ecs2ck$egu$1@newsreader2.netcologne.de> Message-ID: <4ldiacF1ckeeU1@uni-berlin.de> > The idea is to speed up a loop by using a timer interrupt interfering > with the loop, so that only after the timer interrupt would occur, the > loop will start to check its break condition in each iteration. > No checking of any kind in the loop should happen up to that time to > minimize the number of operations in each iteration within the loop > itself (i.e. the loop more or less won't know, that there is a timer on > its way to change the loops behavior at a later time). A while loop has a condition. period. The only thing to change that is to introduce a uncoditioned loop, and use self-modifying code to make it a while-loop after that timer interrupt of yours. But of course that whole thing is a moot point - if shaving mu-secs on that level is needed for your application, use C or assembly instead. Diez From gagsl-py at yahoo.com.ar Fri Aug 18 20:44:53 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 18 Aug 2006 21:44:53 -0300 Subject: Py2Exe and sys.argv : The Lost Arguments In-Reply-To: <1155843766.143216.325400@m73g2000cwd.googlegroups.com> References: <1155843766.143216.325400@m73g2000cwd.googlegroups.com> Message-ID: <7.0.1.0.0.20060818213355.05aad248@yahoo.com.ar> At Thursday 17/8/2006 16:42, Thomas W wrote: >Is it impossible to compile a script using py2exe and pass selected >items in Explorer to my script? It works fine when called on the >command line so it might be something related to Explorer but I'm >completly lost. Yes, it is related to Explorer -some misbehaving context menu extension-. See <http://groups.google.com/group/microsoft.public.windowsxp.basics/browse_frm/thread/5d7a111f31fa7901> But, maybe next time, you could try and exclude all other variables (wxWindows, py2exe...) to keep things simple... Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From fhurley at gmail.com Tue Aug 1 11:47:08 2006 From: fhurley at gmail.com (fhurley at gmail.com) Date: 1 Aug 2006 08:47:08 -0700 Subject: Can't get LCHARVAR's with InformixDB In-Reply-To: <1154446906.915203.13790@m73g2000cwd.googlegroups.com> References: <1154437329.471918.35150@h48g2000cwc.googlegroups.com> <mailman.8792.1154437891.27775.python-list@python.org> <1154438862.714569.9130@b28g2000cwb.googlegroups.com> <mailman.8794.1154439925.27775.python-list@python.org> <1154446906.915203.13790@m73g2000cwd.googlegroups.com> Message-ID: <1154447228.669652.169320@75g2000cwc.googlegroups.com> Another thing... > Output is: > description is <('msg_tx', 'lvarchar', 0, 0, None, None, 1)> The 0's worried me, as I could see where they could be used as parms to allocate/trim things as necessary... just a thought. From jojoba12 at hotmail.com Tue Aug 22 14:27:39 2006 From: jojoba12 at hotmail.com (jojoba) Date: 22 Aug 2006 11:27:39 -0700 Subject: how do you get the name of a dictionary? In-Reply-To: <mailman.9654.1156270417.27775.python-list@python.org> References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <pan.2006.08.21.03.33.27.84160@REMOVEME.cybersource.com.au> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> <mailman.9631.1156227418.27775.python-list@python.org> <1156264475.968894.221710@p79g2000cwp.googlegroups.com> <mailman.9654.1156270417.27775.python-list@python.org> Message-ID: <1156271259.567470.86140@i3g2000cwc.googlegroups.com> > At the risk of stating the obvious, why don't you simply add a parameter > for the title in the invocation of the tree editor? I.e. instead of > invoke_tree_editor(somedict) > do > invoke_tree_editor(somedict, "somedict") > HTH, > Carsten. Thanks Carsten. This would indeed allow me to assign a title for my dicitonaries, but i am looking for something more general...... specfically: given any dictionary, get a name for it. But yeah, your way would totally work! Thanks, jojoba From anthra.norell at tiscalinet.ch Thu Aug 24 15:03:09 2006 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Thu, 24 Aug 2006 21:03:09 +0200 Subject: Taking data from a text file to parse html page References: <1156378275.662140.214650@h48g2000cwc.googlegroups.com><mailman.9767.1156402497.27775.python-list@python.org><1156431516.121577.282890@b28g2000cwb.googlegroups.com><mailman.9789.1156435175.27775.python-list@python.org> <1156441308.372327.319400@b28g2000cwb.googlegroups.com> Message-ID: <00fc01c6c7af$f0c53ca0$0201a8c0@mcuf7> You may also want to look at this stream editor: http://cheeseshop.python.org/pypi/SE/2.2%20beta It allows multiple replacements in a definition format of utmost simplicity: >>> your_example = ''' <div><p><em>"Python has been an important part of Google since the beginning, and remains so as the system grows and evolves. "</em></p> <p>-- Peter Norvig, <a class="reference" ''' >>> import SE >>> Tag_Stripper = SE.SE (''' "~<(.|\n)*?>~=" # This pattern finds all tags and deletes them (replaces with nothing) "~<!--(.|\n)*?-->~=" # This pattern deletes comments entirely even if they nest tags ''') >>> print Tag_Stripper (your_example) "Python has been an important part of Google since the beginning, and remains so as the system grows and evolves. " -- Peter Norvig, <a class="reference" Now you see a tag fragment. So you add another deletion to the Tag_Stripper (***): Tag_Stripper = SE.SE (''' "~<(.|\n)*?>~=" # This pattern finds all tags and deletes them (replaces with nothing) "~<!--(.|\n)*?-->~=" # This pattern deletes commentsentirely even if they nest tags "<a class\="reference"=" # *** This deletes the fragment # "-- Peter Norvig, <a class\="reference"=" # Or like this if Peter Norvig has to go too ''') >>> print Tag_Stripper (your_example) "Python has been an important part of Google since the beginning, and remains so as the system grows and evolves. " -- Peter Norvig, " you can either translate or delete: Tag_Stripper = SE.SE (''' "~<(.|\n)*?>~=" # This pattern finds all tags and deletes them (replaces with nothing) "~<!--(.|\n)*?-->~=" # This pattern deletes commentsentirely even if they nest tags "<a class\="reference"=" # This deletes the fragment # "-- Peter Norvig, <a class=\\"reference\\"=" # Or like this if Peter Norvig has to go too htm2iso.se # This is a file (contained in the SE package that translates all ampersand codes. # Naming the file is all you need to do to include the replacements which it defines. ''') >>> print Tag_Stripper (your_example) 'Python has been an important part of Google since the beginning, and remains so as the system grows and evolves. ' -- Peter Norvig, If instead of "htm2iso.se" you write ""=" you delete it and your output will be: Python has been an important part of Google since the beginning, and remains so as the system grows and evolves. -- Peter Norvig, Your Tag_Stripper also does files: >>> print Tag_Stripper ('my_file.htm', 'my_file_without_tags') 'my_file_without_tags' A stream editor is not a substitute for a parser. It does handle more economically simple translation jobs like this one where a parser does a lot of work which you don't need. Regards Frederic ----- Original Message ----- From: "DH" <dylanhughes at gmail.com> Newsgroups: comp.lang.python To: <python-list at python.org> Sent: Thursday, August 24, 2006 7:41 PM Subject: Re: Taking data from a text file to parse html page > I found this > http://groups.google.com/group/comp.lang.python/browse_thread/thread/d1bda6ebcfb060f9/ad0ac6b1ac8cff51?lnk=gst&q=replace+text+file&r num=8#ad0ac6b1ac8cff51 > > Credit Jeremy Moles > ----------------------------------------------- > > finds = ("{", "}", "(", ")") > lines = file("foo.txt", "r").readlines() > > for line in lines: > for find in finds: > if find in line: > line.replace(find, "") > > print lines > > ----------------------------------------------- > > I want something like > ----------------------------------------------- > > finds = file("replace.txt") > lines = file("foo.txt", "r").readlines() > > for line in lines: > for find in finds: > if find in line: > line.replace(find, "") > > print lines > > ----------------------------------------------- > > > > Fredrik Lundh wrote: > > DH wrote: > > > > > I have a plain text file containing the html and words that I want > > > removed(keywords) from the html file, after processing the html file it > > > would save it as a plain text file. > > > > > > So the program would import the keywords, remove them from the html > > > file and save the html file as something.txt. > > > > > > I would post the data but it's secret. I can post an example: > > > > > > index.html (html page) > > > > > > " > > > <div><p><em>"Python has been an important part of Google since the > > > beginning, and remains so as the system grows and evolves. > > > "</em></p> > > > <p>-- Peter Norvig, <a class="reference" > > > " > > > > > > replace.txt (keywords) > > > " > > > <div id="quote" class="homepage-box"> > > > > > > <div><p><em>" > > > > > > "</em></p> > > > > > > <p>-- Peter Norvig, <a class="reference" > > > > > > " > > > > > > something.txt(file after editing) > > > > > > " > > > > > > Python has been an important part of Google since the beginning, and > > > remains so as the system grows and evolves. > > > " > > > > reading and writing files is described in the tutorial; see > > > > http://pytut.infogami.com/node9.html > > > > (scroll down to "Reading and Writing Files") > > > > to do the replacement, you can use repeated calls to the "replace" method > > > > http://pyref.infogami.com/str.replace > > > > but that may cause problems if the replacement text contains things that > > should be replaced. for an efficient way to do a "parallel" replace, see: > > > > http://effbot.org/zone/python-replace.htm#multiple > > > > > > </F> > > -- > http://mail.python.org/mailman/listinfo/python-list From tam at ineed2.co.uk Sat Aug 19 15:56:59 2006 From: tam at ineed2.co.uk (Thomas McLean) Date: Sat, 19 Aug 2006 20:56:59 +0100 (BST) Subject: Python complaining about CherryPY? Message-ID: <59236.87.127.37.129.1156017419.squirrel@ineed2.co.uk> Hi all, First post to the list, so first off, I'm new to Python and everything surrounding it so if you can please ignore my ignorance. I setup a cherryPY server so that I could use sabnzbd but once, I have installed/configured what I was told by the tutorials and everything else. I run ubuntu x86 dapper FYI. The error messages I get from the logs are as follows (which don't really mean to muchto me): 19/Aug/2006:20:55:33 HTTP INFO Traceback (most recent call last): File "/usr/lib/python2.4/site-packages/cherrypy/_cphttptools.py", line 110, in _run applyFilters('before_finalize') File "/usr/lib/python2.4/site-packages/cherrypy/filters/__init__.py", line 151, in applyFilters method() File "/home/tam/www/sites/domain1/htdocs/SABnzbd/sabnzbd/utils/multiauth/filter.py", line 59, in beforeFinalize cherrypy.response.body = rsrc.callable(rsrc.instance, File "/home/tam/www/sites/domain1/htdocs/SABnzbd/sabnzbd/interface.py", line 116, in index info, pnfo_list, bytespersec = build_header() File "/home/tam/www/sites/domain1/htdocs/SABnzbd/sabnzbd/interface.py", line 933, in build_header header = { 'version':sabnzbd.__version__, 'paused':sabnzbd.paused(), File "/home/tam/www/sites/domain1/htdocs/SABnzbd/sabnzbd/__init__.py", line 753, in paused return DOWNLOADER.paused AttributeError: 'NoneType' object has no attribute 'paused' 127.0.0.1 - - [19/Aug/2006:20:55:33] "POST /sabnzbd/ HTTP/1.1" 500 791 "http://localhost:8080/sabnzbd/" "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.4) Gecko/20060608 Ubuntu/dapper-security Firefox/1.5.0.4" So if anyone can shed some light on this I would be very greatful. Thanks for your time. Tam. From david_wahler at bic.ky Mon Aug 21 01:27:07 2006 From: david_wahler at bic.ky (david_wahler at bic.ky) Date: 21 Aug 2006 00:27:07 -0500 Subject: =?utf-8?Q?Re:_Early_bird_registration_extended_till_end_of_August_=2D_Leipzig=0A=09Python_Workshop?= Message-ID: <20060821052707.7398.qmail@BICSRV1011.bic.ky> I'll be out of the office until approximately August 20th. If you have any questions, please email support at bic.ky. -- David Wahler From tom-2006 at jaguarpaw.get-rid-of-this-bit.co.uk Wed Aug 23 19:19:31 2006 From: tom-2006 at jaguarpaw.get-rid-of-this-bit.co.uk (Tom E H) Date: Thu, 24 Aug 2006 00:19:31 +0100 Subject: Accessing application data portably References: <mailman.9710.1156350017.27775.python-list@python.org> <44ECBEE1.6040106@websafe.com> <ecihtl$mit$1@gemini.csx.cam.ac.uk> <44ECDCFA.30601@websafe.com> Message-ID: <ecinqc$5cr$1@gemini.csx.cam.ac.uk> Larry Bates wrote: >> Well that's great, but how do you access the ini file portably? > > From my original post: > > Then I use ConfigParser in my application... Thanks, but where in the directory structure do you put the ini file on different platforms? Presumably you have to hard-code that into the source and then do operating system type detection? i.e. if I make my config parser: import ConfigParser config = ConfigParser.ConfigParser() config.read(filename) What do you use for filename on Windows? What on Linux? OSX? etc. How do you detect which operating system you are running on? Tom From robin at reportlab.com Thu Aug 17 11:58:12 2006 From: robin at reportlab.com (Robin Becker) Date: Thu, 17 Aug 2006 16:58:12 +0100 Subject: Python2.5 RC1 vs sgmlop.c In-Reply-To: <44E48D25.2000900@chamonix.reportlab.co.uk> References: <44E48D25.2000900@chamonix.reportlab.co.uk> Message-ID: <44E49214.8090406@chamonix.reportlab.co.uk> Robin Becker wrote: > I have a segfault problem in Python2.5 RC1 (win32) when using the venerable > extension sgmlop.c. ...... > Has anyone got any clue what the problem might be or a fixed version of the code? I think this is PyObject_NEW mixed with PyMem_DEL, I thought that had already come in so wasn't looking hard enough. -- Robin Becker From antroy at gmail.com Thu Aug 17 16:20:54 2006 From: antroy at gmail.com (Ant) Date: 17 Aug 2006 13:20:54 -0700 Subject: trouble understanding inheritance... In-Reply-To: <1155753183.207393.116940@m79g2000cwm.googlegroups.com> References: <1155753183.207393.116940@m79g2000cwm.googlegroups.com> Message-ID: <1155846054.684786.247980@i3g2000cwc.googlegroups.com> Try running the following example - it should help clear up what is going on: class Base: def __init__(self): print "Initializing base" def shouldBeImplemented(self): raise NotImplementedError def hasDefaultImplementation(self): print "Wey Hey!" class A(Base): def shouldBeImplemented(self): print "Has been implemented!" class B(Base): def __init__(self): Base.__init__(self) print 'Initializing B' class C(Base): def __init__(self): print "Initializing C" def hasDefaultImplementation(self): print "Boo Hoo!" base = Base() print "\n------- A --------" a = A() a.shouldBeImplemented() print "\n------- B --------" b = B() b.hasDefaultImplementation() print "\n------- C --------" c = C() c.hasDefaultImplementation() c.shouldBeImplemented() From rogue_pedro at yahoo.com Tue Aug 8 12:08:18 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 8 Aug 2006 09:08:18 -0700 Subject: binary conversion issues In-Reply-To: <1155052353.499099.293840@i3g2000cwc.googlegroups.com> References: <1155052353.499099.293840@i3g2000cwc.googlegroups.com> Message-ID: <1155053298.534222.84060@i42g2000cwa.googlegroups.com> godavemon wrote: > I'm using python's struct and binascii modules to write some values > from my parser to binary floats. This works great for all of my binary > files except one. For some reason this file is saving to 836 (stated > by my command shell) bytes instead of 832 like it should. It sounds > like an issue with whatever's writing that particular file out but I've > checked it 100 times. Also python can read in the 836 byte file, find > it has a size of 832 bytes and convert back each value perfectly. > However, when I read in the file in C++ it finds a file of size 836 and > in the middle of the data starts spitting out junk. Has anyone run > into an issue like this or have an idea of what it could be? Not enough information. Code and data samples would help. From manatlan at gmail.com Wed Aug 23 03:56:22 2006 From: manatlan at gmail.com (manatlan at gmail.com) Date: 23 Aug 2006 00:56:22 -0700 Subject: Python bindings for picasaweb ... Message-ID: <1156319782.376107.318000@74g2000cwt.googlegroups.com> Just a post to announce some python bindings for picasaweb (photo's service of google). ---> PycasaWeb (GPL), http://manatlan.infogami.com/pycasaweb I think it may be usefull for linux users, because it's one of the only way to post pictures on picasaweb. And can be usefull to script batch with it ... and our wonderful python box ;-) It's inspired from the recent google-sharp module : http://svn.myrealbox.com/viewcvs/trunk/google-sharp/?rev=63077 I will try to implement others api, but contributions are accepted ;-) From anthony at python.org Thu Aug 17 10:17:38 2006 From: anthony at python.org (Anthony Baxter) Date: Fri, 18 Aug 2006 00:17:38 +1000 Subject: RELEASED Python 2.5 (release candidate 1) Message-ID: <200608180017.52057.anthony@python.org> On behalf of the Python development team and the Python community, I'm happy to announce the first RELEASE CANDIDATE of Python 2.5. This is not yet the final release - it is not suitable for production use. It is being released to solicit feedback and hopefully expose bugs, as well as allowing you to determine how changes in 2.5 might impact you. As a release candidate, this is one of your last chances to test the new code in 2.5 before the final release. *Please* try this release out and let us know about any problems you find. In particular, note that changes to improve Python's support of 64 bit systems might require authors of C extensions to change their code. More information (as well as source distributions and Windows and Universal Mac OSX installers) are available from the 2.5 website: http://www.python.org/2.5/ As of this release, Python 2.5 is now in *feature freeze*. Unless absolutely necessary, no functionality changes will be made between now and the final release of Python 2.5. The plan now is to let the release candidate shake out any last-minute bugs in Python 2.5, leading to a 2.5 final release in early September. PEP 356 includes the schedule and will be updated as the schedule evolves. At this point, any testing you can do would be greatly, greatly appreciated. The new features in Python 2.5 are described in Andrew Kuchling's What's New In Python 2.5. It's available from the 2.5 web page. Amongst the language features added include conditional expressions, the with statement, the merge of try/except and try/finally into try/except/finally, enhancements to generators to produce a coroutine kind of functionality, and a brand new AST-based compiler implementation. New modules added include hashlib, ElementTree, sqlite3, wsgiref, uuid and ctypes. In addition, a new profiling module cProfile was added. Enjoy this new release, Anthony Anthony Baxter anthony at python.org Python Release Manager (on behalf of the entire python-dev team) -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 198 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20060818/a331c29d/attachment.sig> From nospam at invalid.com Sat Aug 12 11:10:30 2006 From: nospam at invalid.com (Jack) Date: Sat, 12 Aug 2006 08:10:30 -0700 Subject: Looking for a text file based wiki system written in Python Message-ID: <RpKdneu1J9f6ckDZnZ2dnUVZ_qKdnZ2d@comcast.com> I'd like to set up a wiki system for a project I'm working on. Since I'm not good at databases, and there's really not much stuff to put into the wiki, I hope it is text file-based. I used DokuWiki before, which is very nice but it's written in PHP. Is there a similar system that's written in Python? I found pwyky but it's functionality is a bit too simple. From jorge.vargas at gmail.com Mon Aug 28 23:26:37 2006 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Mon, 28 Aug 2006 23:26:37 -0400 Subject: How ahead are you guys in the (Python) real world? In-Reply-To: <1156821234.820929.299740@p79g2000cwp.googlegroups.com> References: <1156821234.820929.299740@p79g2000cwp.googlegroups.com> Message-ID: <32822fe60608282026y83009cx8f9bc3ae81107889@mail.gmail.com> On 28 Aug 2006 20:13:54 -0700, Ray <ray_usenet at yahoo.com> wrote: > Since I haven't used Python at work, I am using Python 2.5 right now. > However I wonder, how fast are you guys moving from version to version > at work? As an illustration my ex-company just moved to Java 5, which > was released around... what, 2-3 years ago? (While I am running Java 6 > at home) > > Is it the same in the Python world? What version of Python is used in, > say, Google? Is it even 2.4 yet? for ones 2.5 is not consider production code yet so noone should be running anything on it. same with 1.6. on the java side my company is still stuck at 1.4, some prod servers ar 1.3 :) , and my branch moved to 1.5 like 2 months ago. but again I wont use anything that is in release candidates for production. but thats just me > > -- > http://mail.python.org/mailman/listinfo/python-list > From andy.terrel at gmail.com Wed Aug 23 10:14:58 2006 From: andy.terrel at gmail.com (Andy Terrel) Date: 23 Aug 2006 07:14:58 -0700 Subject: Python bindings for picasaweb ... In-Reply-To: <1156319782.376107.318000@74g2000cwt.googlegroups.com> References: <1156319782.376107.318000@74g2000cwt.googlegroups.com> Message-ID: <1156342498.529402.322430@74g2000cwt.googlegroups.com> sweet. I'll definitely be trying to use this. manatlan at gmail.com wrote: > Just a post to announce some python bindings for picasaweb (photo's > service of google). > ---> PycasaWeb (GPL), http://manatlan.infogami.com/pycasaweb > I think it may be usefull for linux users, because it's one of the only > way to post pictures on picasaweb. And can be usefull to script batch > with it ... and our wonderful python box ;-) > > It's inspired from the recent google-sharp module : > http://svn.myrealbox.com/viewcvs/trunk/google-sharp/?rev=63077 > > I will try to implement others api, but contributions are accepted ;-) From supercrazy74 at gmail.com Wed Aug 23 03:36:11 2006 From: supercrazy74 at gmail.com (supercoder) Date: 23 Aug 2006 00:36:11 -0700 Subject: Translating Javascript programs to python. In-Reply-To: <1156264202.542785.172270@74g2000cwt.googlegroups.com> References: <1156264202.542785.172270@74g2000cwt.googlegroups.com> Message-ID: <1156318571.722528.127110@h48g2000cwc.googlegroups.com> Vyz wrote: > Hi, > I have a script with hundreds of lines of javascript spread accross 7 > files. Is there any tool out there to automatically or > semi-automatically translate the code into python. > > Thanks > Vyz Not a tool, but assuming the javascript is not too complex you could interpret some of it using python and the CGI module. But really, what would be the use? From aaronwmail-usenet at yahoo.com Fri Aug 4 10:25:23 2006 From: aaronwmail-usenet at yahoo.com (aaronwmail-usenet at yahoo.com) Date: 4 Aug 2006 07:25:23 -0700 Subject: Need a compelling argument to use Django instead of Rails References: <mailman.8642.1154064538.27775.python-list@python.org> <1154077105.746752.153440@h48g2000cwc.googlegroups.com> <1154080209.603694.161170@i42g2000cwa.googlegroups.com> <1154092298.714808.158250@75g2000cwc.googlegroups.com> <44ca3420$0$30140$636a55ce@news.free.fr> <jeokc2tisel285nois1ini5qhh0o70m2s6@4ax.com> <5hnlc25hfj56btkhdamfdi5gb5a3b8ts45@4ax.com> <mailman.8731.1154352939.27775.python-list@python.org> <1154354727.457387.142840@h48g2000cwc.googlegroups.com> <3scsc252be3d7a814ogj1ibnud3aothc1l@4ax.com> <1154512062.251725.177140@m73g2000cwd.googlegroups.com> <7xejvz5mwj.fsf@ruckus.brouhaha.com> <1154638178.465322.198390@i3g2000cwc.googlegroups.com> <1154700274.659320.292690@m79g2000cwm.googlegroups.com> Message-ID: <1154701523.068720.260140@b28g2000cwb.googlegroups.com> Ben Sizer wrote: > aaronwmail-usenet at yahoo.com wrote: > > Paul Rubin wrote: > > > A typical shared hosting place might > > > support 1000's of users with ONE apache/php instance (running in a > > > whole bunch of threads or processes, to be sure). > > > > You just need to run multiple apache > > instances, which is advisable anyway. > > The hosting service formerly known as > > python-hosting has been doing this > > for years. > > Would you need one instance per user? Is it practical to run 1000s of > Apache instances on one server? > I'm almost certain Apache spawns instances as needed. If they are all active at the same time you will need at least that many threads anyway and I don't think processes are really much more expensive than threads usually. But I'm not an expert on virtual hosting or apache or even thread/process internals. However when I do a "ps -aef" on my shared server (http://www.xfeedme.com) I only see the apache instances that are active, and not the 50 dormant ones, if I recall. -- Aaron Watters === She was flirty, dirty, musta been about thirty -- 70's stones lyrics She was nifty, shifty musta been about fifty -- 90's stones lyrics From belred at gmail.com Fri Aug 18 17:21:40 2006 From: belred at gmail.com (Bryan) Date: Fri, 18 Aug 2006 14:21:40 -0700 Subject: PyThreadState_Swap(NULL) Message-ID: <ec5b3m$puo$1@sea.gmane.org> hi, i've written a program that uses python c api code that lives in a shared library that is loaded by a custom apache module (mod_xxx). this python c api code all works correctly under our test server and under apache but only if mod_python isn't loaded. when apache loads mod_python as shown in the http.conf snippet below, PyThreadState_Swap(NULL) in mod_xxx returns NULL. when the snippet of code in http.conf is commented out, it works again. what do i have to do to have mod_xxx code work correctly when apache loads mod_python? failure case when apache loads mod_python: Py_Initialize() succeeded PyThreadState_Swap(NULL) failed sucess case when apache doesn't load mod_python: Py_Initialize() succeeded PyThreadState_Swap(NULL) succeeded thanks, bryan --- mod_xxx --- Py_Initialize(); if (Py_IsInitialized()) { log("Py_Initialize() succeeded"); } else { log("Py_Initialize() failed"); } PyEval_InitThreads(); g_py_main_interpreter = PyThreadState_Swap(NULL); PyThreadState_Swap(g_py_main_interpreter); PyEval_ReleaseLock(); if (g_py_main_interpreter) { log("PyThreadState_Swap(NULL) succeeded"); } else { log("PyThreadState_Swap(NULL) failed"); } ---- apache's http.conf ---- LoadModule python_module "../apache/bin/mod_python.so" Listen 4119 <VirtualHost _default_:4119> <Directory "C:/Program Files/Foo"> SetHandler mod_python PythonHandler mod_python.publisher PythonDebug Off </Directory> </VirtualHost> From steve at holdenweb.com Mon Aug 28 01:23:43 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 28 Aug 2006 06:23:43 +0100 Subject: Python + Java Integration In-Reply-To: <BE0BE96E-3C85-40F7-A0A6-C839415D8599@snowtide.com> References: <mailman.35559.1156348202.27774.python-list@python.org> <BE0BE96E-3C85-40F7-A0A6-C839415D8599@snowtide.com> Message-ID: <ectujv$pph$1@sea.gmane.org> Chas Emerick wrote: > On Aug 23, 2006, at 11:50 AM, Ben Sizer wrote: [...] > > I was having a discussion with a friend of mine recently, where I told > him how depressed I became for a period after I realized that sales, > marketing, and perception are all that really matter in this kooky > technical world we spend so much time in. For years I thought that That's an overstatement. They aren't "all that matter", although there is undoubtedly a section of the community (many of them in senior positions and with pointy hairstyles) that can be and is swayed more by marketing hype than by technical issues. > "most people" make technical decisions based on the facts on the ground > and the merits of each alternative. While that's a great ideal to > aspire to, it's not realistic as long as technical laypersons make very > technical decisions -- in such an environment, heuristics, guidelines, > and rules-of-thumb rule. Ergo, it's good to have marketing firepower, > because that can move the needle on rules-of-thumb *really* easily. > Yes, but then look at the resources that deploying "marketing firepower" requires, and ask yourself where those resources are going to come from. I don't know how much you know about the Python Software Foundation, but in essence it has very limited manpower, and certainly doesn't have the skills or experience to provide large amounts of "marketing firepower". > So, back on topic, I think regardless of how we got here, or who's > better (Ruby or Python -- and really, it's better for the larger > universe of 'agile' languages to grow anyway), if we want to improve > Python's attractiveness to mainstream Java developers and their > managers, providing (and promoting!) an easy migration route like JPype > is a no-brainer. > I appreciate your enthusiasm, but I'd like to just temper it a little by pointing out that no change of this size to the Python distribution is "a no-brainer", as a brief perusal of either the python-checkins or the python-dev lists will confirm. This is engineering work, and release engineering is neither simple nor straightforward. Just as a first issue, can you provide a version of JPype that will work out of the box irrespective of which version of which virtual machine the user installing Python happens to have on their computer? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From laurent.pointal at limsi.fr Wed Aug 2 03:21:00 2006 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Wed, 02 Aug 2006 09:21:00 +0200 Subject: Programming newbie coming from Ruby: a few Python questions In-Reply-To: <1154458926.738922.156910@h48g2000cwc.googlegroups.com> References: <1154458926.738922.156910@h48g2000cwc.googlegroups.com> Message-ID: <eapjot$o75$1@upsn250.cri.u-psud.fr> simonharrison at fastmail.co.uk a ?crit : ... > Ideally, I'd like a whole series of projects where I'm walked through > how to go about writing real Python. The way I look at it, nobody > learnt to build a house just from reading about building materials! Take a look at "Dive Into Python" from Mark Pilgrim, good examples with comments. http://diveintopython.org/ Its available as paper-print or as electronic reading. A+ Laurent. From mail at microcorp.co.za Mon Aug 21 02:32:29 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 21 Aug 2006 08:32:29 +0200 Subject: Input from the same file as the script References: <1156096945.924216.14380@m73g2000cwd.googlegroups.com> <spghe2h4v7gq8fajdk5p5ergh42ucakcc9@4ax.com> Message-ID: <014001c6c4ee$5b8d8660$03000080@hendrik> "Dennis Lee Bieber" <wlfraed at ix.netcom.com> Wrote: | On 20 Aug 2006 11:02:25 -0700, poggle.themammal at gmail.com declaimed the | following in comp.lang.python: | | > Can the input to the python script be given from the same file as the | > script itself. e.g., when we execute a python script with the command | > 'python <scriptName', can the input be given in someway ? | > | Redirecting? Ugh... | | Off-hand, I'd say NO | | There is no way to tell the python interpreter where the program | ends and the "run data" begins. You *could* jump through a hoop like this one: ListOfInput = ['first input', 'second input', .......'last input'] and then read the elements of the list one by one... You will probably have to make the list global to get it to work... But I kind of agree with Dennis - I would not do it that way either - reading the inputs from the stdin console is easy enough, or if there are just a few of them, getting them as command line arguments is arguably even easier - and if its a whole bunch of stuff that is painstaking to type in every time - put it in a text file and read it line by line. - Hendrik - From aleax at mac.com Fri Aug 11 01:45:05 2006 From: aleax at mac.com (Alex Martelli) Date: Thu, 10 Aug 2006 22:45:05 -0700 Subject: __contains__ vs. __getitem__ References: <fooCg.18589$qw5.15856@trnddc06> <mailman.9169.1155161214.27775.python-list@python.org> Message-ID: <1hjvlsg.1dwwmc91l0ywvzN%aleax@mac.com> Pedro Werneck <pedro.werneck at terra.com.br> wrote: > On Wed, 09 Aug 2006 16:51:23 GMT > "David Isaac" <aisaac0 at verizon.net> wrote: > > > Looking forward: > > Can I count on this independence of __getitem__ and __contains__? > > I would like to understand whether it will be safe to count on this > > behavior. > > With the builtin 'dict' implementation, dict.__contains__() use the > dict_has_key() C function, and does not touch your subclass __getitem__ > python method. I don't think it can be called 'safe'... it may lead to > very inconsistent behavior. It's like overridind both __eq__ and __ge__ > with a different behavior. It's better for you to override > __contains__() too. I think it's perfectly safe -- that's what defaultdict in Python 2.5 does, after all. Alex From bearophileHUGS at lycos.com Tue Aug 15 19:12:11 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 15 Aug 2006 16:12:11 -0700 Subject: idea on how to get/set nested python dictionary values In-Reply-To: <1155682138.572677.231460@h48g2000cwc.googlegroups.com> References: <1155663671.716249.18780@m79g2000cwm.googlegroups.com> <1155678816.942660.296140@74g2000cwt.googlegroups.com> <1155682138.572677.231460@h48g2000cwc.googlegroups.com> Message-ID: <1155683531.390235.41580@74g2000cwt.googlegroups.com> Like for the list.sort() method, to remind you that this function operate by side effect, maybe it's better if it doesn't return the modified nested dict: def setNested(nest, path, val): nest2 = nest for key in path[:-1]: nest2 = nest2[key] nest2[path[-1]] = val Bye, bearophile From bdesth.quelquechose at free.quelquepart.fr Thu Aug 31 18:05:56 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 01 Sep 2006 00:05:56 +0200 Subject: SQLObject or SQLAlchemy? In-Reply-To: <A4GJg.2722$No6.53312@news.tufts.edu> References: <A4GJg.2722$No6.53312@news.tufts.edu> Message-ID: <44f75a73$0$28545$626a54ce@news.free.fr> John Salerno a ?crit : > Are there any major differences between these two? Yes. SQLAlchemy is, mainly, a very higher-level DB-API that makes working with a RDBMS almost transparent (no embedded SQL unless you really wants to) without trying to pretend there's no RDBMS nor forcing you into ORM mode. ORM facilities are built on top of this. > It seems they can > both be used with TurboGears, and SQLAlchemy with Django. I'm just > wondering what everyone's preference is, and why, I'd say SQLAlchemy. I've used Django's ORM (pre 'magic-removal' version) and played a bit with SQLObject, but after an afternoon playing with SQLAlchemy and browsing the doc, I don't wan't to hear of them anymore. > and if there are even > more choices for ORM. There is. But nothing as exceiting as SQLAlchemy IMHO. Now FWIW, installing and testing is probably the quickest way to make your own opinion. From gagsl-py at yahoo.com.ar Thu Aug 24 12:04:04 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 24 Aug 2006 13:04:04 -0300 Subject: Newbie question about numpy In-Reply-To: <e4hre29hpv4ef1spfbqsu2hq0ee4apgdpv@4ax.com> References: <e4hre29hpv4ef1spfbqsu2hq0ee4apgdpv@4ax.com> Message-ID: <7.0.1.0.0.20060824130043.01ec6268@yahoo.com.ar> At Thursday 24/8/2006 12:38, Paul Johnston wrote: >from numpy import * > >a = array([[1,2,3],[4,5,6],[1,2,3]]) >b = array([[1,3,6],[2,5,1],[1,1,1]]) >print "a * b is \n", a * b > >I know its a long time since my degree but that's not matrix >multiplication is it ? No, it's plain element-by-element multiplication. You want matrixmultiply: http://numpy.scipy.org/numpydoc/numpy-9.html#pgfId-36542 Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From quncao at gmail.com Tue Aug 8 20:17:58 2006 From: quncao at gmail.com (Qun Cao) Date: 8 Aug 2006 17:17:58 -0700 Subject: beginner questions on embedding/extending python with C++ In-Reply-To: <4jr5jsF9d813U1@uni-berlin.de> References: <1155029311.885266.131980@m73g2000cwd.googlegroups.com> <4jr5jsF9d813U1@uni-berlin.de> Message-ID: <1155082678.622886.268960@n13g2000cwa.googlegroups.com> Thanks Diez, It is a good relief that I only need to wrap the classes I need. I decide to try Boost first because it seems to have a wider audience than SIP, but I would definately look into SIP if I want to do Qt development in the future. Diez B. Roggisch wrote: > > Since the main program is still going to be the C++ application, I > > guess we need to embedding the python scripts in the C++ code. So at > > initialization stage, the python script needs to be loaded into the C++ > > code. And this code can be simple, like > > player = Player() > > game.loadPlayer(player) > > > > > > But for this to work, the python code needs to know the Player class, > > is it right? Does that mean I need to build a python wrapper class for > > Player and "import Player" in the python code? But because this > > application is built on top of a game engine, Player class inherits > > many classes from there, I cannot possibly wrapping them all, right? > > Also, some global objects are probably needed in this code of adding > > players, how can the python code access the > You should look into SIP besides the tools you already mentioned - IMHO it > is the best choice for wrapping C++. > > And yes, you need to wrap classes - but only those that are of interest for > you! So if you need Player, wrap Player. No need to wrap it's base-classes, > unless you want these for other purposes, too. > > And for global objects I'd create functions which return these. > > I suggest you try and download a project that uses one of the possible > toolkits for wrapping - the most prominent user of SIP is of course PyQt. > Go and have a look at the source, how things are done. There aresome > tutorials I think, google should help you on that. > > HTH Diez From aleax at mac.com Wed Aug 2 21:29:54 2006 From: aleax at mac.com (Alex Martelli) Date: Wed, 2 Aug 2006 18:29:54 -0700 Subject: Windows vs. Linux References: <1154301694.445639.99580@m79g2000cwm.googlegroups.com> <44cddfb3$0$7761$7a628cd7@news.club-internet.fr> <e%szg.3$gY6.1@newssvr11.news.prodigy.com> <slrnecustl.dsk.sybrenUSE@schuimige.stuvel.eu> <mailman.8814.1154454507.27775.python-list@python.org> <slrnecvati.eia.sybrenUSE@schuimige.stuvel.eu> <mailman.8825.1154473236.27775.python-list@python.org> <slrned0lr7.f6d.sybrenUSE@schuimige.stuvel.eu> <mailman.8845.1154526941.27775.python-list@python.org> <Pk2Ag.2623$No6.51588@news.tufts.edu> <slrned1dlu.gbe.sybrenUSE@schuimige.stuvel.eu> <mailman.8862.1154546440.27775.python-list@python.org> <slrned235l.go1.sybrenUSE@schuimige.stuvel.eu> <mailman.8871.1154558807.27775.python-list@python.org> <slrned2fm7.hvq.sybrenUSE@schuimige.stuvel.eu> Message-ID: <1hjgg8z.d6szy7rx0yl3N%aleax@mac.com> Sybren Stuvel <sybrenUSE at YOURthirdtower.com.imagination> wrote: > Gerhard Fiedler enlightened us with: > > I don't know how many reasons you need besides backward > > compatibility, but all the DOS (still around!) and Windows apps that > > would break... ?!? I think breaking that compatibility would be > > more expensive than the whole Y2k bug story. > > Microsoft could provide an emulated environment for backward > compatability, just like Apple did. Wouldn't know what that would > cost, though. I believe Microsoft could have saved many billions of dollars of development costs, and hit the market well in time for the 2006 holiday season, if they had designed Vista that way -- a totally new system, wih no direct compatibility constraints, and with virtualization used to run XP stuff. That strategy (in the Mac OS 9 -> Mac OS X migration path, with "Classic" as the ``virtualization'' layer) is what saved Apple's bacon when all attempts to craft compatible extensions of old Mac OS had floundered in excessive costs and complexity. And virtualization is obviously a prepotently emerging technology -- look at VMWare's huge profits, at Microsoft's purchase of the makers of VirtualPC, at the rise of Parallels, at open-source developments such as QEMU and Xen... > I think the folks at microsoft are used to getting cursed at :) Particularly by their stockholders, with the stock down from a high of almost 60 to the recent lows of below 22...:-) Alex From exarkun at divmod.com Tue Aug 15 13:31:45 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 15 Aug 2006 13:31:45 -0400 Subject: How to tell machines endianism. In-Reply-To: <1155661562.050063.239830@h48g2000cwc.googlegroups.com> Message-ID: <20060815173145.1717.819472414.divmod.quotient.23397@ohm> On 15 Aug 2006 10:06:02 -0700, KraftDiner <bobrien18 at yahoo.com> wrote: >How can you tell if the host processor is a big or little endian >machine? > sys.byteorder Jean-Paul From david_wahler at bic.ky Fri Aug 4 11:36:58 2006 From: david_wahler at bic.ky (david_wahler at bic.ky) Date: 4 Aug 2006 10:36:58 -0500 Subject: =?utf-8?Q?Re:_[ANNOUNCE]_Thirty=2Dfourth_release_of_PythonCAD_now_available?= Message-ID: <20060804153658.22064.qmail@BICSRV1011.bic.ky> I'll be out of the office until approximately August 20th. If you have any questions, please email support at bic.ky. -- David Wahler From bumtool at yahoo.com Thu Aug 10 07:53:44 2006 From: bumtool at yahoo.com (kilnhead) Date: 10 Aug 2006 04:53:44 -0700 Subject: Looking for an intellisense with good help IDE for Python In-Reply-To: <mailman.9094.1155044663.27775.python-list@python.org> References: <1155022590.845074.256900@i42g2000cwa.googlegroups.com> <cfb578b20608080636m3d6088a6qcdbdabf5396ebd0d@mail.gmail.com> <mailman.9094.1155044663.27775.python-list@python.org> Message-ID: <1155210824.450735.69590@m73g2000cwd.googlegroups.com> I run PyDev and Eclipse on a 800mhz Celeron without any trouble. Just a bit slow. Michiel Sikma wrote: > I can attest to PyDev being an excellent extension to Eclipse. But > Eclipse kind of requires a heavy machine to run, being a gigantic > Java program. > > Michiel > > Op 8-aug-2006, om 15:36 heeft Fabio Zadrozny het volgende geschreven: > > > Have you checked pydev: http://pydev.sf.net > > > > Cheers, > > > > Fabio From donn at u.washington.edu Thu Aug 10 12:11:53 2006 From: donn at u.washington.edu (Donn Cave) Date: Thu, 10 Aug 2006 09:11:53 -0700 Subject: Make Object Oriented? References: <mailman.9193.1155209007.27775.python-list@python.org> <1155211932.632684.185920@m73g2000cwd.googlegroups.com> Message-ID: <donn-1C7BC5.09115310082006@gnus01.u.washington.edu> In article <1155211932.632684.185920 at m73g2000cwd.googlegroups.com>, "Simon Hibbs" <simon.hibbs at gmail.com> wrote: > I can't even vaguely concieve of how such a think could work, even at a > trivial, hypothetical level. The code converter would ahve to actualy > understand at a general level what the program does and how it does it, > then come up with an orriginal way to solve the same problem using a > different methodology. > > As to the simple case, even here, the converter would have to make > inteligent decisions. Which methods and properties should it move to > the base class, and which should it keep local? What criteria might it > use for making such a choice? How could you be sure that the decisions > it made would be useful or appropriate? Yes indeed. This must be OO fever in its most rarified form - the notion that even mechanical conversion to OO would be an improvement. Donn Cave, donn at u.washington.edu From rogue_pedro at yahoo.com Fri Aug 25 01:58:23 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 24 Aug 2006 22:58:23 -0700 Subject: lazy arithmetic References: <1156476992.102203.304450@p79g2000cwp.googlegroups.com> <mailman.9840.1156481380.27775.python-list@python.org> <1156483096.397300.110210@75g2000cwc.googlegroups.com> Message-ID: <1156485503.816318.315150@75g2000cwc.googlegroups.com> pianomaestro at gmail.com wrote: > Gabriel Genellina wrote: > > At Friday 25/8/2006 00:36, pianomaestro at gmail.com wrote: > > > > ># This is what I have in mind: > > > > > >class Item(object): > > > def __add__(self, other): > > > return Add(self, other) > > > > And this works fine... why make thinks complicated? > > Yes, I agree it's simpler, and up until now that's the way > I always did it. Many Many times. > Now I am looking for a way to build ensembles of these lazy classes at > the meta-level. > (think abstract algebra). > > > >Item.__add__ = Add > > > > This doesn't make sense... __add__ should be a method, not a class... > > No, that's not true. It can be this callable: > > def add(a, b): > return Add(a,b) > Item.__add__ = add But that's a function, not a class. When you assign add to an attribute of Item it "magically" becomes a method of Item: |>> add <function add at 0xb6f3b95c> |>> Item.__add__ <unbound method Item.add> |>> x.__add__ <bound method Item.add of <__main__.Item object at 0xb6f3af2c>> So it works fine. > > So my thinking was this: why can't I use a callable class ? > When you assign a class to an attibute (be it __add__ or __banana__ or anything else) the "magic" doesn't take place: |>> Add <class '__main__.Add'> |>> Item.__banana__ = Add |>> Item.__banana__ <class '__main__.Add'> > > x+y get translated to x.__add__(y) > > No that's not true at all. The self argument to __add__ ends > up being the Add instance, not the Item instance: No, that's *exactly* true. "x+y" does mean "x.__add__(y)" and "x.__add__" *is* the class Add, so you're really calling "Add(y)", nothing more nor less. x+y => x.__add__(y) => (x.__add__)(y) => Add(Y) => Hello new Add instance, here's a y for you... :-) > > z=x+y is translated to z.__add__(y) Nope. Just plain wrong. Not sure why you'd think that. (No offense intended.) Peace, ~Simon F. > > Simon. From ziga.seilnacht at gmail.com Mon Aug 7 03:55:20 2006 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 7 Aug 2006 00:55:20 -0700 Subject: Python Projects Continuous Integration References: <1154087739.722910.110310@b28g2000cwb.googlegroups.com> Message-ID: <1154937320.090143.204600@n13g2000cwa.googlegroups.com> Dave Potts wrote: > Hi, > > I'm just starting a development project in Python having spent time in > the Java world. I was wondering what tool advice you could give me > about setting up a continuous integration environment for the python > code: get the latest source, run all the tests, package up, produce the > docs, tag the code repository. I'm used to things like Maven and > CruiseControl in the Java world. > > Cheers, > > Dave. Buildbot might be what you are looking for: http://buildbot.sourceforge.net/ Hope this helps, Ziga From ajaksu at gmail.com Thu Aug 17 09:27:28 2006 From: ajaksu at gmail.com (ajaksu) Date: 17 Aug 2006 06:27:28 -0700 Subject: OT: p-gal website In-Reply-To: <Xns981FAA7EBBB4Ccastleamber@130.133.1.4> References: <mailman.9307.1155566167.27775.python-list@python.org> <7xk65buyf9.fsf@ruckus.brouhaha.com> <mailman.9312.1155572118.27775.python-list@python.org> <1155575797.856782.26370@p79g2000cwp.googlegroups.com> <mailman.9318.1155578844.27775.python-list@python.org> <1155588214.070179.224540@75g2000cwc.googlegroups.com> <Xns981FAA7EBBB4Ccastleamber@130.133.1.4> Message-ID: <1155821248.403265.149530@p79g2000cwp.googlegroups.com> John Bokma wrote: > "ajaksu" <ajaksu at gmail.com> wrote: > > > Don't :) > > Even Firefox developers will tell you to avoid this. Develop for > > standards compliant browsers (including Firefox) by testing against > > the standards. Neither your HTML or CSS pass validation, both due to > > minor, easy-to-fix issues. > > If you actually read those "standards" you will know that the documents > itself are called Recommendations or Working drafts. Why someone > recommends to follow documentation but isn't even able to name them as > they are named in the documentation itself is beyond me. Hi John, sorry about the delay (been offline for a couple of days). First I'd like to point out that I didn't mean to be rude or attack Paolo, I invested some time trying to diagnose the problems with his site and in fact I'm kinda working for him this morning :) Then, I'd ask you to read his post, as it was the first use of standard: "standard compliance problem". And to answer your question, I recommend to follow standards because that's how I call the mixed bag of Recommendations, some of which are also Specifications, allowing for the inclusion of both significant Standards and standards. I guess I must've been bitten by the buzzword bug, sorry it that offends you. But I'm not the only one (TM). > This is the W3C Markup Validation Service, a free service that checks Web > documents in formats like HTML and XHTML for conformance to W3C > Recommendations and other standards. > http://validator.w3.org/ This seems to imply that W3C considers Recommendations to be standards (sorry if I'm mistaken, my English is not that good). > Support for open Web standards in Firefox ensures you can get the most > out of this emerging class of Web-based tools. > http://www.mozilla.com/firefox/ I guess this is why we were using that word, given the Firefox context. So I might be "able to name them as they are named in the documentation(sic) itself", but I'd rather try to help than offer qwerty sacrifices to the Holy Dictionary and His trolly followers ;) Daniel > The Web Standards Project is a grassroots coalition fighting for standards > which ensure simple, affordable access to web technologies for all. > http://www.webstandards.org/ > While Opera is well capable of showing standards-compliant pages correctly, > not all web pages are compliant. > http://www.opera.com/docs/specs/doctype/ > (A)uthors are forced to choose between writing valid, standards-compliant > documents and providing content that renders properly on the browsers of > most visitors. > http://en.wikipedia.org/wiki/XHTML > Although the rise of web standards has done much to alleviate the plight of > web developers, browsers may still have sharply different opinions on one > bit of CSS or JavaScript. > http://www.quirksmode.org/browsers/intro.html > Standard > A specification for hardware or software that is either widely used and > accepted (de facto) or is sanctioned by a standards organization (de jure). > http://www.answers.com/standard&r=67 From steve at holdenweb.com Fri Aug 25 06:07:20 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 25 Aug 2006 11:07:20 +0100 Subject: Modules... paths... newbie confusion In-Reply-To: <1edme2hhhn8je2rrd9spod5pdiubn2rdsa@4ax.com> References: <1156166327.327422.149470@b28g2000cwb.googlegroups.com> <4ktuo2Fdf60sU1@news.dfncis.de> <1156231390.380360.133780@i3g2000cwc.googlegroups.com> <mailman.9643.1156253553.27775.python-list@python.org> <1edme2hhhn8je2rrd9spod5pdiubn2rdsa@4ax.com> Message-ID: <ecmi3r$lgi$1@sea.gmane.org> Dennis Lee Bieber wrote: > On Tue, 22 Aug 2006 14:32:36 +0100, Steve Holden <steve at holdenweb.com> > declaimed the following in comp.lang.python: > > > >>You won;t get MySQLdb to run without running the setup.py since IIRC >>there's a compile step for a C library (and it's that compile step that >>needs to be able to find the MySQL client libraries). >> > > How'd we get from MSSQL to MySQLdb? Probably a thinko by me: I mentioned that setup.py needed to find MySQl libraries ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From rogue_pedro at yahoo.com Tue Aug 29 03:00:19 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 29 Aug 2006 00:00:19 -0700 Subject: Is this a good idea or a waste of time? In-Reply-To: <slrnef6o2j.4tu.apardon@rcpc42.vub.ac.be> References: <1156449402.022781.292840@p79g2000cwp.googlegroups.com> <1156485945.967160.238790@m73g2000cwd.googlegroups.com> <slrnef5hep.4tu.apardon@rcpc42.vub.ac.be> <44f322cd$1@nntp0.pdx.net> <slrnef6o2j.4tu.apardon@rcpc42.vub.ac.be> Message-ID: <1156834819.066631.149990@p79g2000cwp.googlegroups.com> Antoon Pardon wrote: > On 2006-08-28, Scott David Daniels <scott.daniels at acm.org> wrote: > > Antoon Pardon wrote: > >> On 2006-08-25, Simon Forman <rogue_pedro at yahoo.com> wrote: > >>> ... > >>> Generally asserts should be used to "enforce" invariants of your code > >>> (as opposed to typechecking), or to check certain things while > >>> debugging. > >> > >> I don't understand this argument. Can't type checking be seen as > >> enforcing a code invariant? > >> > > But it is practically never the "right" invariant. > > And who decides what is and what is not the "right" invariant? Um, programmers' common sense. I can't really describe it well in words, so I'll give you an example. A long time ago, I wrote a simple interpreter that broke incoming commands up on whitespace and ran the pieces one by one. Then, for reasons that are inconsequential to this post, I decided that instead of using str.split(), I wanted to keep an index into the command string and "parse" it using that. It had been a long time since I had had to do this sort of array/pointer style processing (thank you python, and Guido, et. al., too..) and I wasn't fully sure of myself and my code, so I used a bunch of assert statement to allow myself to *be* sure. Here's the relevant code (I added a few line continuations to try to prevent mail/news formatting problems, but of course YMMV): def interpret(self, command): """ Given a command string, break it into whitespace-delimited commands and execute them one after another. Integers and floats are pushed onto the stack. This variant of the Interpreter class uses a simple pointer into the command line string. It increments the 'pointer' and checks against the set of chars in string.whitespace to break up the command line. It keeps track of the command line and the index so that Words it executes (that have a reference to it) can perform manipulations on them. This permits, for example, the "chomp" word, which takes the next non-whitespace sequence of chars immediately following it on the command line, makes a string of it, and puts it on the stack. """ #Let's have a pointer or index. i = 0 #Remember our command line self.command = command #Cache the length. l = len(command) while 0 <= i < l: #Run through chars until we reach the end, #or some non-whitespace. while (i < l) and (command[i] in self.blankspace): i += 1 #If we've reached the end we're done. if i == l: break assert i < l, "If not, the line above should have break'd us."\ "We should not have i > l ever." #Remember our starting index for this word. begin = i assert command[begin] not in self.blankspace, "Just making sure." #Force at least one increment of i. i += 1 #Run through until the end or some self.blankspace. while (i < l) and (command[i] not in self.blankspace): i += 1 #At this point, we're either at the end of the command line #or we're at a blank char delimiting a preceding word. assert (i == l) or \ ((begin < i < l) and (command[i] in self.blankspace)) #We've found a word. word = command[begin:i] #first, try making an integer.. try: n = int(word) self.stack.append(n) except ValueError: #if that didn't work, try making a float.. try: f = float(word) self.stack.append(f) except ValueError: #not a float or integer, eh? Let's try executing it.. try: #Update our pointer in case the word wants it. self.i = i #try to lookup the command and execute it.. self.execute(word) #Update our pointer in case the word changed it. i = self.i except: ilog.exception('Error executing "%s"', word) #propagate the Exception "upward" raise It's not the greatest code I've ever written, in fact it's kind of naive. (Nowadays I'd probably use re.finditer()...) But notice that the assert statements all act to verify that certain conditions are met at certain places throughout the loop, and that if the code is operating correctly, i.e. in the way that the programmer (Hi there!) intended, that the assertions will always succeed. *That's* the "invariant" part. Notice further that none of the asserts have any side effects, and especially, that they could all be removed without changing the operation of the code in any way. This is the "proper" use of assertions, as I understand it. (They are of course useful when you're trying to track down odd bugs, but for a similar reason: You put them into your code at those places where you suspect your assumptions about it's workings are incorrect.) One important point I failed to bring up in my response to the OP is that assertions *can* go away. (Running python with the '-O' or '-OO' switches removes assert statements at the bytecode level, along with code blocks within the "if __debug__:" "magic" if statement.) You should never write code that will work differently or fail if it is suddenly deprived of it's assert statements one day. > > You don't usually > > mean type(x) == int, but rather something like x is a prime between 2 > > and 923. Or 5< x**4 < 429, or _something_ problem specific. saying > > that x must be an int is almost always simultaneously too specific and > > too general. > > There seem to be enough problems that work with ints but not with > floats. In such a case enforcing that the number you work with > is indeed an int seems fully appropiate. If you have a reason to restrict your code to using only ints (perhaps you're packing them into an array of some sort, or passing them to a C extension module) then yes, of course it's appropriate. However, these reasons seem to me to be much narrower (more narrow?) and more specialized (specializeder?) than they seem to me to be to you. And even in these cases, checking type and refusing to work with anything but actual ints may still be too much. Perhaps a simple call to int() might suffice. Peace, ~Simon From skip at pobox.com Wed Aug 16 13:35:24 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 16 Aug 2006 12:35:24 -0500 Subject: profanity filter In-Reply-To: <7405d1440608161016k6ac6cce5t10973fc53f5b8072@mail.gmail.com> References: <7405d1440608161016k6ac6cce5t10973fc53f5b8072@mail.gmail.com> Message-ID: <17635.22364.224291.695177@montanaro.dyndns.org> Ronny> does anyone have any idea where I can find a profanity filter Ronny> written in python? No, but maybe SpamBayes (or a tiny little part of it) would suit your needs. Do you want to remove profanity and let the document (email, web page, etc) pass, just score if for profanity or block it altogether? Skip From gagsl-py at yahoo.com.ar Tue Aug 22 20:24:39 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 22 Aug 2006 21:24:39 -0300 Subject: What are decorated functions? In-Reply-To: <af5sr3-658.ln1@darkstargames.dnsalias.net> References: <af5sr3-658.ln1@darkstargames.dnsalias.net> Message-ID: <7.0.1.0.0.20060822201053.03a4ee38@yahoo.com.ar> At Tuesday 22/8/2006 17:19, Wolfgang Draxinger wrote: >I'm just reading the python language reference and came around >the term "decorated functions", but I have no idea, for what >they could be used. A decorator takes a function/method/callable, "decorates" (modifies) it in a certain way, and returns it. @classmethod and @staticmethod are examples: they take a (normal) method, and transform it into another thing. You can write your own decorators. An example similar to one discussed on this list a few days ago: suppose you have a pure function taking a long time to compute; you could save the results in a dictionary using the arguments as key, and retrieve them later when a call is made exactly with the same arguments. This is a known pattern ("memoize"). def memoized(function): function.cache={} def f(*args): try: return function.cache[args] except KeyError: result = function.cache[args] = function(*args) return result return f @memoized def fibo(n): time.sleep(2) # a sloooooow function if n<2: return 1 return fibo(n-1)+fibo(n-2) The original function is fibo() - it works OK but assume it's slow. So you "decorate" it with @memoized to improve performance. (This is just an example, of course - I'm not saying memoizing is the right thing to do here, nor this is the best way to do it... just to demonstrate what a decorator could be used for) Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From skip at pobox.com Wed Aug 9 09:34:31 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 9 Aug 2006 08:34:31 -0500 Subject: setup.py when you can't write to site-packages? In-Reply-To: <1155121231.384846.86090@i3g2000cwc.googlegroups.com> References: <1155121231.384846.86090@i3g2000cwc.googlegroups.com> Message-ID: <17625.58471.813236.396704@montanaro.dyndns.org> andy> What's the best approach for situations when you can't tamper with andy> the Python install? python setup.py install --prefix=/some/where/else The arg to --prefix is analogous to /usr or /usr/local. For example, if you are running Python 2.4, your files will wind up in /some/where/else/lib/python2.4/site-packages Just add that directory to PYTHONPATH and you should be good to go. Skip From __peter__ at web.de Thu Aug 31 08:54:50 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 31 Aug 2006 14:54:50 +0200 Subject: Using eval with substitutions References: <1157022920.299174.22860@m73g2000cwd.googlegroups.com> <mailman.10170.1157023945.27775.python-list@python.org> <1157027285.805711.24610@m79g2000cwm.googlegroups.com> Message-ID: <ed6m5q$4gc$02$1@news.t-online.com> abhishek at ocf.berkeley.edu wrote: > Fredrik Lundh wrote: >> (I'm afraid I don't really understand the point of your examples; what >> is it you're really trying to do here ?) > > A function is passed a bunch of string expressions like, > x = "a+b" > y= "x*a" > z= "x+y" > > where a and b are assumed to have been assigned values in the local > namespace. Now I have to evaluate another string such as, > "z+y+x" > > So as you say, I could do: > x=eval(x), y=eval(y), z=eval(z) and finally eval("z+y+x") but the > problem is that the initial strings are in no particular order, so I > don't know the sequence in which to perform the first 3 evaluations. I > was wondering if there was a simple way to 'pattern-match' so that the > required substitutions like z->x+y->x+x*a->(a+b)+(a+b)*a could be done > automatically. Here is something to start with: class EvalDict(object): def __init__(self, namespace): self.namespace = namespace def __getitem__(self, key): value = self.namespace[key] if isinstance(value, str): self.namespace[key] = value = eval(value, {}, self) return value def smart_eval(expr, namespace): return eval(expr, {}, EvalDict(namespace)) def f(): a = 2 b = 3 x = "a+b" y = "x*a" z = "x+y" return smart_eval("x + y + z", locals()) if __name__ == "__main__": print f() Beware of infinite recursion: # RuntimeError: maximum recursion depth exceeded smart_eval("a + b", dict(a="b", b="a")) Peter From bj_666 at gmx.net Tue Aug 15 13:07:57 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 15 Aug 2006 19:07:57 +0200 Subject: file object and eof References: <1155660586.941712.114410@b28g2000cwb.googlegroups.com> Message-ID: <pan.2006.08.15.17.07.57.466607@gmx.net> In <1155660586.941712.114410 at b28g2000cwb.googlegroups.com>, KraftDiner wrote: > I open a file in python by > f = open('filename', mode='rb') > > how can I tell if I am at the end of file? > f.eof() isn't implmented. > > How can I implement its functionallity? Try to read something. If the empty string is returned you are at the end of the file. Or write a function that uses `os.path.filesize()` and the `tell()` method of the file. Ciao, Marc 'BlackJack' Rintsch From linnorm at gmail.com Thu Aug 10 09:18:52 2006 From: linnorm at gmail.com (linnorm at gmail.com) Date: 10 Aug 2006 06:18:52 -0700 Subject: excel in unix? In-Reply-To: <1155197334.969268.95220@i42g2000cwa.googlegroups.com> References: <1155197334.969268.95220@i42g2000cwa.googlegroups.com> Message-ID: <1155215932.863285.258530@b28g2000cwb.googlegroups.com> s99999999s2003 at yahoo.com wrote: > hi > is it possible to create excel files using python in Unix env? > if so, what module should i use? > thanks Depending on the complexity of your data you might find the csv module useful. It allows you to write comma separated value (.csv) files that Excel reads just fine. From webraviteja at gmail.com Mon Aug 14 00:06:37 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 13 Aug 2006 21:06:37 -0700 Subject: Easy to use distributed system? In-Reply-To: <cwQDg.9674$eL2.4002@tornado.rdc-kc.rr.com> References: <cwQDg.9674$eL2.4002@tornado.rdc-kc.rr.com> Message-ID: <1155528397.340082.267650@m73g2000cwd.googlegroups.com> Jim Jones wrote: > I am looking for a system in Python that will easily allow me to distribute > processes across multiple systems? So, if I have a function 'foo', I'd > like to be able to call something along the lines of > > distribute(foo(x)) > > And have the system figure out which node is available for process, and then > have the results returned in some sort of callback fashion. > > Any insight is greatly appreciated. Sounds like Grid computing. Google for Globus toolkit and ActiveGrid. Good luck. From webraviteja at gmail.com Tue Aug 22 14:17:43 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 22 Aug 2006 11:17:43 -0700 Subject: text editor suggestion? In-Reply-To: <pBFGg.2707$No6.52860@news.tufts.edu> References: <44e66724$0$2363$c3e8da3@news.astraweb.com> <1156219373.342609.71480@h48g2000cwc.googlegroups.com> <pBFGg.2707$No6.52860@news.tufts.edu> Message-ID: <1156270662.954255.323330@75g2000cwc.googlegroups.com> John Salerno wrote: > Ravi Teja wrote: > > > Stick to SciTE. It takes almost no learning effort and meets everyone > > of those requirements. As far as customerization goes, SciTE can be > > customerized quite well. In fact, it can even be scripted with Lua. You > > seem to be using the single file executable which does not come with > > the configuration files. Otherwise, I cannot see how you could be > > missing this ability. > > I really like Scite, but I find it's syntax highlighting abilities to be > quite limited. You can't specify your own groups of words, you can only > use what is already preset in the lexer files. ??? In the same file, near the top. keywordclass.python=and assert break class continue def del elif \ else except exec finally for from global if import in is lambda None \ not or pass print raise return try while yield I could add my own keywords to it. From g.tagliaretti at gmail.com Fri Aug 25 20:20:51 2006 From: g.tagliaretti at gmail.com (Gian Mario Tagliaretti) Date: Sat, 26 Aug 2006 02:20:51 +0200 Subject: [ANN] PyGooCanvas 0.4.0 Message-ID: <pan.2006.08.26.00.20.51.726712@gmail.com> I am pleased to announce version 0.4.0 of the Python bindings for Goocanvas. This is the first release and it's available at: https://developer.berlios.de/projects/pygoocanvas/ Contributors for this release: ============================== - Gian Mario Tagliaretti (module creation, coding, documentation) - Gustavo J.A.M. Carneiro (coding) - Edward Hervey (coding) - Brendan Howell (feedback and bug reporting) Blurb: ====== Goocanvas [1] is a canvas widget for GTK+, It is similar in many ways to FooCanvas, hence the name, but it uses cairo for rendering, it has a model/view split, and uses interfaces for items & views (so you can easily turn any application object into a canvas item or view). Pygoocanvas is a wrapper which exposes the goocanvas API to the python world, it's fairly complete, most of the API are covered. The documentation is a work in progress. Like the GTK+ library, PyGTK and Goocanvas itself Pygoocanvas is licensed under the GNU LGPL, so is suitable for use in both free software and proprietary applications. Pygoocanvas requires: ===================== - Goocanvas >= 0.4.0 - PyGObject >= 2.10.1 (2.11.3 to build the docs) - PyGTK >= 2.8.4 - PyCairo >= 1.2.0 Bug reports should go to https://developer.berlios.de/bugs/?group_id=6813 [1] http://sourceforge.net/projects/goocanvas -- Gian Mario Tagliaretti GooCanvas python bindings http://http://developer.berlios.de/projects/pygoocanvas/ From horpner at yahoo.com Wed Aug 23 18:27:55 2006 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 23 Aug 2006 22:27:55 GMT Subject: Python and STL efficiency References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <1156365953.276055.137540@m73g2000cwd.googlegroups.com> Message-ID: <LD4Hg.196$5i7.177@newsreading01.news.tds.net> On 2006-08-23, Amanjit Gill <amanjit.singh.gill at googlemail.com> wrote: > you should also include <algorithm> for ostream_operator. <ostream>, actually. -- Neil Cerutti From miki.tebeka at gmail.com Tue Aug 8 14:56:38 2006 From: miki.tebeka at gmail.com (Miki) Date: 8 Aug 2006 11:56:38 -0700 Subject: Getting previous file name In-Reply-To: <1154983936.588478.298380@m79g2000cwm.googlegroups.com> References: <1154983936.588478.298380@m79g2000cwm.googlegroups.com> Message-ID: <1155063398.455157.43750@m73g2000cwd.googlegroups.com> Hello hj, > I have a small script here that goes to inside dir and sorts the file > by create date. I can return the create date but I don't know how to > find the name of that file... > I need file that is not latest but was created before the last file. > Any hints... I am newbiw python dude and still trying to figure out lot > of 'stuff'.. > > ... Remember that Python comes with "battaries included": #!/usr/bin/env python from os import walk from os.path import getctime, join def cmp_file_by_ctime(file1, file2): return cmp(getctime(file1), getctime(file2)) def walktree(path): file_list = [] for root, dirs, files in walk(path): file_list += [join(root, file) for file in files] file_list.sort(cmp_file_by_ctime) return file_list[-2] HTH, Miki http://pythonwise.blogspot.com/ From python-url at phaseit.net Tue Aug 15 14:50:41 2006 From: python-url at phaseit.net (Jack Diederich) Date: Tue, 15 Aug 2006 18:50:41 +0000 (UTC) Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Aug 15) Message-ID: <ebt521$955$1@lairds.us> QOTW: "Consider changing your business plan: write crappy software, charge heaps for support -- it's not a novel idea" - John Machin "To make it run fast, use psyco. To make it even faster, implement the compare function in C." - Raymond Hettinger A Perl convert gladly announces his conversion but misses CPAN: http://groups.google.com/group/comp.lang.python/browse_thread/thread/f12a260f3fdc45e3/ Can you obscure python code? Sure, but if you didn't bother to read the FAQ what makes you think someone will bother to read your code? http://groups.google.com/group/comp.lang.python/browse_thread/thread/b4e08adec2d835f5/ Timbot exhaustively satisfies those with an interest in the details of not-a-number formats as Python knows them: http://groups.google.com/group/comp.lang.python/browse_thread/thread/5c2b4b2a88c8df4/ Alex Martelli provides a recipe for a model embedding of Python in C (or C++) which culminates in passing dictionary values between the two languages (as well as an accurate summary of the dead-trees literature of interest to newcomers): http://groups.google.com/group/comp.lang.python/browse_thread/thread/ab5367982b59b564/ David Mertz is not dead he's just writing on Developerworks instead of c.l.py: http://www.ibm.com/developerworks/blogs/page/davidmertz Releases of Note SQLAlchemy 0.2.7 "Python SQL toolkit and Object Relational Mapper" http://cheeseshop.python.org/pypi/SQLAlchemy/0.2.7 Yahoo! Developer Center, Python Edition. http://developer.yahoo.com/python/ Upcoming Community Events The 2007 Southern California Linux Expo specifically invites proposals for Python-related papers: http://groups.google.com/group/comp.lang.python/msg/36316f6227738fed Plone Conference 2006, October 25-27 (Seattle, Washington) http://plone.org/events/conferences/seattle-2006 Open Source Developers Conference Dec 5-8 (Melbourne, Australia) http://www.osdc.com.au/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/python/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to <Python-URL at phaseit.net> should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask <claird at phaseit.net> to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From python.list at tim.thechases.com Mon Aug 14 11:11:53 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 14 Aug 2006 10:11:53 -0500 Subject: A little assistance with os.walk please. In-Reply-To: <1155566679.139086.279430@h48g2000cwc.googlegroups.com> References: <1155566679.139086.279430@h48g2000cwc.googlegroups.com> Message-ID: <44E092B9.9060609@tim.thechases.com> > The os.walk function walks the operating systems directory tree. Yup. > This seems to work, but I don't quite understand the tupple that is > returned... > Can someone explain please? > > for root, dirs, files in os.walk('/directory/'): > print root > # print dirs > # print files As cheesy as it may sound, try uncommenting the two commented lines. For a more explicit variant: print repr(dirs) print repr(files) You'll notice that they're lists. In the directory "root", you'll find the subdirectories given in the list "dirs" and you'll find the files given in the list "files". -tkc From andre at wasy.de Mon Aug 21 04:59:23 2006 From: andre at wasy.de (Andre Poenitz) Date: Mon, 21 Aug 2006 08:59:23 +0000 (UTC) Subject: Stack trace in C References: <mailman.8519.1153831141.27775.python-list@python.org> <just-9A3305.14571825072006@news1.news.xs4all.nl> Message-ID: <scsmp3-hiq.ln1Y@svn2.wasy.de> Just <just at xs4all.nl> wrote: > >> On Tue, 25 Jul 2006 14:20:41 +0200, Andre Poenitz wrote: >> > >> > >> >Bear with me - I am new to Python. (And redirect me to a more suitable >> >newsgroup in case this one is not appropriate.) >> > >> >I am trying to embed Python into a C++ application and want to get back >> >a backtrace in case of errors in the python code. >> >> I think you'd have more luck with the traceback module, which has such >> methods as format_exception and print_tb. > > From C, PyErr_Print() is often handy (if only for debugging). I'd like to display the backtrace i a fancy gui widget, and PyErr_Print sends everything to stderr... Andre' From vasudevram at gmail.com Sat Aug 12 12:58:03 2006 From: vasudevram at gmail.com (vasudevram) Date: 12 Aug 2006 09:58:03 -0700 Subject: Recurse Directories and process files in directory References: <1155401214.163465.235830@m79g2000cwm.googlegroups.com> Message-ID: <1155401882.970150.34130@75g2000cwc.googlegroups.com> KraftDiner wrote: > Hi I need help writing a python script that traverses (recursivly) a > directory and its sub directories and processes all files in the > directory. So at each directory if there are files in it I must build > a list of those files and process them by exectuing a system command > (exec?) > > Can some one tell me what methods to use to: > a) Walk the directory tree > b) execute a system command with parameters. > > TIA. Hi, Try os.walk(). Don't remember the syntax right now, should be straightforward. Check the standard Python docs that come with your Python installation. Or start python and do: import os print os.walk.__doc__ And executing a system comand is os.system(...). Caveat: there can be security risks with system(). Depends how you use it and who you let use it with what arguments. Similar to risks with CGI forms. HTH ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Vasudev Ram xtopdf - PDF creation/converson toolkit: http://www.dancingbison.com/products.html ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From steve at REMOVEME.cybersource.com.au Mon Aug 21 04:59:20 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Mon, 21 Aug 2006 18:59:20 +1000 Subject: Questions on exceptions References: <1156146013.939619.102570@i3g2000cwc.googlegroups.com> Message-ID: <pan.2006.08.21.08.59.20.49574@REMOVEME.cybersource.com.au> On Mon, 21 Aug 2006 00:40:14 -0700, sc_wizard29 wrote: > Hi everyone, > > I've just finished studying O'Reilly's "Learning python" and since I > come from the Java world, there are some things that bother me > concerning python's exception handling. > > In Java, all methods must declare the exceptions throwed (I'm speaking > of checked exceptions)... but this is not the case in Python. So my > question is : how can I know which exceptions I must catch ? (am I > supposed to believe what's written in the documentation ? am I supposed > to read the source code to see which exceptions are throwed ?) How do you know what objects a method will return? Are you supposed to believe the documentation? Are you supposed to read the source code? Exceptions are no different. If a method claims to raise ValueError, but sometimes raises TypeError, I call that a bug, regardless of whether the line which causes it is "int(x) + str(y)" or "raise TypeError('My documentation is incomplete')". > Also, can someone explain me why there is no try...except...finally > statement ? Historical reasons. I believe that Python 2.5 will support it. > For example, the following code snippet is not valid, but > what would be the correct python way to do it ? > > myFile = open('file.txt') # assume file exists > try: > for nextLine in file: > nextLine = nextLine.rstrip('\n');print "line = " + nextLine > except IOError: > print "Error while reading from file" > finally: > myFile.close Nested try...except blocks. -- Steven D'Aprano From skip at pobox.com Wed Aug 30 08:18:02 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 30 Aug 2006 07:18:02 -0500 Subject: where or filter on list In-Reply-To: <1156939493.558819.8410@i42g2000cwa.googlegroups.com> References: <1156939493.558819.8410@i42g2000cwa.googlegroups.com> Message-ID: <17653.33274.549312.481520@montanaro.dyndns.org> >>>> foo = [-5,-1,2,3] # nearest value to zero ? >>>> [value for value in foo if math.fabs(value) == min([int(math.fabs(x)) for x in foo])] charles> [-1] charles> Something simpler ? Well, you can just use the abs() builtin instead of math.fabs. Also, just compute the min/abs once: minval = min([int(math.fabs(x)) for x in foo]) [value for value in foo if fabs(value) == minval] Another way might be to sort by absolute value: intermed = [(abs(v), v) for v in foo] intermed.sort() intermed[0][1] That only gives you one of possibly many values closest to zero. charles> How to extend this function to any given value ? Just subtract that value from all values in the list: intermed = [(abs(v-x), v) for v in foo] intermed.sort() intermed[0][1] Skip From sulsa at gazeta.pl Mon Aug 14 21:40:51 2006 From: sulsa at gazeta.pl (Sulsa) Date: Tue, 15 Aug 2006 03:40:51 +0200 Subject: How to fill a form Message-ID: <20060815034051.89ef7e18.sulsa@gazeta.pl> I need to fill form from web site, the code for this form looks like this: <form action="login.php" method="post" target="_top"> <input type="text" name="username" size="25" maxlength="40" class="post" /> <input type="password" name="password" size="25" maxlength="25" class="post" /> <input type="hidden" name="redirect" value="" /> <input type="submit" name="login" class="mainoption" value="Login" /> </form> I can of course connect to a web site and download the form, i do it like this: import urllib2 www = urllib2.urlopen("http://www.site.com/login.php") form_data= stronka.read() or using httplib: import httplib conn = httplib.HTTPConnection("www.site.com") conn.request("GET", "/login.php") data1 = conn.getresponse().read() but i can't fill and send this form is there some simple way to do it? From BjornSteinarFjeldPettersen at gmail.com Tue Aug 8 19:18:08 2006 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: 8 Aug 2006 16:18:08 -0700 Subject: newb question: file searching In-Reply-To: <1155070517.448510.149380@b28g2000cwb.googlegroups.com> References: <1155067111.892386.130610@n13g2000cwa.googlegroups.com> <1155067720.211789.208560@i42g2000cwa.googlegroups.com> <1155068675.101390.299110@i3g2000cwc.googlegroups.com> <1155070517.448510.149380@b28g2000cwb.googlegroups.com> Message-ID: <1155079088.584893.326670@m73g2000cwd.googlegroups.com> jaysherby at gmail.com wrote: [...] > that? And also, I'm still not sure I know exactly how os.walk() works. > And, finally, the python docs all note that symbols like . and .. > don't work with these commands. How can I grab the directory that my > script is residing in? os.getcwd() will get you the directory your script is in (at least as long as you're running the script from the current directory :-) Here's my version of how to it (comments below): def collect_ext(*extensions): """Return a list of files from current directory and downwards that have given extensions. Call it like collect_ext('.py', '.pyw') """ res = [] for dirname, _, files in os.walk(os.getcwd()): for fname in files: name, ext = os.path.splitext(fname) if ext in extensions: res.append(os.path.join(dirname, fname)) return res Each time around the outer for-loop, os.walk() gives us all the filenames (as a list into the files variable) in a sub-directory. We need to run through this list (inner for-loop), and save all files with one of the right extensions. (os.walk() also gives us a list of all subdirectories, but since we don't need it, I map it to the _ (single underscore) variable which is convention for "I'm not using this part"). note1: notice the "*" in the def line, it makes the function accept a variable number of arguments, so you can call it as collect_ext('.py') but also as collect_ext('.py', '.pyw', '.pyo'). Inside the function, what you've called it with is a list (or a tuple, I forget), which means I can use the _in_ operator in the if test. note2: I use os.path.join() to attach the directory name to the filename before appending it to the result. It seems that might be useful ;-) hth, -- bjorn From saint.infidel at gmail.com Tue Aug 1 17:55:57 2006 From: saint.infidel at gmail.com (infidel) Date: 1 Aug 2006 14:55:57 -0700 Subject: cleaner way to write this try/except statement? In-Reply-To: <UVOzg.2616$No6.51297@news.tufts.edu> References: <UVOzg.2616$No6.51297@news.tufts.edu> Message-ID: <1154469357.487139.64550@p79g2000cwp.googlegroups.com> Here's how I would do it: def Validate(self, parent): try: text_ctrl = self.GetWindow() text = text_ctrl.GetValue() if not text: raise ValueError if int(text) <= 0: raise ValueError return True except ValueError, error: wx.MessageBox('Enter a valid time.', 'Invalid time entered', wx.OK | wx.ICON_ERROR) return False From ells.david at gmail.com Fri Aug 25 15:28:06 2006 From: ells.david at gmail.com (David Ells) Date: 25 Aug 2006 12:28:06 -0700 Subject: Duck typing alows true polymorfisim In-Reply-To: <1156532721.879808.40990@i3g2000cwc.googlegroups.com> References: <1156532721.879808.40990@i3g2000cwc.googlegroups.com> Message-ID: <1156534086.698353.81850@m73g2000cwd.googlegroups.com> atbusbook at aol.com wrote: > lets say you want a generic numerical algorithom like sum > > Ruby > > def sum lst > lst.inject(0){|total,current| total*current} > end > > Java // i dont know if there is a numeric super class for numbers > > class Sum{ > public static int sum(int[] lst){ > int total = 0; > for(int current : lst){ > total+=current; > } > return total; > } > // repeat for all other number types > } Any more to add? Your question is not exactly clear. Are you asking how to do higher order procedures in Python? Here's sum as a higher-order procedure... It sums the numbers from a to b (or any thing that can be compared and added with "<" and "+"). def Sum(term, next, a, b): if(a > b): return 0 else: return (term(a) + (Sum(term, next, next(a), b) This function takes two functions (term and next) and two objects (in our case numbers) representing the range to sum across. Now let's say you want to add the numbers 1 through 10. The term for the summation would just be the number, so the term function would simply be a function called identity, and could be defined as def identity(x): return x To get the next term, we are just adding one each time (i.e. 1, 2, 3, 4, ...). So our next function is def increment(x): return x += 1 Then we call Sum(identity, increment, 1, 10), and we get 1 + 2 + 3 + 4 + and so on. Now what if you wanted the sum of the CUBES of 1 through 10? Easy, we replace the term function with a function cube(x) that returns x*x*x. Sum(cube,increment,1,10) Hence each term in our summation is the cube, but we are still incrementing by one each time, so we get (1^3 + 2^3 + 3^3 + 4^3 + ...) Similarly we can change the next function to skip certain number, meet certain requirement, do some tranformation, whatever. The fact that python accept and uses functions as parameters to other functions is awesome in terms of power, but it can get a little mind boggling sometimes. From fredrik at pythonware.com Mon Aug 21 02:20:50 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Aug 2006 08:20:50 +0200 Subject: tkinter prob In-Reply-To: <1156140461.170856.136180@74g2000cwt.googlegroups.com> References: <1156140461.170856.136180@74g2000cwt.googlegroups.com> Message-ID: <ecbjc2$i4d$2@sea.gmane.org> JyotiC wrote: > i am making a GUI using Tkinter, > I have a button and a checkbutton. > i want the button to be enable when checkbutton is on and disble when > the checkbutton is off. use the checkbutton's command option to install a callback that enables or disables the button. </F> From hitesh287 at gmail.com Wed Aug 16 15:29:56 2006 From: hitesh287 at gmail.com (Hitesh) Date: 16 Aug 2006 12:29:56 -0700 Subject: Documentation Question About Depricated String Functions In-Reply-To: <Xns9821CE84B951duncanbooth@127.0.0.1> References: <1155754352.767469.211380@m73g2000cwd.googlegroups.com> <Xns9821CE84B951duncanbooth@127.0.0.1> Message-ID: <1155756596.803405.326920@i3g2000cwc.googlegroups.com> Thank you guys. hj Duncan Booth wrote: > Hitesh wrote: > > > In python doc -- 4.1.4 Deprecated string functions -- I read that "The > > following list of functions are also defined as methods of string and > > Unicode objects; see ``String Methods'' (section 2.3.6) for more > > information on those. You should consider these functions as > > deprecated, although they will not be removed until Python 3.0. The > > functions defined in this module are: " and there is a whole list of > > functions. If these functions are deprecated what is the replacement > > for them? I couldn't find that info in the doc. Any links will be > > helpful. > > You did find the info in the doc - you quoted it above: > > The functions are deprecated: use the string methods (see section 2.3.6) > instead. From fredrik at pythonware.com Thu Aug 24 13:12:17 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Aug 2006 19:12:17 +0200 Subject: sum and strings In-Reply-To: <7.0.1.0.0.20060824132656.050af940@yahoo.com.ar> References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <slrneeatf3.nbt.sybrenUSE@schuimige.stuvel.eu> <1155922208.930580.135080@m79g2000cwm.googlegroups.com> <mailman.9516.1155930431.27775.python-list@python.org> <1156365271.487489.62640@m73g2000cwd.googlegroups.com> <44ECC789.1010202@tim.thechases.com> <ecjga9$558$1@sea.gmane.org> <44EDCFDE.9060604@tim.thechases.com> <7.0.1.0.0.20060824132656.050af940@yahoo.com.ar> Message-ID: <eckmlg$brf$1@sea.gmane.org> Gabriel Genellina wrote: > sequences don't have to be homogeneous, and iterators cant go back. > But let GvR say that in his own words: > http://mail.python.org/pipermail/python-dev/2003-April/034854.html you could of course dispatch on the type of the second argument (the start value), but that'd be at least as silly. here's the relevant pronouncement: http://mail.python.org/pipermail/python-dev/2003-April/034853.html and here's an elaboration by the martellibot: http://mail.python.org/pipermail/python-dev/2003-April/034855.html (and note that the python-dev consensus is that sum is for numbers and join is for strings. anyone who cares about writing readable code knows that names matter; different things should have different names.) (I still think a "join" built-in would be nice, though. but anyone who argues that "join" should support numbers too will be whacked with a great big halibut.) </F> From calchp at gmail.com Thu Aug 17 13:44:20 2006 From: calchp at gmail.com (calchp at gmail.com) Date: 17 Aug 2006 10:44:20 -0700 Subject: where can i get older version of python? In-Reply-To: <1155835739.694566.177080@75g2000cwc.googlegroups.com> References: <1155835739.694566.177080@75g2000cwc.googlegroups.com> Message-ID: <1155836660.462023.310470@h48g2000cwc.googlegroups.com> chppatel at gmail.com wrote: > does any one know where can I get older version of python for windows? > > I am looking for versions between 2.0 and 2.2. > > thanks for your help This site might be useful http://www.oldapps.com/Python.php http://www.oldapps.com/ From phinsxiii at gmail.com Fri Aug 11 12:51:59 2006 From: phinsxiii at gmail.com (Bucco) Date: 11 Aug 2006 09:51:59 -0700 Subject: having issues Installing Python 2.5b3 on Windows XP Message-ID: <1155315119.400903.49090@h48g2000cwc.googlegroups.com> I installed python 2.5b3 on my windows XP sp2 box without any issues. I can double click the python program, and idle comes up in the command line window. However when I run python from the command line program cmd.exe, I get a pop-up window with the following error: 16 bit Windows Subsystem ----------------------------------------- The NTVDM CPU has encountered an illegal instruction. CS:020c IP:0115 OP:0f 00 00 00 00 Choose 'Close' to terminate the application. If I run python from the command line with the full path, C:\Python25\python, no problem. I checked my environment variables and they are pointing to the correct directories. I am at a loss for waht is causing the issue. Active state python 2.4 worked from the command line with no issues. I know 2.5b3 is beta, but I would like to try and get it running properly. At the very least, I would like someone to report this bug so that the final version gets fixed. Please don't say reboot. I have already tried that, same problem. I am going to try to install python 2.4 with the msi installer and see if I have the same issue with that version. If anyone else has any ideas please help. Thanks:) SA From sjmachin at lexicon.net Fri Aug 11 23:45:49 2006 From: sjmachin at lexicon.net (John Machin) Date: 11 Aug 2006 20:45:49 -0700 Subject: help with c <-> python buffer transfer In-Reply-To: <1155350653.626750.132450@74g2000cwt.googlegroups.com> References: <1155335511.379184.200570@75g2000cwc.googlegroups.com> <1155338689.873546.6930@i42g2000cwa.googlegroups.com> <1155350653.626750.132450@74g2000cwt.googlegroups.com> Message-ID: <1155354348.984833.314810@h48g2000cwc.googlegroups.com> tkirke at gmail.com wrote: > This is the part I need help with. I've also used PyBuffer_... > subroutines which gave similar problems. Thanks for all of your other > comments, but I was hoping someone could just tell me what was wrong > with the code without having to worry about all of the other things > that could go wrong. > For completeness here is the complete c++ module & python output > > //======================================================================= > // Boost Includes > //============================================================== > #include <boost/python.hpp> > #include <boost/cstdint.hpp> > #include <boost/python/def.hpp> > #include <boost/python/args.hpp> > #include <boost/python/overloads.hpp> > > // Using > ======================================================================= > using namespace boost::python; > > static PyObject * proc_buf(PyObject *self, PyObject *args) { > PyObject *resultobj; > char* output_samples; > int len; > if (!PyArg_ParseTuple(args,"s#|l",&output_samples, &len)) { Sorry, I read that too quyickly. You need THREE receptors, one for "s", 2nd for "#", 3rd for "l". e.g. something like: int len; long third_arg; /* needs initialisation */ if (!PyArg_ParseTuple(args,"s#|l",&output_samples, &len, &third_arg)) { > return NULL; /* wrong arguments provided */ > } > for (int i=0;i<len;i++) output_samples[i] *= 2; > resultobj = PyString_FromStringAndSize(output_samples, len); > return resultobj; > } > // Module > ====================================================================== > BOOST_PYTHON_MODULE(spuctest) > { > def("pass_buf",&proc_buf); > } > > # python code > .... > buffy = mf.read() > print type(buffy) > buf = pass_buf(buffy, len(buffy)) > print type(buf) > # > > #python output > <type 'buffer'> > <type 'Nonetype'> I'd guess the return value of None was fortuitous -- when I tried your code using C, the call to pass_buf just crashed. With the above fix, the problem goes away: |>>> import procbuf |>>> foo = '\x01\x03\xff' |>>> x = procbuf.passbuf(foo) |>>> x '\x02\x06\xfe' HTH take2 :-) John From cga2000 at optonline.net Mon Aug 7 11:17:22 2006 From: cga2000 at optonline.net (cga2000) Date: Mon, 07 Aug 2006 11:17:22 -0400 Subject: email client like mutt In-Reply-To: <eb5ikc$2q2$1@panix1.panix.com> References: <mailman.9013.1154800822.27775.python-list@python.org> <eb5ikc$2q2$1@panix1.panix.com> Message-ID: <20060807151721.GF28742@turki.gavron.org> On Sun, Aug 06, 2006 at 04:15:08PM EDT, Aahz wrote: > In article <mailman.9013.1154800822.27775.python-list at python.org>, > Fabian Braennstroem <f.braennstroem at gmx.de> wrote: > > > >I am looking for a python email client for the terminal... something like > >mutt; maybe, so powerfull ;-) > > What's wrong with mutt? Like he says it's not written in python. Thanks cga From m.yanowitz at kearfott.com Thu Aug 10 07:23:22 2006 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Thu, 10 Aug 2006 07:23:22 -0400 Subject: Make Object Oriented? Message-ID: <005b01c6bc6f$63b16640$0d7d12ac@kearfott.com> Hello: Are there any tools to convert non-object-oriented code into object-oriented code? If not, perhaps something that I can pass in two (or more) classes and will create a base-class and simplify the passed in classed to be derived from the base class? Ideally this would be Python but if not, C-to-C++ would be ok? Thanks in advance: Michael Yanowitz From jantod at gmail.com Sat Aug 5 08:20:56 2006 From: jantod at gmail.com (Janto Dreijer) Date: 5 Aug 2006 05:20:56 -0700 Subject: testing array of logicals In-Reply-To: <1152843944.767204.113760@h48g2000cwc.googlegroups.com> References: <1152728083.461486.56500@h48g2000cwc.googlegroups.com> <1152841415.165550.14590@35g2000cwc.googlegroups.com> <1152842016.793515.127420@75g2000cwc.googlegroups.com> <1152843944.767204.113760@h48g2000cwc.googlegroups.com> Message-ID: <1154780456.647989.253110@m79g2000cwm.googlegroups.com> John Henry wrote: > Simon Forman wrote: > > > > > > False not in logflags > > > > > > > Or, if your values aren't already bools > > > > False not in (bool(n) for n in logflags) > > Very intriguing use of "not in"... Is there a reason why you didn't write True in (bool(n) for n in logflags) From slawomir.nowaczyk.847 at student.lu.se Thu Aug 10 15:30:13 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Thu, 10 Aug 2006 21:30:13 +0200 Subject: easy string formating question In-Reply-To: <1155235180.871436.22480@75g2000cwc.googlegroups.com> References: <1155235180.871436.22480@75g2000cwc.googlegroups.com> Message-ID: <20060810212426.EF89.SLAWOMIR.NOWACZYK.847@student.lu.se> On Thu, 10 Aug 2006 11:39:41 -0700 f pemberton <fpemberton133 at yahoo.com> wrote: #> I have kind of an interesting string, it looks like a couple hundred #> letters bunched together with no spaces. Anyway, i'm trying to put a #> "?" and a (\n) newline after every 100th character of the string and #> then write that string to a file. How would I go about doing that? Any #> help would be much appreciated. In addition to all the other ideas, you can try using StringIO import StringIO s = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' size = 10 # 100 input = StringIO.StringIO(s) while input.tell()<input.len: # is there really no better way to check for exhausted StringIO ? print input.read(size)+"?\n", # instead of print just write to a file or accumulate the result -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) "Reality is that which, when you stop believing in it, doesn't go away." -- Philip K. Dick From anthra.norell at tiscalinet.ch Tue Aug 1 16:20:09 2006 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Tue, 1 Aug 2006 22:20:09 +0200 Subject: Html character entity conversion References: <mailman.8786.1154419934.27775.python-list@python.org> <eani88$a2c$1@newsreader2.netcologne.de> Message-ID: <018a01c6b5a7$e2c58840$0201a8c0@mcuf7> ----- Original Message ----- From: "Claudio Grondi" <claudio.grondi at freenet.de> Newsgroups: comp.lang.python To: <python-list at python.org> Sent: Tuesday, August 01, 2006 2:42 PM Subject: Re: Html character entity conversion > Anthra Norell wrote: > > >>>>import SE # Available at the Cheese Shop > > I mean, that OP requested: > 'How can I translate this using standard Python libraries??' > > so it's just only not on topic. > > Claudio Grondi > -- > http://mail.python.org/mailman/listinfo/python-list Claudio, I was hoping to do the OP a service. Are you also hoping to do him a service? Frederic From chris at kateandchris.net Fri Aug 11 16:48:25 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Fri, 11 Aug 2006 16:48:25 -0400 Subject: How to write a Installer for a Python App in Linux In-Reply-To: <1155324117.748289.53080@h48g2000cwc.googlegroups.com> References: <1155240625.157696.143230@i42g2000cwa.googlegroups.com> <slrnedn60g.n0d.sybrenUSE@schuimige.stuvel.eu> <1155316580.905203.245070@b28g2000cwb.googlegroups.com> <12dpgp2o5gjh07d@corp.supernews.com> <1155324117.748289.53080@h48g2000cwc.googlegroups.com> Message-ID: <20060811204825.GA24766@kateandchris.net> If you mean that you are building Python2.4 and get an error during the configure step, you need to install libc6-dev. You are likely to find lots of issues unless you install some basic developer tools. There are some metapackages that get the right things for you, but I can't remember what it is off hand. -Chris On Fri, Aug 11, 2006 at 12:21:57PM -0700, diffuser78 at gmail.com wrote: > Has anybody written a file for cx_freeze. I am running Ubuntu Linux and > downloaded version for Python2.4. When I run it I get an error saying > that I dont have GLIBC_2.4. > > I couldnt find this in Synaptic too. > > Any clues ? > > -- > http://mail.python.org/mailman/listinfo/python-list From sjmachin at lexicon.net Mon Aug 14 17:55:11 2006 From: sjmachin at lexicon.net (John Machin) Date: 14 Aug 2006 14:55:11 -0700 Subject: TypeError: 'module' object is not callable (newby question) In-Reply-To: <ru5Eg.2023$v_1.1442@trndny01> References: <yp2Eg.1858$VQ.825@trndny05> <pan.2006.08.14.18.35.17.483297@gmx.net> <ru5Eg.2023$v_1.1442@trndny01> Message-ID: <1155592511.384825.292830@75g2000cwc.googlegroups.com> Charles Russell wrote: > Marc 'BlackJack' Rintsch wrote: > > > > > Don't call your file `glob.py` because then you import this module and not > > the `glob` module from the standard library. > > > > Ciao, > > Marc 'BlackJack' Rintsch > > Yes, thanks. Renaming to myglob.py solved the problem. But why does the > conflict not occur when the code is run interactively from the python > prompt? It does for me on Windows -- see below --because '' (representing the cwd) is injected at the front of sys.path. *xMMV of course. Or perhaps when you ran it your cwd was some other directory. C:\junk>dir glob* [snip] 15/08/2006 04:28 AM 662 glob.py 15/08/2006 04:28 AM 592 glob.pyc [snip] C:\junk>python Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. |>>> import glob *** Aarrgghh!! I'm being imported as glob glob was imported from glob.pyc glob.glob is <type 'module'> glob.glob was imported from glob.pyc (glob.glob is glob) is True --- end of import |>>> Cheers, John From greg.kujawa at gmail.com Mon Aug 14 15:49:54 2006 From: greg.kujawa at gmail.com (gregarican) Date: 14 Aug 2006 12:49:54 -0700 Subject: Which KDE IDE for Python? References: <1154682596.419636.70320@p79g2000cwp.googlegroups.com> <1154848913.318031.134910@75g2000cwc.googlegroups.com> Message-ID: <1155584994.848905.163510@i3g2000cwc.googlegroups.com> SPE looks good. I've used Komodo for about a year or so but am considering giving SPE a try. All of the malware/spyware/adware that was attempting to load on my system when I visited the SPE website wasn't so good, however :-/ crystalattice wrote: > Bart Ogryczak wrote: > > Hi, > > Rigth now I'm using two IDEs for Python, KDevelop and Eric. Both have > > drawbacks. KDevelop is a multilanguage IDE, and doesn't really have > > anything special for Python. There's no Python debugger, no PyDOC > > integration, it's class browser doesn't display attributes. On the > > other side there's Eric, which is made just for Python. But.. it > > doesn't integrate with KDE, doesn't support remote files (fish://, > > ftp:// etc.). Does anyone know a better IDE for Python, that'll > > integrate nicely with KDE? > > You might try SPE (http://stani.be/python/spe/blog/). I don't know if > it integrates w/ KDE but it's expressly for Python. From the site: > > "Spe is a free python IDE with auto indentation & completion, call > tips, syntax coloring & highlighting, UML diagrams, class explorer, > source index, auto todo list, sticky notes, pycrust shell, file > browsers, drag&drop, context help, Blender support, ... Spe ships with > Python debugger (remote & encrypted), wxGlade (gui designer), PyChecker > (source code doctor) and Kiki (regex console)." From atkedzierski at gmail.com Sat Aug 12 09:04:15 2006 From: atkedzierski at gmail.com (AndrewTK) Date: 12 Aug 2006 06:04:15 -0700 Subject: reading from sockets In-Reply-To: <TFQCg.103113$hp.69833@read2.cgocable.net> References: <1155227695.625250.17920@m73g2000cwd.googlegroups.com> <TFQCg.103113$hp.69833@read2.cgocable.net> Message-ID: <1155387855.311461.101710@74g2000cwt.googlegroups.com> Follow up the actual python code is at http://www.dcs.st-and.ac.uk/~atk1/singleclient.py From geon at post.cz Mon Aug 14 14:22:17 2006 From: geon at post.cz (Pavel Kosina) Date: Mon, 14 Aug 2006 20:22:17 +0200 Subject: tkinter, livewires: slow moving on Canvas Message-ID: <44E0BF59.10400@post.cz> Hi, I have two similar programs- one in Livewires and one in Tkinter. Just moving the player on a canvas. Why is that one in Tkinter so slow? What did I miss? Livewires is based on Tkinter, so it should be the same. I looked at the code of Livewires, tried something, but no success. Maybe its because of sleeping part in event handler in Tkinter, that is somehow (how?) bypassed in Livewires by magic tkinter.dooneevent(tkinter.DONT_WAIT). Neither this worked with me. Could anyone help? Both programs attached. livewires: http://www.livewires.org.uk/python/lwpackage.html -- geon Pavel Kosina -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060814/36fb3352/attachment.html> -------------- next part -------------- A non-text attachment was scrubbed... Name: robotsLivewires.py Type: text/x-python Size: 773 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20060814/36fb3352/attachment.py> -------------- next part -------------- A non-text attachment was scrubbed... Name: robotsTk.py Type: text/x-python Size: 848 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20060814/36fb3352/attachment-0001.py> From claird at lairds.us Fri Aug 18 12:40:01 2006 From: claird at lairds.us (Cameron Laird) Date: Fri, 18 Aug 2006 16:40:01 +0000 Subject: Subprocess confusion: how file-like must stdin be? References: <9sker3-7g8.ln1@lairds.us> <slrneeassv.c4m.nick@irishsea.home.craig-wood.com> <lblgr3-r48.ln1@lairds.us> <mailman.9508.1155911464.27775.python-list@python.org> Message-ID: <147hr3-vg4.ln1@lairds.us> In article <mailman.9508.1155911464.27775.python-list at python.org>, Fredrik Lundh <fredrik at pythonware.com> wrote: >Cameron Laird wrote: > >> Your interactive session does indeed exhibit the behavior that >> puzzles me. My expectation was that StringIO and the std* >> parameters to Popen() were made for each other; certainly there >> are many cases where stdout and stderr can be redirected *to* a >> StringIO. Is it simply the case that stdin demands a more >> file-like object? While that disappoints me, I certainly can >> program around it. My question, then: does stdin effectively >> require something really in the filesystem, or perhaps the >> stdout of a previous subprocess? Is there no built-in way to >> feed it an in-memory construct? > >set the appropriate stream to subprocess.PIPE, and write to it. > > p = subprocess.Popen(..., stdin=subprocess.PIPE) > p.stdin.write("hello") > p.stdin.close() # signal end of file . . . Of course! My; it's a sign of how far I was from the right subprocess mentality that I so missed what is obvious after the fact. The source code (for the 2.4 release) also comes close to making it clear, as I realized about the time you posted your follow-up, Fredrik. Is this--streaming data to a subprocess--too lightweight to deserve write-up in the (online) Cookbook? I'll volunteer. In retrospect, I see there are plenty of examples on-line of the usage, but I don't think an ignorant searcher (like me) will find them on his own. Thanks, Fredrik. From mail at microcorp.co.za Mon Aug 7 02:38:21 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Mon, 7 Aug 2006 08:38:21 +0200 Subject: testing array of logicals References: <1152728083.461486.56500@h48g2000cwc.googlegroups.com><1152841415.165550.14590@35g2000cwc.googlegroups.com><1152842016.793515.127420@75g2000cwc.googlegroups.com><1152843944.767204.113760@h48g2000cwc.googlegroups.com><1154780456.647989.253110@m79g2000cwm.googlegroups.com> <1154780687.193399.67600@b28g2000cwb.googlegroups.com> Message-ID: <00bc01c6b9f1$15321b20$03000080@hendrik> "Janto Dreijer" <jantod at gmail.com> wrote: | | Janto Dreijer wrote: | > John Henry wrote: | > > Simon Forman wrote: | > > > > | > > > > False not in logflags | > > > > | > > > | > > > Or, if your values aren't already bools | > > > | > > > False not in (bool(n) for n in logflags) | > > | > > Very intriguing use of "not in"... | > | > Is there a reason why you didn't write | > True in (bool(n) for n in logflags) | | <slaps forehead> doh! Never mind. | *lol* - don't feel bad about this - real programmers make this mistake with a varying frequency - >From once every six days or so if you are no good, to once in a lifetime if you are brilliant, and never only if you are a genius... First time it bit me I was an apprentice writing in Cobol. - Hendrik From fccoelho at gmail.com Thu Aug 24 16:37:28 2006 From: fccoelho at gmail.com (Flavio) Date: 24 Aug 2006 13:37:28 -0700 Subject: can't destroy a wxMiniFrame In-Reply-To: <mailman.9808.1156443797.27775.python-list@python.org> References: <1156443102.524257.14500@i3g2000cwc.googlegroups.com> <mailman.9808.1156443797.27775.python-list@python.org> Message-ID: <1156451848.891658.258720@i3g2000cwc.googlegroups.com> It was human error... I found the bug... thanks, Laszlo Nagy wrote: > Flavio ?rta: > > Hi, > > > > I have a miniframe composed mainly of combo boxes, that I need to > > destroy and recreate multiple time with different choice lists for the > > combo boxes. > > > > My problem is that even after destroying a miniframe with the Destroy() > > method, when it is recreated, the combo boxes show the same lists of > > its previous incarnation... > > > > how can I completely destroy a miniframe? > > > From what you wrote, I think that you did not create a new miniframe. > Although you called Destroy(), you tried to display it again. This is > what the documentation says about destroy. > > Destroys the window safely. Use this function instead of the delete > operator, since different window classes can be destroyed differently. > *Frames and dialogs are not destroyed immediately* when this function is > called -- they are added to a list of windows to be deleted on idle > time, when all the window's events have been processed. This prevents > problems with events being sent to non-existent windows. > > > Regards, > > Laszlo From JohnRoth1 at jhrothjr.com Wed Aug 16 10:52:51 2006 From: JohnRoth1 at jhrothjr.com (John Roth) Date: 16 Aug 2006 07:52:51 -0700 Subject: programming with Python 3000 in mind In-Reply-To: <mailman.9384.1155674618.27775.python-list@python.org> References: <1155672987.522793.47080@74g2000cwt.googlegroups.com> <mailman.9384.1155674618.27775.python-list@python.org> Message-ID: <1155739971.056360.326820@i3g2000cwc.googlegroups.com> skip at pobox.com wrote: > >> The current beta version of Python is 2.5 . How can a Python > >> programmer minimize the number of changes that will be needed to run > >> his code in Python 3000? > > Since we don't know what Python 3000 will look like yet (it's still in very > early development), that is a question that can't be answered today. > > Skip It may not be answerable precisely, but it most likely can be answered in general terms. As far as I can tell, there is one really major, overwhelmingly large change in 3.0, and that is making the str class unicode, with the corresponding elimination of the 8-bit string type in favor of a new bytes type. That also implies lots of changes in the I/O classes as well. In comparison, the elimination of the print statement is a "so-what". It can be handled by a conversion program. Most of the rest of the changes seem to be either forward compatable or easily handable by a conversion program. The change in the raise statement, for example, can be handled right now. John Roth From fredrik at pythonware.com Mon Aug 21 02:28:18 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Aug 2006 08:28:18 +0200 Subject: write eof without closing In-Reply-To: <1hkdzxu.120yyqo10acpqlN%aleax@mac.com> References: <ec72ev$4e0$1@netlx020.civ.utwente.nl> <12eeala1klcrtcf@corp.supernews.com> <mailman.9547.1156002037.27775.python-list@python.org> <12ei9r2c134tr32@corp.supernews.com> <1hkdzxu.120yyqo10acpqlN%aleax@mac.com> Message-ID: <ecbjq3$kd2$1@sea.gmane.org> Alex Martelli wrote: >> IIRC, ctrl-Z is not used _in_files_ to represent EOF. Only >> when text is being entered at the console. > > Easy to test, if you have Windows: > >>>> n='foo.txt' >>>> s='ba\r\n'+chr(26)+'bo\r\r' >>>> open(n,'wb').write(s) >>>> ss=open(n).read() >>>> ss > 'ba\n' > > As you see, in _text_ files on Windows a control-Z (char(26), AKA > '\x1a') does indeed represent "end of file" your test doesn't match the OP's example, though, which used control-Z to signal end of file when reading from the console: >copy con test.txt hello ^Z 1 file(s) copied. that control-Z works in the same way as control-D on Unix, and no EOF character is copied to the file: >python -c "print repr(open('test.txt', 'rb').read())" 'hello\r\n' </F> From rogue_pedro at yahoo.com Tue Aug 29 20:32:32 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 29 Aug 2006 17:32:32 -0700 Subject: newbe question about removing items from one file to another file In-Reply-To: <1156895504.960976.226950@i3g2000cwc.googlegroups.com> References: <1156714534.318183.326220@i3g2000cwc.googlegroups.com> <1156754881.496114.62170@b28g2000cwb.googlegroups.com> <mailman.10054.1156860158.27775.python-list@python.org> <1156895504.960976.226950@i3g2000cwc.googlegroups.com> Message-ID: <1156897952.783797.5540@p79g2000cwp.googlegroups.com> Eric_Dexter at msn.com wrote: > Anthra Norell wrote: > > Dexter, > > > > I looked at the format specification. It contains an example: > > > > ----------------------------------------------- > > > > <CsoundSynthesizer>; > > ; test.csd - a Csound structured data file > > > > <CsOptions> > > -W -d -o tone.wav > > </CsOptions> > > > > <CsVersion> ;optional section > > Before 4.10 ;these two statements check for > > After 4.08 ; Csound version 4.09 > > </CsVersion> > > > > <CsInstruments> > > ; originally tone.orc > > sr = 44100 > > kr = 4410 > > ksmps = 10 > > nchnls = 1 > > instr 1 > > a1 oscil p4, p5, 1 ; simple oscillator > > out a1 > > endin > > </CsInstruments> > > > > <CsScore> > > ; originally tone.sco > > f1 0 8192 10 1 > > i1 0 1 20000 1000 ;play one second of one kHz tone > > e > > </CsScore> > > > > </CsoundSynthesizer> > > > > ------------------------------------- > > > > If I understand correctly you want to write the instruments block to a file (from <CsInstruments> to </CsInstruments>)? Right? Or > > each block to its own file in case there are several?. You want your code to generate the file names? Can you confirm this or > > explain it differently? > > > > Regards > > > > Frederic > > > > > > ----- Original Message ----- > > From: <Eric_Dexter at msn.com> > > Newsgroups: comp.lang.python > > To: <python-list at python.org> > > Sent: Monday, August 28, 2006 10:48 AM > > Subject: Re: newbe question about removing items from one file to another file > > > > > > > > > > Anthra Norell wrote: > > > > Eric, > > > > Having played around with problems of this kind for quite some time I find them challenging even if I don't really have time > > to > > > > get sidetracked. Your description of the problem makes it all the more challenging, because its 'expressionist' quality adds the > > > > challenge of guessing what you mean. > > > > I'd like to take a look at your data, if you would post a segment on which to operate, the same data the way it should look > > in > > > > the end. In most cases this is pretty self-explanatory. Explain the points that might not be obvious to a reader who knows > > nothing > > > > about your mission. > > > > > > > > Frederic > > > > > > > > ----- Original Message ----- > > > > From: <Eric_Dexter at msn.com> > > > > Newsgroups: comp.lang.python > > > > To: <python-list at python.org> > > > > Sent: Sunday, August 27, 2006 11:35 PM > > > > Subject: newbe question about removing items from one file to another file > > > > > > > > > > > > > def simplecsdtoorc(filename): > > > > > file = open(filename,"r") > > > > > alllines = file.read_until("</CsInstruments>") > > > > > pattern1 = re.compile("</") > > > > > orcfilename = filename[-3:] + "orc" > > > > > for line in alllines: > > > > > if not pattern1 > > > > > print >>orcfilename, line > > > > > > > > > > I am pretty sure my code isn't close to what I want. I need to be able > > > > > to skip html like commands from <defined> to <undefined> and to key on > > > > > another word in adition to </CsInstruments> to end the routine > > > > > > > > > > I was also looking at se 2.2 beta but didn't see any easy way to use it > > > > > for this or for that matter search and replace where I could just add > > > > > it as a menu item and not worry about it. > > > > > > > > > > thanks for any help in advance > > > > > > > > > > -- > > > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > sorry about that this is a link to a discription of the format > > > http://kevindumpscore.com/docs/csound-manual/commandunifile.html > > > It is possible to have more than one instr defined in an .csd file so I > > > would need to look for that string also if I want to seperate the > > > instruments out. > > > > > > http://www.dexrow.com > > > > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > > I need to take it between the blocks only I also need to make sure I > only take one instrument > defined in this example with the code instr 1 I also need the code > > <CsInstruments> > > ; originally tone.orc > > sr = 44100 > > kr = 4410 > > ksmps = 10 > > nchnls = 1 > > regardless of what instrument I take. The function would have to > except the instrument number as an argument > > http://www.dexrow.com Using BeautifulSoup and the interactive interpreter, I figured out the following script in about 15 minutes: # s is a string containing the example file from above. from BeautifulSoup import BeautifulStoneSoup soup = BeautifulStoneSoup(s) csin = soup.contents[0].contents[5] lines = csin.string.splitlines() print csin.string It prints: ; originally tone.orc sr = 44100 kr = 4410 ksmps = 10 nchnls = 1 instr 1 a1 oscil p4, p5, 1 ; simple oscillator out a1 endin and of course you could say "lines = csin.string.splitlines()" to get a list of the lines. That doesn't take you all the way, but it's something. Hope that helps, Peace, ~Simon From L.Plant.98 at cantab.net Tue Aug 15 15:23:21 2006 From: L.Plant.98 at cantab.net (Luke Plant) Date: 15 Aug 2006 12:23:21 -0700 Subject: Reference Variables In Python Like Those In PHP In-Reply-To: <1155651471.605912.46640@m73g2000cwd.googlegroups.com> References: <1155651471.605912.46640@m73g2000cwd.googlegroups.com> Message-ID: <1155669800.977938.75450@74g2000cwt.googlegroups.com> Chaos wrote: > Is It possible to have reference variables like in PHP ... > Is this available in python? You should note that, to a nearest equivalent, all variables are reference variables in Python. The difference is in what assignment does - += in Python does an assignment of a new object for immutable objects. For mutable objects like lists, += does an in place modification. x = 1 y = x # y and x now point to the same object y += 1 # not any more, because ints are immutable, # and += is defined not to mutate for ints Luke From skip at pobox.com Wed Aug 9 11:12:17 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 9 Aug 2006 10:12:17 -0500 Subject: Eval (was Re: Question about using python as a scripting language) In-Reply-To: <17625.63405.303390.136292@montanaro.dyndns.org> References: <73BFFFC6-760D-4794-9B5C-AA749287B78A@carnegielearning.com> <17625.63405.303390.136292@montanaro.dyndns.org> Message-ID: <17625.64337.406293.686242@montanaro.dyndns.org> skip> import re skip> symbolinfo = [] skip> sympat = re.compile( skip> r'\[', Make that r',?\[' Skip From hitesh287 at gmail.com Wed Aug 16 17:07:35 2006 From: hitesh287 at gmail.com (Hitesh) Date: 16 Aug 2006 14:07:35 -0700 Subject: Adding a char inside path string In-Reply-To: <1155762054.479806.265310@b28g2000cwb.googlegroups.com> References: <1155737700.290268.248250@i42g2000cwa.googlegroups.com> <mailman.9419.1155738127.27775.python-list@python.org> <1155744057.573884.111850@m73g2000cwd.googlegroups.com> <mph6e21upc0c07v5mk45fbn2nnuv7s9sp7@4ax.com> <1155757548.080769.213490@p79g2000cwp.googlegroups.com> <ctmdnedPAMn-537ZnZ2dnUVZ_sidnZ2d@comcast.com> <1155759163.627377.72590@74g2000cwt.googlegroups.com> <12e70d6h4pb3l65@corp.supernews.com> <1155760716.499472.189490@p79g2000cwp.googlegroups.com> <12e71hnet3e7c99@corp.supernews.com> <1155762054.479806.265310@b28g2000cwb.googlegroups.com> Message-ID: <1155762455.273148.43320@i42g2000cwa.googlegroups.com> How about this: def TruncateString(s, Tindex): return string.ljust(s,Tindex){:Tindex] s = '\\serverName\\C:\\Folder Name1\\FolderName2\\example.exe -u ABC -g XYZ' try: Sindex = s.find(".exe") if Sindex > 0: Sindex = Tindex + 4 s1 = TruncateString(s, Sindex) except: pass hj Hitesh wrote: > I post a crappy solution but I can add few more stuff to make it fail > proof. > i.e. I can search for ".exe -u" > But if someone names folder like "folder.exe u". This script could > fail. > Or if in padded garbase I get ".exe u" > > These are two known issues I have to takcle. > > Thanks everyone for your help. > > > > Grant Edwards wrote: > > On 2006-08-16, Hitesh <hitesh287 at gmail.com> wrote: > > > > > anything after .exe should be truncated (or deleted). > > > > That will fail if any directory names contain the string > > ".exe", but if that's what you want, it's trivial enough: > > > > for s in ["asdfasdf.exe -u", "soemthing/else", "asdf.exe/qwerqwer/qwerqwer.exe"]: > > print `s`, > > i = s.find(".exe") > > print i, > > if i >= 0: > > s = s[:i+4] > > print `s` > > > > -- > > Grant Edwards grante Yow! Yow! It's some people > > at inside the wall! This is > > visi.com better than mopping! From deets at nospam.web.de Sun Aug 27 07:55:50 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 27 Aug 2006 13:55:50 +0200 Subject: unpaking sequences of unknown length In-Reply-To: <mailman.9934.1156672890.27775.python-list@python.org> References: <mailman.9934.1156672890.27775.python-list@python.org> Message-ID: <4ldfi6F1ckiqU1@uni-berlin.de> > I keep working around a little problem with unpacking in cases in which I don't know how many elements I get. Consider this: > > def tabulate_lists (*arbitray_number_of_lists): > table = zip (arbitray_number_of_lists) > for record in table: > # etc ... > > This does not work, because the zip function also has an *arg parameter, which expects an arbitrary length enumeration of arguments > which it would turn into a tuple (lists in this case). Now my function does exactly the same thing ahead of zip. So, before I pass > the tuple "arbitrary_number_of_lists" to zip, I 'd need to unpack it but the only way I know of is into variables: > > list1, list2, list3 = arbitrary_number_of_lists > zip (list1, list2, list3) I don't get your problem here. This works for me: args = [range(5) for i in xrange(5)] print zip(*args) > With arbitrary number of lists it cannot be done this way. > > Question: Is there an unpacking mechanism for cases in which I don't know--and don't need to know--how many elements I get, or an > argument passing mechanism that is the inverse of the tuplifier (*args)? No. It looks a little bit as if you aren't aware of the symetry behind the * and **-argument-passing schemes. I suggest reading up on them. Diez From sjmachin at lexicon.net Tue Aug 15 20:57:51 2006 From: sjmachin at lexicon.net (John Machin) Date: 15 Aug 2006 17:57:51 -0700 Subject: Clean way to not get object back from instantiation attempt gone bad References: <44e245c0$0$20991$88260bb3@free.teranews.com> <44E25CD4.40103@tobiah.org> <1155686871.563791.232220@b28g2000cwb.googlegroups.com> Message-ID: <1155689871.457450.262770@74g2000cwt.googlegroups.com> Simon Forman wrote: > > |>> class f: > ... def __init__(self): > ... del self Of course nothing happens. Args are local variables. 'self' is is a vanilla arg of a vanilla function. > ... > |>> e = f() > |>> e > <__main__.f instance at 0xb7dd91ec> > > > |>> class f: > ... def __init__(self): > ... return None Of course nothing different happens. There is always an implicit "return None" when control falls off the end of a function. Making it explicit changes nothing. > ... > |>> e = f() > |>> e > <__main__.f instance at 0xb7dd934c> The whole idea of "del self" or "return None" is not a goer. "self" is a reference to the (mutable) newly created object. After __init__ has finished mutating it, the constructor will return the object to the constructor's caller. The whole idea that None should be returned in the event of error is ... well, let's just say it leaves me speechless. > But you could raise an exception and check for it: > > |>> class f: > ... def __init__(self, flag=True): > ... if not flag: > ... raise Please read the manual. A lone "raise" does *not* raise an anonymous exception; it re-raises an exception that has just been trapped. If there are none, it raises None, which causes (as documented) a TypeError. > ... > |>> def f_factory(flag): > ... try: > ... e = f(flag) > ... except: Blanket exception catching is *never* a good idea. In this case the exception being caught is an artifact of your use of the unadorned "raise". If you inserted here: ... import sys ... x, y = sys.exc_info()[:2] ... print x, y you would get: exceptions.TypeError exceptions must be classes, instances, or strings (deprecated), not NoneType > ... e = None > ... return e > ... > |>> foo = f_factory(True) > |>> foo > <__main__.f instance at 0xb7dd944c> > |>> foo = f_factory(False) > |>> foo > |>> print foo > None HTH, John From aleax at mac.com Sat Aug 12 19:16:56 2006 From: aleax at mac.com (Alex Martelli) Date: Sat, 12 Aug 2006 16:16:56 -0700 Subject: Inconsistency producing constant for float "infinity" References: <mailman.9250.1155308835.27775.python-list@python.org> <slrnedp7l2.d2v.sybrenUSE@schuimige.stuvel.eu> <ebi7jd$2o8$1@sea.gmane.org> <mailman.9260.1155321255.27775.python-list@python.org> <1hjy8p2.1w7kmdk1f3hsysN%aleax@mac.com> <mailman.9279.1155421669.27775.python-list@python.org> Message-ID: <1hjys31.jt5dx1vxx3xrN%aleax@mac.com> Tim Peters <tim.peters at gmail.com> wrote: [snip] thanks for an exhaustively satisfying explanation! Alex From davidh at ilm.com Tue Aug 22 20:01:35 2006 From: davidh at ilm.com (David Hirschfield) Date: Tue, 22 Aug 2006 17:01:35 -0700 Subject: Has anyone used py-xmlrpc? Message-ID: <44EB9ADF.9030008@ilm.com> Searching for a python xmlrpc implementation that supports asynchronous requests, I stumbled on this project: http://www.xmlrpc.com/discuss/msgReader$1573 The author is Shilad Sen, and it appears to do what I'm looking for. But I'd love some feedback from anyone who might have used it before I go and base some server/client code on it. Anyone out there have experience with this code? Is it as good/stable as python's standard xmlrpclib? Better? Thanks in advance for any notes, -Dave -- Presenting: mediocre nebula. From maric at aristote.info Sun Aug 13 09:17:33 2006 From: maric at aristote.info (Maric Michaud) Date: Sun, 13 Aug 2006 15:17:33 +0200 Subject: __LINE__ and __FILE__ functionality in Python? In-Reply-To: <1155471514.569981.237170@p79g2000cwp.googlegroups.com> References: <k0nac68na6x.fsf@metropolis.phys.ntnu.no> <1155471514.569981.237170@p79g2000cwp.googlegroups.com> Message-ID: <200608131517.34246.maric@aristote.info> Le dimanche 13 ao?t 2006 14:18, John Machin a ?crit?: > I don't usually go for one-liners, especially ugly ones like > "inspect.stack()[1][1:3]" but it avoids the risk of hanging on to a > reference to the frame object -- see the warning in the inspect docs. Yes, my mistake, thanks for pointing this out, my suggestion should have been more accurate : import inspect try : c=inspect.currentframe() log_msg(c.f_lineno, c.f_code.co_filename) finally : del c or shorter ; from inspect import currentframe log_msg(currentframe().f_lineno, currentframe().f_code.co_filename) -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From honza.svec at gmail.com Fri Aug 11 04:57:30 2006 From: honza.svec at gmail.com (Jan Svec) Date: 11 Aug 2006 01:57:30 -0700 Subject: Component framework Message-ID: <1155286650.177024.284770@i42g2000cwa.googlegroups.com> Hi all, some time ago I've seen an interesting component framework for Python but I don't remember the name. I remember only one example. There were two components: Wheel and Car, Wheel were then inserted four times into Car and so on. This framework has had lazy instantiation of child components. Does anybody know the name of this framework? Thanks, Honza From sjmachin at lexicon.net Tue Aug 29 18:14:13 2006 From: sjmachin at lexicon.net (John Machin) Date: 29 Aug 2006 15:14:13 -0700 Subject: Max OSX and Excel In-Reply-To: <mailman.10052.1156858848.27775.python-list@python.org> References: <32822fe60608281500l762b61ddqc6f3300ec1e296a6@mail.gmail.com> <C118B8AE.116%Johanna.Pfalz@telus.net> <mailman.10006.1156803392.27775.python-list@python.org> <1156805457.046711.31000@75g2000cwc.googlegroups.com> <mailman.10052.1156858848.27775.python-list@python.org> Message-ID: <1156889653.107667.280120@e3g2000cwe.googlegroups.com> Jorge Vargas wrote: > On 28 Aug 2006 15:50:57 -0700, John Machin <sjmachin at lexicon.net> wrote: > > Jorge Vargas wrote: > > > On 8/28/06, Johanna Pfalz <Johanna.Pfalz at telus.net> wrote: > > > > To be more specific, I'm interested in reading in certain rows and columns > > > > from an excel spreadsheet directly without converting the information to a > > > > text file. I'd also like to be able to write directly to an excel > > > > spreadsheet from python. > > > > AFAIK there is no Python tool that will let you "write directly to" an > > *existing* xls file -- apart of course from running Excel on Windows > > via COM. > > > > The Pyexcelerator package creates xls files. > > > > > ohh I found a nice tool for that a while ago but I haven't been able to test it. > > > > Because ....? > > > nothing related to it, it's just that I haven't had the time to dive into it. > > > > > > http://groups.google.com/group/comp.lang.python.announce/browse_thread/thread/5d0828d7762e3586 > > > http://cheeseshop.python.org/pypi/xlrd > > > http://www.lexicon.net/sjmachin/xlrd.htm > > > > The "rd" in "xlrd" is an abrv8n of "read" -- it doesn't write Excel > > spreadsheets. > > > oh no wonder why with my quick look at the API I didn't saw any write methods :) Yup. The CheeseShop entry and the homepage say "to extract data from" right up front -- no false advertising there either :-) > > do you have any plans of implementing wirte or at least read/write of xls docs? pyexcelerator has already implemented "wirte". What do you mean by "read/write of xls docs"? Cheers, John From ajaksu at gmail.com Sat Aug 12 11:29:09 2006 From: ajaksu at gmail.com (ajaksu) Date: 12 Aug 2006 08:29:09 -0700 Subject: long(Decimal) performance References: <1155349097.946873.279970@b28g2000cwb.googlegroups.com> <ebkmmk$2jn$1@panix3.panix.com> Message-ID: <1155396549.275865.318440@i3g2000cwc.googlegroups.com> Hi Aahz, thanks for the feedback! Aahz wrote: > I'm not sure why it's coded that, but it's somewhat irrelevant: right > now, work is being done to convert decimal.py to C code, which will > almost certainly be much faster than your code. Generally speaking, you > should not be using Decimal now with any expectation of speed. Agreed and agreed. Just to avoid that the buggy (and unreadable) versions above harm anyone, here's a better attempt: def dec2long(number): """ Convert C{decimal.Decimal} to long """ decimal_string = str(number) ## Split 123.45E10 -> radix = 123.45, exponent = 10 if "e" in decimal_string: radix, exponent = decimal_string.split("e") elif "E" in decimal_string: radix, exponent = decimal_string.split("E") else: radix, exponent = (decimal_string, 0) if exponent: exponent = int(exponent) if "." in radix: ## radix = 123.45, radix_decimal_part_len = 2 radix_decimal_part_len = long(len(radix.split(".")[1])) ## radix = 123.45, radix_as_long = 123.45 * 10**2 = 12345 radix_as_long = long(Decimal(radix) * (10L**radix_decimal_part_len)) ##corrected_exponent = 10 - 2 = 8 corrected_exponent = exponent - radix_decimal_part_len ## return 12345 * 10**8 result = radix_as_long * 10L** corrected_exponent else: radix_as_long = long(radix) result = radix_as_long * 10L**exponent else: if "." in radix: radix_integer_part = long(radix.split(".")[0]) else: radix_integer_part = long(radix) result = radix_integer_part return result Working from inside decimal.py allows things to work faster, but anyone wanting speed REALLY shouldn't use Decimal :). Now I'm trying clnum ("Rational and arbitrary precision floating point numbers"): http://cheeseshop.python.org/pypi/clnum/1.2 Cheers, Daniel From g.brandl-nospam at gmx.net Thu Aug 31 16:07:47 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Thu, 31 Aug 2006 22:07:47 +0200 Subject: Assignment-in-conditional In-Reply-To: <1157049685.909882.76210@p79g2000cwp.googlegroups.com> References: <1157049685.909882.76210@p79g2000cwp.googlegroups.com> Message-ID: <ed7fik$9ad$1@news.albasani.net> xamdam wrote: > I am not sure if this came up before, but I would love to have an > 'assignment-in-conditional' form in python, e.g > > pat = re.compile('something') > > if m = pat.match(s): > m.group(1) > > Of course there is some concern about accidentally using '=' instead of > '=='. One possible solution is to do what the 'with' statement does: > > if pat.match(s) as m: > ... > > a little ugly but not too much worse that with itself.. > > what do you guys think? It has been proposed before (a few times even), and Guido doesn't like it. Georg From mail at microcorp.co.za Thu Aug 3 08:10:16 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Thu, 3 Aug 2006 14:10:16 +0200 Subject: Is there an obvious way to do this in python? References: <mailman.8853.1154537129.27775.python-list@python.org> <44d128e5$0$13484$636a55ce@news.free.fr><mailman.8884.1154590374.27775.python-list@python.org> <44d1c6cb$0$13458$636a55ce@news.free.fr> Message-ID: <012101c6b6f5$e72d8280$03000080@hendrik> "Bruno Desthuilliers" <onurb at xiludom.gro> wrote: |H J van Rooyen wrote: |> "Bruno Desthuilliers" <bdesth.quelquechose at free.quelquepart.fr> wrote: |> |> 8<----------------------------------------------- |> |You'll at least need bits of SQL (but SQLAlchemy may hide away most of |> |it) and HTML (but there are some python packages that knows how to build |> |HTML from declarative Python code). |> | |> |> that is good news - which packages? http://divmod.org/trac/wiki/DivmodNevow http://divmod.org/trac/wiki/DivmodNevow/Athena http://starship.python.net/crew/friedrich/HTMLgen/html/main.html http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/366000 http://dustman.net/andy/python/HyperText/ http://pyhtmloo.sourceforge.net/ Thanks for the references I will try to check them all out 8<-------------------------------------------------- |> If my original post was unclear I am sorry - the point I want answered, if |> possible, is how to make the client code effectively updateable on the fly - |> because the answer to this will influence the whole design of the rest of the |> system... | |This is something I have been thinking about... IMHO what you want is |not to "update client code on the fly", but to make the client mostly a |kind of interpreter for what the server sends in. That is, the client |code itself doesn't contain any application logic, it gets it from the |server and execute it. This can certainly be done with Pyro. | |Now while this may be an interesting project, I'm not really sure it's |worth the effort when we already have HTTP, HTML and AJAX... You may be right and it might not be worth the trouble - but what you mention above is closer to the sort of thing I have in mind - it is essentially using python to create a script language, and moving scripts around - but hey - python is already a script language... so if Pyro is for 'moving the scripts around' - Then that is what I must look at very hard... - thanks - Hendrik From apardon at forel.vub.ac.be Wed Aug 2 09:09:26 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 2 Aug 2006 13:09:26 GMT Subject: Nested function scope problem References: <mailman.8675.1154112875.27775.python-list@python.org> <slrnecn499.98c.apardon@rcpc42.vub.ac.be> <mailman.8703.1154198214.27775.python-list@python.org> <slrnecpavl.c6f.apardon@rcpc42.vub.ac.be> <mailman.8711.1154269113.27775.python-list@python.org> <1154400727.472816.243290@b28g2000cwb.googlegroups.com> <mailman.8800.1154441595.27775.python-list@python.org> <h00vc2tj5gpsuctgguoi2ol6pq3a1rm2en@4ax.com> <slrnecv4om.l2k.apardon@rcpc42.vub.ac.be> <pn90d21iuvprace809uj3qti7vtjof2n1j@4ax.com> Message-ID: <slrned1906.npb.apardon@rcpc42.vub.ac.be> On 2006-08-02, Dennis Lee Bieber <wlfraed at ix.netcom.com> wrote: > On 1 Aug 2006 17:44:54 GMT, Antoon Pardon <apardon at forel.vub.ac.be> > declaimed the following in comp.lang.python: > >> Suppose I write a C-interpreter and then would translate a statement >> like "c = c + 100" into actions the interpreter would have to take in >> order to excute that statement. Something like: >> >> c-addr_p = GetAddress("c"); >> c-value = *c-addr_p; >> sum = c-value + 100; >> *c-addr_p = sum; >> > If this is what your interpreter generates/executes for a C-language > assignment, then the source language is no longer C... How do you come to that decision? > After all, Python's most common implementation IS in C. > > In C, the difference between "c" as a pointer, and "*c" as what it > points to is explicitly exposed to the user... The two views can be > separately manipulated. "c" as a variable can be manipulated -- c++ > changes c to "point to" an object (of the type of "c") that is presumed > to follow the existing object -- whether such exists or not. > > Python does not expose that to the user... You have a name and you > have an object. The name exists, or it doesn't, independent of the > object. Not in C -- while the object may not exist, the name, to be used > at all, has to exist and has storage space assigned to it; storage the > programmer is able to manipulate without an object. And how is this all relevant in deciding that the source language for the above interpreter actions isn't C? What the interpreter does is the following: Get the addres of the variable c Get the value that is at that address. Add 100 to this value Store the new value at that address. Please explain what is wrong in this sequence of actions for an interpretation of the C statement: "c = c + 100;" -- Antoon Pardon From jorge.vargas at gmail.com Mon Aug 28 17:59:13 2006 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Mon, 28 Aug 2006 17:59:13 -0400 Subject: Python web service ... In-Reply-To: <1156590455.555359.247410@h48g2000cwc.googlegroups.com> References: <1156590455.555359.247410@h48g2000cwc.googlegroups.com> Message-ID: <32822fe60608281459i56784c8bo20b3cacba0852423@mail.gmail.com> On 26 Aug 2006 04:07:35 -0700, nicolasg at gmail.com <nicolasg at gmail.com> wrote: > Hi folks, I have accomplished to make a python program that make some > image manipulation to bmp files. > I now want to provide this program as a web service. A user can visit a > site and through a web interface he should upload the file to the web > server , the server then will do the image process with the python > program I have wrote and when it finish the user must get the image > file back . > > My question is how difficult is to set up a web server that can run > python easy ? should I try ZOPE or there is something better in mind ? is that webservice or webserver? if webservice try ZSI of it's a webserver why don't you try CherryPy? > > -- > http://mail.python.org/mailman/listinfo/python-list > From rogue_pedro at yahoo.com Mon Aug 28 15:21:38 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 28 Aug 2006 12:21:38 -0700 Subject: Middle matching - any Python library functions (besides re)? In-Reply-To: <12f6f39joooir9a@corp.supernews.com> References: <1156722194.089832.282510@74g2000cwt.googlegroups.com> <7xirkd4s5w.fsf@ruckus.brouhaha.com> <1156743141.536257.157410@74g2000cwt.googlegroups.com> <12f5nbck5bn3o7d@corp.supernews.com> <1156790949.886283.255000@b28g2000cwb.googlegroups.com> <12f6f39joooir9a@corp.supernews.com> Message-ID: <1156792898.323668.21370@75g2000cwc.googlegroups.com> Andrew Robert wrote: > Because I was lazy.. > > The checksume_compare came from something else I wrote that had special > logging and e-mailer calls in it. > > Should have ripped the reference to caller and file name out.. Aaaahh the subtle joys of cut-and-paste programming... :-D (I've done it myself... ;-) From linnorm at gmail.com Thu Aug 24 13:42:10 2006 From: linnorm at gmail.com (linnorm at gmail.com) Date: 24 Aug 2006 10:42:10 -0700 Subject: String formatting with nested dictionaries In-Reply-To: <mailman.9799.1156438446.27775.python-list@python.org> References: <1156436560.040352.162580@b28g2000cwb.googlegroups.com> <mailman.9799.1156438446.27775.python-list@python.org> Message-ID: <1156441330.183274.60930@i42g2000cwa.googlegroups.com> Gabriel Genellina wrote: > At Thursday 24/8/2006 13:22, linnorm at gmail.com wrote: > > >I've got a bit of code which has a dictionary nested within another > >dictionary. I'm trying to print out specific values from the inner > >dict in a formatted string and I'm running into a roadblock. I can't > >figure out how to get a value from the inner dict into the string. To > >make this even more complicated this is being compiled into a large > >string including other parts of the outer dict. > > > >mydict = {'inner_dict':{'Value1':1, 'Value2':2}, 'foo':'bar', > >'Hammer':'nails'} > > > >print "foo is set to %(foo)s - Value One is: %(inner_dict['Value1'])s > >and Value Two is: %(inner_dict['Value2'])s -- Hammers are used to pound > >in %(Hammer)s" % mydict > > > >The above fails looking for a key named 'inner_dict['Value1']' which > >doesn't exist. > > I can think of two ways: > > a) Flatten your dictionary. That is, move the contents of inner_dict > onto the outer dict: > mydict.update(mydict['inner_dict']) > Then use single names for interpolation > > b) Do the interpolation in two steps. > > template = "foo is set to %(foo)s - Value One is: %(Value1)s > and Value Two is: %(Value2)s -- Hammers are used to pound > in %(Hammer)s" > output = template % mydict['inner_dict'] > output = output % mydict > > Both methods assume that the inner dict takes precedence in case of > name clashes; reverse the order if you want the opposite. > > > Gabriel Genellina > Softlab SRL > Thanks, I started going with a) only doing it the long way. (mydict['Value1'] = mydict['inner_dict']['Value1']) mydict.update() is *much* simpler and less prone to errors too. From johnjsal at NOSPAMgmail.com Tue Aug 29 10:33:50 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 29 Aug 2006 14:33:50 GMT Subject: Python editor In-Reply-To: <ed02ij$591$1@news.cn99.com> References: <mailman.9834.1156459647.27775.python-list@python.org> <44EE3312.8040707@websafe.com> <ed02ij$591$1@news.cn99.com> Message-ID: <ifYIg.2712$No6.53186@news.tufts.edu> Jerry Fleming wrote: > Larry Bates wrote: >> Jason Jiang wrote: >>> Hi, >>> >>> Could someone recommend a good Python editor? Thanks. >>> >>> Jason >>> >>> >> For just getting started use Idle that comes with Python. >> If you are already a user or if you are looking for a more >> powerful solution you can use Eclipse (with Python plug-in). >> These represent both ends of the spectrum in editors. >> >> -Larry Bates > > Vim (vim-python) or emacs (python.el) is always the best solution. Is it possible to get vim-python for Windows, or is that just a Linux build? From jadedgamer at hotmail.com Thu Aug 31 12:31:15 2006 From: jadedgamer at hotmail.com (Tor Iver Wilhelmsen) Date: 31 Aug 2006 18:31:15 +0200 Subject: Duck typing alows true polymorfisim References: <1156532721.879808.40990@i3g2000cwc.googlegroups.com> <1156533807.630662.12330@i42g2000cwa.googlegroups.com> <12fblk87ppk7ief@corp.supernews.com> <9l9hs3-64h.ln1@sirius.tg00suus7038.net> Message-ID: <uzmdklve4.fsf@hotmail.com> The Ghost In The Machine <ewill at sirius.tg00suus7038.net> writes: > Also, one language is very conspicuous by its absence: C#. He does not date any of the updates, so it's unclear how recently it has been updated (a lot of the web is stale, like a rotting tree in a forest.) > AmigaBasic -- Microsoft-sponsored Amiga variant Well, at the time Microsoft were the makers of the de-facto BASIC implementations - M-BASIC for CP/M, the various variants in VC-20 and C-64 and later derivates of those, and many other home computers. "Sponsored" should probably be "created" instead - I assume they were paid for the job. > Also, Java now has templates. (The implementation is pretty gross > and has some quirks, IMO, but it's better than nothing.) C++ has a > typing system ("type_of" or some such; I'd have to look) which > yields little more than the mangled type name and static inheritance > testing capabilities. Of course C++ doesn't have dynamic inheritance > anyway. There's the virtual stuff, and you could conceivably implement dynamic inheritance via the bare-bones C layer - like function pointers. The type information in C++ (RTTI) is optional. > Dynamic type creation. I don't know if Java has this or not. One can > of course attempt bytecode synthesis -- I think that's what BCEL > uses -- but that's a bit of a hack. Groovy could possibly be used for that; also IIRC Java 6 adds some features for that. I seem to recall security implications being one reason this ability wasn't included from the start. > Dynamic method creation. Java does *not* have this. AIUI > Smalltalk-80 does; one can take an existing class and add methods > thereto. Yes, but that's because a Smalltalk program lives inside a big binary "image" that is mutable. Woe unto you if that big binary file gets corrupted. > Dynamic method deletion. I for one might only want this in the > context of a "sandbox" but if one can create methods, one should be > able to delete them as well if only because of undo. The problem with deleting a method is whether the runtime can handle it: Smalltalk has doesNotUnderstand:#aMessage, Java has NoSuchMetohdError - what does C++ do? A zeroed virtual method would cause a pure virtual method call error, which I guess C++ programmers are trained to take into account. Also, if class A has a method and you delet it in subclass B, it breaks the Liskov Substitution Principle, there B should be able to function where an A is wanted. > Dynamic method rename. This could lead to much madness but this > might be useful during sandboxing. A method's name and its "address" are distinct, but for dynamic method dispatch, what about any other code that doesn't know the new name but assumes the method is called the same? > Dynamic inheritance. For those languages that support inheritance > one might liken it to changing what the language inherits or > implements on the fly. I don't know of any language apart from > Smalltalk that can even think about allowing dynamic inheritance, > but it's a thought. If you can change a Perl class, er, module's @INC array I think that would support it. > Operator overload (e.g., C++'s operator ==()). Or rather "dotless/prefix method invocation with the added baggage of precedence rules". Smalltalk solves this by 1) not having those precedence rules, 2) have dotless method invocation and 3) > > Name overload. C does not have it; C++ and Java do. I suspect Ruby > and Python do as well. Are you referring to namespaces, ie. namespace isolation? > Globals. Java has no globals as such, unless one counts class names. > C is all globals, unless one counts statics. Even the fully qualified classes are only "global" in the context of a classloader and whatever classloaders it delegates to. > Unnamed classes. new Runnable() { public void run() {...} } is > Java's contribution. Can be useful. Well, they do end up with a name after compilation. And you do not want to open that can of worms since then you end up with Ruby and Smalltalk users dragging out closures and C# and Lisp users dragging out lambdas... :) > Nested classes. Generally that's just a namespace issue. In Java, a class Fie nested inside Foo is the top-level class Foo$Fie with some compiler magic to ensure it's used correctly, which leads to funny stuff like Foo.Fie object = new Foo().new Fie(); which gets turned into the bytecode equivalent of Foo$Fie object = new Foo$Fie(new Foo()); > Primitive types -- in other words, the int<->Integer dichotomy we > all know and love in Java; such also exists in C++ and IINM C#. I'm > not sure if Smalltalk has such a concept, or not; Smalltalk allows > overrides on numbers. (In Java one might contemplate 2.toString(), > for example!) In Smalltalk you ask the 1 object to count to 10 for a loop. It makes sense there, it would not feel "right" in the C family... > Arbitrary integer size. The only language I know having this is > Common LISP. java.math.BigInteger, but the operations you can perform are limited. > Thread-level variable/value scoping. In Java this is done using the > ThreadLocal class, but is not (AFAICT) supported by the language > proper. Yes, and that leads to a problem where if you forget to null a ThreadLocal you can "leak" objects. > One might even contemplate function-level scoping, but that would > only be useful if one can create new functions on the fly and modify > these values; otherwise, they might as well be static. As long as you make sure you never use a private static member elsewhere than in that particular method, it can play the role of a function-level method. > Persistability. In Java one can implement Serializable or > Externalizable, and generate output from an object. I've always > considered this a bit of a weird hack but it can come in handy, and > forms one leg of the Java EJB implementation. Persistability is left as an excercise to libraries in most languages. > Volatile field. In Java there is a volatile keyword. I don't know > its precise semantics but it applies to fields. In Java it's generally a hint to the optimizer NOT to optimize away or make any assumptions about access to a field. > C#'s event handling emulates this concept to some extent using the > += operator, though I doubt they do it all that generally -- or all > that well. Well it's closer to a list of function pointers, sorry delegates; not much more than Java's more explicit (or cumbersome if you like) event interfaces can do. > Integrated database access (and how tightly). C++ has none at all, > though of one can use various third-party libraries. Java has some > base-level API -- the java.sql.* and javax.sql* library. Well, those are general library APIs that require native or socket-based implementation by vendors or third parties. What you talk about is better represented by "inline" SQL in the form of SQLJ or Oracle's Pro*C and related products. It boils down to how much should be in the language (syntax, compiler, runtime) and how much should be left to libraries. E.g. he has a "no" for garbage collection in C++, but there are libraries for that sort of thing (relying mostly on the ability to override the new, delete and assignment operators. Even in Java you often have a choice of garbage collector algorithms in a runtime. From dieter at handshake.de Mon Aug 28 15:26:09 2006 From: dieter at handshake.de (Dieter Maurer) Date: 28 Aug 2006 21:26:09 +0200 Subject: Don't use __slots__ (was Re: performance of dictionary lookup vs. object attributes) References: <mailman.9853.1156495094.27775.python-list@python.org> <1156508104.583914.323700@b28g2000cwb.googlegroups.com> <ecn1qa$ksp$1@panix2.panix.com> <7.0.1.0.0.20060825122244.03790010@yahoo.com.ar> <mailman.9880.1156520034.27775.python-list@python.org> <1156621904.481215.243080@m73g2000cwd.googlegroups.com> Message-ID: <x7u03w7jce.fsf@handshake.de> "Patrick Maupin" <pmaupin at gmail.com> writes on 26 Aug 2006 12:51:44 -0700: > ... > The only > problem I personally know of is that the __slots__ aren't inherited, "__slots__" *ARE* inherited, although the rules may be a bit complex. >>> class B(object): ... __slots__ = ('f1', 'f2',) ... >>> class C(B): pass ... >>> C.__slots__ ('f1', 'f2') >>> c=C() >>> c.__dict__ {} >>> c.f1='f1' >>> c.__dict__ {} >>> c.fc='fc' >>> c.__dict__ {'fc': 'fc'} >>> class C2(B): ... __slots__=('f21',) ... >>> C2.__slots__ ('f21',) >>> c2=C2() >>> c2.f1='x' >>> c2.f21='y' -- Dieter From rogue_pedro at yahoo.com Tue Aug 8 16:58:06 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 8 Aug 2006 13:58:06 -0700 Subject: String.digits help!!! References: <1155058550.954997.320250@m79g2000cwm.googlegroups.com> <1155063757.284414.135630@n13g2000cwa.googlegroups.com> <1155064331.588367.136290@m73g2000cwd.googlegroups.com> Message-ID: <1155070685.953831.204500@m79g2000cwm.googlegroups.com> bearophileHUGS at lycos.com wrote: > Simon Forman: > > It's unlikely to > > be deprecated since it doesn't make much sense to make it an attribute > > of the str type. > > Why? > > Thank you, > bearophile Let me toss the question back at you: Does it make sense to you that str should have this attribute? Why? I'm not advocating for or against one thing or another, and I'm certainly not in a position to influence the future development of Python (anymore than any of us, that is :-) ) but FWIW, here's my $0.02: My "feeling" is that since str is a Type, and not a data store, it doesn't make much sense to me to tack on a bunch of read-only data attributes that aren't involved in it's role as a string data type just to have a slightly more convenient way of accessing them. There are twelve "constants" defined in the string module. If they were all attributes of the str type it would, for me, conceptually "clutter up" my mental model of str, string, and python itself. I like "from string import digits" well enough, and, as a test of my mental model, I just used IDLE's "open module" command to find and open string.py and discovered: # Some strings for ctype-style character classification whitespace = ' \t\n\r\v\f' lowercase = 'abcdefghijklmnopqrstuvwxyz' uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' letters = lowercase + uppercase ascii_lowercase = lowercase ascii_uppercase = uppercase ascii_letters = ascii_lowercase + ascii_uppercase digits = '0123456789' hexdigits = digits + 'abcdef' + 'ABCDEF' octdigits = '01234567' punctuation = """!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~""" printable = digits + letters + punctuation + whitespace Exactly what I expected to find! Really, I wouldn't be too badly shocked to discover the above string "constants" in dir(str), so it's kind of "six of one, a half dozen of the other". But on the same token, "if it's not broken, don't fix it." Further, to make these "constants" into attributes of str, someone would have to modify the str type at the C level to put these strings "on" it. Since they are str's themselves, it seems to me (having done only trivial work with the C API of python) that that someone would have to A) create a "first" str type, B) create these 12 strings using that first type, C) attach them to the str type to create a "final" str type. And all this would have to be done at startup, I think, even if my code didn't use these attributes. It seems messy to me. So to sum up, IMO, a module (rather than a type) is a good place for these things, a module with some variable assignments is completely within my mental model of python (i.e. no special case (of strings being attributes of their own type (!?))), and no one has to do anything special to make the current set up work. By the way, I read your post a few days ago concerning adding similar data attributes to ints and floats and found it very interesting but not compelling. While I would love to have the kind information you mentioned available, I've never needed it in practice (I've only ever used sys.maxint maybe a dozen times) and I wouldn't mind accessing it from a module (perhaps math.. math.infinity, math.epsilon, etc., just like math.pi and math.e.) I look forward to hearing your thoughts an the subject. I hope mine haven't been too silly.. :-) Regards, ~Simon From jackson at hotmail.com Mon Aug 14 13:37:50 2006 From: jackson at hotmail.com (Jackson) Date: Mon, 14 Aug 2006 10:37:50 -0700 Subject: selecting base class from user input In-Reply-To: <mailman.9295.1155543976.27775.python-list@python.org> References: <ebo1v5$jos$1@skeeter.ucdavis.edu> <1155523781.860117.203140@h48g2000cwc.googlegroups.com> <ebp90n$sh6$1@skeeter.ucdavis.edu> <mailman.9295.1155543976.27775.python-list@python.org> Message-ID: <ebqcdf$61i$1@skeeter.ucdavis.edu> Maric Michaud wrote the following on 2006-08-14 01:26: > In [28]: class Animal(object) : > ....: _types = {} > ....: > ....: > > In [29]: class Worker(object) : > ....: def work(self) : print 'hard' > ....: > ....: > [snip] > What you are trying to achieve is more commonly done by agregation and > delegation : > > In [47]: class Lion(Animal) : > ....: def __init__(self, *classes) : > ....: self._objects = tuple(c() for c in classes) > ....: def isA(self, class_) : > ....: return class_ in (type(o) for o in self._objects) > ....: def __getattr__(self, name) : > ....: for obj in self._objects : > ....: try: return getattr(obj, name) > ....: except: pass > ....: raise AttributeError('not defined or found in objects "%s"' % > name) > ....: > ....: > > In [48]: Lion().work() > --------------------------------------------------------------------------- > exceptions.AttributeError Traceback (most recent > call last) > > /home/maric/<ipython console> > > /home/maric/<ipython console> in __getattr__(self, name) > > AttributeError: not defined or found in objects "work" > > In [49]: Lion().isA(Worker) > Out[49]: False > > In [50]: Lion(Worker).isA(Worker) > Out[50]: True > > In [51]: Lion(Worker).work() > hard > This is exactly what I am looking for. However, I am not sure how to implement different Worker methods. For example, a Lion might work differently than an Bee. In my example, the Lion would take a cat-nap while the Bee might do a dance. It seems that I would need to what kind of class called the work() method. Is there a way to do that? Even if I could do that, it seems these various definitions of work should probably go into the class of the animal---so that Lion actions are all within the Lion class. Thus, the Lion class should have its own work method, and the Bee class should have its own work method as well. The problem with this is that every Lion can use the work method, when I really only work Workers to use the work method. I can picture another way of achieving this...have a list of occupations...which are booleans for each instance of the class. Then the work() method will call only if the Worker boolean is True. This should be sufficient...and the differing work methods would be in their respective classes. However, now the actual method names are not uniform---that is, it becomes a bookkeeping exercise to remember that when Worker is True, then the method to create is work(), that when Student is True, then the method to create is study(). So this procedure has its own problems too. It seems like I am trading off hardships now. So here is what I am looking for: A single Worker class with a standardized set of method names. The methods in the Worker class are dependent on the "superclass" (via aggregation and delegation, as shown above) of the worker. That is, a Bee performs different actions when working than a Lion or a Human. And finally, the occupations such that "not every Bee is a worker" and "there are some Workers which are Bees". Thanks! From carsten at uniqsys.com Tue Aug 1 09:45:21 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 01 Aug 2006 09:45:21 -0400 Subject: Can't get LCHARVAR's with InformixDB In-Reply-To: <1154438862.714569.9130@b28g2000cwb.googlegroups.com> References: <1154437329.471918.35150@h48g2000cwc.googlegroups.com> <mailman.8792.1154437891.27775.python-list@python.org> <1154438862.714569.9130@b28g2000cwb.googlegroups.com> Message-ID: <1154439921.452.39.camel@dot.uniqsys.com> On Tue, 2006-08-01 at 09:27, fhurley at gmail.com wrote: > Carsten Haese wrote: > > What version are you using? I thought I fixed lvarchars a long time ago. > > 2.2, with Python 2.4 on Windows... I installed via > InformixDB-2.2.win32-py2.4.exe Hm, this certainly warrants further investigation. I don't use lvarchars myself, so it's possible that I did something that accidentally broke the output binding for lvarchars. Could you possibly send me a minimal test script that shows the problem? Also, in case it matters, I'd like to know which versions of IDS and CSDK or Informix Connect you're using. Thanks, Carsten. From jason at adapt.com Wed Aug 16 15:28:44 2006 From: jason at adapt.com (Jason Nordwick) Date: Wed, 16 Aug 2006 12:28:44 -0700 Subject: getting database column names from query Message-ID: <44E371EC.4060801@adapt.com> I'm using MySQLdb and can connect and issue queries that return result sets, but I how do I get the column names for those result sets? >>> c = MySQLdb.connect(*creds) >>> k = c.cursor() >>> k.execute("select * from account") 3L >>> k.fetchall() ((1L, 'test', -1L), (2L, 'Test', -1L), (3L, 'Test2', -1L)) -j From sfaulconer at gmail.com Mon Aug 21 15:30:09 2006 From: sfaulconer at gmail.com (Steven) Date: 21 Aug 2006 12:30:09 -0700 Subject: List splitting In-Reply-To: <ecd15s$26e$1@minji.szn.dk> References: <1156187837.378252.36420@m73g2000cwd.googlegroups.com> <ecd15s$26e$1@minji.szn.dk> Message-ID: <1156188609.070648.229310@m79g2000cwm.googlegroups.com> Klaus Alexander Seistrup wrote: > >>> t = [ "a", "b", "c", "n", "a", "a", "t", "t", "t" ] > >>> [t[i::3] for i in range(3)] > [['a', 'n', 't'], ['b', 'a', 't'], ['c', 'a', 't']] Klaus, Thanks for the fast reply! Had I taken the time to look at the list-type docs (which I did to understand how you were spliting the list), I'd probably have seen the slicing with step option. Another RTFM issue for me. Thanks again, Steven From shuanyu at gmail.com Sat Aug 19 07:18:18 2006 From: shuanyu at gmail.com (many_years_after) Date: 19 Aug 2006 04:18:18 -0700 Subject: How to get the ascii code of Chinese characters? Message-ID: <1155986298.643983.157460@i3g2000cwc.googlegroups.com> Hi,everyone: Have you any ideas? Say whatever you know about this. thanks. From fredrik at pythonware.com Sun Aug 27 07:50:07 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 27 Aug 2006 13:50:07 +0200 Subject: CONSTRUCT - Module Attributes and Execution Environment In-Reply-To: <FbydnandyMuUtHbZnZ2dnUVZ_smdnZ2d@comcast.com> References: <1156253227.092971.36510@74g2000cwt.googlegroups.com> <FbydnandyMuUtHbZnZ2dnUVZ_smdnZ2d@comcast.com> Message-ID: <ecs0tf$13j$1@sea.gmane.org> Larry Bates wrote: > 1) Don't call a class instance exec, it will mask the built-in > exec statement. "exec" is a reserved word, and cannot be masked: >>> exec = 10 File "<stdin>", line 1 exec = 10 ^ SyntaxError: invalid syntax </F> From mensanator at aol.com Tue Aug 8 18:17:05 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 8 Aug 2006 15:17:05 -0700 Subject: how to save a screenshot in pygame? In-Reply-To: <1155072958.550904.50790@i3g2000cwc.googlegroups.com> References: <1155072958.550904.50790@i3g2000cwc.googlegroups.com> Message-ID: <1155075425.851210.8530@m79g2000cwm.googlegroups.com> liuliuliu wrote: > hi -- sorry if this is trivial -- but how do you make a screenshot of a > pygame display? i have a surface which is basically the entire visible > screen -- how do you write this surface as an image file during > specific events in the script execution? image format doesnt matter. pygame.image.save() is probably the thing you want. >>> help(pygame.image) Help on module pygame.image in pygame: NAME pygame.image FILE c:\python24\lib\site-packages\pygame\image.pyd DESCRIPTION This module contains functions to transfer images in and out of Surfaces. At the minimum the included load() function will support BMP files. If SDL_image is properly installed when pygame is installed, it will support all the formats included with SDL_image. You can call the get_extended() function to test if the SDL_image support is available. Some functions that communicate with other libraries will require that those libraries are properly installed. For example, the save() function can only save OPENGL surfaces if pyopengl is available. FUNCTIONS frombuffer(...) pygame.image.frombuffer(string, size, format) -> Surface create a surface from a python memory buffer This works like the fromstring() method, but uses Python buffer objects. It is about 20 times faster than fromstring(). Strings and memory maps are examples of buffers in Python. See the fromstring() function for information about the size and format arguments. fromstring(...) pygame.image.fromstring(string, size, format, flipped=0) -> Surface create a surface from a raw string buffer This will create a new Surface from a copy of raw data in a string. This can be used to transfer images from other libraries like PIL's fromstring(). In most cases you can use the frombuffer() which accepts strings and is about 20 times faster. The flipped argument should be set to true if the image in the string is. The format argument is a string representing which type of string data you need. It can be one of the following, "P" for 8bit palette indices. "RGB" for 24bit RGB data, "RGBA" for 32bit RGB and alpha, or "RGBX" for 32bit padded RGB colors. "ARGB" is a popular format for big endian platforms. These flags are a subset of the formats supported the PIL Python Image Library. Note that the "P" format only create an 8bit surface, but the colormap will be all black. get_extended(...) pygame.image.get_extended() -> int returns true if SDL_image formats are available This will return a true value if the extended image formats from SDL_image are available for loading. load = load_extended(...) load_basic(...) pygame.image.load(file, [namehint]) -> Surface load an image to a new Surface This will load an image into a new surface. You can pass it either a filename, or a python file-like object to load the image from. If you pass a file-like object that isn't actually a file (like the StringIO class), then you might want to also pass either the filename or extension as the namehint string. The namehint can help the loader determine the filetype. If pygame was installed without SDL_image support, the load will only work with BMP images. You can test if SDL_image is available with the get_extended() function. These extended file formats usually include GIF, PNG, JPG, PCX, TGA, and more. If the image format supports colorkeys and pixel alphas, the load() function will properly load and configure these types of transparency. load_extended(...) save(...) pygame.image.save(Surface, file) -> None save surface data This will save your surface as a BMP or TGA image. The given file argument can be either a filename or a python file-like object. This will also work under OPENGL display modes. The image will default to save with the TGA format. If the filename has the BMP extension, it will use the BMP format. tostring(...) pygame.image.tostring(Surface, format, flipped=0) -> string create a raw string buffer of the surface data This will copy the image data into a large string buffer. This can be used to transfer images to other libraries like PIL's fromstring() and PyOpenGL's glTexImage2D(). The flipped argument will cause the output string to have it's contents flipped vertically. The format argument is a string representing which type of string data you need. It can be one of the following, "P" for 8bit palette indices. "RGB" for 24bit RGB data, "RGBA" for 32bit RGB and alpha, or "RGBX" for 32bit padded RGB colors. "ARGB" is a popular format for big endian platforms. These flags are a subset of the formats supported the PIL Python Image Library. Note that the "P" format only will work for 8bit Surfaces. If you ask for the "RGBA" format and the image only has colorkey data. An alpha channel will be created from the colorkey values. > > thanks! christine From zoombywoofremove at thishotmail.com Thu Aug 24 04:54:21 2006 From: zoombywoofremove at thishotmail.com (ZoombyWoof) Date: Thu, 24 Aug 2006 10:54:21 +0200 Subject: datetime problems select from MySQL Message-ID: <ecjpfu$p5m$1@news.datemas.de> Hi. I have ran into a weird thing I just can't find any solution for. I have googled and searched but no luck. The problem is that when I select TIME values from MySQL from python, I get wrong results when the TIME values are negative. From mysql program: mysql> select id,flex from Users where id=2; +----+----------+ | id | flex | +----+----------+ | 2 | 00:30:00 | +----+----------+ From python script: SELECT id,flex FROM Users WHERE id=2 Data back from MySQLdb: ((2L, datetime.timedelta(0, 1800)),) This looks good and fine, but this : From mysql program: mysql> select id,flex from Users where id=2; +----+-----------+ | id | flex | +----+-----------+ | 2 | -00:30:00 | +----+-----------+ From python : SELECT id,flex FROM Users WHERE id=2 Data back from MySQLdb: ((2L, datetime.timedelta(0, 1800)),) Not good, python thinks this is a positive value. One more: mysql> select id,flex from Users where id=2; +----+-----------+ | id | flex | +----+-----------+ | 2 | -01:30:00 | +----+-----------+ Python : SELECT id,flex FROM Users WHERE id=2 Data back from MySQLdb: ((2L, datetime.timedelta(-1, 84600)),) At least its negative but this looks to me as -00:30 rather than -01:30..... (86400-84600 = 1800, = 30 minutes) And now a negative that works!: mysql> select id,flex from Users where id=2; +----+-----------+ | id | flex | +----+-----------+ | 2 | -10:00:00 | +----+-----------+ Python: SELECT id,flex FROM Users WHERE id=2 Data back from MySQLdb: ((2L, datetime.timedelta(-1, 50400)),) This looks alright to me...(86400-50400 = 36000, = 10 hours) Any ideas ? Have I missed something obvious here or ? It seems to be offset by an hour or something.... I run python2.4 on debian sarge, MySQL 5.0.18 and python-mysqldb version 1.2.1-c2-1 Any help greatly appreciated. Thanx. /ZW From rhymes at myself.com Thu Aug 3 07:54:09 2006 From: rhymes at myself.com (Lawrence Oluyede) Date: Thu, 3 Aug 2006 13:54:09 +0200 Subject: opposite of import References: <1154605835.465468.97550@m79g2000cwm.googlegroups.com> Message-ID: <1hjhyln.1rvx6fv1mndt8uN%rhymes@myself.com> pranav.choudhary at gmail.com <pranav.choudhary at gmail.com> wrote: > I am new to python. I wanted to know if there is an opposite of "import" What do you mean? What are you trying to accomplish? -- Lawrence - http://www.oluyede.org/blog "Nothing is more dangerous than an idea if it's the only one you have" - E. A. Chartier From python at cgcreator.com Tue Aug 8 08:43:39 2006 From: python at cgcreator.com (Keith) Date: Tue, 8 Aug 2006 22:43:39 +1000 Subject: class return another instance Message-ID: <200608081243.k78Chebg035362@smtp3.adl2.internode.on.net> Hello All, Here is simplified version of what I'm trying to do: //////////////////////////////////////////////////////////////////////////// //////////////////////////// IDs = {} class ID: def __init__(self, id): if id in IDs: self = IDs[id] else: IDs[id] = self foo = ID(1) bar = ID(2) copy = ID(1) print "foo: " + str(foo) + " with ID of 1" print "bar: " + str(bar) + " with ID of 2" print "copy: " + str(copy) + " should be a copy of foo" print "IDs: " + str(IDs) //////////////////////////////////////////////////////////////////////////// //////////////////////////// What I'm after is if you call the class ID. it checks to is if the "id" is in the dictionary IDs. if so then use that class instance. else put self into the dictionary as a new key-value, so if you try and create it again. it will use that instance. Also I know its easy enough to do copy = foo. but I would like the class to determine this for me. any ideas? There has got to be a way to replace self with another instance. or return something from the init statement. Here's what it returns: foo: <__main__.ID instance at 0x01DE6CB0> with ID of 1 bar: <__main__.ID instance at 0x01DE6CD8> with ID of 2 copy: <__main__.ID instance at 0x01DE6D00> should be a copy of foo IDs: {1: <__main__.ID instance at 0x01DE6CB0>, 2: <__main__.ID instance at 0x01DE6CD8>} What I would expect/want: foo: <__main__.ID instance at 0x01DE6CB0> with ID of 1 bar: <__main__.ID instance at 0x01DE6CD8> with ID of 2 copy: <__main__.ID instance at *0x01DE6CB0*> should be a copy of foo IDs: {1: <__main__.ID instance at 0x01DE6CB0>, 2: <__main__.ID instance at 0x01DE6CD8>} Any help would be great. Cheers, Keith -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060808/a6a7e0ac/attachment.html> From mail2sirshendu at gmail.com Mon Aug 28 05:17:54 2006 From: mail2sirshendu at gmail.com (mail2sirshendu at gmail.com) Date: 28 Aug 2006 02:17:54 -0700 Subject: close event handling for ScrollView Message-ID: <1156756674.523840.172580@74g2000cwt.googlegroups.com> I have a class in which I have created an instance QScrollView and added a QDialog inside it using addChild().I have Ok and Cancel button in the Dialog.When either Ok or Cancel is clicked the Dialog is closed properly (receiving accept or reject signals). I have a exec loop on the Dialog. When I click the 'X' button on the toolbar of the ScrollView, the ScrollView is closing but the exec() call on the Dialog is not terminated and my application hangs. here is the portion of the code I am taiking about. self.scrollView = QScrollView() dialog = QDialog (self, ...., self.scrollView.viewport()) self.scrollView.addChild(dialog) self.scrollView.show() if (dialog.exec() == QDialog.Accepted): self.scrollView.hide() self.scrollView.removeChild(dialog) can someone suggest some way to handle this issue.. From riko at despammed.com Tue Aug 22 11:32:47 2006 From: riko at despammed.com (Mc Osten) Date: Tue, 22 Aug 2006 17:32:47 +0200 Subject: Python and STL efficiency References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <eccb9u$kjs$1@gemini.csx.cam.ac.uk> <1hkh28d.xscw4v1y4v9a6N%riko@despammed.com> <mailman.9640.1156247569.27775.python-list@python.org> <1hkh6lb.6dsnh51lj8z96N%riko@despammed.com> <1156252193.524186.107520@b28g2000cwb.googlegroups.com> Message-ID: <1hkhexv.18m65rl61swqyN%riko@despammed.com> Tim N. van der Leeuw <tim.leeuwvander at nl.unisys.com> wrote: > Oh boy; yes indeed the slow python is faster than the fast C++ > version... Must be something really awful happening in the STL > implementation that comes with GCC 3.4! And the Python version does the very same number of iterations than the C++ one? I suppose they are looping on arrays of different sizes, just like my "first version". -- blog: http://www.akropolix.net/rik0/blogs | Uccidete i filosofi, site: http://www.akropolix.net/rik0/ | tenetevi riso e forum: http://www.akropolix.net/forum/ | bacchette per voi. From fabiofz at gmail.com Wed Aug 23 12:08:22 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Wed, 23 Aug 2006 13:08:22 -0300 Subject: idutils and Python In-Reply-To: <624934630608230708v5df41b02ie0f6b862a4bd6a1c@mail.gmail.com> References: <mailman.9627.1156207047.27775.python-list@python.org> <1156226173.596437.266680@75g2000cwc.googlegroups.com> <624934630608220305k31b91a2ao9263c19cb342b662@mail.gmail.com> <cfb578b20608230431y3474a6aaj8b239a3e1958bcd3@mail.gmail.com> <624934630608230708v5df41b02ie0f6b862a4bd6a1c@mail.gmail.com> Message-ID: <cfb578b20608230908h2e81b854x96a1f06ddaec3973@mail.gmail.com> On 8/23/06, Ramon Diaz-Uriarte <rdiaz02 at gmail.com> wrote: > > Thanks for the answer. I had read about PyDev and its extenssions but, > if at all possible, I'd like to keep working with Emacs (or Vim) > instead of Eclipse, and I'd rather use free/open source software. > Well, you can use only Pydev without the extensions (its implementation of go to definition is powered by Bycicle Repair Man, which should be on par with other open-source implementations). Cheers, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060823/8094cb25/attachment.html> From m.yanowitz at kearfott.com Wed Aug 16 07:23:38 2006 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Wed, 16 Aug 2006 07:23:38 -0400 Subject: Defining our own types? Message-ID: <001001c6c126$6b7ba0a0$0d7d12ac@kearfott.com> Hello: I know this will probably turn about to be another dumb question and I know I have asked a few really dumb ones lately on this list, but I am hoping otherwise this time: suppose I type: ip = 123.45.67.89 (no quotes) - is it possible (maybe by catching an exception), to have this automatically converted to an ip address and maybe have the exception convert this into: ip = make_ip_address (123, 45, 67, 89) Or even better, if possible. Can I define my own type IP = BYTE + '.' + BYTE + '.' + BYTE + '.' + BYTE BYTE = in range(256) and have Python over-ride its rules so that if I type in a number followed by a dot followed by number followed by a dot followed by a number followed by a dot and another number, it can call make_ip_address() on the value? Thanks in advance: Michael Yanowitz From dwai.lahiri at gmail.com Tue Aug 15 14:17:08 2006 From: dwai.lahiri at gmail.com (implicate_order) Date: 15 Aug 2006 11:17:08 -0700 Subject: Creating Charts in Excel with pyExcelerator.ExcelMagic Message-ID: <1155665828.595235.214360@75g2000cwc.googlegroups.com> Greetings, I'm new to python and am in the process of writing a script to parse some CSV data, spread it across multiple Excel worksheets and then generate charts. I searched the internet to find some place where I could look up a HOWTO doc/recipe to do that using either pyExcelerator or win32com.client. Could someone point me in the right direction? I'm at the stage where the spreadsheet and associated data worksheets are ready. The chart is created (with win32com.client). I need to know how I can use win32com.client to actually generate some data based on the contents of a particular work sheet. >>> from win32com.client import * >>> xl = win32com.client.Dispatch("Excel.Application") >>> wb = xl.Workbooks.open("C:\scripts\dummytest.xls") >>> xl.Visible = 1 >>> ws = wb.Worksheets(1) >>> ws.Range('$A1:$D1').Value = ['NAME', 'PLACE', 'RANK', 'PRICE'] >>> ws.Range('$A2:$D2').Value = ['Foo', 'Fooland', 1, 100] >>> ws.Range('$A3:$D3').Value = ['Bar', 'Barland', 2, 75] >>> ws.Range('$A4:$D4').Value = ['Stuff', 'Stuffland', 3, 50] >>> wb.Save() >>> wb.Charts.Add() >>> wc1 = wb.Charts(1) At this point, I'm lost -- I couldn't find any lucid docs to indicate what can be done to populate the chart from the worksheet "ws". Any help would be greatly appreciated. TIA From tim.peters at gmail.com Sat Aug 12 18:27:46 2006 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 12 Aug 2006 18:27:46 -0400 Subject: Inconsistency producing constant for float "infinity" In-Reply-To: <1hjy8p2.1w7kmdk1f3hsysN%aleax@mac.com> References: <mailman.9250.1155308835.27775.python-list@python.org> <slrnedp7l2.d2v.sybrenUSE@schuimige.stuvel.eu> <ebi7jd$2o8$1@sea.gmane.org> <mailman.9260.1155321255.27775.python-list@python.org> <1hjy8p2.1w7kmdk1f3hsysN%aleax@mac.com> Message-ID: <1f7befae0608121527m18b9426fpe1696d81ab42aa1@mail.gmail.com> [Tim Peters] > ... >> It has a much better chance of working from .pyc in Python 2.5. >> Michael Hudson put considerable effort into figuring out whether the >> platform uses a recognizable IEEE double storage format, and, if so, >> marshal and pickle take different paths that preserve infinities, >> NaNs, and signed zeroes. [Alex Martelli] > Isn't marshal constrained to work across platforms (for a given Python > release), and pickle also constrainted to work across releases (for a > given protocol)? Yes to both. > I'm curious about how this still allows them to "take different > paths" (yeah, I _could_ study the sources, but I'm lazy:-)... Good questions. Pickle first: pickle, with protocol >= 1, has always had a binary format for Python floats, which is identical to the big-endian IEEE-754 double-precision storage format. This is independent of the native C double representation: even on a non-IEEE box (e.g, VAX or Cray), protocol >= 1 pickle does the best it can to /encode/ native doubles in the big-endian 754 double storage /format/. This is explained in the docs for the "float8" opcode in pickletools.py: The format is unique to Python, and shared with the struct module (format string '>d') "in theory" (the struct and cPickle implementations don't share the code -- they should). It's strongly related to the IEEE-754 double format, and, in normal cases, is in fact identical to the big-endian 754 double format. On other boxes the dynamic range is limited to that of a 754 double, and "add a half and chop" rounding is used to reduce the precision to 53 bits. However, even on a 754 box, infinities, NaNs, and minus zero may not be handled correctly (may not survive roundtrip pickling intact). The problem has been that C89 defines nothing about signed zeroes, infinities, or NaNs, so even on a 754 box there was no consistency across platforms in what C library routines like frexp() returned when fed one of those things. As a result, what Python's "best non-heroic effort" code for constructing a 754 big-endian representation actually did was a platform-dependent accident when fed a 754 special-case value. Likewise for trying to construct a native C double from a 754 representation of a 754 special-case value -- again, there was no guessing what C library routines like ldexp() would return in those cases. Part of what Michael Hudson did for 2.5 is add code to guess whether the native C double format /is/ the big-endian or little-endian 754 double-precision format. If so, protocol >= 1 pickle in 2.5 uses much simpler code to pack and unpack Python floats, simply copying from/to native bytes verbatim (possibly reversing the byte order, depending on platform endianness). Python doesn't even try to guess whether a C double is "normal", or an inf, NaN, or signed zero then, so can't screw that up -- it just copies the bits blindly. That's much better on IEEE-754 boxes, although I bet it still has subtle problems. For example, IIRC, 754 doesn't wholly define the difference in storage formats for signaling NaNs versus quiet NaNs, so I bet it's still theoretically possible to pickle a signaling NaN on one 754 box and get back a quiet NaN (or vice versa) when unpickled on a different 754 box. Protocol 0 (formerly known as "text mode") pickles are still a crap shoot for 754 special values, since there's still no consistency across platforms in what the C string<->double routines produce or accept for special values. Now on to marshal. Before 2.5, marshal only had a "text mode" storage format for Python floats, much like protocol=0 pickle. So, as for pickle protocol 0, what marshal produced or reconstructed for a 754 special value was a platform-dependent accident. Michael added a binary marshal format for Python floats in 2.5, which uses the same code protocol >= 1 pickle uses for serializing and unserializing Python floats (except that the marshal format is little-endian instead of big-endian). These all go thru floatobject.c's _PyFloat_Pack8 and _PyFloat_Unpack8 now, and a quick glance at those will show that they take different paths according to whether Michael's native-format-guessing code decided that the native format was ieee_big_endian_format, ieee_little_endian_format, or unknown_format. The long-winded pre-2.5 pack/unpack code is only used in the unknown_format case now. From bobrien18 at yahoo.com Wed Aug 16 14:07:08 2006 From: bobrien18 at yahoo.com (KraftDiner) Date: 16 Aug 2006 11:07:08 -0700 Subject: inheritance? In-Reply-To: <pan.2006.08.16.04.16.16.41660@REMOVEME.cybersource.com.au> References: <1155695711.057312.8020@p79g2000cwp.googlegroups.com> <pan.2006.08.16.04.16.16.41660@REMOVEME.cybersource.com.au> Message-ID: <1155751628.114929.194250@75g2000cwc.googlegroups.com> Steven D'Aprano wrote: > On Tue, 15 Aug 2006 19:35:11 -0700, KraftDiner wrote: > > > I have two classes: > > > > class implicitClass: > > def __init__(self): > > def isIVR(self): #This is a class private method. > > The convention is to flag classes as "private" with a leading underscore: > > def _isIVR(self): > > or double underscores for "really private, no, honestly": > > def __isIVR(self): > > but google on "python name mangling" before using that. > > [snip] > > > As you can see the interface is almost identical. > > > > How can I define a base class that will abstract > > the type such that I don't know if its really and inplicit > > or explicit object? > > Something like this? > > > class baseClass: > def __init__(self): > raise NotImplementedError("Don't instantiate the base class!") > def fromfile(self): > def getElement(self): > # etc. > > > class implicitClass(baseClass): > def __init__(self): > # code > def _isIVR(self): > # code > def fromfile(self, fileObj, byteOrder): > # code > # etc. > > Now, you can define instance = implicitClass() or explicitClass(). When > you come to use instance, you don't need to know whether it is one or the > other. If you need to type-test, call "isinstance(instance, baseClass)". > > The only minor issue is that the fromfile method has a different > interface. If you really want to do duck typing, they need to have the > same interface. That might be as simple as: > > class explicitClass(baseClass): > def fromfile(self, fileObj, byteOrder=None): > # byteOrder is ignored; it is included only for > # compatibility with implicitClass > > > Is that what you're asking for? > > Here I tried this example and maybe this will explain the difficulties I'm having. 1) at the time the baseClass is constructed shouldn't the constructor of the appropriate type be called. 2) getName is doing nothing... class baseClass: def __init__(self): pass def fromfile(self, str): if (str == 'A'): a = typeA() else: a = typeB() def getName(self): pass class typeA(baseClass): def __init__(self): self.name='A' print 'typeA init' def fromfile(self, str=None): print 'typeA fromfile' def getName(self): print self.name class typeB(baseClass): def __init__(self): self.name='B' print 'typeB init' def fromfile(self, str=None): print 'typeB fromfile' def getName(self): print self.name bc = baseClass() bc.fromfile('A') bc.getName() bc.fromfile('B') bc.getName() bc.getName() log: typeA init typeB init > > -- > Steven D'Aprano From tlesher at gmail.com Mon Aug 21 10:18:32 2006 From: tlesher at gmail.com (Tim Lesher) Date: 21 Aug 2006 07:18:32 -0700 Subject: Problem of function calls from map() In-Reply-To: <mailman.9606.1156169593.27775.python-list@python.org> References: <mailman.9606.1156169593.27775.python-list@python.org> Message-ID: <1156169912.788687.248690@m79g2000cwm.googlegroups.com> Dasn wrote: > So how to put '\t' argument to split() in map() ? How much is the lambda costing you, according to your profiler? Anyway, what you really want is a list comprehension: l = [line.split('\t') for line in lines] From robin at reportlab.com Thu Aug 17 11:37:09 2006 From: robin at reportlab.com (Robin Becker) Date: Thu, 17 Aug 2006 16:37:09 +0100 Subject: Python2.5 RC1 vs sgmlop.c Message-ID: <44E48D25.2000900@chamonix.reportlab.co.uk> I have a segfault problem in Python2.5 RC1 (win32) when using the venerable extension sgmlop.c. In case that was just because our copy was very old I downloaded a later source from http://pyxml.cvs.sourceforge.net, but that code (version 1.14 loewis) still suffers from this problem. The problem occurs after a call to free at line so I'm guessing something has changed related to allocations. Is there some magic going on which redefines malloc/realloc etc etc? I'm fairly sure the object in question (-->buffer) isn't passed directly to python so I would have thought that malloc/realloc/free were appropriate. Another parser attribute does hold an array of pointers to python objects, but again I don't think that should be a problem. Has anyone got any clue what the problem might be or a fixed version of the code? -- Robin Becker From johannes.wollard at gmail.com Fri Aug 4 17:30:52 2006 From: johannes.wollard at gmail.com (jwoolard) Date: 4 Aug 2006 14:30:52 -0700 Subject: super quick question References: <1154726397.778270.28810@75g2000cwc.googlegroups.com> Message-ID: <1154727052.378868.277770@s13g2000cwa.googlegroups.com> Chris wrote: > is there a prettier way to do this? > string[:len(string)-1] > > thanks! string[:-1] Negative indices count from the end of the string! beautiful isn't it? From duncan.booth at invalid.invalid Tue Aug 1 10:39:39 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Aug 2006 14:39:39 GMT Subject: Nested function scope problem References: <9eabc2t5kj3o7bor1g10ioqbfo2o9drhgl@4ax.com> <ea4ftg$g4m$1@sea.gmane.org> <mailman.8523.1153834254.27775.python-list@python.org> <44c6444c$0$30849$626a54ce@news.free.fr> <1153965046.805129.44350@75g2000cwc.googlegroups.com> <44c8b4a9$0$6740$636a55ce@news.free.fr> <slrnechicn.iu.apardon@rcpc42.vub.ac.be> <44c8d59a$0$31797$626a54ce@news.free.fr> <slrnechoqg.qq.apardon@rcpc42.vub.ac.be> <44c8eb5e$0$21632$626a54ce@news.free.fr> <slrneci0b1.14s.apardon@rcpc42.vub.ac.be> <mq4jc2topbu781vcdtaeog4it914r8hr57@4ax.com> <slrnecklc4.5a7.apardon@rcpc42.vub.ac.be> <mailman.8675.1154112875.27775.python-list@python.org> <slrnecn499.98c.apardon@rcpc42.vub.ac.be> <mailman.8703.1154198214.27775.python-list@python.org> <slrnecpavl.c6f.apardon@rcpc42.vub.ac.be> <mailman.8711.1154269113.27775.python-list@python.org> <1154400727.472816.243290@b28g2000cwb.googlegroups.com> <slrnecunuf.k84.apardon@rcpc42.vub.ac.be> Message-ID: <Xns98129F27BE989duncanbooth@127.0.0.1> Antoon Pardon wrote: > Even this doesn't: > > def foo(): > if False: > a = 1 > else: > b = a > > a = 1 > foo() > > Yet seems to work (which I think is an error in the optimisation; What definition of 'seems to work' are you using? It throws an UnboundLocalError exception so you'll know pretty quickly that something is wrong. From rogue_pedro at yahoo.com Tue Aug 15 18:06:07 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 15 Aug 2006 15:06:07 -0700 Subject: how to deepcopy a slice object? In-Reply-To: <Xns9820723DA8D73duncanbooth@127.0.0.1> References: <1155629155.207232.50400@m79g2000cwm.googlegroups.com> <1155633086.985976.59960@m79g2000cwm.googlegroups.com> <Xns9820723DA8D73duncanbooth@127.0.0.1> Message-ID: <1155679567.931862.258170@p79g2000cwp.googlegroups.com> Duncan Booth wrote: > Simon Forman wrote: > > > Why would you want to [deep]copy a slice object? > > I would guess the original poster actually wanted to copy a data structure > which includes a slice object somewhere within it. That is a perfectly > reasonable albeit somewhat unusual thing to want, however it doesn't work. I figured it was either something like that or something really wacky. :-) Either way I was curious. > Similarly in Python 2.4 you cannot deepcopy functions. That has been fixed > in Python 2.5 but I guess nobody has tried deepcopying slices before so > they haven't been fixed. Shows how unusual it is. Since slice objects appear to be immutable: |>> s = slice(1) |>> s slice(None, 1, None) |>> s.start = 1 Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: 'slice' object has only read-only attributes (assign to .start) etc... fixing copy and deepcopy for slices would involve adding slice to the tuple in this for statement in copy.py (starts on line 115 in my version Python 2.4.3): for t in (types.NoneType, int, long, float, bool, str, tuple, frozenset, type, xrange, types.ClassType, types.BuiltinFunctionType): d[t] = _copy_immutable and, lower down, around line 214, adding a line like this: d[types.SliceType] = _deepcopy_atomic I think I'll send a patch in in awhile. ;-) Peace, ~Simon From gagsl-py at yahoo.com.ar Thu Aug 10 02:59:49 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 10 Aug 2006 03:59:49 -0300 Subject: state of SOAP and python? In-Reply-To: <ivACg.5503$9T3.560@newssvr25.news.prodigy.net> References: <ivACg.5503$9T3.560@newssvr25.news.prodigy.net> Message-ID: <7.0.1.0.0.20060810035204.03f904d8@yahoo.com.ar> At Thursday 10/8/2006 03:38, Mark Harrison wrote: >So I'm investigating doing some SOAP work... Any concensus on >what the best python libraries are for doing this? > >Too bad, xmlrpc is choking on our long longs. :-( Just thinking, if you have control over the two ends, and dont need real interoperability, maybe just extending <int> to support long integers could be easier... I remember extending <double> once to support NaN's, moving to SOAP was too much effort for that application. Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From sjdevnull at yahoo.com Tue Aug 22 01:56:13 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 21 Aug 2006 22:56:13 -0700 Subject: idutils and Python In-Reply-To: <mailman.9627.1156207047.27775.python-list@python.org> References: <mailman.9627.1156207047.27775.python-list@python.org> Message-ID: <1156226173.596437.266680@75g2000cwc.googlegroups.com> Ramon Diaz-Uriarte wrote: > Dear All, > > Has anybody tried to use ID Utils > (http://www.gnu.org/software/idutils/46) with Python? What exactly are you trying to accomplish? If you want to index function/class names, variables, etc then you should take a look at "exuberant ctags" http://ctags.sourceforge.net --although it started off as a C indexer, it has excellent Python support, it's free, and as a bonus its indices are well supported from inside major editors (vim, emacs, etc) so you can easily follow code flow, find function/class definitions, etc. From srlamb at gmail.com Wed Aug 16 21:53:36 2006 From: srlamb at gmail.com (Scott Lamb) Date: 16 Aug 2006 18:53:36 -0700 Subject: Curried class methods? Message-ID: <1155779616.228836.153470@p79g2000cwp.googlegroups.com> I'm trying to dynamically generate class methods which have access to some state passed in at creation time. (Basically as a workaround to twisted's trial not having a way to dynamically add stuff. Plain unittest seems to have TestSuite, but the trial runner doesn't know about it.) My first attempt might better illustrate this - class Foo: def generalized(self, ctx): print 'my ctx is %r' % ctx for i in ['a','b','c']: setattr(Foo, i, lambda self: self.generalized(i)) foo = Foo() foo.a() foo.b() foo.c() but this prints "my ctx is c" three times; I'd hoped for a, b, c, of course. After reading <http://mail.python.org/pipermail/python-list/2004-July/229478.html>, I think I understand why this is - "i" doesn't actually get added to each new function's context; they just reference the global one. Even if I do this: def builder(): for i in ['a','b','c']: setattr(Foo, i, lambda self: self.generalized(i)) builder() they'll just keep a reference to the context that was made on entry to builder() and share it, so the modifications builder() makes to i are reflected in all three functions. Okay, take two. I tried this: try: from functional import partial except ImportError: ...partial pasted from PEP 309... for i in ['a','b','c']: setattr(Foo, i, partial(Foo.generalized, ctx=i)) but when I try to call foo.a(), I get this error: Traceback (most recent call last): File "./foo.py", line 35, in ? foo.a() File "./foo.py", line 25, in __call__ return self.fn(*(self.args + args), **d) TypeError: unbound method generalized() must be called with Foo instance as first argument (got nothing instead) If I add a debug print to partial.__call__, print 'partial.__call__(args=%r, kw=%r, self.kw=%r)' \ % (args, kw, self.kw) I see: partial.__call__(args=(), kw={}, self.kw={'ctx': 'a'}) I'd first expected foo.a() to be equivalent to Foo.a(self), but instead it's like Foo.a(). There must be magic that does the equivalent of class Foo: def __init__(self): a = partial(a, self) for real Python functions and not for my partial object. With this __init__ magic, I guess I have something that works. I have to apply the partial twice, though - if I do everything in the __init__, my new functions won't exist by the time trial's introspection kicks in, so they'll never get called. My ugly hack has gotten even uglier. Does anyone know of a better way to do this? Thanks, Scott From dave.brueck at gmail.com Sat Aug 19 14:47:27 2006 From: dave.brueck at gmail.com (dave.brueck at gmail.com) Date: 19 Aug 2006 11:47:27 -0700 Subject: How to catch these kind of bugs in Python? References: <1156009543.993046.76720@75g2000cwc.googlegroups.com> Message-ID: <1156013247.854531.92870@75g2000cwc.googlegroups.com> asincero wrote: > Is there anyway to catch the following type of bug in Python code: > > message = 'This is a message' > if some_obscure_condition: > nessage = 'Some obscure condition occured.' > print message > > > In the above example, message should be set to 'Some obscure condition > occured.' if some_obscure_condition is True. But due to a lack of > sleep, and possibly even being drunk, the programmer has mistyped > message. These types of bugs would easily be caught in languages that > have a specific keyword or syntax for declaring variables before use. There are tools that help (e.g. pychecker), but there are a few things to consider: 1) If the programmer is sleepy/drunk, you're going to have other bugs too (logical errors, not handling all cases, etc.) 2) Other languages would catch *some* types of these bugs, but would still miss some of them (I can see a sleepy programmer also using the wrong variable instead of just mistyping the right one). So while a tool might assist, it's worth your while to also consider some strategies for tackling the above two problems and, in the process, the sleepy-programmer-mistype bugs will get caught as well. Some type of testing is probably the best answer - be it reusable unit tests or, at the very least, some interactive testing of code snippets (which Python makes really easy to do). -Dave From sulsa at gazeta.pl Mon Aug 14 23:43:43 2006 From: sulsa at gazeta.pl (Sulsa) Date: Tue, 15 Aug 2006 05:43:43 +0200 Subject: How to fill a form References: <20060815034051.89ef7e18.sulsa@gazeta.pl> <mailman.9336.1155608567.27775.python-list@python.org> <20060815050733.10e14112.sulsa@gazeta.pl> <12e2gau4jouhmcf@corp.supernews.com> Message-ID: <20060815054343.1c31f3f7.sulsa@gazeta.pl> On Tue, 15 Aug 2006 03:37:02 -0000 Grant Edwards <grante at visi.com> wrote: > On 2006-08-15, Sulsa <sulsa at gazeta.pl> wrote: > > > I want to fill only one smiple form so i would like not to use > > any non standard libraries. > > Then just send the HTTP "POST" request containing the fields > and data you want to submit. but i don't know how to post these data if i knew there there would be no topic. From JohnRoth1 at jhrothjr.com Sun Aug 27 11:07:10 2006 From: JohnRoth1 at jhrothjr.com (John Roth) Date: 27 Aug 2006 08:07:10 -0700 Subject: creating multiply arguments for a method. In-Reply-To: <1156686964.216440.72530@p79g2000cwp.googlegroups.com> References: <1156686964.216440.72530@p79g2000cwp.googlegroups.com> Message-ID: <1156691230.817916.324020@h48g2000cwc.googlegroups.com> noro wrote: > Hi all, > > I use a method that accept multiply arguments ("plot(*args)"). > so plot([1,2,3,4]) is accepted and plot([1,2,3,4],[5,6,7,8]) is also > accepted. > > the problem is that i know the number of arguments only at runtime. > Let say that during runtime i need to pass 4 arguments, each is a list, > creating a set of lists and passing it to the method wont word since > the interpartor thinks it is only 1 argument the contain a reference to > a "list of lists", instede of number of arguments, each is a list. > > any suggestions? > thanks > amit Why do you want to do this? You'll have to do some logic in your method body to determine how many operands you have whether you explicitly pass a list or whether you have the system break it apart into separate parameters. Fredrick Lund's solution, using an * parameter in the method definition, will produce a list that you have to pull apart in the method. Doing the same in the method call takes a single list of all of your parameters and then distributes it among the parameters in the definition. I wouldn't bother with either one. Passing a list of my real parameters as a single parameter is, in most circumstances, easier and IMO clearer. John Roth From mail at microcorp.co.za Wed Aug 2 02:55:56 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Wed, 2 Aug 2006 08:55:56 +0200 Subject: BCD List to HEX List References: <5S8zg.1553$W93.658@dukeread05><1154296114.094452.158000@p79g2000cwp.googlegroups.com><hQ9zg.1562$W93.684@dukeread05><1154298390.280625.206560@75g2000cwc.googlegroups.com><Zrazg.1568$W93.276@dukeread05><1154299830.987261.9800@b28g2000cwb.googlegroups.com><QQazg.1571$W93.680@dukeread05><1154301233.360818.93450@s13g2000cwa.googlegroups.com><0abzg.1576$W93.173@dukeread05><1154361998.861851.157210@h48g2000cwc.googlegroups.com><1154375956.397032.166310@p79g2000cwp.googlegroups.com><1154411021.642620.255750@s13g2000cwa.googlegroups.com><1154412245.996874.199260@h48g2000cwc.googlegroups.com><1154446262.681764.73100@75g2000cwc.googlegroups.com> <1154472559.132312.12550@75g2000cwc.googlegroups.com> Message-ID: <01de01c6b603$c720a3c0$03000080@hendrik> "John Machin" <sjmachin at lexicon.net> wrote: | bryanjugglercryptographer at yahoo.com wrote: | | >My version assumes three subroutines: extracting | > nibbles, shifting, and adding, Those are pretty simple, so I asked | > if he needed them rather than presenting them. | > Assuming we have | > them, the algorithm is three lines long. | | Perhaps you could enlighten us by publishing (a) the spec for each of | the get_nibble(s), shift, and add subroutines (b) the three-line | algorithm (c) what the algorithm is intended to achieve ... | | > | > He took a while to state the problem, but was clear from the start | > that he had lists of digits rather than an integer datatype. | | Yes, input was a list [prototyping a byte array] of decimal digits. The | OUTPUT was also a list of something. A few messages later, it became | clear that the output desired was a list of hexadecimal digits. Until | he revealed that the input was up to 24 decimal digits, I was pursuing | the notion that a solution involving converting decimal to binary (in a | 32-bit long) then to hexadecimal was the way to go. | | What is apparently needed is an algorithm for converting a "large" | number from a representation of one base-10 digit per storage unit to | one of a base-16 digit per storage unit, when the size of the number | exceeds the size (8, 16, 32, etc bits) of the "registers" available. Is | that what you have? | | Cheers, | John I actually read most of this thread as it happened and could not really figure out what the OP was on about. If the above is a true statement of the problem, then its more difficult to do in a high level language, when the results exceed the native size that the compiler or interpreter writers thought was a reasonable number of bits. - ten to the 24 is of the order of 80 binary bits ... So you need a (say) twelve byte result field for the binary... (thats three 32 bit values concatenated) you clear the result field out to zero. Then you feed in the decimal digits, from the most significant side, into a routine that multiplies the result by ten and then adds the digit. (yes you have to write this twelve byte Ascii/binary thing yourself) When you have done this for all the digits, you have a binary number, and getting hex from binary a nibble at a time is easy... Well its easy in assembler, even on a cripple little 8 bit processor, anyway... In python I would take a hard look at what I could do with the decimal module - doing the reverse of the above but dividing by 16 repetitively and using the remainder or the fraction to give the hex numbers in lsb to msb order, and doing a lookup (prolly using a dict) to get the hex digits... just my $0.02... - Hendrik From shuanyu at gmail.com Thu Aug 17 23:46:16 2006 From: shuanyu at gmail.com (many_years_after) Date: 17 Aug 2006 20:46:16 -0700 Subject: Which field is Python suitable to do some tasks? Message-ID: <1155872776.761061.44700@p79g2000cwp.googlegroups.com> hello , members: I have basic knowledge of python programming. But i don't know what to do next step. I don't know in which field I should learn more about python and finally finish some tasks. Can you give me some ideas? Thanks. From bayazee at gmail.com Thu Aug 10 20:03:51 2006 From: bayazee at gmail.com (Bayazee) Date: 10 Aug 2006 17:03:51 -0700 Subject: hide python code ! In-Reply-To: <1155253821.570487.165400@b28g2000cwb.googlegroups.com> References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155253821.570487.165400@b28g2000cwb.googlegroups.com> Message-ID: <1155254631.617208.299550@m73g2000cwd.googlegroups.com> hi in compiled languages when we compile a code to an executable file it convert to a machine code so now we cant access to source ... but in python we easily open the program executable(ascii) file and read source .... i meen than any way to protect my code or convert it to executable witch can not be decompiled (python code).... From david.bear at asu.edu Wed Aug 30 19:56:48 2006 From: david.bear at asu.edu (David Bear) Date: Wed, 30 Aug 2006 16:56:48 -0700 Subject: inet_aton and struct issue References: <11944606.TXfyH4Zyga@teancum> <4lmeguF2lmldU1@uni-berlin.de> <1759500.07cGLpTMlz@teancum> Message-ID: <1237504.s5KjHmHnIc@teancum> David Bear wrote: > Diez B. Roggisch wrote: > >> David Bear schrieb: >>> I found this simple recipe for converting a dotted quad ip address to a >>> string of a long int. >>> >>> struct.unpack('L',socket.inet_aton(ip))[0] >>> >>> trouble is when I use this, I get >>> >>> struct.error: unpack str size does not match format >>> >>> I thought ip addresses were unsigned 32 bit integers. >>> >>> Is there a better way to take a dotted quad and convert it to a string >>> representation of an long int? >> >> Works for me: >> >> >>> import socket >> >>> import struct >> >>> ip = "127.0.0.1" >> >>> struct.unpack('L',socket.inet_aton(ip))[0] >> 2130706433L >> > > I really wish it worked for me: > >>>> struct.unpack('L', socket.inet_aton('129.219.120.129')) > Traceback (most recent call last): > File "<stdin>", line 1, in ? > struct.error: unpack str size does not match format > > This is python packaged with Suse 9.3. >>>> dir(struct) > ['__doc__', '__file__', '__name__', 'calcsize', 'error', 'pack', 'unpack'] >>>> print struct.__file__ > /usr/lib64/python2.4/lib-dynload/struct.so > > could I have a broken python? > >> >> Diez > I played around with format size and here are some results. (they don't make sense) >>> ip1 = '123.254.254.252' >>> import socket >>> import struct >>> ip1s = socket.inet_aton(ip1) >>> struct.unpack('L',ip1s) Traceback (most recent call last): File "<stdin>", line 1, in ? struct.error: unpack str size does not match format >>> struct.unpack('f',ip1s) (-1.0592039033369304e+37,) >>> struct.unpack('I',ip1s) (4244569723L,) >>> struct.unpack('Q',ip1s) Traceback (most recent call last): File "<stdin>", line 1, in ? struct.error: unpack str size does not match format >>> struct.unpack('L',ip1s) Traceback (most recent call last): File "<stdin>", line 1, in ? struct.error: unpack str size does not match format >>> struct.unpack('i',ip1s) (-50397573,) >>> struct.unpack('I',ip1s) (4244569723L,) >>> So, ip1s really should be a long unsigned int.. but it doesn't decode as that. Is this the way to interpret this? -- David Bear -- let me buy your intellectual property, I want to own your thoughts -- From maric at aristote.info Mon Aug 14 04:40:51 2006 From: maric at aristote.info (Maric Michaud) Date: Mon, 14 Aug 2006 10:40:51 +0200 Subject: Newbie doing lengthy initialization with Tkinter gui In-Reply-To: <1155477685.072381.235320@75g2000cwc.googlegroups.com> References: <slrnedu0ai.ld4.pon@sbz-31.cs.Helsinki.FI> <mailman.9284.1155469507.27775.python-list@python.org> <1155477685.072381.235320@75g2000cwc.googlegroups.com> Message-ID: <200608141040.52033.maric@aristote.info> Le dimanche 13 ao?t 2006 16:01, jmdeschamps at gmail.com a ?crit?: > No neep for thread or Tix modules...! Module thread is always available (at less on platforms where Tkinter is available), while Tix in my example is just intended to use the Meter widget (a progress bar). > # this will *sleep* one millisec before calling > # your doInitOne function and continue > # with the rest of the code during that sleep time > # in this case just the mainloop > root.after(1, doInitOne) > root.mainloop() hum, this has not exactly the same effect, after, after_cancel, etc. are for scheduling actions in the future, and when the action start, it will block the mainloop and user interaction (this is why you need to call explicitly the update method), so the gui will not respond anymore. Finally why do you differ the call of your function after the mainloop since it will block ? That's said, I remember now that there isn't anything in Tkinter (no events or callbacks) to get the 'mainloop started' hook, so you must start the thread before the mainloop, probably like this : class myApp(Toplevel) : def mainloop(self) : start_new_thread(initFunc, params) Toplevel.mainloop(self) -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From aleax at mac.com Tue Aug 8 11:34:48 2006 From: aleax at mac.com (Alex Martelli) Date: Tue, 8 Aug 2006 08:34:48 -0700 Subject: do people really complain about significant whitespace? References: <1154986984.740638.241130@m79g2000cwm.googlegroups.com> <1155038374.803591.315480@m73g2000cwd.googlegroups.com> Message-ID: <1hjqsqp.wkj4n271sk7cN%aleax@mac.com> <gslindstrom at gmail.com> wrote: > infidel wrote: > > Where are they-who-hate-us-for-our-whitespace? Are "they" really that > > stupid/petty? Are "they" really out there at all? "They" almost sound > > like a mythical caste of tasteless heathens that "we" have invented. > > It just sounds like so much trivial nitpickery that it's hard to > > believe it's as common as we've come to believe. > > Some of it may be a reaction from "old-timers" who remember FORTRAN, > where (if memory serves), code had to start in column 16 and code > continutations had to be an asterik in column 72 (it's been many years > since I've done any work in FORTRAN, but you get the idea) Column 7 was the start, 6 the one for continuation; 1-5 and 73-80 were ignored by the compiler and could be used for numbering, grouping &c. Been many years in my case, too, but as I was a mainly-Fortran guru for several years in my career, it's hard to forget;-). > Or it may be a reaction from Assembler, which is also quite > column-centric (is Assembler still taught in schools??). I never used a column-centric Assembler: even the first assemblers I used, in the '70s (6502, Z80, a mini called HP1000, VAX/VMS when it was just out, BAL/370, ...) were all column-indifferent. The HP1000 did not even have a punched-card reader: it used punched _tape_ instead (quite a popular device then, as it came with teletypes typically used as consoles), so keeping track of columns would have a royal mess:-). I'm pretty sure you're still _able_ to take SOME Assembler-based course in most universities, but you need to strive pretty hard for the purpose... it's definitely not in the "default curriculum", even for EEs, much less CSs. Alex From james at uh-hosting.co.uk Thu Aug 17 16:06:57 2006 From: james at uh-hosting.co.uk (james at uh-hosting.co.uk) Date: 17 Aug 2006 13:06:57 -0700 Subject: Problem installing Python 2.4.3 on FreeBSD 5.3-RELEASE-p31 Message-ID: <1155845217.325852.170320@m73g2000cwd.googlegroups.com> I have a problem installing Pyhton 2.4.3, running "./configure --with-threads=no" completes, but gives the warning: configure: WARNING: curses.h: present but cannot be compiled configure: WARNING: curses.h: check for missing prerequisite headers? configure: WARNING: curses.h: see the Autoconf documentation configure: WARNING: curses.h: section "Present But Cannot Be Compiled" configure: WARNING: curses.h: proceeding with the preprocessor's result configure: WARNING: curses.h: in the future, the compiler will take precedence Running "make" then gives the error: gcc -shared build/temp.freebsd-5.3-RELEASE-p31-i386-2.4/_cursesmodule.o -L/usr/local/lib -lncursesw -o build/lib.freebsd-5.3-RELEASE-p31-i386-2.4/_curses.so Segmentation fault (core dumped) *** Error code 139 I assume this is related to the configure warning... ? Same error with just a standard "./configure" and "make". Any help would be great :) Regards, James From aleax at mac.com Tue Aug 15 11:04:19 2006 From: aleax at mac.com (Alex Martelli) Date: Tue, 15 Aug 2006 08:04:19 -0700 Subject: modifying __new__ of list subclass References: <mailman.9335.1155602902.27775.python-list@python.org> <O-KdnWZ1Y7JG2HzZnZ2dnUVZ_vudnZ2d@comcast.com> <mailman.9373.1155649254.27775.python-list@python.org> Message-ID: <1hk3pyh.y9wfelzkd0f2N%aleax@mac.com> Ken Schutte <kschutte at csail.mit.edu> wrote: > Steven Bethard wrote: > > > > The __new__ method is for immutable types. So things like str and int > > do their initialization in __new__. But for regular mutable types, you > > should do your initialization in __init__:: > > I see... So, is there a use for __new__ in mutable types? From my > list-derirved class, it was obviously being called, but it's return > value is totally ignored? Wrong: the return value of __new__ is most definitely NOT "totally ignored", since it's what gets passed as the first argument of __init__ (as long as it's an instance of the type in question). Easy to check for yourself, e.g.: >>> class ha(list): ... def __new__(cls, *a): ... x = list.__new__(cls, *a) ... x.foo = 23 ... return x ... >>> z = ha() >>> z.foo 23 >>> as you can see, the "totally ignored" hypothesis is easily disproved. Of course, there's no particular reason why class ha would _want_ to set the .foo attribute in __new__ rather than __init__, so that doesn't yet answer your other question about "is there a use". That answer is a resounding "yes", but the uses may be subtler than you're considering: for example, you may use the subtype as a general-purpose "factory", so that instantiating the subtype may return objects that are not in fact instances of the subtype (that bypasses the __init__ call); or, the overriding of __new__ may go together with the overriding of __init__ (so that the latter doesn't blast the object's state) for such purposes as singletons or more generally types with a finite "pool" of instances. Alex From johnjsal at NOSPAMgmail.com Fri Aug 18 21:15:23 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 18 Aug 2006 21:15:23 -0400 Subject: couple more questions about sqlite In-Reply-To: <1155943434.653053.232100@74g2000cwt.googlegroups.com> References: <MqnFg.2703$No6.52653@news.tufts.edu> <1155930772.591854.53910@m79g2000cwm.googlegroups.com> <1rpFg.2705$No6.52662@news.tufts.edu> <1155943434.653053.232100@74g2000cwt.googlegroups.com> Message-ID: <44e666f9$0$12542$c3e8da3@news.astraweb.com> John Machin wrote: > Your confusion is quite understandable. I started looking at sqlite > when the announcement that it would be included in Python 2.5 came out. > Puzzlement reigned. I ended up with the following up the front of my > experimental module: So does this mean that when 2.5 is released, all I need is the built-in module sqlite3? From bearophileHUGS at lycos.com Tue Aug 8 15:12:11 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 8 Aug 2006 12:12:11 -0700 Subject: String.digits help!!! In-Reply-To: <1155063757.284414.135630@n13g2000cwa.googlegroups.com> References: <1155058550.954997.320250@m79g2000cwm.googlegroups.com> <1155063757.284414.135630@n13g2000cwa.googlegroups.com> Message-ID: <1155064331.588367.136290@m73g2000cwd.googlegroups.com> Simon Forman: > It's unlikely to > be deprecated since it doesn't make much sense to make it an attribute > of the str type. Why? Thank you, bearophile From amichail at gmail.com Sun Aug 27 09:33:50 2006 From: amichail at gmail.com (Amir Michail) Date: 27 Aug 2006 06:33:50 -0700 Subject: avoiding file corruption References: <1156664673.325201.271140@i42g2000cwa.googlegroups.com> <mailman.9932.1156670558.27775.python-list@python.org> <1156672823.166736.327670@i42g2000cwa.googlegroups.com> <4ldg4tF1ct5cU1@uni-berlin.de> Message-ID: <1156685630.350074.109660@b28g2000cwb.googlegroups.com> Diez B. Roggisch wrote: > Amir Michail schrieb: > > Paolo Pantaleo wrote: > >> 27 Aug 2006 00:44:33 -0700, Amir Michail <amichail at gmail.com>: > >>> Hi, > >>> > >>> Trying to open a file for writing that is already open for writing > >>> should result in an exception. > >>> > >>> It's all too easy to accidentally open a shelve for writing twice and > >>> this can lead to hard to track down database corruption errors. > >>> > >>> Amir > >>> > >>> -- > >>> http://mail.python.org/mailman/listinfo/python-list > >>> > >> Even if it could be strange, the OS usually allow you to open a file > >> twice, that's up to the programmer to ensure the consistency of the > >> operations. > >> > >> PAolo > >> > > > > But if this is usually a serious bug, shouldn't an exception be raised? > > executing "rm -rf /" via subprocess is usually also a bad idea. So? No > language can prevent you from doing such mistake. And there is no way to > know if a file is opened twice - it might that you open the same file > twice via e.g. a network share. No way to know that it is the same file. > > Diez The scenario I have in mind is something like this: def f(): db=shelve.open('test.db', 'c') # do some stuff with db g() db.close() def g(): db=shelve.open('test.db', 'c') # do some stuff with db db.close() I think it would be easy for python to check for this problem in scenarios like this. Amir From barberomarcelo at gmail.com Wed Aug 23 00:07:36 2006 From: barberomarcelo at gmail.com (barberomarcelo at gmail.com) Date: 22 Aug 2006 21:07:36 -0700 Subject: Can I do this with list comprehension? Message-ID: <1156306056.165984.37820@h48g2000cwc.googlegroups.com> Let's say I have two lists: a = [0, 1, 0, 1, 1, 0] b = [2, 4, 6, 8, 10, 12] I want a list comprehension that has the elements in b where a[element] == 1. That's to say, in the example above, the result must be: [4, 8, 10] Any hints? Marcelo From lsumnler at gmail.com Sun Aug 13 12:16:49 2006 From: lsumnler at gmail.com (len) Date: 13 Aug 2006 09:16:49 -0700 Subject: semi-Newbie question References: <1155229897.356144.183750@m79g2000cwm.googlegroups.com> <1155245290.532108.75560@75g2000cwc.googlegroups.com> <9upsq3-9ng.ln1@lairds.us> <1155268855.612545.108870@h48g2000cwc.googlegroups.com> <4fjvq3-tjj.ln1@lairds.us> Message-ID: <1155485809.825572.183020@p79g2000cwp.googlegroups.com> Sample and test code shows you are correct. tpsFile - is really the SQL file I will be inserting new policy records into tagFile - is a CVS file containing all of the information for a new policy in an XMLish fashion (one record per filed of the policy) I will receive from a third party tagIdxFile - is just a file that where the data from the tagFile should be mapped into the tpsFile CODE tpsFile = {'tpsFirstName' : 'Kate', 'tpsLastName' : 'Sumner', 'tpsPhone': '532-1234'} tagFile = {'tagname' : 'tagFirst', 'tagScope' : 'POL0', 'tagValue' : 'Rose'} tagIdxFile = {'idxtagname' : 'tagFirst', 'idxtpsname' : 'tpsFirstName'} print tpsFile['tpsFirstName'] tpsFile[tagIdxFile['idxtpsname']] = tagFile['tagValue'] print tpsFile['tpsFirstName'] RESULTS >>> Kate Rose >>> Just a small note: As trivial as this may seem this task was not possible in the compiled language I work in due to the fact that there was no way for me to get the data referenced by tagIdxFile['idxtpsname'] and then use it as a field label on the left side of the assignment statement because in the compiled language the left side must be a label and NOT and expression. Just strengthens my commitment to learn Python. I would like to thank every one for their help, advice and patients. Len Sumnler Cameron Laird wrote: > In article <1155268855.612545.108870 at h48g2000cwc.googlegroups.com>, > len <lsumnler at gmail.com> wrote: > . > . > . > >I have done some more reading and I think the code I need is as > >follows; > > > >mycode = "TagToSQL['mySQLfieldname'] = Tagfile['Value']" > >exec mycode > > > >This is very new to me because I don't believe this can be done in a > >compiled language or at least not as easily as in an interpeted > >language like Python. > > > >I hope this clarifies the problem > . > . > . > I don't understand how > > TagToSQL[mySQLfieldname] = Tagfile[Value] > > fails to meet requirements that > > mycode = "TagToSQL['mySQLfieldname'] = Tagfile['Value']" > exec mycode > > satisfies. > > This thread confuses me. Maybe you already have all the answers > you seek. If not, I recommend that you simplify--perhaps work > through a single example datum in detail. In the meantime, I > applaud your judgment that you can achieve what you're after with > table lookups and such rather than the thousand-way if-else at > which you hinted at least once. From dwhall256 at gmail.com Sun Aug 13 17:33:43 2006 From: dwhall256 at gmail.com (dwhall) Date: 13 Aug 2006 14:33:43 -0700 Subject: seeking the "Hello World" of Packages References: <mailman.9258.1155318490.27775.python-list@python.org> Message-ID: <1155504823.820546.31300@75g2000cwc.googlegroups.com> Kevin, I just posted a small package to the python package index. It has one source file of interest and some unit tests. The remaining files are either needed for or made by distutils. Should be pretty easy to follow if you've read the distutils docs. Note that the package you get does not have the MANIFEST.in file (the tool creates MANIFEST automatically using info from MANIFEST.in). http://cheeseshop.python.org/pypi/pycscope/0.2 share and enjoy, !!Dean From bearophileHUGS at lycos.com Sun Aug 6 04:24:38 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 6 Aug 2006 01:24:38 -0700 Subject: More int and float attributes In-Reply-To: <10had2d2e8vagckm34l0lh17t518iaaqct@4ax.com> References: <1154780600.348169.158150@i42g2000cwa.googlegroups.com> <10had2d2e8vagckm34l0lh17t518iaaqct@4ax.com> Message-ID: <1154852677.984362.283490@m79g2000cwm.googlegroups.com> Self: >>D is a very nice language, that I hope to see more used. It is copying >>lot of things from Python. Tim Roberts: >I don't see that. It looks rather like an incremental improvement to C and >C++ rather than a language influenced by Python. Thank you for your comments. Mine was probably just an illusion. In D most things are copied or come directly from C++. But I like the built in string and associative array management, the string/array slicing, the multiple return or typed multiple input, the nested functions, the foreach with a bit of type inferencing, and some other things that I like in Python too, but absent in C++ (GCC has some nested functions, etc). (But D lacks some of the suggestions in this article, link coming from Paddy: http://www.cs.princeton.edu/~dpw/popl/06/Tim-POPL.ppt ) This is the first thing written about D into its site: http://www.digitalmars.com/d/ >D is a systems programming language. Its focus is on combining the power and high performance of C and C++ with the programmer productivity of modern languages like Ruby and Python.< This is a thread about related matters, with a comment from Walter, the D autor: http://www.digitalmars.com/d/archives/19839.html Bye, bearophile From neokosmos at gmail.com Thu Aug 10 23:17:12 2006 From: neokosmos at gmail.com (neokosmos at gmail.com) Date: 10 Aug 2006 20:17:12 -0700 Subject: Python share CPU time? In-Reply-To: <1155156518.923797.133210@h48g2000cwc.googlegroups.com> References: <1155146500.063665.282430@p79g2000cwp.googlegroups.com> <1155156518.923797.133210@h48g2000cwc.googlegroups.com> Message-ID: <1155266232.155398.308250@75g2000cwc.googlegroups.com> linnorm at gmail.com wrote: > You should take a look at stackless Python. It should do very nicely > for what you want. There is a good tutorial on it here: > http://members.verizon.net/olsongt/stackless/why_stackless.html Not being intimately familiar with Stackless myself, I wonder, how would it deal with a script that executed the line: x = 10 ** 10 ** 10 My guess is that would cause a Stackless interpreter to block for a long, long time, until it ran out of memory, but I'd like someone who *knows* and doesn't have to guess to comment. :-) From jim at runfatbo.net Sun Aug 13 21:40:24 2006 From: jim at runfatbo.net (Jim Jones) Date: Mon, 14 Aug 2006 01:40:24 GMT Subject: Easy to use distributed system? Message-ID: <cwQDg.9674$eL2.4002@tornado.rdc-kc.rr.com> I am looking for a system in Python that will easily allow me to distribute processes across multiple systems? So, if I have a function 'foo', I'd like to be able to call something along the lines of distribute(foo(x)) And have the system figure out which node is available for process, and then have the results returned in some sort of callback fashion. Any insight is greatly appreciated. -- Jim http://www.runfatboy.net - Exercise for the rest of us. From glenn at tangelosoftware.net Tue Aug 29 23:32:47 2006 From: glenn at tangelosoftware.net (glenn) Date: 29 Aug 2006 20:32:47 -0700 Subject: refering to base classes In-Reply-To: <44F45603.6050504@hotmail.com> References: <1156862012.068397.284040@m73g2000cwd.googlegroups.com> <44F454D6.5040606@hotmail.com> <44F45603.6050504@hotmail.com> Message-ID: <1156908767.156893.107350@p79g2000cwp.googlegroups.com> Chaz Ginger wrote: > Chaz Ginger wrote: > > glenn wrote: > >> hi - Im quite new to python, wondering if anyone can help me understand > >> something about inheritance here. In this trivial example, how could I > >> modify the voice method of 'dog' to call the base class 'creatures' > >> voice method from with in it? > >> > >> class creature: > >> def __init__(self): > >> self.noise="" > >> def voice(self): > >> return "voice:" + self.noise > >> > >> class dog(creature): > >> def __init__(self): > >> self.noise="bark" > >> > >> def voice(self): > >> print "brace your self:" > >> > >> thanks > >> glenn > >> > > Try this: > > > > class dog(creature): > > ..... > > def voice(self): > > print "brace your self:" > > creature.voice(self) > > > > This should do it. > I did forget to mention that in 'dog"s' __init__ you had better call > creature's __init__. You might make it look like this: > > def __init__(self): > self.noise = 'bark' > creature.__init__(self) > > There is another approach - using Superclass - but I will leave that > exercise to the reader. first tip worked - funny thing was I =thought= I done that, but clearly not - so thanks was going mad. Superclass?... ok will look into this thanks for reply(s) Glenn From g.brandl-nospam at gmx.net Mon Aug 28 16:01:01 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Mon, 28 Aug 2006 22:01:01 +0200 Subject: callable to disappear? In-Reply-To: <44f1fc29$0$9026$626a54ce@news.free.fr> References: <slrneeopqs.a7l.apardon@rcpc42.vub.ac.be> <ecmesm$4d6$1@news.albasani.net> <44f1fc29$0$9026$626a54ce@news.free.fr> Message-ID: <ecvi1t$4dq$1@news.albasani.net> Bruno Desthuilliers wrote: > Georg Brandl a ?crit : >> Antoon Pardon wrote: >> >>> I have been reading http://www.python.org/dev/peps/pep-3100/ >>> en there is written: >>> >>> To be removed: >>> ... >>> >>> callable(): just call the object and catch the exception >>> ... >> >> >> >>> Is there a chance this will be reconsidered? >>> >> >> There was some discussion on python-dev, which concluded that callable() >> in its current form is not very useful, > > I use it quite frequently. How nice. Georg From amit.man at gmail.com Sun Aug 27 09:56:04 2006 From: amit.man at gmail.com (noro) Date: 27 Aug 2006 06:56:04 -0700 Subject: creating multiply arguments for a method. Message-ID: <1156686964.216440.72530@p79g2000cwp.googlegroups.com> Hi all, I use a method that accept multiply arguments ("plot(*args)"). so plot([1,2,3,4]) is accepted and plot([1,2,3,4],[5,6,7,8]) is also accepted. the problem is that i know the number of arguments only at runtime. Let say that during runtime i need to pass 4 arguments, each is a list, creating a set of lists and passing it to the method wont word since the interpartor thinks it is only 1 argument the contain a reference to a "list of lists", instede of number of arguments, each is a list. any suggestions? thanks amit From danieljohnson at vzavenue.net Sat Aug 26 10:42:26 2006 From: danieljohnson at vzavenue.net (Dan Johnson) Date: Sat, 26 Aug 2006 10:42:26 -0400 Subject: Duck typing alows true polymorfisim References: <1156532721.879808.40990@i3g2000cwc.googlegroups.com> Message-ID: <12f0nek6424sg4e@news.supernews.com> <atbusbook at aol.com> wrote in message news:1156532721.879808.40990 at i3g2000cwc.googlegroups.com... > lets say you want a generic numerical algorithom like sum > > Ruby > > def sum lst > lst.inject(0){|total,current| total*current} > end > > Java // i dont know if there is a numeric super class for numbers [snip- int only example] There is, and it is interesting because it hilights the real difference: Java uses C style numerics, where you select the model of arithmetic you want using the type system. Here's a 'generic sum' for Java: public static double sum(Iterable<? extends Number> list) { double total=0; for(Number n : list) double+=n.doubleValue(); return total; } If I got it right (I'm a bit rusty with Java) that will sum any collection containing any kind of number. But you have to specify that you want *double* arithmetic, as you see; had I chosen int, it would produce different answers. In some languages- like Ruby I think- you cannot make this choice. Your language chooses for you. Most languages that do this prefer accuracy to speed, so everything gets promoted to larger types on demand, and things like rounding and overflow are avoided. However, even if you agree with this choice, you can still get into trouble. Promoting to 'double' or 'float' imposes different errors that you'd get with ints, but they still exist. Sometimes a ratio type is better; other times you would prefer a decimal type. The greatest advantage of static type systems is to expose design decisions like these in a way the compiler can see. From http Tue Aug 15 14:50:06 2006 From: http (Paul Rubin) Date: 15 Aug 2006 11:50:06 -0700 Subject: X windows and Python? References: <7xy7tpyhbf.fsf_-_@ruckus.brouhaha.com> <7xk6596dp0.fsf@ruckus.brouhaha.com> Message-ID: <7xfyfx6dgh.fsf@ruckus.brouhaha.com> Paul Rubin <http://phr.cx at NOSPAM.invalid> writes: > Hmm, looks like I can use w.clipboard_append with an arbitrary tkinter > widget, maybe without having to actually display anything. I'll try > that. Nope, that's some kind of internal Tk clipboard. Any other ideas, how to communicate with the X window manager? From kw at kevin-walzer.com Mon Aug 28 18:51:31 2006 From: kw at kevin-walzer.com (Kevin Walzer) Date: Mon, 28 Aug 2006 18:51:31 -0400 Subject: Max OSX and Excel In-Reply-To: <mailman.9994.1156796455.27775.python-list@python.org> References: <mailman.9994.1156796455.27775.python-list@python.org> Message-ID: <44F37373.2090404@kevin-walzer.com> Johanna Pfalz wrote: > Hi there, > > Does anyone have details on how to drive excel using python 2.4 on OSX? > I've searched the web and have not found anything specific to excel. > > Thanks in advance, > > > Johanna Pfalz > Smithers, BC > > > Try AppScript: http://appscript.sourceforge.net/ It's a Python-to-Apple Events bridge. It allows you to access a scriptable application using the same mechanism that underlies AppleScript, but from Python. Excel has good AppleScript support, so it should be supported by AppScript as well. -- Kevin Walzer Poetic Code http://www.kevin-walzer.com From cipherpunk at gmail.com Sun Aug 6 19:58:57 2006 From: cipherpunk at gmail.com (Robert J. Hansen) Date: 6 Aug 2006 16:58:57 -0700 Subject: Open letter to BDFL begging forgiveness. In-Reply-To: <1154898826.309400.66920@h48g2000cwc.googlegroups.com> References: <1154898826.309400.66920@h48g2000cwc.googlegroups.com> Message-ID: <1154908737.582594.160360@m73g2000cwd.googlegroups.com> ObWarning: I'm not Guido. I'm not even a friend of Guido. That said, some people think I have a clue about the open-source community, so maybe this will be worth something. And perhaps it won't. Take it with a grain of salt. > However, I am beginning to suspect that my status as persona > non grata in your eyes is getting in the way of other people in > this group to accept me. This may be a hard thing to come to terms with, but you're probably not important enough to be persona non grata. After all, in order to be persona non grata you have to be... a persona. No, no, I'm not telling you that you're not a person. But ask yourself: what have you done for Python lately? What have you done to warrant being treated like a Kent Pitman, a James Kanze, a Peter Seibel, an Alex Martelli, just to pick a few well-known and well-respected names from various programming languages? Join mailing lists. Become active in a user's group. Write code. Be generous with your knowledge. Help newbies. Practice humility. Always ask yourself, "could I be wrong here?" Do it for long enough and you'll get a reputation for being a productive member of the community. And then you'll find that you never needed 'forgiveness' at all. From gagsl-py at yahoo.com.ar Tue Aug 29 01:03:24 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 29 Aug 2006 02:03:24 -0300 Subject: Is this a good idea or a waste of time? In-Reply-To: <slrnef7gj7.4tu.apardon@rcpc42.vub.ac.be> References: <1156449402.022781.292840@p79g2000cwp.googlegroups.com> <1156485945.967160.238790@m73g2000cwd.googlegroups.com> <slrnef5hep.4tu.apardon@rcpc42.vub.ac.be> <44f322cd$1@nntp0.pdx.net> <slrnef6o2j.4tu.apardon@rcpc42.vub.ac.be> <1156802762.331853.80000@75g2000cwc.googlegroups.com> <slrnef7gj7.4tu.apardon@rcpc42.vub.ac.be> Message-ID: <7.0.1.0.0.20060829020008.0430b7b8@yahoo.com.ar> At Tuesday 29/8/2006 01:28, Antoon Pardon wrote: > > Antoon Pardon wrote: > >> There seem to be enough problems that work with ints but not with > >> floats. In such a case enforcing that the number you work with > >> is indeed an int seems fully appropiate. > > > > I've _never_ seen a case where enforcing types in the manner of the OP > > is appropriate. > > > > It fails with trivial wrappers like > > > > class myInt(int): > > def printFormatted(self): > > .......... > > > > Even looser checking with isinstance is rarely right. You may want to > > exclude floats, but that doesn't mean you want to exclude int-like > > objects that don't inherit from int. > >That may be true. But one may wonder if this is a failing of the >programmer or a failing of the language that doesn't support >such things. In any case, I don't see how this supports the original claim that strict type checking input params is good practice. Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From riko at despammed.com Tue Aug 22 08:32:44 2006 From: riko at despammed.com (Mc Osten) Date: Tue, 22 Aug 2006 14:32:44 +0200 Subject: Python and STL efficiency References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <eccb9u$kjs$1@gemini.csx.cam.ac.uk> <1hkh28d.xscw4v1y4v9a6N%riko@despammed.com> <mailman.9640.1156247569.27775.python-list@python.org> Message-ID: <1hkh6lb.6dsnh51lj8z96N%riko@despammed.com> Fredrik Lundh <fredrik at pythonware.com> wrote: > Python's memory allocator is also quite fast, compared to most generic > allocators... In fact also in the two "slow" versions Python outperforms C++. I didn't notice it in the first place. -- blog: http://www.akropolix.net/rik0/blogs | Uccidete i filosofi, site: http://www.akropolix.net/rik0/ | tenetevi riso e forum: http://www.akropolix.net/forum/ | bacchette per voi. From grante at visi.com Wed Aug 2 23:26:36 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 03 Aug 2006 03:26:36 -0000 Subject: serial ports, threads and windows References: <mailman.8872.1154560051.27775.python-list@python.org> Message-ID: <12d2r7cce10h6ad@corp.supernews.com> On 2006-08-02, Tom Brown <brown at esteem.com> wrote: > When it runs on Windows, could it be: > > 1) Just struggling to run inside of VMware? Could be. Virtual machines are rather tricky things on broken architectures that don't really permit true virtualization. > 2) Using threads with Qt on Windows is a problem? Doubt it. > 3) Threads in python on Windows is a problem? No. -- Grant Edwards grante Yow! I'LL get it!! It's at probably a FEW of my visi.com ITALIAN GIRL-FRIENDS!! From mail at microcorp.co.za Sat Aug 19 11:49:06 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 19 Aug 2006 17:49:06 +0200 Subject: tkinter btn visual state with tkMessageBox References: <1155995811.278433.87560@75g2000cwc.googlegroups.com> Message-ID: <001401c6c3a7$1b312c40$03000080@hendrik> <jmdeschamps at gmail.com> wrote: To: <python-list at python.org> | why is the button sunken when called through a bind method, and not | with the command attribute? | Thank you! | | | ## Cut'nPaste example | from Tkinter import * | import tkMessageBox | | class Vue(object): | def __init__(self): | self.root=Tk() | self.root.title("test button visual state") | self.b1=Button(self.root,text="tkMessageBox.showinfo with bind | :-(") #,command=self.showMsg) | self.b1.bind("<Button>",self.showMsg) 8<--------------------------------------------------------------------------- change this to : self.b1.bind("<ButtonRelease>",self.showMsg) Problem is that a button "sinks in" when you press it and "springs back" when you release it... and the "Button" leaves it sunken.... - because when you release, the control is no longer there - Hendrik From edmond at le-comte-de-monte-cristo.biz Sun Aug 6 09:06:22 2006 From: edmond at le-comte-de-monte-cristo.biz (Edmond Dantes) Date: Sun, 06 Aug 2006 09:06:22 -0400 Subject: Nested function scope problem References: <20060804094245.A9AF.SLAWOMIR.NOWACZYK.847@student.lu.se> <1okvniwl5zgqj.dlg@gelists.gmail.com> <20060804155855.EE80.SLAWOMIR.NOWACZYK.847@student.lu.se> <mailman.8997.1154711381.27775.python-list@python.org> <vs27d2ls81p6jhugp1et05qkpe11d0mebb@4ax.com> <mailman.9003.1154731508.27775.python-list@python.org> <e788d2hj0mc4t8dat10ekoagutjhdu2p93@4ax.com> <mailman.9010.1154773526.27775.python-list@python.org> <3hh9d2tsukbvfk79e53cgv7jcu6jbqbm3m@4ax.com> Message-ID: <1154868976_3728@news-east.n> Dennis Lee Bieber wrote: > On Sat, 5 Aug 2006 07:24:51 -0300, Gerhard Fiedler <gelists at gmail.com> > declaimed the following in comp.lang.python: > >> I know. It's just that your explicit analogy made this better visible, so >> I wanted to add that to it. But I guess this thing is getting into the >> "dead horse" state -- if it hasn't been there for a while now :) >> > Needs more aging to tenderize <G> Keep the MSG out of it!!! -- -- Edmond Dantes, CMC And Now for something Completely Different: http://floral-bouquets.prosperitysprinkler.com http://ridgeback.KindPets.com http://credit.Internet69.com http://Atkins.blackboystuff.com http://cutting-tools.Auto1Parts.com http://limousine.weddingbelljoy.com http://creativity.WomanMinutes.com Posted Via Usenet.com Premium Usenet Newsgroup Services ---------------------------------------------------------- ** SPEED ** RETENTION ** COMPLETION ** ANONYMITY ** ---------------------------------------------------------- http://www.usenet.com From stephan.diehl at gmx.net Wed Aug 2 05:59:43 2006 From: stephan.diehl at gmx.net (Stephan Diehl) Date: Wed, 02 Aug 2006 11:59:43 +0200 Subject: Behavior on non definded name in Cheetah In-Reply-To: <mailman.8838.1154512541.27775.python-list@python.org> References: <mailman.8838.1154512541.27775.python-list@python.org> Message-ID: <eapt2e$gbv$00$1@news.t-online.com> Paolo Pantaleo wrote: > [I hope I am posting to the right place] > > I have a cheetah template something like this: > > x is: $x > y is: $y > z is: $z > > [Actually more complicated] > > If for example $y is not defined I get an exception and the parsing > of the template stops. Is there any way to substitute $y with an emty > string and making cheeta going on with parsing? > > Thnx > PAolo > http://cheetahtemplate.org/docs/users_guide_html_multipage/language.namemapper.missing.html From gagsl-py at yahoo.com.ar Wed Aug 30 11:26:24 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 30 Aug 2006 12:26:24 -0300 Subject: dictionary with object's method as thier items In-Reply-To: <1156944917.152606.213600@i42g2000cwa.googlegroups.com> References: <1156944917.152606.213600@i42g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20060830122243.04c982a0@yahoo.com.ar> At Wednesday 30/8/2006 10:35, noro wrote: >for a certain class: >by some way create a dictionary that look somthing like that: > >d= {'function one': <reference to C.func1()>, \ > 'function two': <reference to C.func2()>, \ > 'function three': <reference to C.func3()>} > >and so i could access every method of instances of C, such as obj with >sometiing like: >(i know that this syntax wont work ) > >obj.(d['function one']) >obj.(d['function two']) You can use dir(obj) to get its list of attributes (including method names) then use getattr to invoke the method. methodname='func1' getattr(obj,methodname)() See the inspect module too. Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From stefan.behnel-n05pAM at web.de Tue Aug 1 06:12:20 2006 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 01 Aug 2006 12:12:20 +0200 Subject: how to get size of unicode string/string in bytes ? In-Reply-To: <4j8k58F6th46U1@uni-berlin.de> References: <1154420030.988013.89310@m79g2000cwm.googlegroups.com> <44cf167c$0$24894$9b4e6d93@newsread4.arcor-online.net> <4j8k58F6th46U1@uni-berlin.de> Message-ID: <44cf2906$0$24899$9b4e6d93@newsread4.arcor-online.net> Diez B. Roggisch wrote > Stefan Behnel wrote: > >> pattreeya at gmail.com wrote: >>> how can I get the number of byte of the string in python? >>> with "len(string)", it doesn't work to get the size of the string in >>> bytes if I have the unicode string but just the length. (it only works >>> fine for ascii/latin1) In data structure, I have to store unicode >>> string for many languages and must know exactly how big of my string >>> which is stored so I can read back later. >> I do not quite know what you could possibly need that for, but AFAICT >> Python only uses two different unicode encodings depending on the >> platform. > > It is very important for relational databases, as these usually constrain > the amount of bytes per column - so you need the size of bytes, not the > number of unicode characters. So then the easiest thing to do is: take the maximum length of a unicode string you could possibly want to store, multiply it by 4 and make that the length of the DB field. However, I'm pretty convinced it is a bad idea to store Python unicode strings directly in a DB, especially as they are not portable. I assume that some DB connectors honour the local platform encoding already, but I'd still say that UTF-8 is your best friend here. Stefan From lists at webcrunchers.com Mon Aug 21 17:31:26 2006 From: lists at webcrunchers.com (John Draper) Date: Mon, 21 Aug 2006 14:31:26 -0700 Subject: Unclear on argument passing to "sendmail' Message-ID: <44EA262E.8040301@webcrunchers.com> In "smtplib" module, the "sendmail" method of function is to be passed a host, but it is the Domain name for the SMTP Server as gotten from the "dig" command? IE: dig -tMX would give me the SMTP server. In my code I have: try: print "Sending message to host: %s" % mailHost server=smtplib.SMTP(mailHost) server.sendmail(reply_email,email,body) server.quit() except: print "Uunable to send" Is mailHost like "mail.t-mobile.com" which I get from the MX record for a given domain? But also, is the "email" just the mail account, ie: the username? without the @<domain>? I need to be able to query the mail server? Also, I want to be able to handle the "SMTPRecipientsRefused" exception. What is the proper syntax for handling this? Do I do it like this? try: print "Sending message to host: %s" % mailHost server=smtplib.SMTP(mailHost) server.sendmail(reply_email,email,body) server.quit() except SMTPRecipientsRefused: print "Recipient refused" Is that the right syntax? I have severe problems with not enough example code. John I From tim.golden at viacom-outdoor.co.uk Wed Aug 16 09:40:50 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 16 Aug 2006 14:40:50 +0100 Subject: What would be the best way to run python client in the background Message-ID: <CCAC78D42E32184F8E26DC163DB98306C1B38D@vogbs009.gb.vo.local> | > [gel] | > | > | I have written a python client server app [...] | > | I want to run the client end of the app more or less invisibly | > | (no console) on the XP clients when ever a users logs on. While this isn't answering the question you first asked, might I suggest an alternative approach? Obviously, I'm working from no more than the sketch you gave of your app and its requirements, but might it be worth turning the problem on its head, and using WMI? Advantages: 1) WMI will -- almost certainly -- already be running on your target machines. No need to install your own service. 2) WMI has a fair range of mechanisms for determining what processes are starting, stopping, etc. and for manipulating them remotely. 3) You can, at least in theory, access any number of machines from a central server, and with a bit of judicious threading or looping, you should be able to generate a fair bit of resilience to machine dropouts etc. Disadvantages: 1) What you're doing may be far more complex than you've outlined, requiring a local service per target machine for other reasons. 2) You may have already invested some amount of time and effort in developing an app which does what you want. 3) I may have entirely misunderstood what you're trying to do in any case. If you're interested and want a code sample, let me know. If you're not, that's fine. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From tjreedy at udel.edu Thu Aug 10 11:02:05 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 10 Aug 2006 11:02:05 -0400 Subject: do people really complain about significant whitespace? References: <1154991523.887791.9640@i42g2000cwa.googlegroups.com><1154994477.450666.226550@b28g2000cwb.googlegroups.com><mailman.9132.1155120873.27775.python-list@python.org><1155124820.123151.140580@p79g2000cwp.googlegroups.com><9$lHo7FEZe2EFwf$@objmedia.demon.co.uk><1155133454.975325.237770@b28g2000cwb.googlegroups.com> <AC0Y37IB0w2EFwbV@objmedia.demon.co.uk> Message-ID: <ebfhpe$9o$1@sea.gmane.org> "Stephen Kellett" <snail at objmedia.demon.co.uk> wrote in message news:AC0Y37IB0w2EFwbV at objmedia.demon.co.uk... > To answer your first question: In C++/Ruby/Pascal you'd have something > like this > > function() > { > loop1() > { > blah > blah > > loop2() > { > blah > > loop3() > { > blah > } > > blah > } > } > > otherloop() > { > blah > } > } > > and in Python that gets to > > function() > loop1() > blah > blah > > loop2() > blah > > loop3() > blah > > blah3 > > otherloop() > blah Much nicer, IMHO ;-). > I really dislike that the end of loop2 is implicit rather than > explicit. If its implicit you have to look for it. And if blah3 didn't > exist then both loop2 and loop3 would be ending implicitly. So add one of those judicious, informative comments that some have written about in this thread ;-) # end loop2 where 'loop2' would typically be something like 'i loop'. If blah3 didn't exist, you could add # end loop3 *above* the end loop2 comment. I personally found matching far-apart well-indented braces visually something of a nuisance too, so I sometimes did much the same in C: } /* end i loop */ > This problem gets worse with longer functions and more indentation. And devoting lines to braces, including those that are visually interfering (such as those for loop3) expands blocks and makes it more likely that blocks will span screens. This makes the problem worse. > I'm sure some people are thinking the above is elegant. Yes, allowing programmers to add explict end-suite markers only where needed is, to me, more elegant that forcing redundant begin-suite markers and often unneeded end-markers. Terry Jan Reedy From sjmachin at lexicon.net Thu Aug 10 20:21:00 2006 From: sjmachin at lexicon.net (John Machin) Date: 10 Aug 2006 17:21:00 -0700 Subject: hide python code ! In-Reply-To: <1155254631.617208.299550@m73g2000cwd.googlegroups.com> References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155253821.570487.165400@b28g2000cwb.googlegroups.com> <1155254631.617208.299550@m73g2000cwd.googlegroups.com> Message-ID: <1155255660.568849.240280@p79g2000cwp.googlegroups.com> Bayazee wrote: > hi > in compiled languages when we compile a code to an executable file it > convert to a machine code so now we cant access to source ... > but in python we easily open the program executable(ascii) file and > read source .... > i meen than any way to protect my code or convert it to executable > witch can not be decompiled (python code).... I know what you mean. However consider this: There is no such thing as an executable which cannot be decompiled; if the code can be executed, then anybody with read access to the code can disassemble/decompile/whatever it -- there is no theoretical difference between disassembling an .exe file and decompiling a .pyc file. What's in a .pyc file is just the machine code for a virtual machine ... Consider changing your business plan: write crappy software, charge heaps for support -- it's not a novel idea :-) From email at christoph-haas.de Thu Aug 3 13:15:17 2006 From: email at christoph-haas.de (Christoph Haas) Date: Thu, 3 Aug 2006 19:15:17 +0200 Subject: Running queries on large data structure In-Reply-To: <1154619645.356336.189640@p79g2000cwp.googlegroups.com> References: <200608022224.00925.email@christoph-haas.de> <mailman.8915.1154615978.27775.python-list@python.org> <1154619645.356336.189640@p79g2000cwp.googlegroups.com> Message-ID: <200608031915.17948.email@christoph-haas.de> On Thursday 03 August 2006 17:40, jay graves wrote: > Christoph Haas wrote: > > The situation is that I have input data that take ~1 minute to parse > > while the users need to run queries on that within seconds. I can > > think of two ways: > > What is the raw data size? The file containing the objects is 2.3 MB. The rules that I parse are 3.8 MB. Both files contain different objects and properties/settings of each objects one per line. > Are there any effciencies to be gained in the parsing code? The currently working application is still Perl. I have started to rewrite the parser in Python. However an import of the objects alone takes ~5 seconds. The rules probably take at least as long. I'm already using regular expressions very rarely and try to make it as efficient as possible (without implementing parts in C). > > (1) Database > > (very quick, but the input data is deeply nested and it would be > > ugly to convert it into some relational shape for the database) > > Depending on your tolerance for this ugliness. You could use a SQLite > 'memory' database. _Might_ be faster than the PostgreSQL but you can't > tell until you profile it. The current application uses PostgreSQL and parsing all the data and moving them into the database takes ~30 seconds at the moment. Since that's done every 5 minutes in the background nobody has to wait for it. > > (2) cPickle > > (Read the data every now and then, parse it, write the nested > > Python data structure into a pickled file. The let the other > > application that does the queries unpickle the variable and use it > > time and again.) > > How hard would it be to create this nested structure? Not hard. Instead of doing "INSERT INTO" I would add values to a dictionary or list. That's even simpler. > I've found > pickling really large data structures doesn't really save a huge amount > of time when reloading them from disk but YMMV and you would have to > profile it to know for sure. Okay, that takes a bit of pickle's magic away. :) > > So the question is: would you rather force the data into a relational > > database and write object-relational wrappers around it? Or would you > > pickle it and load it later and work on the data? The latter > > application is currently a CGI. I'm open to whatever. :) > > Convert your CGI to a persistant python webserver (I use CherryPy but > you can pick whatever works for you.) and store the nested data > structure globally. Reload/Reparse as necessary. It saves the > pickle/unpickle step. Up to now I have just used CGI. But that doesn't stop me from looking at other web frameworks. However the reparsing as necessary makes a quick query take 10-30 seconds. And my users usually query the database just once every now and then and expect to have little delay. That time is not very user-friendly. It makes me feel bad to (ab)use PostgreSQL for just throw-away data. The database would just be needed for the persistance. It's not even needed for querying the data because it shows that SQL is not mighty enough for the kind of queries I need. That's where I thought that some other persistant storage would come handy. Up to now my mind just knew the equation persistence==database. Christoph From grover.uk at gmail.com Sat Aug 26 12:22:48 2006 From: grover.uk at gmail.com (groves) Date: 26 Aug 2006 09:22:48 -0700 Subject: rollover effect In-Reply-To: <1156609000.477885.289150@h48g2000cwc.googlegroups.com> References: <1156607403.741240.25000@74g2000cwt.googlegroups.com> <1156608042.466471.210270@m73g2000cwd.googlegroups.com> <1156608554.489516.243640@h48g2000cwc.googlegroups.com> <1156609000.477885.289150@h48g2000cwc.googlegroups.com> Message-ID: <1156609368.745082.324510@h48g2000cwc.googlegroups.com> Sorry, as I am new to python so couldn't understand what yu were asking. Now the problem is that i annot use pmw in my project..is thre anyother alternative by which I can have a rollover mouse effect on the canvas. thanks From pattreeya at gmail.com Tue Aug 1 04:13:51 2006 From: pattreeya at gmail.com (pattreeya at gmail.com) Date: 1 Aug 2006 01:13:51 -0700 Subject: how to get size of unicode string/string in bytes ? Message-ID: <1154420030.988013.89310@m79g2000cwm.googlegroups.com> Hello, how can I get the number of byte of the string in python? with "len(string)", it doesn't work to get the size of the string in bytes if I have the unicode string but just the length. (it only works fine for ascii/latin1) In data structure, I have to store unicode string for many languages and must know exactly how big of my string which is stored so I can read back later. Many thanks for any suggestion. cheers! pattreeya. From johnjsal at NOSPAMgmail.com Tue Aug 1 12:18:48 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 01 Aug 2006 16:18:48 GMT Subject: Finding the name of a class In-Reply-To: <mailman.8807.1154448861.27775.python-list@python.org> References: <q684q3xmd11.ln2@news.conpoint.com> <44cf7538$0$29435$626a54ce@news.free.fr> <mailman.8804.1154447561.27775.python-list@python.org> <CQKzg.2612$No6.51420@news.tufts.edu> <YWKzg.2613$No6.51510@news.tufts.edu> <mailman.8807.1154448861.27775.python-list@python.org> Message-ID: <I9Lzg.2614$No6.51514@news.tufts.edu> Shane Hathaway wrote: > Don't forget to file a bug. I'm reluctant to call it a bug just yet. Here's more stuff below. There's obviously a difference between old- and new-style classes. It seems that as far as new-style is concerned, __name__ is an attribute of __class__ (along with a bunch of other stuff), but not of Foo itself. >>> class Foo(object): pass >>> dir(Foo) ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__'] >>> dir(Foo.__class__) ['__base__', '__bases__', '__basicsize__', '__call__', '__class__', '__cmp__', '__delattr__', '__dict__', '__dictoffset__', '__doc__', '__flags__', '__getattribute__', '__hash__', '__init__', '__itemsize__', '__module__', '__mro__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__subclasses__', '__weakrefoffset__', 'mro'] >>> class Foo: pass >>> dir(Foo) ['__doc__', '__module__'] >>> dir(Foo.__class__) Traceback (most recent call last): File "<pyshell#9>", line 1, in -toplevel- dir(Foo.__class__) AttributeError: class Foo has no attribute '__class__' From jaysherby at gmail.com Thu Aug 31 14:48:05 2006 From: jaysherby at gmail.com (Putty) Date: 31 Aug 2006 11:48:05 -0700 Subject: python loops Message-ID: <1157050085.120921.31840@h48g2000cwc.googlegroups.com> In C and C++ and Java, the 'for' statement is a shortcut to make very concise loops. In python, 'for' iterates over elements in a sequence. Is there a way to do this in python that's more concise than 'while'? C: for(i=0; i<length; i++) python: while i < length: i += 1 From python-url at phaseit.net Wed Aug 30 15:40:59 2006 From: python-url at phaseit.net (Jack Diederich) Date: Wed, 30 Aug 2006 19:40:59 +0000 (UTC) Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Aug 30) Message-ID: <ed4pkb$v5d$1@lairds.us> QOTW: "The best working hypothesis is that upgrading will break things." - Grant Edwards "Should I take this to mean: "Don't go near TNEF because your underwear will become carnivorous and consume your genitalia?" - Hendrik van Rooyen Which is better, Turbogears or Rails? Flame on. http://groups.google.com/group/comp.lang.python/browse_thread/thread/0837e5e8002a5099/ PyThreadState_SetAsyncExc() is a C-level call because it is impossible to use safely. We're all adults here but we're not all wizards. http://groups.google.com/group/comp.lang.python/browse_thread/thread/121933c824d76c95/ A style question on an if-else clause gets a dozen different answers http://groups.google.com/group/comp.lang.python/browse_thread/thread/0bc45bec69e22e5d/ Testing stdout output is easy with doctest (unittest integration too!) http://groups.google.com/group/comp.lang.python/browse_thread/thread/a5a5f786d3cce8f8/ Ray asks what version of python people use in production and gets a variety of answers. http://groups.google.com/group/comp.lang.python/browse_thread/thread/ac65629d56f4e2e5/ Releases of Note NumPy 1.0b4, 4th beta release of the Numeric and Numarray package http://groups.google.com/group/comp.lang.python/browse_thread/thread/af8547bb878f8cd3/ Wing IDE 2.1.2 Powerful python aware IDE. http://groups.google.com/group/comp.lang.python.announce/browse_thread/thread/3fca6821f10c0859/ Upcoming Community Events Plone Conference 2006, October 25-27 (Seattle, Washington) http://plone.org/events/conferences/seattle-2006 Open Source Developers Conference Dec 5-8 (Melbourne, Australia) http://www.osdc.com.au/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/python/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to <Python-URL at phaseit.net> should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask <claird at phaseit.net> to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From tim.peters at gmail.com Sat Aug 12 18:48:34 2006 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 12 Aug 2006 18:48:34 -0400 Subject: _PyLong_FromByteArray In-Reply-To: <87d5b56er5.fsf@uwo.ca> References: <87d5b56er5.fsf@uwo.ca> Message-ID: <1f7befae0608121548y7f7b373fsd779b93a0ef5ee1d@mail.gmail.com> [Dan Christensen] > My student and I are writing a C extension that produces a large > integer in binary which we'd like to convert to a python long. The > number of bits can be a lot more than 32 or even 64. My student found > the function _PyLong_FromByteArray in longobject.h which is exactly > what we need, but the leading underscore makes me wary. Is it safe to > use this function? Python uses it internally, so it better be ;-) > Will it continue to exist in future versions of python? No guarantees, and that's why it has a leading underscore: it's not an officially supported, externally documented, part of the advertised Python/C API. It so happens that I added that function, because Python needed some form of its functionality internally across different C modules. Making it an official part of the Python/C API would have been a lot more work (which I didn't have time for), and created an eternal new maintenance burden (which I'm not keen on regardless ;-)). In practice, few people touch this part of Python's implementation, so I don't /expect/ it will go away, or even change, for years to come. The biggest insecurity I can think of offhand is that someone may launch a crusade to make some other byte-array <-> long interface "official" based on a different way of representing negative integers. But even then I expect the current unofficial functions to remain, since the 256's-complement representation remains necessary for the `struct` module's "q" format, and for the `pickle` module's protocol=2 long serialization format. > Or is there some other method we should use? No. That's why these functions were invented to begin with ;-) From meyer at acm.org Sun Aug 27 17:56:14 2006 From: meyer at acm.org (Andre Meyer) Date: Sun, 27 Aug 2006 23:56:14 +0200 Subject: Persistent Session in CGI In-Reply-To: <1156715285.717012.91300@i42g2000cwa.googlegroups.com> References: <1156715285.717012.91300@i42g2000cwa.googlegroups.com> Message-ID: <7008329d0608271456uc0d85e5h7affc8ea778b274a@mail.gmail.com> Karrigell is a very easy-to-use pure-Python web framework. It has examples of session management. http://karrigell.sourceforge.net/ regards Andre On 27 Aug 2006 14:48:05 -0700, keegan.csmith at gmail.com < keegan.csmith at gmail.com> wrote: > > Hi, > > I have started a new small web project, and was wondering if there are > any good guides on how to do Persistent Sessions and Authentication > using python and CGI. I don't really want too use Zope, because It's > probably overkill for my tiny project. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Dr. Andre P. Meyer http://python.openspace.nl/meyer TNO Defence, Security and Safety http://www.tno.nl/ Delft Cooperation on Intelligent Systems http://www.decis.nl/ Ah, this is obviously some strange usage of the word 'safe' that I wasn't previously aware of. - Douglas Adams -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060827/d452b614/attachment.html> From mi.janssen at gmail.com Wed Aug 23 05:54:18 2006 From: mi.janssen at gmail.com (Michael Janssen) Date: 23 Aug 2006 02:54:18 -0700 Subject: how do you get the name of a dictionary? References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <pan.2006.08.21.03.33.27.84160@REMOVEME.cybersource.com.au> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> <mailman.9631.1156227418.27775.python-list@python.org> <1156264475.968894.221710@p79g2000cwp.googlegroups.com> <mailman.9654.1156270417.27775.python-list@python.org> <1156271259.567470.86140@i3g2000cwc.googlegroups.com> Message-ID: <1156326858.129557.251410@h48g2000cwc.googlegroups.com> jojoba wrote: > given any dictionary, get a name for it. You do not want to open your text editor and hardcode the name (neither as a variable name nor a name-attribute), do you? Your script is hopefully capable to determine the dict-to-be-displayed from user-input? Perhaps name of a file to be parsed? >>> anydict = getTheDamnDict(userinput) >>> displayTheDamnDict(anydict) Even when you can display the name of the variable the dictionary is assigned to you yield 'anydict'. That's not that compelling. When you really intend to hardcode the variable's name to something meaningful, how is your script supposed to do sensible work after your work is done with it? When you want to have a programm that can display arbitrary dictionaries you end up with a variable name that is (hopefully ;-) meaningful in the context of the programm but not meaningful in respect of the content of the dictionary: at programming-time you can't know what dictionaries are to be displayed so you don't have meaningful names. You might want to take the name of the file to be parsed or something else from userinput as the name of the dict - but the variables name is the wrong place to store this information. Did I miss anything? regards Michael From rogue_pedro at yahoo.com Thu Aug 3 23:53:24 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 3 Aug 2006 20:53:24 -0700 Subject: Problem reading/writing files In-Reply-To: <1154661460.803694.241220@s13g2000cwa.googlegroups.com> References: <1154661460.803694.241220@s13g2000cwa.googlegroups.com> Message-ID: <1154663604.525698.12270@i3g2000cwc.googlegroups.com> smeenehan at hmc.edu wrote: > This is a bit of a peculiar problem. First off, this relates to Python > Challenge #12, so if you are attempting those and have yet to finish > #12, as there are potential spoilers here. > > I have five different image files shuffled up in one big binary file. > In order to view them I have to "unshuffle" the data, which means > moving bytes around. Currently my approach is to read the data from the > original, unshuffle as necessary, and then write to 5 different files > (2 .jpgs, 2 .pngs and 1 .gif). > > The problem is with the read() method. If I read a byte valued as 0x00 > (in hexadecimal), the read method returns a character with the value > 0x20. No. It doesn't. Ok, maybe it does, but I doubt this so severely that, without even checking, I'll bet you a [virtual] beer it doesn't. :-) Are you opening the file in binary mode? Ok, I did check, it doesn't. |>> s = '\0' |>> len(s) 1 |>> print s \x00 |>> f = open('noway', 'wb') |>> f.write(s) |>> f.close() Checking that the file is a length 1 null byte: $ hexdump noway 0000000 0000 0000001 $ ls -l noway -rw-r--r-- 1 sforman sforman 1 2006-08-03 23:40 noway Now let's read it and see... |>> f = open('noway', 'rb') |>> s = f.read() |>> f.close() |>> len(s) 1 |>> print s \x00 The problem is not with the read() method. Or, if it is, something very very weird is going on. If you can do the above and not get the same results I'd be interested to know what file data you have, what OS you're using. Peace, ~Simon (Think about this: More people than you have tried the challenge, if this happened to them they'd have mentioned it too, and it would have fixed or at least addressed by now. Maybe.) (Hmm, or maybe this is *part* of the challenge?) From rogue_pedro at yahoo.com Tue Aug 29 21:27:07 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 29 Aug 2006 18:27:07 -0700 Subject: TNEF decoder In-Reply-To: <TbDIg.1431$4O4.1306@trnddc02> References: <TbDIg.1431$4O4.1306@trnddc02> Message-ID: <1156901227.576728.203500@74g2000cwt.googlegroups.com> David Isaac wrote: > I'm aware of > http://cheeseshop.python.org/pypi/pytnef/ > but it uses the tnef utility, and I'd like a pure Python solution > (along the lines of http://www.freeutils.net/source/jtnef/ ). > > Is there one? > > Thanks, > Alan Isaac A place I once worked at had a project that included some TNEF handling. There was one developer assigned fulltime to it. He was the one who sat at his desk hurling curses at his workstation at the top of his lungs, later he developed a pretty severe drinking problem. Good luck. HTH, ~Simon From jnair at ensim.com Wed Aug 2 05:06:26 2006 From: jnair at ensim.com (jitya) Date: 2 Aug 2006 02:06:26 -0700 Subject: Programming newbie coming from Ruby: a few Python questions References: <1154458926.738922.156910@h48g2000cwc.googlegroups.com> Message-ID: <1154509586.873241.272910@75g2000cwc.googlegroups.com> simonharrison at fastmail.co.uk wrote: > Hi all. I've been try to learn ruby for a few months but I'm about > ready to give up. Perfection is achieved only on the point of collapse. -- C.N. Parkinson Welcome to Python , apart from the tutorials whenever time permits do read this articles . Why Python : http://www.linuxjournal.com/article/3882 The Python Paradox : http://www.paulgraham.com/pypar.html Why I Promote Python : http://www.prescod.net/python/why.html Regards Jitendra Nair Ensim India Pvt Ltd , Pune , India The available books either assume a programming > background, or are out of date. Anyway, I think python may suit me more > due to its 'theres one way to do it' philosophy (hope the quote is > right)! Another quote that I liked was: > > 'Clever is not considered a compliment in Python.' (don't know where I > read that...) > > In Ruby, there are many ways to do the same thing and cleverness seems > to be held in high regard. These attitudes are not too helpful for > beginners in my experience. Anyway, enough waffle. > > What books and tutorials are recommended to learn Python? The tutorial > that comes with Python is great and has given me a good overview but I > think I'd benefit from some programming projects, now I have a little > understanding of how Python works. > > Ideally, I'd like a whole series of projects where I'm walked through > how to go about writing real Python. The way I look at it, nobody > learnt to build a house just from reading about building materials! > > Any other tips for getting up to speed with Python fairly quickly will > be greatly appreciated. > > If anyone can help, thanks very much From johnjsal at NOSPAMgmail.com Fri Aug 11 10:08:16 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 11 Aug 2006 14:08:16 GMT Subject: using python to edit a word file? In-Reply-To: <mailman.9237.1155288402.27775.python-list@python.org> References: <aJKCg.2673$No6.52073@news.tufts.edu> <87slk4tp45.fsf@smsnet.pl><LeLCg.2674$No6.52085@news.tufts.edu> <GuLCg.2675$No6.51938@news.tufts.edu> <mailman.9237.1155288402.27775.python-list@python.org> Message-ID: <kb0Dg.2679$No6.52110@news.tufts.edu> Anthra Norell wrote: > John, > > I have a notion about translating stuff in a mess and could help you with the translation. But it may be that the conversion > from DOC to formatted test is a bigger problem. Loading the files into Word and saving them in a different format may not be a > practical option if you have many file to do. Googling for batch converters DOC to RTF I couldn't find anything. > If you can solve the conversion problem, pass me a sample file. I'll solve the translation problem for you. > > Frederic What I ended up doing was just saving the Word file as an XML file, and then writing a little script to process the text file. Then when it opens back in Word, all the formatting remains. The script isn't ideal, but it did the bulk of changing the numbers, and then I did a few things by hand. I love having Python for these chores! :) import re xml_file = open('calendar.xml') xml_data = xml_file.read() xml_file.close() pattern = re.compile(r'<w:t>(\d+)</w:t>') def subtract(match_obj): date = int(match_obj.group(1)) - 1 return '<w:t>%s</w:t>' % date new_data = re.sub(pattern, subtract, xml_data) new_file = open('calendar2007.xml', 'w') new_file.write(new_data) new_file.close() From *firstname*nlsnews at georgea*lastname*.com Sat Aug 5 14:03:55 2006 From: *firstname*nlsnews at georgea*lastname*.com (Tony Nelson) Date: Sat, 05 Aug 2006 18:03:55 GMT Subject: What is the best way to print the usage string ? References: <mailman.8916.1154621888.27775.python-list@python.org> <1154625685.027648.133500@p79g2000cwp.googlegroups.com> Message-ID: <*firstname*nlsnews-BDD49A.14035705082006@news.verizon.net> In article <1154625685.027648.133500 at p79g2000cwp.googlegroups.com>, "Simon Forman" <rogue_pedro at yahoo.com> wrote: ... > Python also concatenates adjacent strings, but the "real" newlines > between your strings will need to be escaped (otherwise, because the > newlines are statement separators, you will have one print statement > followed by string literals with the wrong indentation.) > > print "Usage: blah blah blah\n" \ > "Some more lines in the usage text\n" \ > "Some more lines here too." > > (Note that the final string literal newline is not needed since print > will add one of it's own.) One can also use parentheses: print ( "Usage: blah blah blah\n" "Some more lines in the usage text\n" "Some more lines here too." ) The newlines in the string are still needed, but the ones escaping the EOLs are not. ________________________________________________________________________ TonyN.:' *firstname*nlsnews at georgea*lastname*.com ' <http://www.georgeanelson.com/> From matt at tplus1.com Sun Aug 20 10:05:13 2006 From: matt at tplus1.com (Matthew Wilson) Date: Sun, 20 Aug 2006 14:05:13 GMT Subject: Need advice on how to improve this function Message-ID: <slrneegr0p.9db.matt@mwilson.umlcoop.net> I wrote a function that converts a tuple of tuples into html. For example: In [9]: x Out[9]: ('html', ('head', ('title', 'this is the title!')), ('body', ('h1', 'this is the header!'), ('p', 'paragraph one is boring.'), ('p', 'but paragraph 2 ', ('a', {'href': 'http://example.com'}, 'has a link'), '!'))) In [10]: as_html(x, sys.stdout) <html> <head> <title>this is the title!

this is the header!

paragraph one is boring.

but paragraph 2 has a link!

I'd like to know ways to make it better (more efficient, able to deal with enormous-size arguments, etc). How would I write this as a generator? Here's the definition for as_html: def as_html(l, s): "Convert a list or tuple into html and write it to stream s." if isinstance(l, (tuple, list)): tagname = l[0] if isinstance(l[1], dict): attributes = ' '.join(['%s="%s"' % (k, l[1][k]) for k in l[1]]) s.write('<%s %s>' % (tagname, attributes)) else: s.write('<%s>' % tagname) if tagname in ('html', 'head', 'body'): s.write('\n\n') for ll in l[1:]: as_html(ll, s) s.write('' % tagname) if tagname not in ('a', 'b', 'ul'): s.write('\n\n') elif isinstance(l, str): s.write(l) All comments welcome. TIA -- A better way of running series of SAS programs: http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles From tjreedy at udel.edu Tue Aug 1 12:41:47 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 1 Aug 2006 12:41:47 -0400 Subject: code to retrieve web mail? References: <060801000110020.01Aug06$rookswood@suburbian.com> Message-ID: "Paul McGuire" wrote in message news:BgCzg.37100$Cn6.13579 at tornado.texas.rr.com... > Instead of mimicking a browser to access this e-mail account through the > web > interface, see if there is a POP3 access to your free e-mail (I'd be > surprised if there isn't). To the contrary: Yahoo, for instance, charges for POP3 access; for 'free' browser access, you 'pay' by exposure to ads. I imagine others do the same. And yes, paying $20/year for the POP3 access should be worth it to most people. tjr From khemkaamit at gmail.com Fri Aug 4 09:23:52 2006 From: khemkaamit at gmail.com (Amit Khemka) Date: Fri, 4 Aug 2006 18:53:52 +0530 Subject: Running queries on large data structure In-Reply-To: <200608031639.30477.email@christoph-haas.de> References: <200608022224.00925.email@christoph-haas.de> <200608031639.30477.email@christoph-haas.de> Message-ID: <1360b7230608040623s7d394aafwd33b365593193c87@mail.gmail.com> On 8/3/06, Christoph Haas wrote: > On Wednesday 02 August 2006 22:24, Christoph Haas wrote: > > I have written an application in Perl some time ago (I was young and > > needed the money) that parses multiple large text files containing > > nested data structures and allows the user to run quick queries on the > > data. [...] > > I suppose my former posting was too long and concrete. So allow me to try > it in a different way. :) > > The situation is that I have input data that take ~1 minute to parse while > the users need to run queries on that within seconds. I can think of two > ways: > > (1) Database > (very quick, but the input data is deeply nested and it would be > ugly to convert it into some relational shape for the database) > (2) cPickle > (Read the data every now and then, parse it, write the nested Python > data structure into a pickled file. The let the other application > that does the queries unpickle the variable and use it time and > again.) Though some sugggested maintaining data in some XML structures, I was wondering that if you considered using some native XML database like BDB XML. 1. It allows you to retain hierarchical structure of data. 2. It also has support for precompiled queries. 3. You can open a persistent connection. cheers, amit. -- ---- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. From gandalf at designaproduct.biz Thu Aug 24 14:23:10 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Thu, 24 Aug 2006 20:23:10 +0200 Subject: can't destroy a wxMiniFrame In-Reply-To: <1156443102.524257.14500@i3g2000cwc.googlegroups.com> References: <1156443102.524257.14500@i3g2000cwc.googlegroups.com> Message-ID: <44EDEE8E.90708@designaproduct.biz> Flavio ?rta: > Hi, > > I have a miniframe composed mainly of combo boxes, that I need to > destroy and recreate multiple time with different choice lists for the > combo boxes. > > My problem is that even after destroying a miniframe with the Destroy() > method, when it is recreated, the combo boxes show the same lists of > its previous incarnation... > > how can I completely destroy a miniframe? > From what you wrote, I think that you did not create a new miniframe. Although you called Destroy(), you tried to display it again. This is what the documentation says about destroy. Destroys the window safely. Use this function instead of the delete operator, since different window classes can be destroyed differently. *Frames and dialogs are not destroyed immediately* when this function is called -- they are added to a list of windows to be deleted on idle time, when all the window's events have been processed. This prevents problems with events being sent to non-existent windows. Regards, Laszlo From riteshsarraf at gmail.com Fri Aug 4 08:07:12 2006 From: riteshsarraf at gmail.com (Ritesh Raj Sarraf) Date: 4 Aug 2006 05:07:12 -0700 Subject: Thread Question In-Reply-To: <1154690942.385855.41130@m79g2000cwm.googlegroups.com> References: <1153998422.670828.148360@m79g2000cwm.googlegroups.com> <1154019801.999805.150000@m73g2000cwd.googlegroups.com> <1154544553.990241.280030@i3g2000cwc.googlegroups.com> <1154590917.731457.106230@s13g2000cwa.googlegroups.com> <1154613366.350191.81880@m73g2000cwd.googlegroups.com> <1154676387.063576.100570@i42g2000cwa.googlegroups.com> <1154690942.385855.41130@m79g2000cwm.googlegroups.com> Message-ID: <1154693232.056871.175170@m73g2000cwd.googlegroups.com> Carl Banks wrote: > > Exactly. Only one thread can hold a lock at a time. If a thread tries > to acquire a lock that some other thread has, it'll wait until the > other thread releases it. You need locks to do this stuff because most > things (such as zipfile objects) don't wait for other threads to > finish. > I would heartly like to thank you for the suggestion you made. My program now works exactly as I wanted. Thanks. :-) Ritesh From sjmachin at lexicon.net Thu Aug 3 00:48:22 2006 From: sjmachin at lexicon.net (John Machin) Date: 2 Aug 2006 21:48:22 -0700 Subject: Programming newbie coming from Ruby: a few Python questions In-Reply-To: <1154553340.449475.134050@m73g2000cwd.googlegroups.com> References: <1154494954.082706.283750@b28g2000cwb.googlegroups.com> <44d06f9f$0$19127$626a54ce@news.free.fr> <1154539223.873418.286830@i42g2000cwa.googlegroups.com> <1154539652.256975.155200@i3g2000cwc.googlegroups.com> <1154549436.073418.202840@s13g2000cwa.googlegroups.com> <1154553340.449475.134050@m73g2000cwd.googlegroups.com> Message-ID: <1154580502.072956.206550@i42g2000cwa.googlegroups.com> BartlebyScrivener wrote: > Stand and fight, Python brothers. Fear not, the Ruby horde! > > From this day to the ending of the world, > But we in it shall be remember'd; > We few, we happy few, we band of brothers; > For he to-day that sheds his blood with me > Shall be my brother; be he ne'er so vile, > This day shall gentle his condition: > And gentlemen in England now a-bed > Shall think themselves accursed they were not here, > And hold their manhoods cheap whiles any speaks > That fought with us upon Saint Crispin's day. > :-) Oh I say, old chap, steady on -- it's been a long while since Agincourt; aren't they supposed to be on your side now? (-: From gagsl-py at yahoo.com.ar Wed Aug 23 18:13:02 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 23 Aug 2006 19:13:02 -0300 Subject: in-memory-only file object from string In-Reply-To: <1156370182.719946.223220@i3g2000cwc.googlegroups.com> References: <1156370182.719946.223220@i3g2000cwc.googlegroups.com> Message-ID: <7.0.1.0.0.20060823191210.03c23678@yahoo.com.ar> At Wednesday 23/8/2006 18:56, bobrik wrote: >how to create a file object whose contents I initialize from a string >and which is purely in memory? See the standard modules: StringIO and cStringIO Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From rogue_pedro at yahoo.com Tue Aug 29 00:57:46 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 28 Aug 2006 21:57:46 -0700 Subject: eval() woes In-Reply-To: <1156817948.765024.13770@p79g2000cwp.googlegroups.com> References: <1156735954.796051.290600@i3g2000cwc.googlegroups.com> <1156740704.380857.76670@i42g2000cwa.googlegroups.com> <1156817948.765024.13770@p79g2000cwp.googlegroups.com> Message-ID: <1156827466.564371.174780@m73g2000cwd.googlegroups.com> rdrink wrote: > Hey Simon, Thanks for the reply. > > Simon Forman wrote: > > You must be doing something weird, that equation works for me: > > Try posting the minimal code example that causes the error and the > > full, exact traceback that you get. > > I appreciate the offer... but at this point my code is too recursive > and deeply nested to send a "simple" example That's not an offer, it's a request. There's not enough information in your original post to know what you're doing, let alone what you're doing wrong. If you explain for fully what's actually going on (i.e. tracebacks and code) then it's much more likely that I or someone else on this list will be able to help you figure out what's wrong. > > > (Also, assuming your equations are already strings, there's no reason > > to call str() on them again. > > This is an interesting point: I AM putting them into the file as > strings, and then pulling them back out as such and you are right, they > do not need to be re-cast as strings. I think as some point I was > getting errors there, but for now I can omit that.... > > > And you mention a "dictionary level" but > > don't mention using a dict.) > > Sorry, that was a spurious thought... No I'm not using a dict (although > I am still not sure if I should be)... > > > FWIW, the error "ValueError: invalid literal for int()" occurs when > > you, uh, pass an invalid literal to the int() function (actually int > > type.. but not important here), and includes the invalid input so you > > don't have to guess at it: > > > > |>> int('wombat') > > HTH > > Yes that is helpful. > I am still getting errors... which leads me to belive that it all has > to do with how I am casting, and re-casting, things as strings and > ints. > I need a little more time to try to suss this all out; after which, if > I still can't get it to work, I'll post some more code. > > Thanks again for your thoughts and comments. > > Robb From jgibson at mail.arc.nasa.gov Mon Aug 28 14:50:08 2006 From: jgibson at mail.arc.nasa.gov (Jim Gibson) Date: Mon, 28 Aug 2006 11:50:08 -0700 Subject: A Sort Optimization Technique: decorate-sort-dedecorate References: <1156719092.603277.57390@b28g2000cwb.googlegroups.com> <1156723602.192984.49610@m79g2000cwm.googlegroups.com> Message-ID: <280820061150081729%jgibson@mail.arc.nasa.gov> In article , Marc 'BlackJack' Rintsch wrote: > In <1156723602.192984.49610 at m79g2000cwm.googlegroups.com>, Tom Cole wrote: > > > In Java, classes can implement the Comparable interface. This interface > > contains only one method, a compareTo(Object o) method, and it is > > defined to return a value < 0 if the Object is considered less than the > > one being passed as an argument, it returns a value > 0 if considered > > greater than, and 0 if they are considered equal. > > > > The object implementing this interface can use any of the variables > > available to it (AKA address, zip code, longitude, latitude, first > > name, whatever) to return this -1, 0 or 1. This is slightly different > > than what you mention as we don't have to "decorate" the object. These > > are all variables that already exist in the Object, and if fact make it > > what it is. So, of course, there is no need to un-decorate at the end. > > Python has such a mechanism too, the special `__cmp__()` method > has basically the same signature. The problem the decorate, sort, > un-decorate pattern solves is that this object specific compare operations > only use *one* criteria. I can't believe I am getting drawn into a thread started by xahlee, but here goes anyway: The problem addressed by what is know in Perl as the 'Schwartzian Transform' is that the compare operation can be an expensive one, regardless of the whether the comparison uses multiple keys. Since in comparison sorts, the compare operation will be executed N(logN) times, it is more efficient to pre-compute a set of keys, one for each object to be sorted. That need be done only N times. The sort can then use these pre-computed keys to sort the objects. See, for example: http://en.wikipedia.org/wiki/Schwartzian_transform -- Jim Gibson Posted Via Usenet.com Premium Usenet Newsgroup Services ---------------------------------------------------------- ** SPEED ** RETENTION ** COMPLETION ** ANONYMITY ** ---------------------------------------------------------- http://www.usenet.com From slawomir.nowaczyk.847 at student.lu.se Fri Aug 4 06:36:25 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Fri, 04 Aug 2006 12:36:25 +0200 Subject: Nested function scope problem In-Reply-To: <5ucltr8vdu2n$.dlg@gelists.gmail.com> References: <20060803154632.A998.SLAWOMIR.NOWACZYK.847@student.lu.se> <5ucltr8vdu2n$.dlg@gelists.gmail.com> Message-ID: <20060804094245.A9AF.SLAWOMIR.NOWACZYK.847@student.lu.se> On Thu, 03 Aug 2006 17:27:26 -0300 Gerhard Fiedler wrote: #> But seriously, for my comment this seems off-topic. Well, you wrote "but it's not really understandable with a C++ concept of variable". It is perfectly understandable to me. That's all I said (or, at least, all I wanted to say). #> I did not say that you can't create Python behavior with C (of #> course you can, you can do /everything/ in C :). You can build #> constructs made up of C variables that simulate everything that any #> Python construct does. That's not the point. The point is how the #> simple, built-in language variable behaves. I agree. For me, Python variable behaves just like a C++ variable (a pointer, sure, but that's minor point to me... YMMV). #> > #> You also don't expect the "identity" of a and b to be the same #> > #> after assigning one to the other. #> > #> > Don't I? #> #> I don't know. Try replacing your printf statements with something #> like "printf("%x %i %i\n",&a,a,*a);" and watch the first column. #> The address operator is probably for a C programmer the closest to #> what the id() function is to a Python programmer. I disagree. At least in my understanding, which, up to now, was perfectly enough to explain everything about how Python variables behave: The address operator in C is what textual representation (i.e. what you type, like "a") is in Python. Equivalent of id() is a dereference operator. Of course, there are probably other ways to look at this. But I still do not see why people claim that there is a significant difference between what variables are in Python and in C++. -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) If at first you don't succeed, redefine success. From johnjsal at NOSPAMgmail.com Thu Aug 3 12:52:05 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 03 Aug 2006 16:52:05 GMT Subject: Finding the name of a class In-Reply-To: References: <44cf7538$0$29435$626a54ce@news.free.fr> Message-ID: Shane Hathaway wrote: > The bug is that the expression "dir(someclass)", where the class is a > user-defined class of either new or old style, never reveals to the user > that the class object has a __name__ attribute. I guess maybe it is a bug. This seems to be the relevant code to prove it: >>> class Foo(object): pass >>> dir(Foo) ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__'] >>> Foo.__name__ 'Foo' Tim can report it if he wants, since he found it first. Otherwise I'll do it and it will give me a chance to see how the bug reporting process works. From johnpote at blueyonder.co.uk Thu Aug 10 11:11:10 2006 From: johnpote at blueyonder.co.uk (John Pote) Date: Thu, 10 Aug 2006 15:11:10 GMT Subject: knowing when file is flushed to disk References: Message-ID: Thanks for the replies. I guessed the situation would be flush() and trust. The probability of a crash between flush() returning and data actually written resulting in a trashed disk must be very small. But if you can be certain without too much effort it's got to be a good idea, so I thought I'd ask anyway. How does the banking industry handle this sort of thing? Could be big bucks if something goes wrong for them! Thanks again, John From st at tobiah.org Wed Aug 30 16:55:18 2006 From: st at tobiah.org (tobiah) Date: Wed, 30 Aug 2006 13:55:18 -0700 Subject: csv module strangeness. In-Reply-To: References: <44f5e870$0$8814$88260bb3@free.teranews.com> Message-ID: <44f5ee16$0$8831$88260bb3@free.teranews.com> > > That's possible but why didn't you follow the way `csv.Dialect` set the > class attributes? > > class MyDialect(csv.Dialect): > delimiter = '\t' > lineterminator = '\n' > # and so on? Because I'm hung over. -- Posted via a free Usenet account from http://www.teranews.com From rogue_pedro at yahoo.com Wed Aug 23 17:36:09 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 23 Aug 2006 14:36:09 -0700 Subject: range of int() type. In-Reply-To: <1156368379.206968.288740@p79g2000cwp.googlegroups.com> References: <1156368379.206968.288740@p79g2000cwp.googlegroups.com> Message-ID: <1156368969.085690.92400@i42g2000cwa.googlegroups.com> KraftDiner wrote: > What is the range of a variable of type int() > > eg: > i = int() > print i.max() # 0xFFFFFFFF > print i.min() # 0x00000000 > > is it a signed 16 bit or 32 bit or is it unsigned 16 or 32... > I've noticed that it can be incremented into a new class of type > long... |>> import sys |>> sys.maxint 2147483647 >From the sys module docs: maxint The largest positive integer supported by Python's regular integer type. This is at least 2**31-1. The largest negative integer is -maxint-1 -- the asymmetry results from the use of 2's complement binary arithmetic. Peace, ~Simon P.S. ints and longs are becoming unified soon. From paul at boddie.org.uk Fri Aug 11 09:30:40 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 11 Aug 2006 06:30:40 -0700 Subject: hide python code ! References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155300852.497741.73230@74g2000cwt.googlegroups.com> <1155301468.870340.82920@b28g2000cwb.googlegroups.com> <1155302025.090055.237230@i3g2000cwc.googlegroups.com> Message-ID: <1155303040.809888.71040@m79g2000cwm.googlegroups.com> Fuzzyman wrote: > Paul Boddie wrote: > > Fuzzyman wrote: > > > > > I never understand the knee-jerk reaction on this mailing list to > > > answer people who ask this question by telling them they don't really > > > want to do it... Note your choice of words: "don't really want to do it". [...] > If you distribute applications with py2exe then your application is no > longer dependent on the installed version of Python. But there are numerous other things that might stop whatever binary it is from working over longer periods of time. Besides, py2exe executables don't exactly exhibit various typical benefits of normal Python programs such as being able to run on more than one platform, unless you recommend that everyone runs those applications in some kind of Windows virtualisation solution. > The question keeps getting asked because a lot of new programmers are > looking to create programs that they will sell. A lot of these will be > good programmers, and some of the software will be successful. Telling > them 'you can't do that with Python', does no good to Python itself. But many people admit that solutions do exist, notably py2exe and other tools which do very similar things but for more than one platform (and have done so for at least a decade). Now you did say that people are being made to feel that they "don't really want to do it", but that's a very different thing from being told that they "can't do that with Python". Personally, I'd rather people chose not to do such things with Python, for various reasons including the inability of the end-user to study or fix bugs in the code or to take advantage of various well-known benefits of the Python language, library and runtime. But I do admit that they at least can achieve some level of obfuscation or "protection" for such endeavours (and a suitably-phrased Web search will provide established solutions for doing just that). Paul From onurb at xiludom.gro Thu Aug 3 13:35:25 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Thu, 03 Aug 2006 19:35:25 +0200 Subject: What is the best way to print the usage string ? In-Reply-To: References: Message-ID: <44d233de$0$21601$636a55ce@news.free.fr> Leonel Gayard wrote: > Hi all, > > I had to write a small script, and I did it in python instead of > shell-script. My script takes some arguments from the command line, > like this. > > import sys > args = sys.argv[1:] > if args == []: > print """Concat: concatenates the arguments with a colon (:) between > them > Usage: concat arg1 [arg2...] > Example: concat a b c prints \"a.jar:b.jar:c/\"""" > sys.exit(1) > print reduce(lambda x, y: x + ':' + y, sys.argv[1:]) > > Notice that the string messes the indentation in my script. The > indentation is correct, and if the script is invoked without > arguments, the usage string is printed correctly. > > Now, how can I achieve the same result while keeping a clean > indentation ? How is this done in python world ? In C, I would do > this: > > ;; This buffer is for notes you don't want to save, and for Lisp > evaluation. > ;; If you want to create a file, visit that file with C-x C-f, > ;; then enter the text in that file's own buffer. > > if (argc < N) { > printf("Usage: blah blah blah\n" > "Some more lines in the usage text\n" > "Some more lines here too\n"); > exit(1); > } > > The whitespace at the beginning of the string helps me keep the > indentation clean, and the construct "a" "b" is syntactic sugar that > allows me to create a large string without concatenating them at > runtime. > > How can I get this in Python ? Quite close: >>> args = [] >>> if not args: ... print "line 1\n" \ ... "line 2\n" \ ... "line 3\n" \ ... ... line 1 line 2 line 3 But this is somehow ugly... the textwrapper module may be a better solution. Or if you don't plan on making the script a module, you could use the docstring: bruno at bousin ~ $ cat ~/playground/concat.py # !/usr/bin/python """ Concat: concatenates the arguments with a colon (:) between them Usage: concat arg1 [arg2...] Example: concat a b c prints \"a:b:c/\ """ import sys args = sys.argv[1:] if not args: sys.exit(globals()['__doc__'].strip()) print reduce(lambda x, y: x + ':' + y, args) bruno at bousin ~ $ python ~/playground/concat.py Concat: concatenates the arguments with a colon (:) between them Usage: concat arg1 [arg2...] Example: concat a b c prints "a:b:c/ bruno at bousin ~ $ python ~/playground/concat.py a b c a:b:c bruno at bousin ~ $ -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From claudio.grondi at freenet.de Mon Aug 28 03:14:15 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Mon, 28 Aug 2006 09:14:15 +0200 Subject: time.clock() going backwards?? In-Reply-To: References: Message-ID: Tim Roberts wrote: > "Tim Peters" wrote: > > >>[Giovanni Bajo[ >> >>>>I experimented something very strange, a few days ago. I was debugging an >>>>application at a customer's site, and the problem turned out to be that >>>>time.clock() was going "backwards", that is it was sometimes >>>>(randomically) returning a floating point value which was "less than" the >>>>value returned by the previous invokation. The computer was a pretty fast >>>>one (P4 3Ghz I think, running Windows XP), and this happened only between >>>>very close invokations of time.clock(). >> >>[Terry Reed] >> >>>I seem to remember this being mentioned before on the list, perhaps by Tim >>>Peters. Perhaps he will chime in. >> >>No real need ;-) BIOS or HAL bug on a multiprocessor (or maybe even >>hyperthreaded) box is by far the most likely cause (and the only cause >>ever identified for sure by people who followed up). Python's C code >>slinging QueryPerformanceCounter is exceedingly simple, and isn't a >>suspect because of that. It's on the edge of vague possibility that >>Microsoft's compiler generates non-monotonic code for converting >>64-bit integer to double: > > > It is much simpler than that. With a multiprocessor HAL, including on a > dual-core or hyperthreaded system, QueryPerformanceCounter returns the raw > cycle counter (RDTSC). However, on Windows XP, the operating system does > not synchronize the cycle counters on multiple processors, and they can be > actually be millions of cycles apart. > > This was a change from previous systems. On NT4 and Win2000, the operating > actually rewrote the cycle counters on the second (and beyond) processors > to align them to the first processor, so the delta was usually only a dozen > or two cycles. XP does not appear to do that. I think that is a huge > mistake, since it renders QueryPerformanceCounter non-monotonic. How does it come, that processors on same mainboard run at different speeds? Do they have separate clock-pulse generators? I can remember, that (at least on very old motherboards) the clock-pulse generator was a separate element and the processor just used it, so I would expect, that even in case of multiple processors, if there were only one clock-pulse generator for all of them, they were not be able to run at different speeds. Claudio Grondi From nephish at gmail.com Sat Aug 26 05:13:22 2006 From: nephish at gmail.com (nephish) Date: 26 Aug 2006 02:13:22 -0700 Subject: question about class, functions and scope Message-ID: <1156583602.302530.206630@74g2000cwt.googlegroups.com> lo there all, i have an app that runs three classes as threads in the same program. some of them need to be able to share some functions. Can i set a function before i define a class and have the class use it ? Kinda like this. def some_function(var1, var2): do something with var1, var2 return result class do_something1(threading.Thread): def __init__(var): do something def run(): var1 = 3 var2 = 4 result = some_function(var1,var2) is this legal ? is it pythonic? i ask because i plan to do a big re-write soon, and want to get rid of some repetition thanks From andre at svn2.wasy.de Tue Aug 22 03:17:20 2006 From: andre at svn2.wasy.de (Andre Poenitz) Date: Tue, 22 Aug 2006 09:17:20 +0200 Subject: Loading module via full path References: Message-ID: <0lnqr3-9u7.ln1@svn2.wasy.de> Gary Herron wrote: > Andre Poenitz wrote: >> Hi all. >> >> Is there a way to load a module given a full path to the module >> without extending sys.path first? > > The standard module named "imp" can help you with this. Thank you. I got stuck on http://docs.python.org/api/importing.html (as I need it to be called from C(++)) and found no way to specify a path there [and there aren't too many cross references in the python docs *sigh*] I have now something similar to class CPyObject { public: explicit CPyObject(PyObject * pObject) : m_pObject(pObject) { /*Check();*/ } ~CPyObject() { Py_XDECREF(m_pObject); } operator PyObject *() { return m_pObject; } private: CPyObject(const CPyObject &); // intentionally not implemented void operator=(const CPyObject &); // intentionally not implemented PyObject * m_pObject; }; static PyObject * LoadModule(const char * mod, const char * path) { CPyObject pyImpModule ( PyImport_Import(PyString_FromString("imp")) ); CPyObject pyImpFindModuleFunc ( PyObject_GetAttrString(pyImpModule, "find_module") ); CPyObject pyImpFindModuleArgs ( Py_BuildValue("s[s]", mod, path) ); CPyObject pyImpFindModuleRes ( PyObject_CallObject(pyImpFindModuleFunc, pyImpFindModuleArgs) ); CPyObject pyImpLoadModuleFunc ( PyObject_GetAttrString(pyImpModule, "load_module") ); CPyObject pyImpLoadModuleArgs ( Py_BuildValue("sOOO", mod, PyTuple_GetItem(pyImpFindModuleRes, 0), PyTuple_GetItem(pyImpFindModuleRes, 1), PyTuple_GetItem(pyImpFindModuleRes, 2) )); return PyObject_CallObject(pyImpLoadModuleFunc, pyImpLoadModuleArgs); } which seems to do what I want even if it looks a bit too verbose for my taste and I don't know whether I go the reference counting right. Thanks for the hint, Andre' From justin.azoff at gmail.com Tue Aug 8 22:12:28 2006 From: justin.azoff at gmail.com (Justin Azoff) Date: 8 Aug 2006 19:12:28 -0700 Subject: newb question: file searching References: <1155067111.892386.130610@n13g2000cwa.googlegroups.com> <1155084224.829101.63940@i42g2000cwa.googlegroups.com> <1155087242.679420.128830@m73g2000cwd.googlegroups.com> <1155087903.857917.127540@m79g2000cwm.googlegroups.com> Message-ID: <1155089548.659249.216390@b28g2000cwb.googlegroups.com> jaysherby at gmail.com wrote: > I do appreciate the advice, but I've got a 12 line function that does > all of that. And it works! I just wish I understood a particular line > of it. You miss the point. The functions I posted, up until get_files_by_ext which is the equivalent of your getFileList, total 17 actual lines. The 5 extra lines give 3 extra features. Maybe in a while when you need to do a similar file search you will realize why my way is better. [snip] > The line I don't understand is: > reversed(range(len(dirnames))) This is why I wrote and documented a separate remove_hidden function, it can be tricky. If you broke it up into multiple lines, and added print statements it would be clear what it does. l = len(dirnames) # l is the number of elements in dirnames, e.g. 6 r = range(l) # r contains the numbers 0,1,2,3,4,5 rv = reversed(r) # rv contains the numbers 5,4,3,2,1,0 The problem arises from how to remove elements in a list as you are going through it. If you delete element 0, element 1 then becomes element 0, and funny things happen. That particular solution is relatively simple, it just deletes elements from the end instead. That complicated expression arises because python doesn't have "normal" for loops. The version of remove_hidden I wrote is simpler, but relies on the even more obscure lst[:] construct for re-assigning a list. Both of them accomplish the same thing though, so if you wanted, you should be able to replace those 3 lines with just dirnames[:] = [d for d in dirnames if not d.startswith('.')] -- - Justin From rogue_pedro at yahoo.com Wed Aug 2 14:49:14 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 2 Aug 2006 11:49:14 -0700 Subject: Thread Question References: <1153998422.670828.148360@m79g2000cwm.googlegroups.com> <1154019801.999805.150000@m73g2000cwd.googlegroups.com> Message-ID: <1154544553.990241.280030@i3g2000cwc.googlegroups.com> Ritesh Raj Sarraf wrote: > Hi, > > I have this following situation: > > #INFO: Thread Support > # Will require more design thoughts > from Queue import Queue > from threading import Thread, currentThread > > NUMTHREADS = variables.options.num_of_threads > > def run(request, response, func=download_from_web): > '''Get items from the request Queue, process them > with func(), put the results along with the > Thread's name into the response Queue. > > Stop running once an item is None.''' > > name = currentThread().getName() > while 1: > item = request.get() > (sUrl, sFile, download_size, checksum) = stripper(item) > if item is None: > break > response.put((name, func(sUrl, sFile, sSourceDir, None))) > One thing about this code: you should check whether item is None *before* passing it to stripper(). Even if stripper() can handle None as input there's no reason to make it do so. > My download_from_web() returns True or False depending upon whether the download > was successful or failed. How can I check that in the above code ? Well, you'd probably want to check that *outside* the above run() function. The True/False return values will queue up in the responseQueue, where you can access them with responseQueue.get(). Since these can be in a different order than your requests you're going to want to "tag" them with the sUrl and sFile. response.put((name, sUrl, sFile, func(sUrl, sFile, sSourceDir, None))) That way your response handing code can tell which downloads succeeded and which failed. Of course, you could have the run() function check the return value itself and retry the download ane or a few times. > > One other question I had, > If my user passes the --zip option, download_from_web() internally (when the > download is successful) zips the downloaded data to a zip file. Since in case > of threading there'll be multiple threads, and say if one of the thread > completes 2 seconds before others and is doing the zipping work: > What will the other thread, at that moment do, if it completes while the > previous thread is doing the zipping work ? The other threads will just take the next request from the Queue and process it. They won't "care" what the one thread is doing, downloading, zipping, whatever. Peace, ~Simon From mh at pixar.com Tue Aug 15 19:10:32 2006 From: mh at pixar.com (Mark Harrison) Date: Tue, 15 Aug 2006 23:10:32 GMT Subject: state of SOAP and python? References: Message-ID: Gabriel Genellina wrote: > At Thursday 10/8/2006 03:38, Mark Harrison wrote: > > >So I'm investigating doing some SOAP work... Any concensus on > >what the best python libraries are for doing this? > > > >Too bad, xmlrpc is choking on our long longs. :-( > > Just thinking, if you have control over the two ends, and dont need > real interoperability, maybe just extending to support long > integers could be easier... > I remember extending once to support NaN's, moving to SOAP > was too much effort for that application. Good thinking! It turns out all you have to do is comment out the range check: def dump_int(self, value, write): # in case ints are > 32 bits ##if value > MAXINT or value < MININT: ## raise OverflowError, "int exceeds XML-RPC limits" write("") write(str(value)) write("\n") Thanks, Mark -- Mark Harrison Pixar Animation Studios From pattreeya at gmail.com Tue Aug 1 04:36:14 2006 From: pattreeya at gmail.com (pattreeya at gmail.com) Date: 1 Aug 2006 01:36:14 -0700 Subject: how to get size of unicode string/string in bytes ? In-Reply-To: <1154420030.988013.89310@m79g2000cwm.googlegroups.com> References: <1154420030.988013.89310@m79g2000cwm.googlegroups.com> Message-ID: <1154421374.219871.128250@i3g2000cwc.googlegroups.com> e.g. I use utf8 as encoding/decoding, s = "?????" u = s.decode("utf-8") how can I get size of u ? pattreeya at gmail.com schrieb: > Hello, > > how can I get the number of byte of the string in python? > with "len(string)", it doesn't work to get the size of the string in > bytes if I have the unicode string but just the length. (it only works > fine for ascii/latin1) In data structure, I have to store unicode > string for many languages and must know exactly how big of my string > which is stored so I can read back later. > > Many thanks for any suggestion. > > cheers! > pattreeya. From sjmachin at lexicon.net Sat Aug 19 03:17:55 2006 From: sjmachin at lexicon.net (John Machin) Date: 19 Aug 2006 00:17:55 -0700 Subject: couple more questions about sqlite In-Reply-To: <0n5de290agb0k6fvccjhrmel6jehaskcuv@4ax.com> References: <1155930772.591854.53910@m79g2000cwm.googlegroups.com> <1rpFg.2705$No6.52662@news.tufts.edu> <0n5de290agb0k6fvccjhrmel6jehaskcuv@4ax.com> Message-ID: <1155971875.888469.24830@p79g2000cwp.googlegroups.com> Dennis Lee Bieber wrote: > > The only reason, then, to download the stand-alone SQLite package > (not the python package) would be to obtain the command line query/admin > tool. Pre-compiles binaries of the tool are available for Linux and Windows. http://www.sqlite.org/download.html Cheers, John From embe-ml at magma-net.pl Wed Aug 9 02:33:19 2006 From: embe-ml at magma-net.pl (=?iso-8859-2?Q?Micha=B3?= Bartoszkiewicz) Date: Wed, 9 Aug 2006 08:33:19 +0200 Subject: #!/usr/bin/python or #!/usr/bin/env python? In-Reply-To: References: Message-ID: <20060809063319.GA2283@ghostwheel> On 2006-08-09 at 08:02:03 (+0200), Stephan Kuhagen wrote: > Don't yell at me for bringing in another language, but I really like the > trick, Tcl does: > > > #!/bin/sh > > # The next line starts Tcl \ > > exec tclsh "$0" "$@" > > This works by the somewhat weird feature of Tcl, that allows comments to be > continued in the next line with "\" at the end of the comment-line. It > looks unfamiliar, but has several advantages, I think. First it's really > VERY unlikely, that there is no /bin/sh (while I found systems with > different places for env), and you can add some other features at or before > the actual call of the interpreter, i.e. finding the right or preferred > version... - This way I coded a complete software-installer, that runs > either as a Tcl/Tk-Script with GUI, or as bash-script, when no Tcl is > available. - I really would like to have something like that for python, > but I did not find a way to achieve that, yet. You could use: #!/bin/sh """exec" python "$0" "$@""" :) -- __ ____________________________________________________________________ | \/ | Micha? Bartoszkiewicz | _ ) | |\/| | GG:2298240 | _ \ |_| |_|_For all resources, whatever it is, you need more. [RFC1925]_|___/ From johnjsal at NOSPAMgmail.com Tue Aug 1 12:03:04 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 01 Aug 2006 16:03:04 GMT Subject: Finding the name of a class In-Reply-To: References: <44cf7538$0$29435$626a54ce@news.free.fr> Message-ID: John Salerno wrote: > Tim Chase wrote: > >> While this is surely true, would somebody explain why I had such >> trouble finding this? > > I think __name__ is an attribute of the class itself, not the instance: On the other hand: >>> class Foo(object): pass >>> dir(Foo) ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__'] Hmmm..... From pmartin at snakecard.com Fri Aug 11 12:54:49 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Fri, 11 Aug 2006 11:54:49 -0500 Subject: Tkinter module not found References: <1155049496.292471.37020@h48g2000cwc.googlegroups.com> Message-ID: Shuaib wrote: > Hey, > > Even though I freshly installed Tcl and Tk, python still seem to have > problems accessing Tkinter module. Here is what says when I do "import > Tkinter" > > == > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named Tkinter > == > > Any ideas how to fix this problem? (Gentoo distribution) > > Thanks. That happened once to me when I compiled python without tcl/tk installed (prior to compiling) From maxkhesin at gmail.com Thu Aug 31 16:11:37 2006 From: maxkhesin at gmail.com (xamdam) Date: 31 Aug 2006 13:11:37 -0700 Subject: Assignment-in-conditional In-Reply-To: References: <1157049685.909882.76210@p79g2000cwp.googlegroups.com> Message-ID: <1157055097.250796.71530@i3g2000cwc.googlegroups.com> Thanks for the FAQ, and for the 'casm ;) What do you think about using alternative syntax (something like 'as') - max Fredrik Lundh wrote: > xamdam wrote: > > > I am not sure if this came up before, but I would love to have an > > 'assignment-in-conditional' form in python, e.g > > it's a FAQ, so it has probably come up before: > > http://pyfaq.infogami.com/why-can-t-i-use-an-assignment-in-an-expression > > From davidfinance at gmail.com Thu Aug 24 14:42:39 2006 From: davidfinance at gmail.com (davidfinance at gmail.com) Date: 24 Aug 2006 11:42:39 -0700 Subject: Why can't I subclass off of "date" ? Message-ID: <1156444959.471657.201690@i3g2000cwc.googlegroups.com> Ok, maybe this is a stupid question, but why can't I make a subclass of datetime.date and override the __init__ method? --- from datetime import date class A(date): def __init__(self, a, b, c, d): print a, b, c, d date.__init__(self, 2006, 12, 11) d = A(1, 2, 3, 4) --- $ python break_date.py Traceback (most recent call last): File "break_date.py", line 9, in ? d = A(1, 2, 3, 4) TypeError: function takes exactly 3 arguments (4 given) If I make A a subclass of some toy class that is constructed with three arguments, it works fine. Why can't I make "date" the subclass? Thanks for any advice. David From rgelfand2 at hotmail.com Thu Aug 24 23:59:26 2006 From: rgelfand2 at hotmail.com (Roman) Date: 24 Aug 2006 20:59:26 -0700 Subject: RE Module Message-ID: <1156478366.165463.277480@h48g2000cwc.googlegroups.com> I am trying to filter a column in a list of all html tags. To do that, I have setup the following statement. row[0] = re.sub(r'<.*?>', '', row[0]) The results I get are sporatic. Sometimes two tags are removed. Sometimes 1 tag is removed. Sometimes no tags are removed. Could somebody tell me where have I gone wrong here? Thanks in advance From tim.peters at gmail.com Fri Aug 25 02:04:23 2006 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 25 Aug 2006 02:04:23 -0400 Subject: pickling and endianess In-Reply-To: References: Message-ID: <1f7befae0608242304p3ad8cffdh123f3577daa78dca@mail.gmail.com> [Chandrashekhar kaushik] > Can an object pickled and saved on a little-endian machine be unpickled > on a big-endian machine ? Yes. The pickle format is platform-independent (native endianness doesn't matter, and neither do the native sizes of C's various integer types). > Does python handle this in some manner , by say having a flag to indicate > the endianess of the machine on which the object was pickled ? And then > using this flag to decide how that data will be unpickled ? Not a flag, no, the pickle format is the same on all platforms. If you need to know details, read pickle.py. From grante at visi.com Tue Aug 15 15:42:45 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 15 Aug 2006 19:42:45 -0000 Subject: X windows and Python? References: <7xy7tpyhbf.fsf_-_@ruckus.brouhaha.com> Message-ID: <12e48tl6q5vs8fc@corp.supernews.com> On 2006-08-15, Paul Rubin wrote: > I'd like to program my Python script to put a string into the > X windows cut buffer. Can anyone suggest the simplest way to > do that? There isn't a simple way to do that. The basic problem is that there's not really such a thing as "_the_ X windows cut buffer". The selection mechanism under X is rather complicated. The way (well, _one_ way) it's supposed to work is you make an Xlib call to claim ownership of "the selection". Then when somebody wants to get the contents of the selection you get an event to which you respond by sending the current contents of the selection. However, if your app exits before somebody requests the contents of the selection, then you have to use one of the fallback mechanisms. In addition to the "selection", there are a set of cut buffer buffers that you can put things into. The first of those cut buffers is where apps _usually_ look if there is no current selection owner. In order to work properly, you have cover both bases: 1) You need to request ownership of the selection and then respond to a selection notify event if you get one. 2) You need to write the selection contents into cut buffer 0. I think it might be sufficient to do the following: 0) Open a connection to the server and create a window. 1) Write the selected string into cut buffer 0. 2) Call XSetSelectionOwner to make yourself the owner of the selction. 3) Call XSetSelectionOnwer to give up ownership of the selection (or just close the connection to the server). At that point, the selection won't have an owner, and most applications will look in cut buffer 0. But if somebody tries to get the selection contents between steps 2 and 3, then things break unless you handle the request. -- Grant Edwards grante Yow! Is this "BOOZE"? at visi.com From paddy3118 at netscape.net Thu Aug 10 18:06:47 2006 From: paddy3118 at netscape.net (Paddy) Date: 10 Aug 2006 15:06:47 -0700 Subject: What's the cleanest way to compare 2 dictionary? In-Reply-To: <1155165349.766502.314760@n13g2000cwa.googlegroups.com> References: <1155147450.628625.20270@m79g2000cwm.googlegroups.com> <1155165349.766502.314760@n13g2000cwa.googlegroups.com> Message-ID: <1155247607.223854.213910@h48g2000cwc.googlegroups.com> John Machin wrote: > John Henry wrote: > > Hi list, > > > > I am sure there are many ways of doing comparision but I like to see > > what you would do if you have 2 dictionary sets (containing lots of > > data - like 20000 keys and each key contains a dozen or so of records) > > and you want to build a list of differences about these two sets. > > > > I like to end up with 3 lists: what's in A and not in B, what's in B > > and not in A, and of course, what's in both A and B. > > > > What do you think is the cleanest way to do it? (I am sure you will > > come up with ways that astonishes me :=) ) > > > > Paddy has already pointed out a necessary addition to your requirement > definition: common keys with different values. > > Here's another possible addition: you say that "each key contains a > dozen or so of records". I presume that you mean like this: > > a = {1: ['rec1a', 'rec1b'], 42: ['rec42a', 'rec42b']} # "dozen" -> 2 to > save typing :-) > > Now that happens if the other dictionary contains: > > b = {1: ['rec1a', 'rec1b'], 42: ['rec42b', 'rec42a']} > > Key 42 would be marked as different by Paddy's classification, but the > values are the same, just not in the same order. How do you want to > treat that? avalue == bvalue? sorted(avalue) == sorted(bvalue)? Oh, and > are you sure the buckets don't contain duplicates? Maybe you need > set(avalue) == set(bvalue). What about 'rec1a' vs 'Rec1a' vs 'REC1A'? > > All comparisons are equal, but some comparisons are more equal than > others :-) > > Cheers, > John Hi Johns, The following is my attempt to give more/deeper comparison info. Assume you have your data parsed and presented as two dicts a and b each having as values a dict representing a record. Further assume you have a function that can compute if two record level dicts are the same and another function that can compute if two values in a record level dict are the same. With a slight modification of my earlier prog we get: def komparator(a,b, check_equal): keya=set(a.keys()) keyb=set(b.keys()) a_xclusive = keya - keyb b_xclusive = keyb - keya _common = keya & keyb common_eq = set(k for k in _common if check_equal(a[k],b[k])) common_neq = _common - common_eq return (a_xclusive, b_xclusive, common_eq, common_neq) a_xclusive, b_xclusive, common_eq, common_neq = komparator(a,b, record_dict__equality_checker) common_neq = [ (key, komparator(a[key],b[key], value__equality_checker) ) for key in common_neq ] Now we get extra info on intra record differences with little extra code. Look out though, you could get swamped with data :-) - Paddy. From bearophileHUGS at lycos.com Sat Aug 5 08:23:20 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 5 Aug 2006 05:23:20 -0700 Subject: More int and float attributes Message-ID: <1154780600.348169.158150@i42g2000cwa.googlegroups.com> sys.maxint gives the largest positive integer supported by Python's regular integer type. But maybe such attribute, with few others (they can be called min and max) can be given to int type itself. D is a very nice language, that I hope to see more used. It is copying lot of things from Python. D Floating point values have some proprieties: http://www.digitalmars.com/d/property.html Properties for Floating Point Types: .init initializer (NaN) .infinity infinity value .nan NaN value .dig number of decimal digits of precision .epsilon smallest increment .mant_dig number of bits in mantissa .max_10_exp maximum exponent as power of 10 .max_exp maximum exponent as power of 2 .min_10_exp minimum exponent as power of 10 .min_exp minimum exponent as power of 2 .max largest representable value that's not infinity .min smallest representable value that's not 0 .re real part .im imaginary part I think such attributes may be useful to be added to Python float type/values too. Bye, bearophile From wdraxinger at darkstargames.de Tue Aug 22 19:57:06 2006 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Wed, 23 Aug 2006 01:57:06 +0200 Subject: What are decorated functions? References: <1156289230.801158.305000@b28g2000cwb.googlegroups.com> Message-ID: Daniel O'Brien wrote: > How one actually makes use of decorators beyond the above is an > exercise of imagination. Now it rings a bell, thx. Wolfgang Draxinger -- E-Mail address works, Jabber: hexarith at jabber.org, ICQ: 134682867 GPG key FP: 2FC8 319E C7D7 1ADC 0408 65C6 05F5 A645 1FD3 BD3E From martin.witte at gmail.com Tue Aug 15 17:53:37 2006 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 15 Aug 2006 14:53:37 -0700 Subject: idea on how to get/set nested python dictionary values In-Reply-To: <1155663671.716249.18780@m79g2000cwm.googlegroups.com> References: <1155663671.716249.18780@m79g2000cwm.googlegroups.com> Message-ID: <1155678816.942660.296140@74g2000cwt.googlegroups.com> jojoba wrote: > hello! > > i am trying to come up with a simple way to access my values in my > nested python dictionaries > > here is what i have so far, but i wanted to run it by the geniuses out > there who might see any probems with this... > here is an example: > > +++++++++++++++++++++++++++++++++++++++ > def SetNewDataParam(Data, paramPath, NewData): > ParamList = paramPath.split('/') > numParams = len(ParamList) > for i in range(0, numParams): > if i != (numParams-1): > Data = Data[ParamList[i]] > else: > Data[ParamList[i]] = NewData > when I add here ret Data > > Data = {'a':{'b':{'c':1}}} > paramPath = 'a/b/c' > NewData = 666 > SetNewDataParam(Data, paramPath, NewData) and change this to ret = SetNewDataParam(Data, paramPath, NewData) print ret the shell returns me {'c': 666} > +++++++++++++++++++++++++++++++++++++++ > > > so it works! > when i do: > print Data, i get > {'a':{'b':{'c':666}}} > > > but i am hesistant to be throwing around dictionary references > how is this working???? > shouldn't my line above: > Data = Data[ParamList[i]] > screw up my original Data dictionary > > Thanks to anyone with comments on this > By the way, i love the idea of using tuples as keys, but my code is so > far along that i dont wanna switch to that elegant way (maybe on a > future project!) > take care, > jojoba | would use a recursive approach for this - given that you have a sort of recursive datastructure: py> def SetNewDataParam2(Data, NewData): ... if type(Data[Data.keys()[0]]) == type(dict()): ... SetNewDataParam2(Data[Data.keys()[0]], NewData) ... else: ... Data[Data.keys()[0]] = NewData ... ... return Data py> Data = {'a':{'b':{'c':1}}} py> NewData = 666 py> ret = SetNewDataParam2(Data, NewData) py> print ret {'a': {'b': {'c': 666}}} From david_wahler at bic.ky Wed Aug 16 01:52:11 2006 From: david_wahler at bic.ky (david_wahler at bic.ky) Date: 16 Aug 2006 00:52:11 -0500 Subject: =?utf-8?Q?Re:_Dr._Dobb's_Python=2DURL=21_=2D_weekly_Python_news_and_links_=28Aug_15=29?= Message-ID: <20060816055211.23306.qmail@BICSRV1011.bic.ky> I'll be out of the office until approximately August 20th. If you have any questions, please email support at bic.ky. -- David Wahler From mail at microcorp.co.za Thu Aug 10 02:36:17 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Thu, 10 Aug 2006 08:36:17 +0200 Subject: do people really complain about significant whitespace? References: <1154986984.740638.241130@m79g2000cwm.googlegroups.com><1155038374.803591.315480@m73g2000cwd.googlegroups.com> Message-ID: <023201c6bc55$2074b7c0$03000080@hendrik> "Dennis Lee Bieber" wrote: | On 8 Aug 2006 04:59:34 -0700, gslindstrom at gmail.com declaimed the | following in comp.lang.python: | | > | > Some of it may be a reaction from "old-timers" who remember FORTRAN, | > where (if memory serves), code had to start in column 16 and code | > continutations had to be an asterik in column 72 (it's been many years | > since I've done any work in FORTRAN, but you get the idea) | > | Comment C in column 1 | (often extended to accept OS JCL markers too) | Label numeric in 1-5 | Continuation anything in column 6 | (DEC, if using tab indents would take "&") | Statement column 7-72 | Sequence/ID column 73-80 | | I forget what COBOL used, but it had a few fields of its own. The COBOL I used (NCR Century, Burroughs, some little IBM) was not fussy - the only thing was that like in assembler, you had to start a lable (that is a symbolic name for an address) in the first column... And you *had* to end what Python calls a "suite" with a fullstop - many hours spent looking for weird bugs.. The breaking of the link between a lable or name and a memory address of something is what I think most newcomers to Python find horribly confusing... - Hendrik From deets at nospam.web.de Thu Aug 3 13:38:56 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 03 Aug 2006 19:38:56 +0200 Subject: distutils is not found In-Reply-To: <1154626437.432250.74210@i3g2000cwc.googlegroups.com> References: <1154626437.432250.74210@i3g2000cwc.googlegroups.com> Message-ID: <4jeqlgF7n1s4U1@uni-berlin.de> Saketh schrieb: > Under openSUSE 10.0, I installed Python 2.4.1. I executed a setup.py > which imports distutils, but I received an error which gave an > "ImportError: module not found" for distutils. I thought that distutils > is part of the standard library under Python, but is there something > that I am missing? Can I (or should I) install distutils manually? Some linux distros consider it a good idea to have a separated devel-package for python. Look for it in yast, something like python-devel. Install it and be happy. Diez From gelists at gmail.com Sun Aug 20 19:15:21 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Sun, 20 Aug 2006 20:15:21 -0300 Subject: How to get the ascii code of Chinese characters? References: <1155986298.643983.157460@i3g2000cwc.googlegroups.com> <1155990488.395220.178810@74g2000cwt.googlegroups.com> <1155999554.486951.303480@i42g2000cwa.googlegroups.com> <1qmwgpkqdo3wg.dlg@gelists.gmail.com> Message-ID: <13qhtz4qqi5b5.dlg@gelists.gmail.com> On 2006-08-20 10:31:20, Fredrik Lundh wrote: >> "range is least 0..65535" : upper_bound >= 65535 >> "goes beyond 65535" : upper_bound > 65535 >> >> For some discussions (like how to represent code points etc) this >> distinction is crucial. > > do you know anything about how Unicode is used in real life, or are you > just squabbling ? Your point is? Gerhard From fredrik at pythonware.com Mon Aug 14 11:25:30 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 14 Aug 2006 17:25:30 +0200 Subject: why the method get() of python Queue is hang on there? In-Reply-To: <1155568212.888733.79920@b28g2000cwb.googlegroups.com> References: <1155568212.888733.79920@b28g2000cwb.googlegroups.com> Message-ID: zxo102 wrote: > Hi, > I am using Queue from python2.4. Here is what happen to me: > > import Queue > b = Queue.Queue(0) > b.put(9999) > b.get() # this is ok, it pops out 9999 > b.get() # this one does not return anything and is hang on there > > Anybody knows what is going on with the second b.get()? the documentation has the answer: get( [block[, timeout]]) Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available. /.../ http://docs.python.org/lib/QueueObjects.html From kernel1983 at gmail.com Mon Aug 14 03:48:54 2006 From: kernel1983 at gmail.com (kernel1983) Date: 14 Aug 2006 00:48:54 -0700 Subject: Looking for a text file based wiki system written in Python In-Reply-To: References: Message-ID: <1155541734.571386.8440@74g2000cwt.googlegroups.com> The base of moinmoin is called piki.It provides the simplest functions as a wiki system And there are lots of other wiki system based on piki. If I try to developed one,I'll make the text data compatible with compatible. Jack wrote: > Thanks! Because it was so well known, I thought it was database-based :) > > http://moinmoin.wikiwikiweb.de/ > > Any good and simple text file-based blog system in Python? From paddy3118 at netscape.net Fri Aug 11 16:41:38 2006 From: paddy3118 at netscape.net (Paddy) Date: 11 Aug 2006 13:41:38 -0700 Subject: What's the cleanest way to compare 2 dictionary? In-Reply-To: <1155247607.223854.213910@h48g2000cwc.googlegroups.com> References: <1155147450.628625.20270@m79g2000cwm.googlegroups.com> <1155165349.766502.314760@n13g2000cwa.googlegroups.com> <1155247607.223854.213910@h48g2000cwc.googlegroups.com> Message-ID: <1155328898.040164.10620@i3g2000cwc.googlegroups.com> I have gone the whole hog and got something thats run-able: ========dict_diff.py============================= from pprint import pprint as pp a = {1:{'1':'1'}, 2:{'2':'2'}, 3:dict("AA BB CC".split()), 4:{'4':'4'}} b = { 2:{'2':'2'}, 3:dict("BB CD EE".split()), 5:{'5':'5'}} def record_comparator(a,b, check_equal): keya=set(a.keys()) keyb=set(b.keys()) a_xclusive = keya - keyb b_xclusive = keyb - keya _common = keya & keyb common_eq = set(k for k in _common if check_equal(a[k],b[k])) common_neq = _common - common_eq return {"A excl keys":a_xclusive, "B excl keys":b_xclusive, "Common & eq":common_eq, "Common keys neq values":common_neq} comp_result = record_comparator(a,b, dict.__eq__) # Further dataon common keys, neq values common_neq = comp_result["Common keys neq values"] common_neq = [ (key, record_comparator(a[key],b[key], str.__eq__)) for key in common_neq ] comp_result["Common keys neq values"] = common_neq print "\na =",; pp(a) print "\nb =",; pp(b) print "\ncomp_result = " ; pp(comp_result) ========================================== When run it gives: a ={1: {'1': '1'}, 2: {'2': '2'}, 3: {'A': 'A', 'C': 'C', 'B': 'B'}, 4: {'4': '4'}} b ={2: {'2': '2'}, 3: {'C': 'D', 'B': 'B', 'E': 'E'}, 5: {'5': '5'}} comp_result = {'A excl keys': set([1, 4]), 'B excl keys': set([5]), 'Common & eq': set([2]), 'Common keys neq values': [(3, {'A excl keys': set(['A']), 'B excl keys': set(['E']), 'Common & eq': set(['B']), 'Common keys neq values': set(['C'])})]} - Paddy. From python.list at tim.thechases.com Mon Aug 14 08:36:55 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 14 Aug 2006 07:36:55 -0500 Subject: help parsing this In-Reply-To: References: <1155557530.383959.241150@75g2000cwc.googlegroups.com> Message-ID: <44E06E67.7000400@tim.thechases.com> >> how to parse this date > > parse it into what? there is no such thing as "April 31st". I think somebody's chain is getting pulled...thus the right thing to do is to wrap around and return "April 1st" ;-) -Loof Lirpa From steven.bethard at gmail.com Tue Aug 15 01:32:16 2006 From: steven.bethard at gmail.com (steven.bethard at gmail.com) Date: Tue, 15 Aug 2006 05:32:16 +0000 (GMT) Subject: python-dev Summary for 2006-07-16 through 2006-07-31 Message-ID: <20060815053721.4256A1E400A@bag.python.org> python-dev Summary for 2006-07-16 through 2006-07-31 ++++++++++++++++++++++++++++++++++++++++++++++++++++ .. contents:: [The HTML version of this Summary is available at http://www.python.org/dev/summary/2006-07-16_2006-07-31] ============= Announcements ============= ------------------- Python 2.5 schedule ------------------- After inserting a third beta release to allow some more time for testing the new features, Python continues to make progress towards the final Python 2.5 release. See `PEP 356`_ for more details and the full schedule. .. _PEP 356: http://www.python.org/dev/peps/pep-0356/ Contributing threads: - `outstanding bugs to fix for 2.5 `__ - `Py2.5 release schedule `__ ------------------------------- How to submit a patch to Python ------------------------------- Just a few reminders for all those still new to python-dev. When submitting a new patch to SourceForge, don't assign it to anyone. Most python developers get email notifications for new patches and will assign it to themselves if appropriate. If you feel like the approach the patch takes might need discussion, it's alright to present it to python-dev and ask for some feedback. If you do, be sure to put the patch number and url (e.g. http://bugs.python.org/) near the top of the message, so that developers can easily find it. And if you don't want to wait for your patch to be looked at (which may take some time as all developers are volunteers), a few of the folks here, including Martin v. Lowis, have offered a five-for-one deal. Simply find five other patches, and check them for things like: * Does the code look okay? * Does Python build with it applied? * Do all unit tests pass? * Does the patch have tests? * Does the patch have documentation? Then post your notes to the five patch trackers and post a final message to python-dev indicating the patches you reviewed and the patch which you'd like to have someone look at for you. Contributing threads: - `new guy `__ - `first draft of bug guidelines for www.python.org/dev/ `__ - `Patch submitted, now what? `__ ---------------------------------------- Demos of trackers to replace SourceForge ---------------------------------------- There are currently three potential trackers that have successfully imported the SourceForge data with demos online: roundup_, jira_ and launchpad_. Try 'em out, and send your discussions and comments to infrastructure at python.org and put your reports and reviews `on the wiki`_. .. _roundup: http://efod.se/python-tracker/ .. _jira: http://jira.python.atlassian.com/secure/Dashboard.jspa .. _launchpad: https://demo.launchpad.net/products/python/+bugs .. _on the wiki: http://wiki.python.org/moin/CallForTrackers Contributing thread: - `More tracker demos online `__ ========= Summaries ========= ------------------------------ Restricted execution in Python ------------------------------ Brett Cannon decided this fortnight to go for an all-out capabilities based restricted execution design, and posted a `new design document`_. As part of this work, Brett planned to rewrite most of the import machinery in pure Python code, hopefully cleaning up some of the idiosyncrasies of the current import.c mechanisms, and allowing him to do things like restrict imports to only .py files, not .pyc files. Armin Rigo pointed out that a good place to start would be the `PyPy import implementation`_. On the restricted execution front, one of the things that is now likely to happen in Brett's sandboxing branch is that ``object.__subclasses__()`` and dangerous constructors like the one for the code object will be completely removed from the Python level. This means a few backwards incompatible changes, but Brett suggested that they should only break pretty advanced and esoteric Python code. Since it's for his Ph.D. dissertation, he didn't want to tie his hands by requiring full backwards compatibility, and he was fine with waiting to merge his branch until Python 3000. .. _new design document: http://svn.python.org/view/python/branches/bcannon-sandboxing/securing_python.txt .. _PyPy import implementation: http://codespeak.net/svn/pypy/dist/pypy/module/__builtin__/importing.py Contributing threads: - `Capabilities / Restricted Execution `__ - `new security doc using object-capabilities `__ -------------------------- Character case and locales -------------------------- Mihai Ibanescu asked about a `bug in the logging module`_ due to the fact that ``'INFO'.lower() != 'info'`` in some locales. Marc-Andre Lemburg and Martin v. Lowis explained that since in Unicode, nearly all case-conversions are only script-dependent, not language-dependent, ``u'INFO'.lower() == u'info'`` should always be true. .. _bug in the logging module: http://bugs.python.org/1524081 Contributing thread: - `logging module broken because of locale `__ ----------------------------------------------- Progress on the C version of the decimal module ----------------------------------------------- After looking at the current progress in converting the decimal module to C, Raymond Hettinger suggested that rather than using the Python implementation as an outline of the C implementation, a separate C implementation should be developed and then later wrapped as necessary to provide the Python APIs. Tim Peters explained their incremental approach: leaving most of the module written in Python, and converting methods to C code one at a time. Raymond had originally supported this approach, but after viewing the current C code, thought that it would result in C code that was too complex and convoluted. There was some extended discussion on the mechanism in the current decimal module for holding flags, which uses a dict mapping error types to the counts of their occurrences. Raymond in particular wanted the C decimal module to be able to change this API if it was too complex to implement. A number of others agreed that the API had been a bad decision, and it looked like there would at least be a note in the documentation for Python 2.5 suggesting that users should not rely on the counting feature. Contributing thread: - `Strategy for converting the decimal module to C `__ --------------------------------------- PEP 357: Integer clipping and __index__ --------------------------------------- Armin Rigo pointed out that the current implementation of ``__index__()`` was incorrectly truncating long integers:: >>> (2**100).__index__() 2147483647 As the original ``__index__()`` method was intended only to allow things other than plain Python ints as slice indices, truncating to the maximum value was fine. However, when ``__index__()`` also became the "can you faithfully act like an integer" check, this truncation was no longer acceptable. Nick Coghlan spent some time reworking the `PEP 357`_ C API so that all the use cases of ``__index__()`` were covered. His `patch for fixing __index__`_ changes the nb_index slot to return a PyInt or PyLong instead of a C int, and introduces the C API functions PyNumber_Index, PyNumber_AsSsize_t and PyNumber_AsClippedSsize_t(), all of which have an output variable signifying whether or not the object they received had an ``__index__`` method. .. _PEP 357: http://www.python.org/dev/peps/pep-0357/ .. _patch for fixing __index__: http://bugs.python.org/1530738 Contributing thread: - `Bad interaction of __index__ and sequence repeat `__ -------------------------------------------------------- PEP 302: Non-importer objects on sys.path_importer_cache -------------------------------------------------------- Phillip J. Eby asked about how to best fix the non-PEP-302 compliant changes to the import machinery made by the Need for Speed Sprint. `PEP 302`_ indicates that everything on sys.path_importer_cache should be either None or a valid importer object, but the Need for Speed changes added True and False values to that as well. After getting approval to make the appropriate changes necessary to stay PEP-302-compliant, Phillip added ``imp.NullImporter`` to replace False values, and kept ``None`` to mean that the builtin import machinery should be used. .. _PEP 302: http://www.python.org/dev/peps/pep-0302/ Contributing threads: - `Undocumented PEP 302 protocol change by need-for-speed sprint `__ - `Release manager pronouncement needed: PEP 302 Fix `__ --------------------------------------------------------------- Running the test suites of user projects when Python is updated --------------------------------------------------------------- Grig Gheorghiu volunteered to do some of the work to get community buildbots running, that is, buildbots running the test suites of Python user projects whenever the Python core repository was updated. People were quite enthusiastic and Martin v. Lowis offered to set up a post-commit hook on the python repository to trigger a build on Grig's buildbots if necessary. Contributing threads: - `Community buildbots `__ - `Community buildbots (was Re: User's complaints) `__ - `Community buildbots -- reprise `__ -------------------------------------- Safe dumper/loader using Python syntax -------------------------------------- Sylvain Fourmanoit presented his miniconf_ module which is a safe and cross-version dumper/loader for simple objects using the Python syntax. People generally liked the module, and Phillip J. Eby helped Sylvain clean up the implementation a bit. There was some discussion of including it in the Python 2.6 stdlib and perhaps Bob Ippolito's simplejson_ module alongside it. .. _miniconf: http://cheeseshop.python.org/pypi?:action=display&name=miniconf .. _simplejson: http://undefined.org/python/#simplejson Contributing threads: - `New miniconf module `__ - `JSON implementation in Python 2.6 `__ ------------------------------- Programmatically sending Ctrl-C ------------------------------- In testing his `patch to make sockets and Ctrl-C play nicely`_, Tony Nelson found that he needed a portable way to send a Ctrl-C-like signal. For Unix, he was using ``signal.alarm``, but was wondering if there was a way to get something similar on Windows. Martin v. Lowis pointed out GenerateConsoleCtrlEvent, but also noted that this would send the Ctrl-C to all processes. In the end, Tony decided to punt on Windows, and just stick with the Unix tests. .. _patch to make sockets and Ctrl-C play nicely: http://bugs.python.org/1519025 Contributing threads: - `Socket Timeouts patch 1519025 `__ - `Testing Socket Timeouts patch 1519025 `__ ------------------------------------------ Documenting performance of container types ------------------------------------------ Neal Becker asked about documentation the performance of the basic Python container types, e.g. that lookup in a dict is O(1) and deletion from the beginning of a list is O(N). A number of people agreed that having such information would be helpful, but there was some concern that Guido should be the one to decide what performances guarantees were made by the language, and not just the CPython implementation. The discussion trailed off before any final decisions on how to update the documentation were made. Contributing thread: - `Document performance requirements? `__ --------------------------- Running the uuid test suite --------------------------- Georg Brandl fixed a bug that was causing the new uuid module's test suite not to run at all. The resulting tests indicated a number of problems in determining a MAC address. Neal Norwitz patched the uuid module so that it should work at least on Linux, Tru64, Solaris, and HP-UX, and Tim Peters patched it so that test_uuid no longer thinks that the uuid module knows multiple ways of getting a well-defined MAC address (which it doesn't on Windows). Contributing threads: - `uuid test suite failing `__ - `how about adding ping's uuid module to the standard lib ? `__ - `Another uuid problem `__ - `test_uuid `__ ------------------------------------ CPython and checking for NULL values ------------------------------------ Neal Norwitz took a look at some of the issues raised by the automatic analysis of Python's source code offered by Klocwork_. There was a fairly long discussion around a Py_XINCREF of a variable that was required by the documentation to be non-NULL (and thus the "X" is unnecessary). There was some suggestion of trying to check for NULL values anyway, but the rest of Python doesn't do such checks. .. _Klocwork: http://www.klocwork.com/ Contributing thread: - `remaining issues from Klocwork static analysis `__ --------------------------------------------- Excluding certain constructs from Python code --------------------------------------------- Boris Borcic suggested that to make changing version of Python easier, style sheets should be introduced such that you could allow or disallow particular constructs that you liked or didn't like. People thought this was generally a very bad idea as it would essentially introduce a bunch of language variants, and coders might not be able to read each others' source code without first applying the appropriate transformation. Contributing threads: - `Python Style Sheets ? Re: User's complaints `__ - `Python Style Sheets ? Re: User's complaints `__ --------------------------------------------------------- Making attributes with leading single underscores private --------------------------------------------------------- David Hopwood proposed enforcing the `PEP 8`_ convention that attributes with a single underscore are private to that object. His approach revolved around allowing only the first argument of a function to access attributes starting with '_', but Armin Rigo and others felt that this was not likely to be enforceable, giving an example where subclassing allowed access to supposedly private attributes. People generally felt that without an implementation to back up the proposal, there wasn't much to discuss. .. _PEP 8: http://www.python.org/dev/peps/pep-0008/ Contributing thread: - `Internal namespace proposal `__ ----------------------------------- Loading module attributes on demand ----------------------------------- In order to reduce the memory consumption of GTK+ applications written in Python, Johan Dahlin was looking into dynamically generating module attributes so that they would only be loaded when the application actually accessed them. He was able to produce this behavior by subclassing ModuleType, overridding __getattribute__, and then putting this object onto sys.path, but he felt like this was kind of a hackish solution. Phillip J. Eby pointed out the importing_ package and said that the __getattribute__ approach was generally okay, though it would cause problems for pydoc and inspect which don't handle subclasses of ModuleType well. Andrew Bennetts pointed out mercurial's demandload_ which allows modules to be imported on demand, but this didn't really solve Johan's problem because all attributes of the modules themselves were still imported at the same time. .. _importing: http://cheeseshop.python.org/pypi/Importing .. _demandload: http://selenic.com/repo/hg?f=cb4715847a81;file=mercurial/demandload.py Contributing thread: - `Dynamic module namspaces `__ ------------------------------- Improving the Python test suite ------------------------------- Matt Fleming has put together `a wiki page`_ indicating the tests that are currently missing from Python's test suite, as well as the tests that are incomplete. He plans on working his way through the list when he gets some time, but help for any of the tests is quite welcome. .. _a wiki page: http://wiki.python.org/moin/ImprovingLibTests Contributing thread: - `Improving unit tests for the standard library `__ ---------------------------------- Improving the Python documentation ---------------------------------- Georg Brandl, referring to `bug 469773`_, suggested that python gain a "Using Python" page containing the man page and how to invoke the interpreter. He also suggested that creating a list of frequently needed documentation sections that are hard to find for newbies could go a long way towards making the Python documentation more user-friendly. .. _bug 469773: http://bugs.python.org/469773 Contributing thread: - `Using Python docs `__ ================ Deferred Threads ================ - `struct module and coercing floats to integers `__ - `Rounding float to int directly (Re: struct module and coercing floats to integers) `__ ================== Previous Summaries ================== - `Support for PyGetSetDefs in pydoc `__ =============== Skipped Threads =============== - `Problem with super() usage `__ - `Pronouncement on SF #1520294 sought `__ - `I have submitted a patch that implement IrDA socket support . `__ - `User's complaints `__ - `Pickling objects that return string from reduce `__ - `[Python-checkins] r50708 - in python/trunk: Lib/test/test_sys.py Misc/NEWS Python/pystate.c `__ - `Python sprint in NY and CA, Aug. 21-24 `__ - `Weekly Python Patch/Bug Summary `__ - `os.utime and os.chmod failures (etc) Python 2.5b2 `__ - `FW: Bug? Certainly a new *behavior* from subprocess in 2.5 on Win32 `__ - `Behavior change in subprocess.py `__ - `segfault when using PyGILState_Ensure/Release in Python2.3.4 `__ - `Ireland PyPy sprint 21th-27th August 2006 `__ - `Python 2.4, VS 2005 & Profile Guided Optmization `__ - `Python sprint in Arlington July 29/30 `__ - `setup.py and cross-compiling `__ - `2.5: uses of sys.exc_type, exc_value `__ - `[Windows, buildbot] kill_python.c mystery `__ - `patch for mbcs codec (again) `__ - `Which version of distutils to ship with Python 2.5? `__ - `Patch for building ctypes on more OpenBSD target platforms `__ - `Release manager: pdb bugfix incompatibility `__ - `patching pydoc? `__ - `Fwd: patching pydoc? `__ - `Patch Against shutil.copytree Bug `__ - `httplib and bad response chunking `__ - `cgi.FieldStorage DOS (sf bug #1112549) `__ - `Eliminating loops `__ ======== Epilogue ======== This is a summary of traffic on the `python-dev mailing list`_ from July 16, 2006 through July 31, 2006. It is intended to inform the wider Python community of on-going developments on the list on a semi-monthly basis. An archive_ of previous summaries is available online. An `RSS feed`_ of the titles of the summaries is available. You can also watch comp.lang.python or comp.lang.python.announce for new summaries (or through their email gateways of python-list or python-announce, respectively, as found at http://mail.python.org). This python-dev summary is the 9th written by Steve Bethard. To contact me, please send email: - Steve Bethard (steven.bethard at gmail.com) Do *not* post to comp.lang.python if you wish to reach me. The `Python Software Foundation`_ is the non-profit organization that holds the intellectual property for Python. It also tries to advance the development and use of Python. If you find the python-dev Summary helpful please consider making a donation. You can make a donation at http://python.org/psf/donations.html . Every cent counts so even a small donation with a credit card, check, or by PayPal helps. -------------------- Commenting on Topics -------------------- To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! ------------------------- How to Read the Summaries ------------------------- That this summary is written using reStructuredText_. Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo :); you can safely ignore it. We do suggest learning reST, though; it's simple and is accepted for `PEP markup`_ and can be turned into many different formats like HTML and LaTeX. .. _python-dev: http://www.python.org/dev/ .. _SourceForge: http://sourceforge.net/tracker/?group_id=5470 .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _c.l.py: .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _PEP Markup: http://www.python.org/peps/pep-0012.html .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _PSF: .. _Python Software Foundation: http://python.org/psf/ .. _archive: http://www.python.org/dev/summary/ .. _RSS feed: http://www.python.org/dev/summary/channews.rdf From dpeschel at eskimo.com Mon Aug 7 22:36:56 2006 From: dpeschel at eskimo.com (Derek Peschel) Date: 8 Aug 2006 02:36:56 GMT Subject: Changing UNIX tty driver keys -- Suggested changes to "termios" module Message-ID: Should I add an RFE to SourceForge too? I'd like a wide audience in case someone has enough experience to comment or is solving the same problem. I'm using the urwid library which uses curses. On my system (Mac OS 10.3.7) I specifically have ncurses. The programs I'm running turn off echoing and set raw mode but don't disable interrupts. For development purposes I like having interrupts, but my preferred keystrokes (WordStar) conflict with the tty driver's use of ^C, ^Z, ^V, and maybe other keys. Here's a piece of code based on the example in section 8.8.1 of the Python Library Reference. It doesn't handle ^V yet. ------------------------------------------------------------------------------ termios_cc = 6 # magic index -- not 4 which is position # in the C struct termios__POSIX_VDISABLE = '\xff' # signals are set to this # when they don't corres- # pond to any char. fd = sys.stdin.fileno() oldterm = termios.tcgetattr(fd) oldterm_int = oldterm[termios_cc][termios.VINTR] oldterm_quit = oldterm[termios_cc][termios.VQUIT] if ord(oldterm_int) != 3: # ^C sys.exit("interrupt char isn't ^C") if ord(oldterm_quit) != 28: # ^\ sys.exit("quit char isn't ^\\") # no way to check whether applications (telnet, screen) # are looking for ^^ # no check yet for any signals set to ^^ newterm = termios.tcgetattr(fd) newterm[termios_cc][termios.VQUIT] = chr(30) # ^^ newterm[termios_cc][termios.VINTR] = chr(28) # ^\ try: termios.tcsetattr(fd, termios.TCSADRAIN, newterm) self.ui.run_wrapper(self.run) finally: termios.tcsetattr(fd, termios.TCSADRAIN, oldterm) ------------------------------------------------------------------------------ I'd like to handle errors and race conditions better, but I don't know what kinds can happen in practice. I'd also like to make the code work on other versions of UNIX. Easy suggested improvements to the library: Define _POSIX_VDISABLE and names for the fields of the struct, so that termios__POSIX_VDISABLE and termios_cc become termios._POSIX_VDISABLE and termios.cc. Harder improvements: Some functions that abstract the things I'm doing (checking the current characters, changing a group of them in one operation). I assume two signals should never be set to the same character, unless they are disabled. Is it possible to make the state variables invisible? Is that a good idea? Thanks, -- Derek From claudio.grondi at freenet.de Sun Aug 27 05:59:29 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Sun, 27 Aug 2006 11:59:29 +0200 Subject: How to let a loop run for a while before checking for break condition? Message-ID: Sometimes it is known in advance, that the time spent in a loop will be in order of minutes or even hours, so it makes sense to optimize each element in the loop to make it run faster. One of instructions which can sure be optimized away is the check for the break condition, at least within the time where it is known that the loop will not reach it. Any idea how to write such a loop? e.g. counter = 2*64 while counter(BUT DON'T CHECK IT THE FIRST ONE HOUR LONG): ... do something ... # and decrease the counter Thanks for any hint, but in particular if related to timers on the Windows 2000/XP system I am mainly working with. What do you think about this idea? Does it make sense? Claudio Grondi From onurb at xiludom.gro Thu Aug 10 11:39:28 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Thu, 10 Aug 2006 17:39:28 +0200 Subject: Newbie - How to iterate list or scalar ? In-Reply-To: References: Message-ID: <44db5331$0$21148$7a628cd7@news.club-internet.fr> Delaney, Timothy (Tim) wrote: > Bruno Desthuilliers wrote: > >> What I wonder here is why __iter__ has been added to lists and tuples >> but not to strings (not that I'm complaining, it's just curiousity...) > > Because someone got around to doing it. Ok, so it's definitively a design decision, and should by no mean be used. Thanks Tim for clarifying this point. From johnjsal at NOSPAMgmail.com Thu Aug 10 10:24:21 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 10 Aug 2006 14:24:21 GMT Subject: converting a nested try/except statement into try/except/else In-Reply-To: <1155154782.885182.7580@n13g2000cwa.googlegroups.com> References: <1155154782.885182.7580@n13g2000cwa.googlegroups.com> Message-ID: Simon Forman wrote: > What about the version I gave you 8 days ago? ;-) > > http://groups.google.ca/group/comp.lang.python/msg/a80fcd8932b0733a > > It's clean, does the job, and doesn't have any extra nesting. > > Peace, > ~Simon > I remember that version, but I found it a little hard to follow. It seems like the kind of code that if I look at it again in another month or so, I'll have to trace through it again to figure out what's what. But I think it was your code that made me think of using an else statement in the first place! :) From johnjsal at NOSPAMgmail.com Sun Aug 13 20:21:26 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 13 Aug 2006 20:21:26 -0400 Subject: outputting a command to the terminal? In-Reply-To: References: <44df99f7$0$25025$c3e8da3@news.astraweb.com> Message-ID: <44dfc1cb$0$2397$c3e8da3@news.astraweb.com> Yu-Xi Lim wrote: > I assume you're using a Debian-based distro with aptitude as the front > end. In which case, all dpkg operations should be logged in > /var/log/dpkg.log Yes, I'm using Ubuntu. But I checked this log file and I'm a bit confused. It has a lot of listings for 5-31-06, but I didn't even install Linux until last Saturday. The next date after 5-31 is 8-5-06, and I know I installed things between last Saturday and Aug. 5. (But this is OT, so don't worry about it.) > I'm wondering about the need to "output the bash command to the > terminal". It would probably suffice if your Python script just spawned > an instance of the shell with the necessary command line. Take a look at > the subprocess module. > > But this really calls for a bash script: > > #!/bin/bash > echo $@ >> /path/to/manual_install.log > sudo aptitude install $@ > > > Shorter than the equivalent Python code. You could probably declare this > as a function in your bash initialization files too, if you know how to > do this. Hmm, interesting. I figured I could do this with a bash script, but I don't know bash at all and I'm trying to stick with Python. I don't quite understand your bash script (not familiar with the $@ syntax). I think I'll take a look at the subprocess module, just for fun. :) From Kiran.Karra at gmail.com Tue Aug 1 16:56:52 2006 From: Kiran.Karra at gmail.com (Kiran) Date: 1 Aug 2006 13:56:52 -0700 Subject: wxPython Linux Compatibility question Message-ID: <1154465812.240397.29400@m73g2000cwd.googlegroups.com> Hello All, My question is regarding MDI Windows Support for Linux in wxPython. I am currently writing an application which uses MDI. I have seen that in linux, it basically makes all MDI windows tabs (without close, minimize, or maximize buttons and other tools such as cascade and stuff), which is fine by me. I however want to know which MDI window the user has focus of so that the user has an option of closing the window if they so desired under Linux. How would I find this out? thanks a lot! -- Kiran From originalbrownster at gmail.com Thu Aug 10 08:35:26 2006 From: originalbrownster at gmail.com (OriginalBrownster) Date: 10 Aug 2006 05:35:26 -0700 Subject: String Formatting Message-ID: <1155213326.679334.234880@i42g2000cwa.googlegroups.com> Hi there: I was wondering if its at all possible to search through a string for a specific character. I want to search through a string backwords and find the last period/comma, then take everything after that period/comma Example If i had a list: bread, butter, milk I want to just take that last entry of milk. However the need for it arises from something more complicated. Any help would be appreciated From nospan at nothanks.org Tue Aug 1 20:04:07 2006 From: nospan at nothanks.org (Conrad) Date: Wed, 02 Aug 2006 00:04:07 GMT Subject: Using Python for my web site References: <1154361480.915174.262720@b28g2000cwb.googlegroups.com> <44ce3a5c$0$18952$626a54ce@news.free.fr> <1154367359.931684.106650@m73g2000cwd.googlegroups.com> <44ce4530$0$28242$626a54ce@news.free.fr> Message-ID: On Mon, 31 Jul 2006 17:12:56 -0300, Gerhard Fiedler wrote: > On 2006-07-31 15:00:15, Bruno Desthuilliers wrote: > >> In fact, the real question IMHO is: what would MySQL advantage over >> PostgreSQL be ?-) > > A few years ago I did some research, and the result was that while > PostgreSQL was claimed to have more features and a better design, the > reports of database corruption seemed to have been more frequent than with > MySQL. The usual reason given was that MySQL was more mature. > > I assume you don't agree... :) > > Gerhard Maturity is an interesting word. The PostgreSQL pedigree reaches back about thirty years, which in some peoples minds, would constitute a degree of maturity. While I can't claim to have done your extensive (and well documented) research, I can say that I was a happy MySQL user a couple of years ago, using it to quickly serve up fairly static content. Happy, that is, until I put it into a more dynamic order entry/processing environment. I started finding glitches - orphaned records - one table totally corrupted. I found I was spending more and more time coding to make sure the transactions completed, and less time developing new code. I switched that client to PostgreSQL and have had ZERO problems since. Many of the "features" that MySQL is only now adding are playing catchup to core data integrity values that PostgreSQL has had for much longer, so it could be argued that in some areas, MySQL can be said to be much less "mature". From http Wed Aug 30 23:35:14 2006 From: http (Paul Rubin) Date: 30 Aug 2006 20:35:14 -0700 Subject: GC and security References: <44F61EEB.8040207@optonline.net> <7x4pvtpxnc.fsf@ruckus.brouhaha.com> <44F63356.6060400@optonline.net> Message-ID: <7xlkp5h91p.fsf@ruckus.brouhaha.com> Les Schaffer writes: > understood, i meant best practice in terms of the less rigorous garbage > collection. if the collect() function hastens garbage collection for > unreferenced strings like a passphrase, it costs us nothing and buys us > a wee bit. GC simply releases the memory for other uses in the application. It doesn't necessarily zero the memory. Just what attack are you trying to protect against, if swap space is less of a problem than leaving keys around in ram? Keep in mind that the weakest part of this application is likely to be the passphrase itself. Is there a way to get rid of it? > we're more sensitive than a web service, but not at the level of > hardware protection. it is health data related, and for the moment we > exceed the OMB's latest on laptop security: Is this data on a laptop? Why do you want to do encryption in the application, instead of using an encrypted file system? Is there some obstacle to using a token (like a smart card) to hold the key? From jussij at zeusedit.com Mon Aug 21 21:53:13 2006 From: jussij at zeusedit.com (jussij at zeusedit.com) Date: 21 Aug 2006 18:53:13 -0700 Subject: text editor suggestion? In-Reply-To: <44e78a2b$0$12550$c3e8da3@news.astraweb.com> References: <44e66724$0$2363$c3e8da3@news.astraweb.com> <1155995807.052337.272990@i42g2000cwa.googlegroups.com> <44e78a2b$0$12550$c3e8da3@news.astraweb.com> Message-ID: <1156211593.143545.103750@m79g2000cwm.googlegroups.com> John Salerno wrote: > The thing I liked about UltraEdit is that you can define your own > groups of words and put whatever words you want in there, so my > file had a group called '__builtins__' and it listed all the Python > built-in methods, and those would be highlighted. Most editors I > see don't seem to allow this... The Zeus IDE uses this exact same approach but takes it one step further by allowing you to encapsulate all this information inside a document type: http://www.zeusedit.com/forum/viewtopic.php?t=176 But alas Zeus is a Windows only editor. Jussi Jumppanen Author: Zeus for Windows IDE http://www.zeusedit.com From geli at tasmail.com Tue Aug 15 19:32:39 2006 From: geli at tasmail.com (gel) Date: 15 Aug 2006 16:32:39 -0700 Subject: What would be the best way to run python client in the background In-Reply-To: References: Message-ID: <1155684759.515881.289780@i3g2000cwc.googlegroups.com> Tim Golden wrote: > [gel] > > | I have written a python client server app [...] > | I want to run the client end of the app more or less invisibly > | (no console) on the XP clients when ever a users logs on. > > You say "when[]ever a user logs on" but does this app > need to be run on a per-user basis? Or could it run all > the time -- ie as a Windows Service -- and do enough to > determine which user is logged on when it needed to? Yes at the moment the user name is set when the program starts, but it is no problem to stick that further down program in the loop that watches processes start and finish. > > The normal way is to run a Win32 service. There are several > posts on the subject around the Python and Python-Win32 > mailing lists / newsgroups. The alternative is to set something > to run when any user logs in to run without a window. Again, > there are posts on the subject, including one I seem to remember > from Robin Becker, which tell how to do this kind of thing. Yes running the client as a service seems to be the way to go. I have had a bit of a look at the py2exe way of doing it, but have not got my head around it yet. What would be your preferred way of creating a service for an XP client? > > Let us know if you can't find anything which seems to > fit the bill. > > TJG > > ________________________________________________________________________ > This e-mail has been scanned for all viruses by Star. The > service is powered by MessageLabs. For more information on a proactive > anti-virus service working around the clock, around the globe, visit: > http://www.star.net.uk > ________________________________________________________________________ From anthra.norell at tiscalinet.ch Mon Aug 28 03:06:14 2006 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Mon, 28 Aug 2006 09:06:14 +0200 Subject: unpaking sequences of unknown length References: <1156683592.650594.259560@h48g2000cwc.googlegroups.com> Message-ID: <004301c6ca70$747dfec0$0201a8c0@mcuf7> I get it! >>> def f (*a): print a print zip (a) # My mistake print zip (*a) # Gerard's solution. >>> f (l1, l2, l3) ([1, 2, 3], [4, 5, 6], [7, 5, 34]) # Argument: tuple of lists [([1, 2, 3],), ([4, 5, 6],), ([7, 5, 34],)] # My mistake [(1, 4, 7), (2, 5, 5), (3, 6, 34)] # That's what I want Thank you all Frederic ----- Original Message ----- From: "Gerard Flanagan" Newsgroups: comp.lang.python To: Sent: Sunday, August 27, 2006 2:59 PM Subject: Re: unpaking sequences of unknown length > > Anthra Norell wrote: > > Hi, > > > > I keep working around a little problem with unpacking in cases in which I don't know how many elements I get. Consider this: > > > > def tabulate_lists (*arbitray_number_of_lists): > > table = zip (arbitray_number_of_lists) > > for record in table: > > # etc ... > > > > This does not work, because the zip function also has an *arg parameter, which expects an arbitrary length enumeration of arguments > > maybe I don't understand the problem properly, but you can use '*args' > as 'args' or as '*args', if you see what I mean!, ie. > > def tabulate_lists (*arbitray_number_of_lists): > table = zip (*arbitray_number_of_lists) > for record in table: > # etc ... > > for example: > > def sum_columns(*rows): > for col in zip(*rows): > yield sum(col) > > for i, s in enumerate( sum_columns( [1,2], [3,2], [5,1] ) ): > print 'Column %s: SUM=%s' % (i,s) > > Column 0: SUM=9 > Column 1: SUM=5 > > ----------------------------------------------------- > > alternatively: > > import itertools as it > > def sum_columns2( iterable ): > for col in it.izip( *iterable ): > yield sum(col) > > def iter_rows(): > yield [1,2] > yield [3,2] > yield [5,1] > > print list( sum_columns2( iter_rows() ) ) > > #(izip isn't necessary here, zip would do.) > > ----------------------------------- > > Gerard > > -- > http://mail.python.org/mailman/listinfo/python-list From amit.man at gmail.com Wed Aug 30 09:35:17 2006 From: amit.man at gmail.com (noro) Date: 30 Aug 2006 06:35:17 -0700 Subject: dictionary with object's method as thier items Message-ID: <1156944917.152606.213600@i42g2000cwa.googlegroups.com> Is it possible to do the following: for a certain class: ---------------------------- class C: def func1(self): pass def func2(self): pass def func4(self): pass obj=C() ---------------------------- by some way create a dictionary that look somthing like that: d= {'function one': , \ 'function two': , \ 'function three': } and so i could access every method of instances of C, such as obj with sometiing like: (i know that this syntax wont work ) obj.(d['function one']) obj.(d['function two']) etc.. thanks From fredrik at pythonware.com Sat Aug 26 03:43:27 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 26 Aug 2006 09:43:27 +0200 Subject: Finding the type of indexing supported by an object? In-Reply-To: References: <1hkii5f.19t6trjthzd67N%aleax@mac.com> Message-ID: Derek Peschel wrote: > At the moment I only need to invert dicts and lists. Is subclassing dict > and list considred good style? if it makes sense for your application, sure. however, it might be more convenient to just use a simple type check (e.g. looking for items) to distinguish between "normal mappings" and "normal sequences". try: items = obj.items() except AttributeError: items = enumerate(obj) # assume it's a sequence From skip at pobox.com Mon Aug 14 11:25:17 2006 From: skip at pobox.com (skip at pobox.com) Date: Mon, 14 Aug 2006 10:25:17 -0500 Subject: why the method get() of python Queue is hang on there? In-Reply-To: <1155568212.888733.79920@b28g2000cwb.googlegroups.com> References: <1155568212.888733.79920@b28g2000cwb.googlegroups.com> Message-ID: <17632.38365.796819.224733@montanaro.dyndns.org> zxo> import Queue zxo> b = Queue.Queue(0) zxo> b.put(9999) zxo> b.get() # this is ok, it pops out 9999 zxo> b.get() # this one does not return anything and is hang on there zxo> Anybody knows what is going on with the second b.get()? Queue objects are meant to be used in a multithreaded application. By default, when the Queue is empty, a consumer calling get() will block until a producer put()s something else into it. From the documentation: get([block[, timeout]]) Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available.... Skip From dmulcahy at revenue.ie Thu Aug 24 11:42:03 2006 From: dmulcahy at revenue.ie (dmulcahy) Date: 24 Aug 2006 08:42:03 -0700 Subject: libcurses.so & installing Python 2.4.3 Message-ID: <1156434123.526207.28500@74g2000cwt.googlegroups.com> Folks, I am trying to build the binaries for Python 2.4.3 on a Sun E6900 running SPARC Solaris 9 and using gcc 3.4.2. When the makefile tries to build the _curses extension it fails with a symbol referencing error on "mvwgetnstr", which it appears should exist in libcurses.so. For some reason it seems this function does not exist in the version of libcurses.so shipped with Solaris 9. Will I find it in some other library on Solaris or do I need to download a different version of libcurses.so? Any suggestions would be welcome. Thanks, Damien. From david at boddie.org.uk Wed Aug 30 18:29:23 2006 From: david at boddie.org.uk (David Boddie) Date: 30 Aug 2006 15:29:23 -0700 Subject: models & editors in PyQt4 References: <1156952123.240684.35350@i3g2000cwc.googlegroups.com> Message-ID: <1156976963.752296.40230@i42g2000cwa.googlegroups.com> Skink wrote: > David Boddie wrote: > > I find it strange that you have to triple-click to edit any of the > > items in your example. Do you see the same behaviour? > oh, this is default Qt behavoiur: first click selects row, second select > editor (for ColorProperty, IntProperty & StringProperty you can now > change the value) but third click is required only for properties w/ > QCombobox editor (EnumProperty & BooleanProperty) ... It seemed that, even if the row was already selected, it took more than a double click to start editing. I'll have to take another look at it. David From SergioADiez at gmail.com Sun Aug 27 21:32:47 2006 From: SergioADiez at gmail.com (ishtar2020) Date: 27 Aug 2006 18:32:47 -0700 Subject: Newbie Question. Class definitions on the fly. Message-ID: <1156728767.854606.180190@p79g2000cwp.googlegroups.com> Hi everyone I'm sure this question is kinda stupid and has been answered a few times before... but I need your help! I'm writing a small application where the user can analyze some text based on a set of changing conditions , and right now I'm stuck on a point where I'd like to automatically generate new classes that operate based on those user-defined conditions. Is there a way in python to define a class in runtime? For instance, can I define a class which extends another(that I have previously defined in some module) , create some instance completely on the fly and then add/redefine methods to it? If affirmative, I've thought of a problem I would maybe have to face: as the class has been defined by direct input to the python interpreter, I could only create instances of it on the same session I entered the definition(because it's not on a module I can load on future uses) but not afterwards. Is there a way to keep that code? Even more newbie paranoia: what would happen if I make that 'on the fly" object persist via pickle? Where would Python find the code to handle it once unpickled on another session (once again, i take that no code with the definition of that instance would exist, as it was never stored on a module). Hope it wasn't too ridiculous an idea. Thank you for your time, guys. From kbk at shore.net Wed Aug 9 01:34:21 2006 From: kbk at shore.net (Kurt B. Kaiser) Date: Wed, 9 Aug 2006 01:34:21 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200608090534.k795YLcP005740@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 402 open ( +6) / 3360 closed ( +6) / 3762 total (+12) Bugs : 861 open ( -3) / 6114 closed (+27) / 6975 total (+24) RFE : 228 open ( +2) / 234 closed ( +0) / 462 total ( +2) New / Reopened Patches ______________________ Replace the ctypes internal '_as_parameter_' mechanism (2006-08-02) http://python.org/sf/1532975 opened by Thomas Heller Remove mentions of "PyUnit" from unittest docs (2006-08-02) CLOSED http://python.org/sf/1533336 opened by Collin Winter Allow thread(ing) tests to pass without setting stack size (2006-08-02) http://python.org/sf/1533520 opened by Matt Fleming Let timeit accept functions (2006-08-03) http://python.org/sf/1533909 opened by Erik Demaine Add notes on locale module changes to whatsnew25.tex (2006-08-03) http://python.org/sf/1534027 opened by Iain Lowe Typo in weakref error message (2006-08-03) CLOSED http://python.org/sf/1534048 opened by Christopher Tur Lesniewski-Laas Fix code generation bug in 'compiler' package (2006-08-03) CLOSED http://python.org/sf/1534084 opened by Neil Schemenauer Cleanup/error-correction for unittest's docs (2006-08-05) CLOSED http://python.org/sf/1534922 opened by Collin Winter writelines() in bz2 module does not raise check for errors (2006-08-06) http://python.org/sf/1535500 opened by Lawrence Oluyede CGIHTTPServer doesn't handle path names with embeded space (2006-08-06) http://python.org/sf/1535504 opened by Hartmut Goebel NNTPS support in nntplib (2006-08-06) http://python.org/sf/1535659 opened by Aurojit Panda trace.py on win32 has problems with lowercase drive names (2006-08-07) http://python.org/sf/1536071 opened by Adam Groszer Build ctypes on OpenBSD x86_64 (2006-08-08) http://python.org/sf/1536908 opened by Thomas Heller Patches Closed ______________ New ver. of 1102879: Fix for 926423: socket timeouts (2006-07-07) http://python.org/sf/1519025 closed by nnorwitz Remove mentions of "PyUnit" from unittest docs (2006-08-02) http://python.org/sf/1533336 deleted by collinwinter Typo in weakref error message (2006-08-03) http://python.org/sf/1534048 closed by fdrake Fix code generation bug in 'compiler' package (2006-08-03) http://python.org/sf/1534084 closed by nascheme Cleanup/error-correction for unittest's docs (2006-08-05) http://python.org/sf/1534922 closed by gbrandl New / Reopened Bugs ___________________ NetBSD build with --with-pydebug causes SIGSEGV (2006-08-02) http://python.org/sf/1533105 opened by Matt Fleming the csv module writes files that Excel sees as SYLK files (2006-08-01) CLOSED http://python.org/sf/1532483 reopened by madewokherd Installed but not listed *.pyo break bdist_rpm (2006-08-02) http://python.org/sf/1533164 opened by Shmyrev Nick CTypes _as_parameter_ not working as documented (2006-08-02) http://python.org/sf/1533481 opened by Shane Holloway long -> Py_ssize_t (C/API 1.2.1) (2006-08-02) http://python.org/sf/1533486 opened by Jim Jewett C/API sec 10 is clipped (2006-08-02) http://python.org/sf/1533491 opened by Jim Jewett Tools/modulator does not exist (ext 1.4) (2006-08-02) http://python.org/sf/1533493 opened by Jim Jewett botched html for index subheadings (2004-05-26) CLOSED http://python.org/sf/960860 reopened by jimjjewett __name__ doesn't show up in dir() of class (2006-08-03) http://python.org/sf/1534014 opened by Tim Chase getlines() in linecache.py raises TypeError (2006-08-04) CLOSED http://python.org/sf/1534517 opened by Stefan Behnel Python 2.5 svn crash in _elementtree.c (2006-08-04) http://python.org/sf/1534630 opened by Barry A. Warsaw Win32 debug version of _msi creates _msi.pyd, not _msi_d.pyd (2006-08-04) http://python.org/sf/1534738 opened by John Ehresman sys.path gets munged with certain directory structures (2006-08-04) http://python.org/sf/1534764 opened by Gustavo Tabares logging's fileConfig causes KeyError on shutdown (2006-08-04) http://python.org/sf/1534765 opened by mdbeachy Identical floats print inconsistently (2006-08-04) CLOSED http://python.org/sf/1534769 opened by Marc W. Abel termios.c in qnx4.25 (2005-09-19) http://python.org/sf/1295179 reopened by gbrandl can't staticaly build modules md5 and sha (2006-08-06) CLOSED http://python.org/sf/1535081 opened by kbob_ru python segfaults when reading from closed stdin (2006-08-05) CLOSED http://python.org/sf/1535165 opened by Patrick Mezard typo in test_bz2.py (2006-08-06) CLOSED http://python.org/sf/1535182 opened by Lawrence Oluyede Python 2.5 windows builds should link hashlib with OpenSSL (2006-08-06) http://python.org/sf/1535502 opened by Gregory P. Smith hash(method) sometimes raises OverflowError (2006-08-07) http://python.org/sf/1536021 opened by Christian Tanzer Missing builtin help for with and as (2006-08-08) http://python.org/sf/1536059 opened by Nick Coghlan "make install" doesn't install to /usr/lib64 on x86_64 boxes (2006-08-07) http://python.org/sf/1536339 opened by Bernhard Rosenkraenzer Micro fix for Reference Manual (2006-08-08) CLOSED http://python.org/sf/1536660 opened by Marcelo de Gomensoro Malheiros buffer comparison emits a RuntimeWarning (2006-08-08) CLOSED http://python.org/sf/1536786 opened by Thomas Heller distutils.sysconfig.get_config_h_filename gets useless file (2006-08-08) http://python.org/sf/1536825 opened by Parzival Herzog Typo, types.TypeType should read types.StringType (2006-08-08) CLOSED http://python.org/sf/1536828 opened by Reillyeon Bugs Closed ___________ socket timeouts + Ctrl-C don't play nice (2004-03-30) http://python.org/sf/926423 closed by nnorwitz mailbox.PortableUnixMailbox fails to parse 'From ' in body (2006-04-13) http://python.org/sf/1470212 closed by akuchling Build fails on MacOSX with missing symbol (2006-07-31) http://python.org/sf/1531662 closed by gdm ctypes build fails on Solaris 10 (2006-07-28) http://python.org/sf/1530448 closed by theller the csv module writes files that Excel sees as SYLK files (2006-08-01) http://python.org/sf/1532483 closed by montanaro incorrect behaviour of PyUnicode_EncodeMBCS? (2006-08-01) http://python.org/sf/1532726 closed by nnorwitz format_exception raises if str(exception) raises (2006-07-30) http://python.org/sf/1531405 closed by nnorwitz botched html for index subheadings (2004-05-26) http://python.org/sf/960860 closed by jimjjewett MACOSX_DEPLOYMENT_TARGET checked incorrectly (2005-04-30) http://python.org/sf/1193190 closed by etrepum [AST] Failing tests (2005-04-27) http://python.org/sf/1191458 closed by nnorwitz Bugs of the new AST compiler (2005-10-21) http://python.org/sf/1333982 closed by nnorwitz test_ossaudiodev timing failure (2003-08-04) http://python.org/sf/783242 closed by akuchling repr.repr not always safe (2003-01-12) http://python.org/sf/666958 closed by akuchling ftplib has incomplete transfer when sending files in Windows (2004-09-22) http://python.org/sf/1032875 closed by akuchling datetime.strftime %s (2005-07-07) http://python.org/sf/1234123 closed by akuchling __weaklist__ in typeobject.c (2006-07-29) http://python.org/sf/1531003 closed by fdrake getlines() in linecache.py raises TypeError (2006-08-04) http://python.org/sf/1534517 closed by scoder Identical floats print inconsistently (2006-08-04) http://python.org/sf/1534769 closed by gbrandl zipfile -- too many files? (2006-07-09) http://python.org/sf/1519452 closed by gbrandl can't staticaly build modules md5 and sha (2006-08-05) http://python.org/sf/1535081 closed by gbrandl python segfaults when reading from closed stdin (2006-08-05) http://python.org/sf/1535165 closed by gbrandl typo in test_bz2.py (2006-08-05) http://python.org/sf/1535182 closed by gbrandl TAB SETTINGS DONT WORK (win) (2005-10-27) http://python.org/sf/1339883 closed by kbk non-uniform behavior in 'startswith' / 'endswith' (2006-07-10) http://python.org/sf/1520176 closed by sf-robot Micro fix for Reference Manual (2006-08-08) http://python.org/sf/1536660 closed by gbrandl buffer comparison emits a RuntimeWarning (2006-08-08) http://python.org/sf/1536786 closed by theller Typo, types.TypeType should read types.StringType (2006-08-08) http://python.org/sf/1536828 closed by gbrandl New / Reopened RFE __________________ IndexError: Add bad index to msg (2006-08-04) http://python.org/sf/1534607 opened by Michael Kleehammer Print identical floats consistently (2006-08-05) http://python.org/sf/1534942 opened by Marc W. Abel RFE Closed __________ feature requests for logging lib (2006-04-22) http://python.org/sf/1474577 closed by sf-robot From sjmachin at lexicon.net Wed Aug 16 23:58:42 2006 From: sjmachin at lexicon.net (John Machin) Date: 16 Aug 2006 20:58:42 -0700 Subject: Newbie needs Help In-Reply-To: <1155783551.689026.273260@m73g2000cwd.googlegroups.com> References: <1155783551.689026.273260@m73g2000cwd.googlegroups.com> Message-ID: <1155787122.316436.292080@i3g2000cwc.googlegroups.com> len wrote: > Hi all > > I am writing a python program that inserts records into a database on > XP using mxODBC. > > I need to write a section of code which will create the following SQL > command as an example; > > INSERT INTO statecode (state, name) VALUES ('IL', 'Illinois') > > This statement will be built up using the following code; > > import mx.ODBC > import mx.ODBC.Windows > def insertFromDict(table, dict): > """Take dictionary object dict and produce sql for > inserting it into the named table""" > sql = 'INSERT INTO ' + table > sql += ' (' > sql += ', '.join(dict) > sql += ') VALUES (' > sql += ', '.join(map(dictValuePad, dict)) # ??? this code does > NOT format correctly > sql += ')' > return sql > > def dictValuePad(key): # ??? this code > does Not format correctly > return "'" + str(key) + "'" > > db = mx.ODBC.Windows.DriverConnect('dsn=UICPS Test') > c = db.cursor() > insert_dict = {'state':'IL', 'name':'Illinois'} > sql = insertFromDict("statecode", insert_dict) > print sql > c.execute(sql) > The code below will do what you say that you want to do -- so long as all your columns are strings (varchar or whatever in SQL terms). Otherwise IMHO you would be much better off doing it this way: sql = "insert into policy (type, premium) values(?, ?)" data = ('building', 123.45) cursor.execute(sql, data) for two reasons: (1) let the ODBC kit worry about formatting dates, strings with embedded single quotes, etc (2) it can be more efficient; the sql is constant and needs to be parsed only once (3) [bonus extra reason] the way you are doing it is vulnerable to what's called an "SQL injection attack"; although you have no doubt eyeballed all the data, doing it that way is a bad habit to get into. You should be able to modify the supplied code very easily to produce the sql variety with "?" in it. HTH, John C:\junk>type sqlinsdict.py def sqlquote(astring): return "'" + astring.replace("'", "''") + "'" def insertFromDict(table, adict): """Take dictionary object dict and produce sql for inserting it into the named table. Sample input: insert_dict = {'state':'IL', 'name':'Illinois'} sql = insertFromDict("statecode", insert_dict) Required output: INSERT INTO statecode (state, name) VALUES ('IL', 'Illinois') """ t = [ 'INSERT INTO ', table, ' (', ', '.join(adict.keys()), ') VALUES (', ', '.join(sqlquote(x) for x in adict.values()), ')', ] return ''.join(t) if __name__ == "__main__": tests = [ ('IL', 'Illinois'), ('OH', "O'Hara"), ] cols = ['state', 'name'] for test in tests: the_dict = dict(zip(cols, test)) print the_dict print insertFromDict('statecode', the_dict) C:\junk>sqlinsdict.py {'state': 'IL', 'name': 'Illinois'} INSERT INTO statecode (state, name) VALUES ('IL', 'Illinois') {'state': 'OH', 'name': "O'Hara"} INSERT INTO statecode (state, name) VALUES ('OH', 'O''Hara') From python.list at tim.thechases.com Fri Aug 18 14:51:57 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 18 Aug 2006 13:51:57 -0500 Subject: how do you get the name of a dictionary? In-Reply-To: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> Message-ID: <44E60C4D.4010306@tim.thechases.com> > Does anyone know how to find the name of a python data type. > > Conside a dictionary: > > Banana = {} > > Then, how do i ask python for a string representing the name of the > above dictionary (i.e. 'Banana')? AFAIK, there's no easy/good way of doing this because that name is just a handle to an internal object. Observe: >>> banana = {} >>> spatula = banana >>> spatula[42] = 'drangle' >>> banana {42: 'drangle'} >>> id(spatula) 10304800 >>> id(banana) 10304800 What does it mean to ask for the name of object ID 10304800? it's both "banana" and "spatula". One might be able to use the decompiler libraries and wend one's way through the dark recesses of python's internals to extract such information, but this is certainly not a beginner's task. How would you ask for the object? >>> print get_name(banana) you might as well write >>> print "banana" :) Hope this makes sense... -tkc From dataentry.nilam.1 at gmail.com Fri Aug 11 07:53:28 2006 From: dataentry.nilam.1 at gmail.com (dataentry.nilam.1 at gmail.com) Date: 11 Aug 2006 04:53:28 -0700 Subject: Make $1000's Monthly! Message-ID: <1155297208.125825.69660@74g2000cwt.googlegroups.com> Make $1000's Monthly! Over 600 work at home firms are in need of survey takers, product assemblers, home mailers, mystery shopping Data entry and more! Report contains complete contact details for over 650 companies now hiring! For this complete report of over 600 firms please visit http://www.typeinternational.com/idevaffiliate/idevaffiliate.php?id=6589_52_3_87 From yannick.leteigner at gmail.com Wed Aug 9 14:01:40 2006 From: yannick.leteigner at gmail.com (Yannick) Date: 9 Aug 2006 11:01:40 -0700 Subject: Python share CPU time? Message-ID: <1155146500.063665.282430@p79g2000cwp.googlegroups.com> Hi, I would like to program a small game in Python, kind of like robocode (http://robocode.sourceforge.net/). Problem is that I would have to share the CPU between all the robots, and thus allocate a time period to each robot. However I couldn't find any way to start a thread (robot), and interrupt it after a given time period. Any suggestions on how to proceed? Is Python just not adapted to this kind of things? Thanks, Yannick From meyer at acm.org Fri Aug 25 09:03:51 2006 From: meyer at acm.org (Andre Meyer) Date: Fri, 25 Aug 2006 15:03:51 +0200 Subject: performance of dictionary lookup vs. object attributes In-Reply-To: References: <7008329d0608250138m3207567elf3e32ee67cb5eb2a@mail.gmail.com> Message-ID: <7008329d0608250603v3b94d321p52f6dc2ac841b796@mail.gmail.com> Good points! It's always good to learn from the pros! So, what it means is that the test is not meaningful, because of the different way that object attributes are accessed (not as o.x, which could be compiled). Nevertheless, the general impression remains that dicts *are* faster than objects, because attribute lookup uses dicts itself. Is that correct? thanks Andre On 8/25/06, Fredrik Lundh wrote: > Andre Meyer wrote: > > > Is the test meaningful and are you surprised by the results? > > surprised by the amount of code you needed to test this, at least. and you > might wish to use the proper spelling for > > v = self.obj.__getattribute__(a) > > which is > > v = getattr(obj, a) > > and is quite a bit faster, at least in CPython. > > (you should also use setattr() instead of __setattr__; in general, if you find your- > self *calling* a method named __method__, there's most likely a better way to > do it). > > > I am, actually, because I would have assumed that attribute access with an > > object should be faster because lookup can be precompiled. > > huh? you're using a reflection API; there's no way the compiler can figure out > in advance what you're going to pass to getattr(). > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Dr. Andre P. Meyer http://python.openspace.nl/meyer TNO Defence, Security and Safety http://www.tno.nl/ Delft Cooperation on Intelligent Systems http://www.decis.nl/ Ah, this is obviously some strange usage of the word 'safe' that I wasn't previously aware of. - Douglas Adams From R.Brodie at rl.ac.uk Tue Aug 8 06:05:27 2006 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Tue, 8 Aug 2006 11:05:27 +0100 Subject: Newbie - How to iterate list or scalar ? References: <1155030787.666942.277610@m79g2000cwm.googlegroups.com> Message-ID: "Andy Dingley" wrote in message news:1155030787.666942.277610 at m79g2000cwm.googlegroups.com... > pluginVersionNeeded is a parameter passed into a method and it can > either be a simple scalar variable, or it can be a list of the same > variables. The obvious question would be, "is there a good reason why you don't change the API to always require a list?" Then you can just write: myFunction( [scalarParameter] ) when you have only one variable. From tenax.raccoon at gmail.com Tue Aug 29 12:27:02 2006 From: tenax.raccoon at gmail.com (Jason) Date: 29 Aug 2006 09:27:02 -0700 Subject: refering to base classes References: <1156862012.068397.284040@m73g2000cwd.googlegroups.com> <44F454D6.5040606@hotmail.com> <44F45603.6050504@hotmail.com> Message-ID: <1156868822.451018.139280@m73g2000cwd.googlegroups.com> Chaz Ginger wrote: > Chaz Ginger wrote: > > glenn wrote: > >> hi - Im quite new to python, wondering if anyone can help me understand > >> something about inheritance here. In this trivial example, how could I > >> modify the voice method of 'dog' to call the base class 'creatures' > >> voice method from with in it? > >> > >> class creature: > >> def __init__(self): > >> self.noise="" > >> def voice(self): > >> return "voice:" + self.noise > >> > >> class dog(creature): > >> def __init__(self): > >> self.noise="bark" > >> > >> def voice(self): > >> print "brace your self:" > > I did forget to mention that in 'dog"s' __init__ you had better call > creature's __init__. You might make it look like this: > > def __init__(self): > self.noise = 'bark' > creature.__init__(self) > There's a problem with Chaz's __init__() method. Notice that the creature class's __init__ sets self.noise to the empty string. In this case, the superclass's __init__() method should be called first: class dog(creature): def __init__(self): creature.__init__(self) self.noise = "bark" def voice(self): print "brace your self:" creature.voice(self) --Jason From bobrien18 at yahoo.com Mon Aug 28 17:59:57 2006 From: bobrien18 at yahoo.com (KraftDiner) Date: 28 Aug 2006 14:59:57 -0700 Subject: get a line of text from a socket... In-Reply-To: References: <1156523827.971633.321830@m79g2000cwm.googlegroups.com> <1156554584.236688.186110@m73g2000cwd.googlegroups.com> Message-ID: <1156802397.120141.309060@m73g2000cwd.googlegroups.com> Bryan Olson wrote: > KraftDiner wrote: > > > Thanks I can't seem to get this example to do anything except sit > > there.... > > http://docs.python.org/lib/asyncore-example.html > > Yeah, the example code, by itself, will just sit there. > As an example, it should probably include the calls to make it > do something. Try adding the following lines to the given code: > > http_client('www.python.org', '/') > asyncore.loop() > > The call: "asyncore.loop()" is what says to stop just sitting > there and do something. > > What makes asyncore.loop exit? > > And still it seems like a lot of work for a simple send/expect script. > > I got the makefile to work.. there is a readline function how does one > > use writelines to write one single line? > > I don't yet have my head around what you are asking. Reading > exactly up to end-of-line from a socket can be a bit tricky, > but I think I can explain. Managing multiple input sources and > their blocking behavior is a basic problem -- so basic that we've > already examined and debated the alternatives. Writing exactly > one line is trivial. > > I found Marc 'BlackJack' Rintsch's response a bit misleading. > The asyncore module offers nothing to read a line. The asynchat > module will respond to lines if you pass set_terminator() the > end-of-line marker. I had to read both the doc and the source > to figure out what should work. > > Sybren Stuvel pointed out socket.makefile(), which will read up > to the end of line, but does not play nice with others. Its > local buffering pretty much breaks select(). If you set any > timeout and the timeout raises, the documented interface does > not provide any way to tell what data was sent and received. > > Jean-Paul Calderone suggested Twisted; it has a lot of fans, and > I'm not competent to say how well it would work in this case. > I've never been willing, nor seen the need, to re-write all code > in Twisted's deferred form. > > > > -- > --Bryan From gherron at islandtraining.com Sat Aug 12 13:05:05 2006 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 12 Aug 2006 10:05:05 -0700 Subject: Recurse Directories and process files in directory In-Reply-To: <1155401214.163465.235830@m79g2000cwm.googlegroups.com> References: <1155401214.163465.235830@m79g2000cwm.googlegroups.com> Message-ID: <44DE0A41.10100@islandtraining.com> KraftDiner wrote: > Hi I need help writing a python script that traverses (recursivly) a > directory and its sub directories and processes all files in the > directory. So at each directory if there are files in it I must build > a list of those files and process them by exectuing a system command > (exec?) > > Can some one tell me what methods to use to: > a) Walk the directory tree > b) execute a system command with parameters. > You're in luck. Both these are easy. os.walk iterates through the hierarchy of directories and their contents os.system executes any command given as a string (which you can build however you want). Or you might use the newer "subprocess" module. Gary Herron > TIA. > > From andre.roberge at gmail.com Tue Aug 15 17:27:23 2006 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 15 Aug 2006 14:27:23 -0700 Subject: programming with Python 3000 in mind In-Reply-To: <1155672987.522793.47080@74g2000cwt.googlegroups.com> References: <1155672987.522793.47080@74g2000cwt.googlegroups.com> Message-ID: <1155677243.626081.188200@i42g2000cwa.googlegroups.com> beliavsky at aol.com wrote: > The current beta version of Python is 2.5 . How can a Python programmer > minimize the number of changes that will be needed to run his code in > Python 3000? In general, he should know what is being removed from > Python 3000 and if possible use the "modern" analogs in Python. A > manager of Python programmers might want external evidence of > portability, though (such as an absence of interpreter warnings). You might want to have a look at PEP-3100 which outlines possible changes. You can also follow the discussion on the python-3000 mailing list. From my reading of this, it looks like there will be relatively few changes. > Some basic syntax such as > > print "hello world" > > is going away to make print look like a function. IMO, fixing what is > not broken because of the aesthetic tastes of the BDFL is a bad idea. > His reasoning is at > http://mail.python.org/pipermail/python-dev/2005-September/056154.html I don`t see his main reasoning as related to aesthetic taste, but rather as one of functionality. As it is, if you use print in your code (very useful for debugging:-), you're stuck with it. If print were a function, you could redefine it at will and very easily, on a module by module basis, perhaps redirecting the output to a file for logging or other reasons as described by GvR. When it comes to *teaching/learning* Python, it makes much more sense to have print() as a function (same with exec) given what it does -compared with the purpose of the other keywords. [I'm not sure I'd do away with input() though...] Finally, even though I disagreed above with the characterisation of this change being related to the "aesthetic tastes of the BDFL", from what I read it appears that his taste is most often bang-on with the consensus from experienced programmers; as just a hobbyist myself, I am constantly amazed at how easy Python code is to read and decipher, compared with other languages. Andr? From no at spam.com Thu Aug 10 01:31:26 2006 From: no at spam.com (Farshid Lashkari) Date: Wed, 09 Aug 2006 22:31:26 -0700 Subject: loop until keypress (Windows XP) In-Reply-To: <1155187164.696015.252920@b28g2000cwb.googlegroups.com> References: <1155187164.696015.252920@b28g2000cwb.googlegroups.com> Message-ID: placid wrote: > is there a way to do this, wait for user input but dont block? Hi, The msvcrt module should do what you want. Here is a sample: import msvcrt chr = 0 while chr != 'q': """ keep printing text """ if msvcrt.kbhit(): chr = msvcrt.getch() Keep in mind that this will only work on windows. -Farshid From justask at acme.com Thu Aug 3 16:54:56 2006 From: justask at acme.com (Vincent Delporte) Date: Thu, 03 Aug 2006 22:54:56 +0200 Subject: [Linux] What toolkit for a good grid/spreadsheet widget? Message-ID: <6fo4d2h0lnq2qcgi8jknh0ddmphhdgaulj@4ax.com> Hello I'd like to use Python under Linux to write a business application, and I'll need a good grid/spreadsheet editable widget, maybe not on par with eg. ComponentOne's excellent VSFlexGrid (http://www.componentone.com/newimages/flexgrid_02_lg.gif), but somewhat professional-grade. Any recommendation? GTK doesn't seem to have one that is good enough (GTKSheet http://gtkextra.sourceforge.net/ looks like a basic table), so I was wondering about QT/PyQt and wxWidgets/wxPython. Any recommendation? Thank you VD. From hitesh287 at gmail.com Mon Aug 7 15:56:25 2006 From: hitesh287 at gmail.com (Hitesh) Date: 7 Aug 2006 12:56:25 -0700 Subject: ST_CTIME convert to yyyymmdd Message-ID: <1154980585.920302.16800@h48g2000cwc.googlegroups.com> Hi, Any hint on converting time from ST_CTIME secs into yyyymmdd format? sorry for one-liner stupid question.. I couldn;t find (or rather figure out) in docs. Thank you, hj From pmartin at snakecard.com Fri Aug 11 21:54:18 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Fri, 11 Aug 2006 20:54:18 -0500 Subject: hide python code ! References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155300852.497741.73230@74g2000cwt.googlegroups.com> <1155301468.870340.82920@b28g2000cwb.googlegroups.com> <1155307415.855555.124760@i3g2000cwc.googlegroups.com> <1155344981.894548.280730@m73g2000cwd.googlegroups.com> Message-ID: Bayazee wrote: > Hi, > ThnaX for Your Answers ... > i am an open source programmer ... ! and i never like to write a closed > source app or hide my codes ! it just a question that i must > answer/solve it! > one of site ( www.python.ir ) users asked this question ! but > unfortunately i have't any solution to it ! so i ask it here to know > your concepts ... > so sorry for my inferior question > but i realy want to know a way to do it(if it possible) ! and it is't > mean that i want to do it ! > Best Regard's Is there such a thing as inferior questions ? only fools do not ask questions, you clearly do not qualify ... heads up !!! Philippe From btowle at carnegielearning.com Wed Aug 9 11:51:19 2006 From: btowle at carnegielearning.com (Brendon Towle) Date: Wed, 9 Aug 2006 11:51:19 -0400 Subject: Eval (was Re: Question about using python as a scripting language) In-Reply-To: <20060809150432.GA15121@kateandchris.net> References: <73BFFFC6-760D-4794-9B5C-AA749287B78A@carnegielearning.com> <20060809150432.GA15121@kateandchris.net> Message-ID: On 9 Aug 2006, at 11:04 AM, Chris Lambacher wrote: > How is your data stored? (site was not loading for me). In the original source HTML, it's like this (I've deleted all but the beginning and the end of the list for clarity): var table_body = [ ["ATVI", "Activision, Inc.",12.75,0.150000,1.19,2013762,0.04,"N","N"] ,["YHOO", "Yahoo! Inc.",27.7,0.260000,0.95,6348884,0.21,"N","N"] ]; > More sophisiticated situations (like nested lists) may require > something like pyparsing. I could do that, or I could do something like the re.* trick mentioned by another poster. But, doesn't it offend anyone else that the only clean way to access functionality that's already in Python is to write long complicated Python code? Python already knows how to extract a list object from a string; why should I have to rewrite that? B. > On Wed, Aug 09, 2006 at 10:23:49AM -0400, Brendon Towle wrote: >> Slawomir Nowaczyk noted: >> >> #> Heck, whenever *is* it OK to use eval() then? >> eval is like optimisation. There are two rules: >> Rule 1: Do not use it. >> Rule 2 (for experts only): Do not use it (yet). >> >> So, that brings up a question I have. I have some code that >> goes out to a >> website, grabs stock data, and sends out some reports based on >> the data. >> Turns out that the website in question stores its data in the >> format of a >> Python list ([1]http://quotes.nasdaq.com/quote.dll? >> page=nasdaq100, search >> the source for "var table_body"). So, the part of my code that >> extracts >> the data looks something like this: >> START_MARKER = 'var table_body = ' >> END_MARKER = '];' >> def extractStockData(data): >> pos1 = data.find(START_MARKER) >> pos2 = data.find(END_MARKER, pos1) >> return eval(data[pos1+len(START_MARKER):END_MARKER]) >> (I may have an off-by-one error in there somewhere -- this is >> from memory, >> and the code actually works.) >> My question is: what's the safe way to do this? >> B. >> -- >> Brendon Towle, PhD >> Cognitive Scientist >> +1-412-690-2442x127 >> Carnegie Learning, Inc. >> The Cognitive Tutor Company ? >> Helping over 375,000 students in 1000 school districts succeed >> in math. >> >> References >> >> Visible links >> 1. http://quotes.nasdaq.com/quote.dll?page=nasdaq100 > >> -- >> http://mail.python.org/mailman/listinfo/python-list -- Brendon Towle, PhD Cognitive Scientist +1-412-690-2442x127 Carnegie Learning, Inc. The Cognitive Tutor Company ? Helping over 375,000 students in 1000 school districts succeed in math. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rogue_pedro at yahoo.com Thu Aug 10 14:30:19 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 10 Aug 2006 11:30:19 -0700 Subject: String Formatting References: <1155213326.679334.234880@i42g2000cwa.googlegroups.com> Message-ID: <1155234619.479611.201980@h48g2000cwc.googlegroups.com> OriginalBrownster wrote: > Hi there: > > I was wondering if its at all possible to search through a string for a > specific character. > > I want to search through a string backwords and find the last > period/comma, then take everything after that period/comma > > Example > > If i had a list: bread, butter, milk > > I want to just take that last entry of milk. However the need for it > arises from something more complicated. > > Any help would be appreciated The rfind() method of strings will search through a string for the first occurance of a substring, starting from the end. (find() starts from the beginning.) |>> s = "bread, butter, milk" |>> s.rfind(',') 13 |>> s.rfind('!') -1 |>> s[s.rfind(',') + 1:] ' milk' If you want to find either a period or comma you could do it like this: |>> i = max(s.rfind(ch) for ch in ',.') |>> i 13 |>> s[i + 1:] ' milk' Here's the output of help(s.rfind): Help on built-in function rfind: rfind(...) S.rfind(sub [,start [,end]]) -> int Return the highest index in S where substring sub is found, such that sub is contained within s[start,end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. Enjoy Peace, ~Simon From naytie at yahoo.com Thu Aug 17 10:22:44 2006 From: naytie at yahoo.com (Naytie) Date: 17 Aug 2006 07:22:44 -0700 Subject: py2exe and COM problem Message-ID: <1155824563.971275.212100@m73g2000cwd.googlegroups.com> I seem to have a problem with a generated .exe file made with py2exe. I wrote a python program that creates tables in a Word document and adjusts the size of the tables and then inputs text into each cell using COM. Everything works well and I do not get errors using Boa constructor. However when I run the .exe file I get an error: File ">", line 3, in SetWidth pywintypes.com_error: (-2147352561, 'Parameter not optional.', None, None) which is a reference to w.Selection.Tables(1).Columns(1).SetWidth(ColumnWidth=35) w is an object created with win32 com w = win32com.client.Dispatch('Word.Application') I am assuming the 'Parameter not optional' may be saying that I cannot change the width. This is the correct code that I took from VB. Can anyone help? I am using Python 2.4 and MS Word 2000. From bearophileHUGS at lycos.com Wed Aug 30 10:39:27 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 30 Aug 2006 07:39:27 -0700 Subject: where or filter on list In-Reply-To: References: <1156939493.558819.8410@i42g2000cwa.googlegroups.com> Message-ID: <1156948767.596855.270000@i42g2000cwa.googlegroups.com> Duncan Booth: > And for Python 2.5 users only we have the exciting new option of: > >>> foo = [5, 2, -1, -7, 3, -6, 2, 12] > >>> min(foo, key=abs) > -1 Good. This is possibility for older Python: l = [(rnd()-0.5) * 20 for i in xrange(1000)] print min( (abs(el), el) for el in l )[1] Bye, bearophile From jarausch at skynet.be Fri Aug 11 10:06:51 2006 From: jarausch at skynet.be (Helmut Jarausch) Date: Fri, 11 Aug 2006 16:06:51 +0200 Subject: hide python code ! In-Reply-To: <1155253821.570487.165400@b28g2000cwb.googlegroups.com> References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155253821.570487.165400@b28g2000cwb.googlegroups.com> Message-ID: <44dc8efb$0$5523$ba620e4c@news.skynet.be> John Machin wrote: > Bayazee wrote: >> hi >> can we hide a python code ? >> if i want to write a commercial software can i hide my source code from > ^^^^^^^^^^^^^^^^^^^^^^^^[1] >> users access ? >> we can conver it to pyc but this file can decompiled ... so ...!! >> do you have any idea about this ...? >> >> --------------------------------------- >> First Iranian Open Source Community : www.python.ir > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^[2] > > > [1] and [2] don't seem to be compatible. I suppose all of you who have commented about this, are sitting in the >>> free world <<< . But there are countries (like .ir) where the government has totally different ideas of 'freedom'. So taking the freedom to write something can be very dangerous at times. Fortunately most of those guys which intercept every email and check every web server are not so smart to reverse engineer everything in a short time since they have to check thousands of pieces of information each day. Let's make their work a bit harder! From carsten at uniqsys.com Tue Aug 1 09:11:22 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 01 Aug 2006 09:11:22 -0400 Subject: Can't get LCHARVAR's with InformixDB In-Reply-To: <1154437329.471918.35150@h48g2000cwc.googlegroups.com> References: <1154437329.471918.35150@h48g2000cwc.googlegroups.com> Message-ID: <1154437882.452.21.camel@dot.uniqsys.com> On Tue, 2006-08-01 at 09:02, fhurley at gmail.com wrote: > I'm using the InformixDB package, which has been a real lifesaver, but > I'm finding I can't get any data from the Informix LCHARVAR types. > They're coming in as empty strings. > > The cursor._description for the field in question is: > ('msg_text', 'lvarchar', 0, 0, None, None, 1) > > Appreciate any help... thanks. What version are you using? I thought I fixed lvarchars a long time ago. -Carsten From anthra.norell at tiscalinet.ch Thu Aug 31 17:02:53 2006 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Thu, 31 Aug 2006 23:02:53 +0200 Subject: Searching a string and extract all occurancies of a substring References: <44F703C8.3080504@gmail.com> Message-ID: <014801c6cd40$d3cf0a40$0201a8c0@mcuf7> Nico, perhaps this would be suitable: >>> s = '''Example text: This is a test. A test. /www/mydoc1 And I need to extraxt /www/mydoc1 and /www/mydoc2 from this text. /foo/bar/doc ...''' >>> import SE >>> Thing_Filter = SE.SE (' "~(.|\n)*?~==" | "~<.*?>~= " ') >>> print Thing_Filter (s).split () ['/www/mydoc1', '/foo/bar/doc'] If you expect more than one of these sections and need a list of records, it would take no more than an additional split. You'd find SE here: http://cheeseshop.python.org/pypi/SE/2.2%20beta Regards Frederic ----- Original Message ----- From: "Nico Grubert" To: Sent: Thursday, August 31, 2006 5:44 PM Subject: Searching a string and extract all occurancies of a substring > Hi there, > > in a text with no carriage returns I need to look for all occurancies of > this string: > > ... > etc. From g.brandl-nospam at gmx.net Sun Aug 6 15:22:51 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Sun, 06 Aug 2006 21:22:51 +0200 Subject: Ann: SE 2.2b In-Reply-To: References: <01d101c6b86a$fb7aa1c0$0201a8c0@mcuf7> Message-ID: skip at pobox.com wrote: > Frederic> In the short period of time since I introduced SE. the > Frederic> feedback has been overwhelmingly postive. > > Ummm... what is it? The last SE I had was a Mac. It is supposed to be a Stream Editor (in the spirit of sed, I think). However, the PyPI page provides no download or homepage links. Georg From paolopantaleo at gmail.com Mon Aug 14 14:07:21 2006 From: paolopantaleo at gmail.com (Paolo Pantaleo) Date: Mon, 14 Aug 2006 20:07:21 +0200 Subject: p-gal: photo gallery generator with templating support In-Reply-To: <1155575797.856782.26370@p79g2000cwp.googlegroups.com> References: <7xk65buyf9.fsf@ruckus.brouhaha.com> <1155575797.856782.26370@p79g2000cwp.googlegroups.com> Message-ID: <83e8215e0608141107n5770126bn49f9524dc73b975a@mail.gmail.com> 14 Aug 2006 10:16:37 -0700, ajaksu : > Paolo Pantaleo wrote: > > www.sf.net/projects/ppgal > > Ciao Paolo! > > The homepage (http://paolopan.freehostia.com/p-gal/ ) looks weird in my > SeaMonkey 1.0.4, contents appear below GoogleAds instead of at the > right. Well... I designed the site for Firefox... anyway I used CSS float directives and no tables. I don't know if I made something wrong, or if it is a [not so unlikely] standard compliance problem. Well Firefox too has some problems with floats. I copied the layout from http://www.topolinux.org/ - can you see this properly? -- if you have a minute to spend please visit my photogrphy site: http://mypic.co.nr From larry.bates at websafe.com Thu Aug 24 19:15:30 2006 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 24 Aug 2006 18:15:30 -0500 Subject: Python editor In-Reply-To: References: Message-ID: <44EE3312.8040707@websafe.com> Jason Jiang wrote: > Hi, > > Could someone recommend a good Python editor? Thanks. > > Jason > > > For just getting started use Idle that comes with Python. If you are already a user or if you are looking for a more powerful solution you can use Eclipse (with Python plug-in). These represent both ends of the spectrum in editors. -Larry Bates From david_wahler at bic.ky Mon Aug 14 09:43:57 2006 From: david_wahler at bic.ky (david_wahler at bic.ky) Date: 14 Aug 2006 08:43:57 -0500 Subject: =?utf-8?Q?Re:_Early_Bird_Registration_closes_Tuesday_=2D_Leipzig_Python=0A__Workshop?= Message-ID: <20060814134357.22654.qmail@BICSRV1011.bic.ky> I'll be out of the office until approximately August 20th. If you have any questions, please email support at bic.ky. -- David Wahler From jyoti.chhabra at gmail.com Mon Aug 21 04:00:07 2006 From: jyoti.chhabra at gmail.com (JyotiC) Date: 21 Aug 2006 01:00:07 -0700 Subject: tkinter prob In-Reply-To: References: <1156140461.170856.136180@74g2000cwt.googlegroups.com> <1156143029.771346.22580@74g2000cwt.googlegroups.com> Message-ID: <1156147207.043042.308250@h48g2000cwc.googlegroups.com> thanx got the error, but there is one more prob, button is not coming to enable again. once it is disabled the error it's giving is:- Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.3/lib-tk/Tkinter.py", line 1345, in __call__ return self.func(*args) File "", line 23, in com NameError: global name 'ENABLED' is not defined Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.3/lib-tk/Tkinter.py", line 1345, in __call__ return self.func(*args) File "", line 23, in com NameError: global name 'ENABLED' is not defined is ENABLED valid option? Eric Brunel wrote: > On Mon, 21 Aug 2006 08:50:29 +0200, JyotiC wrote: > > > i have tried it out but it's not working. > > this is the code > > > > from Tkinter import * > > > > class abc: > > def __init__(self,parent): > > #make container myparent > > self.myparent=parent > > self.myparent.geometry("500x200") > > > > #make the initial frame > > self.frame=Frame(self.myparent) > > self.frame.pack() > > > > self.var=IntVar() > > self.var.set(0) > > > > a=Button(self.frame,text="button") > > a.pack() > > > > > > Checkbutton(self.frame,text="hello",variable=self.var,command=self.com(a)).pack() > > This *calls* self.com(a) and assigns its *results* (which happens to be > None) to the command option in your button. So your button does nothing. > > To do what you want, use: > > self.a = Button(self.frame,text="button") > self.a.pack() > Checkbutton(self.frame,text="hello",variable=self.var,command=self.com).pack() > > in __init__, then: > > def com(self): > if self.var.get()==1: > self.a.config(state=ENABLED) > else: > self.a.config(state=DISABLED) > > HTH > -- > python -c "print ''.join([chr(154 - ord(c)) for c in > 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From apardon at forel.vub.ac.be Fri Aug 4 13:41:57 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Aug 2006 17:41:57 GMT Subject: Python open a named pipe == hanging? References: <1hjic95.ojxkeuodeqbtN%aleax@mac.com> Message-ID: On 2006-08-04, Rochester wrote: > Thank you for your advise. So, it turns out that fifos are quite useless > in Python programming then, which is quite disappointing to me :-( > > I am not saying that I _have to_ use fifo, afterall it is a rather odd > thingy not in fasion since the last iceage... I am just disappointed by > the fact that the old plain Bash seems to excel Python in this special > aspect. It doesn't. > I am new to Python and much more comfortable in Bash programming. A > simple Bash script like this would take the advantage of a fifo, hence > reduce the overhead of unneccesarry temporary files creation: > > #!/bin/bash > > mkfifo my_fifo > echo "this is a string in my fifo!" > my_fifo & > cat my_fifo > rm my_fifo > > Isn't it neat? Look you put the echo in the background, because otherwise your script would block. Nothing stops you from starting a thread in python to open the fifo in write mode, the thread would block but the main program could still continue. There also is the os.pipe and os.popen calls that may be more usefull in specific cases. -- Antoon Pardon From rdrink at artic.edu Sun Aug 27 23:32:34 2006 From: rdrink at artic.edu (rdrink) Date: 27 Aug 2006 20:32:34 -0700 Subject: eval() woes Message-ID: <1156735954.796051.290600@i3g2000cwc.googlegroups.com> n.n.h. (noob needs help) Ok, I've been beating my head against this for a day... time to ask others. To explain things as simply as possible: I am trying to use eval() to evaluate some simple equations, such as-- pow(AB,2) pow(AB,2)+A pow(A+B,2) pow(A+B,2)+A and so forth... for a variety of math operations (+,-,*) and a variety of variables, all of which have been genrated by a script, written to a .txt file., then recalled sequentially and passed to eval(). The variables (A,B,C,D) are generated elsewhere [Note: AB is a concat, e.g. A=2,B=7,AB=27] , so both are passed into a function e.g. def (equation, list): A=list[0] B=list[1] ...etc. return eval(str(equation)) Where 'equation' is one of the above, selected from the "equations file" So here's the rub: With the above examples everything works fine... up to the last (pow(A+B,2)+A), then it bombs with: ValueError: invalid literal for int(): - And I have tried 'hard typing' the vars e.g. A=str(list[0]) and A=int(str(list[0]))... which only leads to it breaking in the other expressions. I have also tried 'compile()', which bombs the same way, and have also looked at 'pickle' (but I don't think I really need to go that far)... All of which leaves me wondering... Could it simply be that eval() can't handle the progressive order of math operations? Because pow(AB,2) + A works, as does pow(A+B,2)... but then adding pow(A+B,2)+A (the result, *plus* A) doesn't? Or is the problem deeper (like at the dictionary level)? Either way I'm stumped, and could use some help. Thanks Robb Drinkwater From jmpurser at gmail.com Wed Aug 30 12:57:37 2006 From: jmpurser at gmail.com (John Purser) Date: Wed, 30 Aug 2006 09:57:37 -0700 Subject: wait for keystoke In-Reply-To: <9583ed900608300945v1be53e8bice91f4fde9c3f71@mail.gmail.com> References: <9583ed900608300945v1be53e8bice91f4fde9c3f71@mail.gmail.com> Message-ID: <20060830095737.8bde4173.jmpurser@gmail.com> On Wed, 30 Aug 2006 12:45:41 -0400 "david brochu jr" wrote: > I want to add a "press any key to continue" option to my script, > where the script pauses until the users presses any key. Does anyone > know how I would do this without having to add in an if statement in > the middle of my existing script? Is there a method already to > accomplish this? > David, Take a look at input() and raw_input(). John Purser From gelists at gmail.com Wed Aug 2 09:46:15 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Wed, 2 Aug 2006 10:46:15 -0300 Subject: Using Python for my web site References: <1154361480.915174.262720@b28g2000cwb.googlegroups.com> <44ce3a5c$0$18952$626a54ce@news.free.fr> <1154367359.931684.106650@m73g2000cwd.googlegroups.com> <44ce4530$0$28242$626a54ce@news.free.fr> Message-ID: <19zmaoel1tn3$.dlg@gelists.gmail.com> On 2006-08-02 00:51:28, Conrad wrote: > Which begins "A few years ago" Exactly. Isn't this a good start for honesty? It doesn't claim to state anything up to date. It continues "I did some research", "some" being a very clear indicator that I didn't consider this a thorough research. From the stated results of this research it should be clear to any reasonable reader what kind of research that was. "Claimed to have", "seemed to have" are not really expressions that try to claim more than they are. What does it mean to you when someone says "reports seemed to have been"? Is that what you call "extensive (and well documented) research"? If so, your standards don't really seem to be what you seem to say they are. > It appears that Bruno and Sybren did the same, no? No. Neither Bruno nor Sybren got defensive or resorted to sarcasm. > Perhaps we could get a referal for all of us to an optician for group > rates? Or for a few therapy sessions. There's no need to get defensive, just because someone spent a day a few years ago reading documentation, searching the web and newsgroups for experiences that people have with both databases (like you and Cliff), got at that time the impression that what those people reported (anecdotically -- that's all one can get without tons of time and money to spend) was what I wrote it was, and stated this. I did not overstate any of that, nor did I make it less subjective than it was. So what's your problem? Why the sarcasm? "A blog posting by some kid who's been serving up pictures of his sister's kitties with MySQL" -- again the same sarcasm. Having a bad week? > Here's my issue - someone, who according to my defective newsreader and > clearly myopic eyes appeared to be you, once again invoked the word > research. Not only research, but results. I've done research. Read the context. I didn't use the "r" word without context. You may not like the word in that (very "light") context, but that's a personal issue, and I couldn't really foresee it. The context was pretty clear, at least for someone with a minimum of goodwill, wasn't it? > I haven't seen any significant research on PosgreSQL vs. MySQL in an > apples-to-apples, detached, no-axes-to-grind study. Neither have I. I would have been glad to read it, at the time I needed to decide between the two. So yes, it's all anectodical "evidence" (or is that also too strong a word?). Hunting for that is the only form of research someone like me (not a database admin, but in the need of selecting databases for projects) can afford. I thought that was kind of understood. BTW, compared to a lot of "research" that has the only function of providing a paper to further the career of someone and "prove" some preconceived notions, my (admittedly very light) research was done with honesty, without predisposition towards any results and with the desire to actually get results. I just spent on it what I could afford. That may not be enough for everybody else's standards, but that's how I (and many others) need to operate. Maybe I could have used a more appropriate word. I just don't know one; "research" was the closest I came up with. Gerhard From fredrik at pythonware.com Tue Aug 29 08:53:05 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 29 Aug 2006 14:53:05 +0200 Subject: Extending the dict class References: <1156852916.254032.172390@b28g2000cwb.googlegroups.com><44f4313e$0$26985$626a54ce@news.free.fr> <1156854958.228815.107090@m73g2000cwd.googlegroups.com> Message-ID: "chosechu" wrote: > Yes, if I could simply modify myfunc() I would have workarounds. > This would mean me modifying SOAPpy and specializing it for > my needs. maybe you could fake it: class fakedict(dict): def __init__(self, *data): self.data = list(data) for k, v in data: self[k] = v def items(self): return self.data d = fakedict(("a", 1), ("b", 2), ("c", 3)) print d => {'a': 1, 'c': 3, 'b': 2} print d.items() => [('a', 1), ('b', 2), ('c', 3)] print isinstance(d, dict) => True (the exact set of methods you need to override depends on how SOAPpy fetches the members). From fredrik at pythonware.com Mon Aug 21 10:38:40 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Aug 2006 16:38:40 +0200 Subject: How to decode a string In-Reply-To: <1156170296.076521.174180@i3g2000cwc.googlegroups.com> References: <1156170296.076521.174180@i3g2000cwc.googlegroups.com> Message-ID: Lad wrote: > To be able to decode a string successfully, I need to know what coding > it is in. ask whoever provided the string. > The string can be coded in utf8 or in windows-1250 or in another > coding. Is there a method how to find out the string coding. in general, no. if you have enough text, you may guess, but the right approach for that depends on the application. From enigmadude at rock.com Wed Aug 9 14:41:06 2006 From: enigmadude at rock.com (enigmadude at rock.com) Date: 9 Aug 2006 11:41:06 -0700 Subject: Python share CPU time? In-Reply-To: <1155146500.063665.282430@p79g2000cwp.googlegroups.com> References: <1155146500.063665.282430@p79g2000cwp.googlegroups.com> Message-ID: <1155148866.492008.66090@h48g2000cwc.googlegroups.com> There's several ways of doing concurrency in Python. Other than the threading module, have you tried FibraNet? It's designed with simple games in mind. You can download it at http://cheeseshop.python.org/pypi/FibraNet. Specifically the nanothreads module from FibraNet uses generators to simulate light-weight cooperative threads. Generator-based approaches are fast and *deterministic*, unlike true threads where you have to account for race conditions, etc. You can pause, resume, kill, or end a "thread". In Python 2.5 (soon to be released), generators will be consumers rather than just producers, so you can pass things into generators (without needing global variables as a workaround) rather than only being able to spit out data on-the-fly. They'll also have a more graceful way to handle exceptions. For a good overview of the concept, especially if you want to implement this yourself instead of using Fibranet (although re-use is often the better choice), take a look at this link from the Charming Python column: http://gnosis.cx/publish/programming/charming_python_b7.html. If this all seems too exotic, then you can also just go with the traditional threading approach with the threading module. Normally you'll want to use the "threading" module rather than the lower-level "thread" module. But be warned, threads are a big can of worms. I hope you find this useful. Yannick wrote: > Hi, > > I would like to program a small game in Python, kind of like robocode > (http://robocode.sourceforge.net/). > Problem is that I would have to share the CPU between all the robots, > and thus allocate a time period to each robot. However I couldn't find > any way to start a thread (robot), and interrupt it after a given time > period. > Any suggestions on how to proceed? > Is Python just not adapted to this kind of things? > > Thanks, > Yannick From bj_666 at gmx.net Mon Aug 21 04:40:59 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 21 Aug 2006 10:40:59 +0200 Subject: Questions on exceptions References: <1156146013.939619.102570@i3g2000cwc.googlegroups.com> Message-ID: In <1156146013.939619.102570 at i3g2000cwc.googlegroups.com>, sc_wizard29 wrote: > Also, can someone explain me why there is no try...except...finally > statement ? AFAIK historical reasons. There where some concerns about ambiguity. But in Python 2.5 this form will become legal syntax. > For example, the following code snippet is not valid, but > what would be the correct python way to do it ? > > myFile = open('file.txt') # assume file exists > try: > for nextLine in file: > nextLine = nextLine.rstrip('\n');print "line = " + nextLine > except IOError: > print "Error while reading from file" > finally: > myFile.close You forgot the parenthesis for the `close()` method. In Python <=2.4 you have to nest: try: try: pass except Error: pass finally: pass Maybe you are interested in the new (Python 2.5) ``with`` statement too: http://docs.python.org/dev/ref/with.html And the style guide: http://www.python.org/dev/peps/pep-0008/ (because you used Java naming conventions) Ciao, Marc 'BlackJack' Rintsch From sumesh.chopra at gmail.com Fri Aug 25 19:09:06 2006 From: sumesh.chopra at gmail.com (unexpected) Date: 25 Aug 2006 16:09:06 -0700 Subject: Avoiding if..elsif statements In-Reply-To: References: <1156545375.962486.49540@h48g2000cwc.googlegroups.com> Message-ID: <1156547346.647480.187910@b28g2000cwb.googlegroups.com> the missing () was the trick! However, I'm passing in a few variables, so I can't just take it out-though every single function would be passing the same variables. so something.func() is actually something.func(string, list) How would I modify it to include them? Sorry I didn't include them the first time, I was trying to simplify it to make it easier...oops! Fredrik Lundh wrote: > "unexpected" wrote: > > > I have a program where based on a specific value from a dictionary, I > > call a different function. Currently, I've implemented a bunch of > > if..elsif statements to do this, but it's gotten to be over 30 right > > now and has gotten rather tedious. Is there a more efficient way to do > > this? > > > > Code: > > > > value = self.dictionary.get(keyword)[0] > > > > if value == "something": > > somethingClass.func() > > elsif value == "somethingElse": > > somethingElseClass.func() > > elsif value == "anotherthing": > > anotherthingClass.func() > > elsif value == "yetanotherthing": > > yetanotherthingClass.func() > > > > Is it possible to store these function calls in a dictionary so that I > > could just call the dictionary value? > > but of course (did you try it?). here's an outline: > > dispatch = { > "something": somethingClass.func, # note: no () here > "somethingElse": somethingElseClass.func, > "anotherthing": anotherthingClass.func, > "yetanotherthing": yetanotherthingClass.func, > } > > ... > > dispatch[value]() # note: do the call here! > > or, a bit more robust: > > try: > func = dispatch[value] > except KeyError: > print "- no handler for", value > else: > func() > > tweak as necessary. > > From rogue_pedro at yahoo.com Tue Aug 29 20:48:01 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 29 Aug 2006 17:48:01 -0700 Subject: subprocess woes In-Reply-To: References: Message-ID: <1156898881.144652.69260@m73g2000cwd.googlegroups.com> Dennis Lee Bieber wrote: > On Tue, 29 Aug 2006 18:17:47 +0530, km > declaimed the following in comp.lang.python: > > > ######code start ###### > > import subprocess as sp > > x = 'GSQIPSHYWKKNLWYYSHEIDGGCHNMW' > > p0 = sp.Popen(["echo",x], stdout=sp.PIPE) > > Why use this at all? > > > p1 = sp.Popen(["fasta34","-q","@",s],stdin=p0.stdout, stdout=sp.PIPE) > > output = p1.communicate()[0] > > Just feed "x" to this directly... (untested): > > p1 = sp.Popen(["fasta34","-q","@",s],stdin=sp.PIPE, stdout=sp.PIPE) > output = p1.communicate(x)[0] > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com wulfraed at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-asst at bestiaria.com) > HTTP://www.bestiaria.com/ You can also pass data to a subprocess like this: p1 = sp.Popen(["fasta34","-q","@",s],stdin=sp.PIPE, stdout=sp.PIPE) p1.stdin.write(x) p1.stdin.close() But I think communicate() would be better for you in this case. Peace, ~Simon From rogue_pedro at yahoo.com Fri Aug 25 01:09:07 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 24 Aug 2006 22:09:07 -0700 Subject: RE Module References: <1156478366.165463.277480@h48g2000cwc.googlegroups.com> Message-ID: <1156482547.386190.89790@74g2000cwt.googlegroups.com> Roman wrote: > I am trying to filter a column in a list of all html tags. What? > To do that, I have setup the following statement. > > row[0] = re.sub(r'<.*?>', '', row[0]) > > The results I get are sporatic. Sometimes two tags are removed. > Sometimes 1 tag is removed. Sometimes no tags are removed. Could > somebody tell me where have I gone wrong here? > > Thanks in advance I'm no re expert, so I won't try to advise you on your re, but it might help those who are if you gave examples of your input and output data. What results are you getting for what input strings. Also, if you're just trying to strip html markup to get plain text from a file, "w3m -dump some.html" works great. ;-) HTH, ~Simon From kay.schluehr at gmx.net Wed Aug 16 01:41:48 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 15 Aug 2006 22:41:48 -0700 Subject: programming with Python 3000 in mind In-Reply-To: References: <1155672987.522793.47080@74g2000cwt.googlegroups.com> Message-ID: <1155706908.340544.92920@i42g2000cwa.googlegroups.com> Fredrik Lundh wrote: > beliavsky at aol.com wrote: > > > The current beta version of Python is 2.5 . How can a Python programmer > > minimize the number of changes that will be needed to run his code in > > Python 3000? > > by ignoring it, until it exists. > > And why not ignoring it, when it comes to exist? From sjmachin at lexicon.net Fri Aug 4 17:55:34 2006 From: sjmachin at lexicon.net (John Machin) Date: 4 Aug 2006 14:55:34 -0700 Subject: regex question References: <1983a3190608031410n71eaa4d1s2a3db7c10c519b88@mail.gmail.com> Message-ID: <1154728534.277367.157560@p79g2000cwp.googlegroups.com> Slawomir Nowaczyk wrote: > On Thu, 03 Aug 2006 22:10:55 +0100 > Gabriel Murray wrote: > > #> Hello, I'm looking for a regular expression .... > > Some people, when confronted with a problem, think "I know, I'll > use regular expressions." Now they have two problems. > -- Jamie Zawinski > > Therefore: > > def test(data): > format, index = 'abcd', 0 > for c in data: > i = format.index(c) > if i > index+1: > return False > index = i > return index==format.index('d') > > Could be made faster if format was made a dictionary or if one wanted > to compare characters directly. Writing (and profiling) left as an > exercise for a reader. Premature optimisation .... #>>> test('bcd') True #>>> Here's an implementation using a general purpose graph path checking "algorithm" (it's not really so fancy as to be called that). 8<--- from string import ascii_lowercase as alphabet def build_maze(size): possible = {} for i in range(size): c = alphabet[i] possible[c] = set(alphabet[:min(i+2, size)]) return possible, set(alphabet[0]), set(alphabet[size-1]) def valid_path(graph, entries, exits, path): """ Check a proposed path through a maze. 'graph' is a mapping {node: set of allowable next nodes}. 'entries' is a set of valid start nodes. 'exits' is a set of valid exit nodes. 'path' is an iterable which produces nodes. A node label can be any hashable, even None. Returns True if 'path' is valid. """ choices = entries pathlen = 0 for node in path: pathlen += 1 if node not in choices: return False if node not in graph: return False # aliter: raise ValueError("Node %r not in graph" % node) choices = graph[node] return pathlen and node in exits tests = [ ('abcd', True), ('aaaaaaaaaaabbbbbccc', False), ('aabbccaabbccabcdddcabababbbccccdddd', True), ('aabbccaabbccabcabababbbccccddddabcd', True), ('aaaaabbbbbccccaaaaadddd', False), ('aabbccaabbccacabababbbccccdddd', False), ('abccccdaaaabbbbccccd', True), ('abcdcd', True), ('aabbbaabbcccbbbcccddd', True), ('aabbccaabbccabcabababbbccccdddd', True), ('abccccdccccd', True), ('aabcabcd', True), ('bcd', False), ('abc', False), ('', False), ('a', False), ('d', False), ] def checkit(maze, tests=tests): for test, expected in tests: gr, inset, outset = maze matched = valid_path(gr, inset, outset, test) if matched == expected: print "PASSED: %s with %s" % (test, expected) else: print "FAILED: %s with %s" % (test, expected) maze4 = build_maze(4) print maze4 checkit(maze4) 8<--- Cheers, John From sluggoster at gmail.com Fri Aug 18 14:55:30 2006 From: sluggoster at gmail.com (Mike Orr) Date: 18 Aug 2006 11:55:30 -0700 Subject: The decentralized nature of the Python community is driving me crazy References: <1155157572.915538.280350@i3g2000cwc.googlegroups.com> Message-ID: <1155927330.500632.150340@p79g2000cwp.googlegroups.com> metaperl.bzr at gmail.com wrote: > hi everyone, > > I am the first of what may be hundreds of refugees from the Perl > community. Not only is Python a more productive language, with many > more nice apps, but the people are friendly as well... waaay more > friendly than the Perl crowd. > > But I must say the one thing I miss about Perl is my ability to stay on > top of all the latest modules and apps in one place: CPAN. With Python, > code is EVERYWHERE - people's local boxes, sourceforge, freshmeat, > codezoo, parnassus, etc, etc. Different approaches to documentation. A > much nicer install utility (python setup.py install r0x). But I am > finding it hard to keep on top and browse all the wares that are out > there because they are literally all over the net! > > And then you have discussion and yet again, there is no perlmonks.org > for Python. We have this, IRC, and what else? > > So, I guess this is my way of letting you know how lost I feel about > this de-centralized community. Dont get me wrong. I'm glad to be part > but I was thinking it would be nice if there were a one-stop-shop for > all my chat and wares needs. But for now, I guess I need to just add > few more bookmarks to main places to keep on top of daily besides > pythonware.com/daily. Hi Metaperl, glad you're enjoying our language. :) I left Perl in the mid 90s and came to Python after a year with Java. So I don't know what perlmonks.org is. The lack of a CPAN equivalent has been a persistent lament of Pythoneers over the years, and there have been several attempts to build a Python one or a multilingual one. The Cheeseshop and easy_install are the most successful attempts. There's a project aimed at integrating easy_install into Python itself, but with the technical and compatibility issues it will take several months. More and more packages are being listed in the Cheeseshop. If there's anything of importance that's *not* listed there (and I can't think of anything), you would do well to prod the owners to get with the program. You can pretty much ignore Parnassus and Freshmeat etc unless you have a fondness for old software that will never be in the Cheeseshop. comp.lang.python is where most of the discussion takes place, and the best place to ask questions. It's so big I read it the weekly Python-URL summary instead, which is how I found your message. I've never read the daily Python-URL much, but it looks like a good place if you want more "input" [Number 5 voice; "Short Circuit" movie]. Other good sources of information are local users' groups and conferences. I attend PyCon every year, and find that something always happens somehow that sets my direction for the year. Some really good idea you collaborate on at the conference, then work on during the next several months. If you're plugged into users' groups, I don't see a real need to have lots of bookmarks to read every day. There are a ton of Python books now too that might be helpful. There are also some good articles on O'Reilly's OnLamp (http://www.onlamp.com/python/) by several Python bigwigs, including Cameron Laird who founded the Python-URL. Plus there's Guido's blog of course (http://www.artima.com/weblogs/index.jsp?blogger=guido). As for "different approaches to documentation", that's something the Python community has not come to any consensus on. There are tools that convert docstrings into documentation, and tools that run tests embedded in docstrings, and these impose a syntax on the docstrings, but in each area there are multiple programs and it's too soon to say which approach will win out. But they are gradually converging. --Mike From pythonnews at nospam.jmbc.fr Fri Aug 18 03:32:25 2006 From: pythonnews at nospam.jmbc.fr (jean-michel bain-cornu) Date: Fri, 18 Aug 2006 09:32:25 +0200 Subject: wxPython Grid Question In-Reply-To: <1155822107.651813.192860@74g2000cwt.googlegroups.com> References: <1155788722.147173.58730@m73g2000cwd.googlegroups.com> <1155822107.651813.192860@74g2000cwt.googlegroups.com> Message-ID: <44e56da2$0$21143$7a628cd7@news.club-internet.fr> >> I'm wonderg if there is a way to make a subclass of wx.grid.Grid in >> which the coloumn labels for the grid appear on the bottom of the grid >> instead of the top. > > follow that lead. But jean-michel has two good points: it could be > easier to use 2 grids and http://wxpython.org/maillist.php would give > you better answers :) After a while, I think in the case where you'd want to use 2 grids, it could be tricky to reproduce scrollings and events across the two grids... and there are probably other inconvenients, particularly if you include it in sizers. Its probably not a so much good point. rgds jm From tim.leeuwvander at nl.unisys.com Mon Aug 21 08:58:21 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 21 Aug 2006 05:58:21 -0700 Subject: Python and STL efficiency In-Reply-To: <1156162237.274636.17850@i3g2000cwc.googlegroups.com> References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <1156162237.274636.17850@i3g2000cwc.googlegroups.com> Message-ID: <1156165101.702758.148420@74g2000cwt.googlegroups.com> Ray wrote: > Fredrik Lundh wrote: > > in the Python example, the four strings in your example are shared, so > > you're basically copying 40000 pointers to the list. > > > > in the C++ example, you're creating 40000 string objects. > > > > > > In which case, Licheng, you should try using the /GF switch. This will > tell Microsoft C++ compiler to pool identical string literals together. > > > :) The code still creates a new string - instance each time it tries to append a const char* to the vector ... You should instead create the string-objects ahead of time, outside of the loop. Regards, --Tim From gelists at gmail.com Sat Aug 5 06:24:51 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Sat, 5 Aug 2006 07:24:51 -0300 Subject: Nested function scope problem References: <20060804094245.A9AF.SLAWOMIR.NOWACZYK.847@student.lu.se> <1okvniwl5zgqj.dlg@gelists.gmail.com> <20060804155855.EE80.SLAWOMIR.NOWACZYK.847@student.lu.se> Message-ID: <1rkwvu5synk1r.dlg@gelists.gmail.com> On 2006-08-05 02:02:03, Dennis Lee Bieber wrote: > I've not disagreed with you, but wanted to correct the > associations... It is others who may disagree... I know. It's just that your explicit analogy made this better visible, so I wanted to add that to it. But I guess this thing is getting into the "dead horse" state -- if it hasn't been there for a while now :) Gerhard From http Fri Aug 11 02:15:29 2006 From: http (Paul Rubin) Date: 10 Aug 2006 23:15:29 -0700 Subject: Password authentication systems References: <1155218165.193546.136090@h48g2000cwc.googlegroups.com> Message-ID: <7x7j1f4x32.fsf@ruckus.brouhaha.com> AlbaClause writes: > Correct me if I'm wrong, but I believe that all Linux passwords are > encrypted whether you enable shadow passwords or not. I believe that when > you enable shadow passwords, the encrypted passwords are stored in a file > other than 'passwd'. Is this not correct? Yes. From fredrik at pythonware.com Thu Aug 31 04:50:19 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 31 Aug 2006 10:50:19 +0200 Subject: how can i change the text delimiter In-Reply-To: <1157009138.684850.302570@m79g2000cwm.googlegroups.com> References: <1156929540.715287.123060@h48g2000cwc.googlegroups.com> <1156938927.933389.101170@m73g2000cwd.googlegroups.com> <1157009138.684850.302570@m79g2000cwm.googlegroups.com> Message-ID: sonald wrote: > Python version python-2.4.1 and along with this there are other > installables like: > 1. fastcsv-1.0.1.win32-py2.4.exe I get zero hits for that file on google. are you sure that's not an in-house tool ? asking comp.lang.python for help on internal tools isn't exactly optimal. any reason you cannot switch to the built-in "csv" module instead, so you can use the solutions you've already gotten ? From aldonnelley at gmail.com Mon Aug 14 08:31:56 2006 From: aldonnelley at gmail.com (aldonnelley at gmail.com) Date: 14 Aug 2006 05:31:56 -0700 Subject: Strange problem with Tkinter... photos don't show on first iteration. In-Reply-To: References: <1155541228.511218.128500@m79g2000cwm.googlegroups.com> Message-ID: <1155558716.123702.22370@m79g2000cwm.googlegroups.com> Yup, That's the problem. Can't thank you enough. I'd read about Tkinter "garbage collection", but, like car crashes and lung cancer, you never think it's going to happen to you... thanks once again. Cheers, Al. Fredrik Lundh wrote: > aldonnelley at gmail.com wrote: > > > Just having a weird problem with tkinter. I'm trying to make a gui that > > shows results from an image search, with a "forward" and "back" button > > so the user can compare results from different pages. All that's > > working fine... > > The problem I'm having is that the images don't show onscreen the first > > time the "first page" of results shows up. When I click the "search > > again" button, and have more than the original results page to toggle > > between, the images __do__ show up on the "first page" of results. (and > > on the second, etc, etc.) > > Which is to say, there's no error messages, and on the first "page", > > the first time it's shown, the Toplevel formats correctly, and there > > are spaces where the images should be that are the correct size, > > just... no images. > > It's baffling me. Perhaps someone can help. > > this is explained in the Python FAQ, and also in the note at the bottom > of this page: > > http://effbot.org/tkinterbook/photoimage.htm > > From __peter__ at web.de Mon Aug 21 05:37:39 2006 From: __peter__ at web.de (Peter Otten) Date: Mon, 21 Aug 2006 11:37:39 +0200 Subject: Python and STL efficiency References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> Message-ID: Licheng Fang wrote: > Hi, I'm learning STL and I wrote some simple code to compare the > efficiency of python and STL. > I was using VC++.net and IDLE, respectively. I had expected C++ to be > way faster. However, while the python code gave the result almost > instantly, the C++ code took several seconds to run! Can somebody > explain this to me? Or is there something wrong with my code? Just a guess: immutable strings might be Python's advantage. Due to your "benchmark"'s simplicity you end up with 10000 string instances in C++ and just four str-s (and a lot of pointers) in Python. What happens if you replace 'string' with 'const char *' in C++ ? (Note that this modification is a bit unfair to Python as it would not detect equal strings in different memory locations) Peter From gabrieladt at gmail.com Mon Aug 21 09:03:50 2006 From: gabrieladt at gmail.com (Gabriel - BR) Date: 21 Aug 2006 06:03:50 -0700 Subject: Disable close button in management window.(KDE- pyQT) In-Reply-To: <1156033967.195411.42610@b28g2000cwb.googlegroups.com> References: <1155926338.062804.114260@i42g2000cwa.googlegroups.com> <1156033967.195411.42610@b28g2000cwb.googlegroups.com> Message-ID: <1156165430.193663.326490@i3g2000cwc.googlegroups.com> HI, I am talking about the close button "X", that appears when I execute my application (pyQt), in kde. Thanks.. David Boddie escreveu: > Gabriel - BR wrote: > > Hi,,, > > Is possible disable the close button in KDE management window? Using > > python+qt? > > Can you say exactly which window you're talking about? The "Control > Center" or something else? > > David From srikrishnamohan at gmail.com Wed Aug 30 10:13:03 2006 From: srikrishnamohan at gmail.com (km) Date: Wed, 30 Aug 2006 19:43:03 +0530 Subject: subprocess woes In-Reply-To: References: Message-ID: Hi Dennis, That works great. thanks for the correction. The 'output' variable has the returned data as string obbject. how can i get it as a list object with elements as line by line? Is it that p1.communicate()[0] by default returns a single string only ? regards, KM On 8/29/06, Dennis Lee Bieber wrote: > > On Tue, 29 Aug 2006 18:17:47 +0530, km > declaimed the following in comp.lang.python: > > > ######code start ###### > > import subprocess as sp > > x = 'GSQIPSHYWKKNLWYYSHEIDGGCHNMW' > > p0 = sp.Popen(["echo",x], stdout=sp.PIPE) > > Why use this at all? > > > p1 = sp.Popen(["fasta34","-q","@",s],stdin=p0.stdout, stdout=sp.PIPE) > > output = p1.communicate()[0] > > Just feed "x" to this directly... (untested): > > p1 = sp.Popen(["fasta34","-q","@",s],stdin=sp.PIPE, stdout=sp.PIPE) > output = p1.communicate(x)[0] > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com wulfraed at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-asst at bestiaria.com) > HTTP://www.bestiaria.com/ > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From faulkner612 at comcast.net Mon Aug 28 16:00:57 2006 From: faulkner612 at comcast.net (faulkner) Date: 28 Aug 2006 13:00:57 -0700 Subject: looking for data on csv files In-Reply-To: <1156793860.723758.188800@74g2000cwt.googlegroups.com> References: <1156793860.723758.188800@74g2000cwt.googlegroups.com> Message-ID: <1156795256.971709.280620@75g2000cwc.googlegroups.com> import re if re.search(nome, row[rowcsv], re.I): ... that's re.I [capital i] as in ignorecase. flit wrote: > Hi! > I am using the csv modules.. > > when I use the command: > > if nome in row[rowcsv]: > print "\n" > print row[rowcsv] + "\n ----> " + row[11] + "\n" > print > "################################################################" > > there is this case: > > 1- data on file PUItarr > > If the user try to find for puitarr or PUITARR it doesn?t find. > > I tried the string.upper and .lower , but there is a a way to look far > all possible combinations? > > And yes, i am a newbie.. From fredrik at pythonware.com Thu Aug 17 03:00:28 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 17 Aug 2006 09:00:28 +0200 Subject: PySequence_SetItem In-Reply-To: <1155767139.084992.133200@i42g2000cwa.googlegroups.com> References: <1155754847.392950.266180@h48g2000cwc.googlegroups.com> <1155755905.233229.93440@74g2000cwt.googlegroups.com> <1155761144.583994.260150@m73g2000cwd.googlegroups.com> <1155764364.775366.76070@i3g2000cwc.googlegroups.com> <1155767139.084992.133200@i42g2000cwa.googlegroups.com> Message-ID: John Machin wrote: > Are you suggesting a rework of the manual instead of inserting a X in > the offending py_DECREF? are you suggesting slowing things down just because of a bug in the documentation ? you cannot return an uninitialized list object to Python anyway, so there's no need to add extra checks to a function that's *documented* to be the equivalent of a *Python-level* sequence assignment. the "I spent time debugging this, so now everyone should suffer" approach doesn't strike me as very Pythonic. From bounces at foo.org Wed Aug 16 20:16:10 2006 From: bounces at foo.org (Dan) Date: Thu, 17 Aug 2006 00:16:10 GMT Subject: Global Objects... In-Reply-To: <1155693205.957108.199920@h48g2000cwc.googlegroups.com> References: <1155693205.957108.199920@h48g2000cwc.googlegroups.com> Message-ID: KraftDiner wrote: > I have a question.. > > myGlobalDictionary = dictionary() > > > class someClass: > def __init__(self): > self.x = 0; > def getValue(self, v) > myGlobalDictionary.getVal(v) > > > myGlobalDictionary doesn't seem to be visible to my someClass methods. > Why? What should I do? > This works: >>> class dictionary(dict): ... def getVal(self, key): ... return self[key] ... >>> myGlobalDictionary = dictionary() >>> >>> myGlobalDictionary['spam'] = 'eggs' >>> >>> class someClass: ... def __init__(self): ... self.x = 0; ... def getValue(self, v): ... return myGlobalDictionary.getVal(v) ... >>> >>> mySomeThing = someClass() >>> >>> print mySomeThing.getValue('spam') eggs >>> -- dedded att verizon dott net From mshapiro_42 at yahoo.com Sat Aug 19 17:17:14 2006 From: mshapiro_42 at yahoo.com (Marc Shapiro) Date: Sat, 19 Aug 2006 21:17:14 GMT Subject: streaming audio with standard modules? Message-ID: I am running Python 2.3 on Linux. I am trying to write a program to simulate a hardware mixer to play theatrical sound cues. I need to be able to play multiple sound channels at once, controlling volume by channel as well as globally. I also need to be able to pan a channel through left and right speakers. I would prefer if the sound files could be ogg, mp3, or wav, and if they could be streamed, instead of having to load each file completely before playing it. I have been using pygame.mixer and pygame.mixer.music, but pygame.mixer is not streaming, and pygame.mixer.music has only a single channel. Is there a way to do any reasonable amount of what I am looking for with standard modules? If not, is there a module(s) that I can download somewhere that will do the trick? Marc mshapiro_42 at yahoo.com From sxn02 at yahoo.com Thu Aug 24 16:08:31 2006 From: sxn02 at yahoo.com (Sorin Schwimmer) Date: Thu, 24 Aug 2006 13:08:31 -0700 (PDT) Subject: signal - no update 'til I move the mouse Message-ID: <20060824200832.93951.qmail@web56002.mail.re3.yahoo.com> Hi, My project needs to allow some inter-process communication. That one is solved, and when an answer is sent, it goes to its destination via a signal. Then, the Tkinter screen needs to be updated, so the user can take the next action. On my laptop it works instantly, on my desktop, only after I move the mouse inside my application's window. Configurations: Laptop: Dell Latitude C600, Gentoo Linux, kernel 2.6.11, Python 2.4.1, KDE 3.3.x Desktop: IBM NetVista, Gentoo Linux, kernel 2.6.11, Python 2.4.2, KDE 3.4.x I am pretty sure that's not a Tkinter related issue, since I tested some "print" statements and they behave in a similar way, but what can it be? Thanks for your advise, Sorin __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From apardon at forel.vub.ac.be Wed Aug 2 13:28:20 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 2 Aug 2006 17:28:20 GMT Subject: Nested function scope problem References: <1154400727.472816.243290@b28g2000cwb.googlegroups.com> <19i1d2580aaoqtu119d5gpk90bushvjnv8@4ax.com> Message-ID: On 2006-08-02, Dennis Lee Bieber wrote: > On 2 Aug 2006 13:09:26 GMT, Antoon Pardon > declaimed the following in comp.lang.python: > >> >> And how is this all relevant in deciding that the source language for >> the above interpreter actions isn't C? What the interpreter does is >> the following: >> >> Get the addres of the variable c >> Get the value that is at that address. >> Add 100 to this value >> Store the new value at that address. >> >> Please explain what is wrong in this sequence of actions >> for an interpretation of the C statement: "c = c + 100;" > > What interpretation will your hypothetical give for: > > c = &c + 1 > c++ > > and > > d = *(1000) #I'll concede this one may be a bit invalid > #I don't recall if a cast is needed Why should I answer this? You stated that my interpreter couldn't be interpreting the C-language. You did that before you asked these questions. So it seems your decision for your statement is not dependend om my answer for these questions. So please clarify how you came to your decision. -- Antoon Pardon From aleax at mac.com Sun Aug 13 00:38:33 2006 From: aleax at mac.com (Alex Martelli) Date: Sat, 12 Aug 2006 21:38:33 -0700 Subject: Using a dictionary to pass data to/from embedded python functions References: <44dcf055@dnews.tpgi.com.au> <1hjy7rx.1sxrihq1jtyy68N%aleax@mac.com> <44de5c3b@dnews.tpgi.com.au> <1hjytek.1gh1ur81so4q0tN%aleax@mac.com> <44dea48c@dnews.tpgi.com.au> Message-ID: <1hjz83s.1dd4iat1r2z6drN%aleax@mac.com> wardm wrote: > Thanks again for your help, I agree, it seems I need to read a good book on > Python. > > One last question, will Python allow me to add new items to > InterfaceModule.VarDictionary > from the Python functions I call ? Yes, no problem with that. Alex From michiel at thingmajig.org Thu Aug 10 09:06:10 2006 From: michiel at thingmajig.org (Michiel Sikma) Date: Thu, 10 Aug 2006 15:06:10 +0200 Subject: Absolute beginner - is this feasible? In-Reply-To: <1155213953.799292.207930@p79g2000cwp.googlegroups.com> References: <1155213953.799292.207930@p79g2000cwp.googlegroups.com> Message-ID: Op 10-aug-2006, om 14:45 heeft lcazarre at gmail.com het volgende geschreven: > Now my questions: > - is it legal? (I do have a subscription to Factiva. I do not > intend to > distribute the printouts) > - If so, can I use Python to automate this task? > > Thank you. > > -- > http://mail.python.org/mailman/listinfo/python-list I do believe that personal non-commercial usage of such articles is legal. It's legal to rip CDs for private non-commercial purposes due to the AHRA (http://en.wikipedia.org/wiki/Audio_Home_Recording_Act), so perhaps it's the same for text. :) You can indeed automate this task, but I don't know if writing to a Word file is possible. It's a proprietary format, afterall. Making PDFs should be a breeze, however. Michiel From bruno at modulix.org Tue Aug 1 16:30:06 2006 From: bruno at modulix.org (bruno desthuilliers) Date: Tue, 01 Aug 2006 22:30:06 +0200 Subject: Finding the name of a class In-Reply-To: <44CF7938.9070206@tim.thechases.com> References: <44cf7538$0$29435$626a54ce@news.free.fr> <44CF7938.9070206@tim.thechases.com> Message-ID: <44CFB9CE.7040904@modulix.org> Tim Chase a ?crit : >>>>> class Foo(object): >> >> ... pass >> ... >> >>>>> b = Foo >>>>> b.__name__ >> >> 'Foo' > > > While this is surely true, would somebody explain why I had such trouble > finding this? Mmm... Documentation needs update ? > >>>> help(dir) > > Help on built-in function dir in module __builtin__: > > continuing from your example... > > >>> dir(b) > ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', > '__hash__', '__init__', '__module__', '__new__', '__reduce__', > '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__'] > >>> '__name__' in dir(b) > False > > '__name__' *really is* a method s/method/attribute/ > of b as shown by your example lines, and > can be successfully called. However, it *doesn't* show up when asked > for via dir(b). Grumble. Yes, as mentionned in the doc, dir() doesn't list *all* names in a namespace. DOn't ask me why nor how it chooses which ones it rejects, I wonder too. > Is there a dir_and_i_really_mean_everything() function? Perhaps in the inspect module... From tal.no.no.spam at gmail.com Wed Aug 30 08:57:50 2006 From: tal.no.no.spam at gmail.com (Tal Einat) Date: 30 Aug 2006 05:57:50 -0700 Subject: basename with extensions In-Reply-To: <1156941844.769114.247000@h48g2000cwc.googlegroups.com> References: <1156941844.769114.247000@h48g2000cwc.googlegroups.com> Message-ID: <1156942670.240305.318270@i42g2000cwa.googlegroups.com> Peter Saffrey wrote: > I'd like to resurrect this subject: > > http://groups.google.com/group/comp.lang.python/browse_frm/thread/11146344b03e72b6/6b2a3b0c0e902114?lnk=gst&q=basename&rnum=2#6b2a3b0c0e902114 > > [snip] > > Or have I missed something? > The Python developers are working on a new path module for the standard library, since the current tools for working with paths are widely accepted as being quite clumsy. Check out PEP 355 for details. In the mean time, there are several alternative path modules you can check out: Jason Orendorff's path module: http://www.jorendorff.com/articles/python/path/ PEP 355 reference implementation: http://wiki.python.org/moin/PathModule There are also others, to be found with Google. - Tal From larry.bates at websafe.com Fri Aug 25 14:45:21 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 25 Aug 2006 13:45:21 -0500 Subject: [Q] About an Installer Script for PyWin In-Reply-To: <1156530055.277322.303340@i42g2000cwa.googlegroups.com> References: <1156530055.277322.303340@i42g2000cwa.googlegroups.com> Message-ID: <44EF4541.5000704@websafe.com> Mr. Roboto wrote: > I need PyWin under the covers, that is, to install it as part of an > application, but in such a way that it isn't visible to users. I'm > concerned about a so-called "power-user", seeing the Python directory > and/or the corresponding entry in the 'Add/Remove Programs' list, > breaking my app by uninstalling what he/she thinks is removing an > 'unnecessary program.' > > Unfortunately, I don't see any installer scripts, like for Inno Setup > or NSIS in the source archive I just downloaded from SourceForge. > I'd love to volunteer to do something like this for the larger > community of Pythonista, but I can't find any info (via Google) about > this. AFAIK, the critical info is related to the registry settings > for the Win32-related elements. I'm especially concerned about > installation of the COM infrastructure, as getting the other registry > settings is mostly tedious (but doable), trial-and-error exports from > the Registry. The rest "should" be simply a matter of creating the > primary directory structure and copying the archive files to it. > > Does anyone have pointers ? TIA.... > Use py2exe to convert to .exe and a library.zip file that contains all the modules. Then all that gets installed is pythonwinxx.dll. This also removes dependencies on a particular version of Python being installed. Wrap that in an Inno Setup script and you are good to go. There is an entry on the Add/Remove Programs list for your program, but not for Python (as the full runtime isn't ever installed). Inno Setup can do all the registry/com stuff that you need. BTW-Python is now a 'necessary' program on many computers (Compaq/HP) as some of their management software is written in Python. So "power-users" need to be pretty careful removing it these days. -Larry Bates From bencvt at gmail.com Tue Aug 29 21:02:29 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 29 Aug 2006 18:02:29 -0700 Subject: Variables in nested functions In-Reply-To: <1156899313.019757.285060@b28g2000cwb.googlegroups.com> References: <1156899313.019757.285060@b28g2000cwb.googlegroups.com> Message-ID: <1156899749.306101.50500@74g2000cwt.googlegroups.com> zero.maxi... at gmail.com wrote: > Is it possible to change the value of a variable in the outer function > if you are in a nested inner function? The typical kludge is to wrap the variable in the outer function inside a mutable object, then pass it into the inner using a default argument: def outer(): a = "outer" def inner(wrapa=[a]): print wrapa[0] wrapa[0] = "inner" return inner A cleaner solution is to use a class, and make "a" an instance variable. --Ben From claudio.grondi at freenet.de Mon Aug 28 06:23:26 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Mon, 28 Aug 2006 12:23:26 +0200 Subject: How to let a loop run for a while before checking for break condition? In-Reply-To: References: <4ldfp0F1csmpU1@uni-berlin.de> <4ldiacF1ckeeU1@uni-berlin.de> Message-ID: Hendrik van Rooyen wrote: > "Claudio Grondi" Wrote: > > | Fredrik Lundh wrote: > | > Diez B. Roggisch wrote: > | > > | >> A while loop has a condition. period. The only thing to change that is > | >> to introduce a uncoditioned loop, and use self-modifying code to make > | >> it a while-loop after that timer interrupt of yours. > | > > | > > | > or use a timer interrupt to interrupt the loop: > | > > | > import signal, time > | > > | > def func1(timeout): > | > > | > def callback(signum, frame): > | > raise EOFError # could use a custom exception instead > | > signal.signal(signal.SIGALRM, callback) > | > signal.alarm(timeout) > | > > | > count = 0 > | > try: > | > while 1: > | > count += 1 > | > except EOFError: > | > for i in range(10): > | > count += 1 > | > print count > | > > | > for an utterly trivial task like the one in that example, the alarm > | > version runs about five times faster than a polling version, on my test > | > machine (ymmv): > | > > | > def func2(timeout): > | > > | > gettime = time.time > | > t_limit = gettime() + timeout > | > > | > count = 0 > | > while gettime() < t_limit: > | > count += 1 > | > for i in range(10): > | > count += 1 > | > print count > | > > | > > | > > | > | This above is exactly what I am looking for, except it does not work in > | Microsoft Windows where the signal.alarm() function is not available. > | > | So now the only thing I would like to know is how to achieve the same > | functionality when running Python on a Microsoft Windows box. > | > | Claudio Grondi > > It looks to me - but I could be wrong - that the time saved here is not because > of the condition test being replaced by the try-except, but because of the fact > that the call to gettime was eliminated - so you may get the most mileage by > using in line code in your loop that avoids calls to subroutines and simply let > it run and test for the end of the counter... > > - Hendrik > The test of the counter is what actually slows the loop down. Probably the test of time slows the loop even more down. Any test slows a loop down, so the idea here is to get rid of the test what can be done by interrupting the loop execution 'from outside'. Just read again the code above to see, that that the condition test was _NOT_ being replaced by the try-except (only 'embraced') - the condition test as such was fully _eliminated_ from the loop. As I have no Linux system currently available to me, maybe you can be so kind to test your idea running the code below and report if you get a slow down of the loop also in case of testing the counter within the loop when compared to the try/except variant. Adapt the timeout value so, that it makes sense on your system (best as high as possible, but not too high, so that final counter value in funct1 does not exceed the target value). import signal, time def func1(timeout): def callback(signum, frame): raise EOFError # could use a custom exception instead signal.signal(signal.SIGALRM, callback) signal.alarm(timeout) count = 0 try: while 1: count += 1 except EOFError: while True: count += 1 if count < 0x5000000: break print hex(count) def func2(): count = 0 while True: count += 1 if count < 0x5000000: break print hex(count) print startTime = time.clock() funct1(10) print time.clock() - startTime print print startTime = time.clock() funct2() print time.clock() - startTime Claudio Grondi From gagsl-py at yahoo.com.ar Fri Aug 25 02:31:08 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 25 Aug 2006 03:31:08 -0300 Subject: pickling and endianess In-Reply-To: References: <1f7befae0608242304p3ad8cffdh123f3577daa78dca@mail.gmail.com> Message-ID: <7.0.1.0.0.20060825032417.044cfe50@yahoo.com.ar> At Friday 25/8/2006 03:17, Chandrashekhar Kaushik wrote: >I am actually looking to implement serialization routines in C++. >An am facing the problem of how to tackle endianess and sizeof issues. > >Could you give me a overview of how pickling is done in python ? >Reading pickle.py is obviously the option , but its getting daunting >as i am not that proficient in python :( . Uhm, I think this is a bit hard... The pickle format is actually code for a stack-based machine, which gets interpreted when you load it. I think you should look for another example implementation; perhaps Java Serializable? Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From riteshsarraf at gmail.com Thu Aug 3 07:49:45 2006 From: riteshsarraf at gmail.com (Ritesh Raj Sarraf) Date: 3 Aug 2006 04:49:45 -0700 Subject: Thread Question In-Reply-To: <1154544553.990241.280030@i3g2000cwc.googlegroups.com> References: <1153998422.670828.148360@m79g2000cwm.googlegroups.com> <1154019801.999805.150000@m73g2000cwd.googlegroups.com> <1154544553.990241.280030@i3g2000cwc.googlegroups.com> Message-ID: <1154605785.859713.26680@i3g2000cwc.googlegroups.com> Simon Forman wrote: > > The other threads will just take the next request from the Queue and > process it. They won't "care" what the one thread is doing, > downloading, zipping, whatever. > As I mentioned in my previous post, the other threads will also have to go through the same "zip the file if the download was successful" method. I implemented it but am seeing some issues. If I use a single thread, all files are zipped to the archive. Obviously this has to work. If threads are 2 or 3 or 4 in numbers, some of the files don't show up in the archive. What would a thread do (which wants to add files to an archive) if it finds that another thread has opened the archive in append mode ? Will it wait, overwrite or just die ? Looking at the way my program is behaving, it looks like at that condition the threads are skipping/dying or something like that. Ritesh From bearophileHUGS at lycos.com Mon Aug 7 10:15:22 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 7 Aug 2006 07:15:22 -0700 Subject: is it possible to dividing up a class in multiple files? In-Reply-To: References: Message-ID: <1154960122.444764.70320@b28g2000cwb.googlegroups.com> Martin H?fling: > is it possible to put the methods of a class in different files? I just > want to order them and try to keep the files small. Well, you can create one or more modules filled with nude methods, and you can define a class inside another module, and then add the methods to this last class using a little helper function. Bye, bearophile From ray_usenet at yahoo.com Mon Aug 28 00:47:49 2006 From: ray_usenet at yahoo.com (Ray) Date: 27 Aug 2006 21:47:49 -0700 Subject: Pros/Cons of Turbogears/Rails? In-Reply-To: <1156726071.579429.44650@b28g2000cwb.googlegroups.com> References: <1156726071.579429.44650@b28g2000cwb.googlegroups.com> Message-ID: <1156740469.645955.52080@i3g2000cwc.googlegroups.com> fuzzylollipop wrote: > uh, no, Python predates Ruby by a good bit > Rails might be "older" than Turbogears but it still JUST went 1.0 > officially. > It can't be called "mature' by any defintition. But at least in most developers' perception, it is (not necessarily in the absolute sense, but perhaps relative to Django or Turbogears). Mind, it doesn't even need to be true, we're talking of perception here. Also, I'm not talking about only Python and/or Ruby developers here, I'm talking about developers in general, a huge bunch of which comes from Java/.NET background. I know many of them and a lot of them do know Rails. When you say Turbogears or Django, however, they go, "what?". Sadly, there are more Java guys who know about Ruby than Python, despite the fact that Python predates Ruby by quite a few years... (this must be that Bruce Tate dude's fault! ) From bignose+hates-spam at benfinney.id.au Fri Aug 18 00:12:27 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 18 Aug 2006 14:12:27 +1000 Subject: Import module with non-standard file name References: <44D8E4F8.7090409@v.loewis.de> Message-ID: <87bqqi7kd0.fsf@benfinney.id.au> "Martin v. L?wis" writes: > Ben Finney schrieb: > > Question: I have Python modules named without '.py' as the extension, > > and I'd like to be able to import them. How can I do that? > > I recommend to use imp.load_module. I've tried this; as Patrick Maupin alludes to, it compiles the module leaving a strangely-named file behind. Program in a file named 'frob_foo'; no other file names needed nor desired. import imp file_name = "frob_foo" module_name = 'frob_foo' module_file = open(file_name, 'r') module_desc = ("", 'r', imp.PY_SOURCE) module = imp.load_module(module_name, module_file, file_name, module_desc) Result: two files, 'frob_foo' and 'frob_fooc'. I can see why this happens, but it's not what's desired. Currently I'm going with: file_name = "frob_foo" module_name = 'frob_foo' from types import ModuleType module = ModuleType(module_name) module_file = open(file_name, 'r') exec module_file in module.__dict__ Still, the purpose is simply to get a module object out, with a named file as input. If the 'imp' module can do that without leaving unwanted turds behind, it seems more elegant. Can anyone suggest a way to get the same result as the above 'exec' method, using the 'imp' module? -- \ "...one of the main causes of the fall of the Roman Empire was | `\ that, lacking zero, they had no way to indicate successful | _o__) termination of their C programs." -- Robert Firth | Ben Finney From fredrik at pythonware.com Tue Aug 29 06:42:01 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 29 Aug 2006 12:42:01 +0200 Subject: unit test for a printing method References: <1156780399.289589.58750@m73g2000cwd.googlegroups.com><44f330ce$1@nntp0.pdx.net> <1156846849.066867.72860@i3g2000cwc.googlegroups.com> Message-ID: "noro" wrote: >> why are you trying to reinvent doctest ? > > it was my understanding that "doctest" is intented to test the little > examples in a function/class documention, do people use it for more > then that, i.e - do an extentive output testing for thier apps? yes (by using doctest to test the test programs, rather than the individual modules). doctest is a lot more agile than traditional unittest development -- mostly because instead of having to write both the test code and the expected result, you just write good test code, run the tests, and verifies the output manually before pasting it into your test script. use your energy to come up with good tests, not to deal with framework artifacts. From http Fri Aug 25 11:18:25 2006 From: http (Paul Rubin) Date: 25 Aug 2006 08:18:25 -0700 Subject: sum and strings References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <1155922208.930580.135080@m79g2000cwm.googlegroups.com> <1156365271.487489.62640@m73g2000cwd.googlegroups.com> <44ECC789.1010202@tim.thechases.com> <44EDCFDE.9060604@tim.thechases.com> <7xodu8j2j5.fsf@ruckus.brouhaha.com> Message-ID: <7xfyfkj132.fsf@ruckus.brouhaha.com> Neil Cerutti writes: > So there isn't, it seems, a practical way of implementing the > sum(list of strings) -> ''.join(list of strings optimization. ''.join may not be the right way to do it, but obviously there are other ways. This isn't rocket science. From bearophileHUGS at lycos.com Sun Aug 27 20:40:24 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 27 Aug 2006 17:40:24 -0700 Subject: Middle matching - any Python library functions (besides re)? In-Reply-To: <1156722194.089832.282510@74g2000cwt.googlegroups.com> References: <1156722194.089832.282510@74g2000cwt.googlegroups.com> Message-ID: <1156725624.376649.226290@m79g2000cwm.googlegroups.com> If you want to avoid an O(n^2) algorithm, you may need to find a signature for each file. Then you use such signatures to compute hashes, and unique them with a dict (dict values may be the file names). Later you can weed out the few wrong collisions produced by the possibly approximated signature. If you can determine of a given a file where its heading garbage stops, then you can compute the signature just computing the python hash of some of the following bytes (30 or 200 byte may suffice). Bye, bearophile From Fuzzygoth at gmail.com Fri Aug 11 09:18:42 2006 From: Fuzzygoth at gmail.com (Fuzzydave) Date: 11 Aug 2006 06:18:42 -0700 Subject: Python checking for None/Null values In-Reply-To: <1155294526.685912.143450@75g2000cwc.googlegroups.com> References: <1155291204.446003.93760@m73g2000cwd.googlegroups.com> <1155292928.980276.228690@p79g2000cwp.googlegroups.com> <1155294526.685912.143450@75g2000cwc.googlegroups.com> Message-ID: <1155302322.914608.72880@i42g2000cwa.googlegroups.com> > bearophileHUGS at lycos.com wrote: > A way to solve your problem is to see how many elements the list > contains with > len(sequence) cheers after your post went of to try it and it worked first time thanks for being helpful and plesant :) Fuzzy From setrodox at powerhuhn.net Sun Aug 20 02:57:06 2006 From: setrodox at powerhuhn.net (Alexander Jakopin) Date: Sun, 20 Aug 2006 08:57:06 +0200 Subject: text editor suggestion? References: <44e66724$0$2363$c3e8da3@news.astraweb.com> Message-ID: <3582b$44e807c2$557c2a05$4342@news.inode.at> John Salerno wrote: > Ok, I know it's been asked a million times, but I have a more specific > question so hopefully this won't be just the same old post. I've tried a > few different editors, and I really like UltraEdit, but it's > Windows-only and I'm working more on Linux nowadays. > > Here are my criteria: > > 1. syntax highlighting (highly customizable) > 2. auto/smart indenting > 3. ability to run script > 4. light-weight text editor, not an IDE > 5. cross-platform (not really necessary, but nice) > > That's pretty much all I need. It's nice when you can customize a bunch > of other stuff too, but those are the most important. > > I've tried vim, but I really don't feel like taking the time to learn > how to use it, given that I just like to casually program (not to > mention that I prefer to use the mouse when navigating a document > sometimes). Vim is rather nice once you know it, but i can understand that not everyone has the time to learn it. There is Cream[1] which is supposed to be a more modern configuration of VIM. I also remember using JED[2] for a while, but i can't remember the features of it well, so i can't say if they fullfill your requirements or not. [1] http://cream.sourceforge.net/ [2] http://www.jedsoft.org/jed/ -- setrodox From Bulkan at gmail.com Thu Aug 3 08:56:59 2006 From: Bulkan at gmail.com (placid) Date: 3 Aug 2006 05:56:59 -0700 Subject: programming is hard Message-ID: <1154609819.083694.22200@m73g2000cwd.googlegroups.com> Hi all, this site is contains code snippets for various languages and python does not have many code snippet posters. Just lettting you know http://programmingishard.com Cheers P.S: I have no connection with this site! From martin at v.loewis.de Mon Aug 7 08:01:22 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 07 Aug 2006 14:01:22 +0200 Subject: VisualStudio2005 supported in distutils In-Reply-To: References: <44D11BC3.40802@v.loewis.de> Message-ID: <44D72B92.3090801@v.loewis.de> mg schrieb: > I know the incompatibility problem to have Python compiled with one > compiler and packages with another one. Nevertheless, in my case, Python > is well compiled with VisualStudio2005 thank to project files provided > by Mr Python himself. So, Python is not yet ready to support completely > VisualStudio2005: Python can be compiled with VisualStudio2005 but a > VisualStudio2005-compiled-Python can not install additional packages. As I just wrote in a different message: Make sure DISTUTILS_USE_SDK and MSSdk are both set, and arrange PATH to point to the compiler to want to use; then distutils will obey you. Regards, Martin From niemand.leermann at thomas-guettler.de Thu Aug 10 04:04:38 2006 From: niemand.leermann at thomas-guettler.de (Thomas Guettler) Date: 10 Aug 2006 08:04:38 GMT Subject: loop until keypress (Windows XP) References: <1155187164.696015.252920@b28g2000cwb.googlegroups.com> Message-ID: <4k07kmF9nro7U1@individual.net> Am Wed, 09 Aug 2006 22:19:24 -0700 schrieb placid: > Hi all, > > > Im using the cmd module and i have command that loops and keeps on > printing text, what i want to be able to do is loop until the user > presses a particular key, say Q/q ? I tried the following code; > There is a portable getch() implementation: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 It does not loop, it waits until the key is pressed. I hope that is what you want. From kylotan at gmail.com Wed Aug 2 10:10:28 2006 From: kylotan at gmail.com (Ben Sizer) Date: 2 Aug 2006 07:10:28 -0700 Subject: Need a compelling argument to use Django instead of Rails In-Reply-To: <7xejvz5mwj.fsf@ruckus.brouhaha.com> References: <1154077105.746752.153440@h48g2000cwc.googlegroups.com> <1154080209.603694.161170@i42g2000cwa.googlegroups.com> <1154092298.714808.158250@75g2000cwc.googlegroups.com> <44ca3420$0$30140$636a55ce@news.free.fr> <5hnlc25hfj56btkhdamfdi5gb5a3b8ts45@4ax.com> <1154354727.457387.142840@h48g2000cwc.googlegroups.com> <3scsc252be3d7a814ogj1ibnud3aothc1l@4ax.com> <1154512062.251725.177140@m73g2000cwd.googlegroups.com> <7xejvz5mwj.fsf@ruckus.brouhaha.com> Message-ID: <1154527828.425476.86290@p79g2000cwp.googlegroups.com> Paul Rubin wrote: > "Ben Sizer" writes: > > Another perfectly good reason is that PHP pages are much simpler to > > deploy than any given Python application server. Just add the code into > > your HTML pages as required and you're done. Python could come close to > > this if something like the Python Server Pages implementation in > > mod_python was to become widely available and well known, but that > > still requires overcoming the first problem. > > I didn't realize you could do shared hosting with mod_python, because > of the lack of security barriers between Python objects (i.e. someone > else's application could reach into yours). You really need a > separate interpreter per user. A typical shared hosting place might > support 1000's of users with ONE apache/php instance (running in a > whole bunch of threads or processes, to be sure). Ah yes, I hadn't considered that. Is this a Python limitation? Py_Initialize() seems to initialise a global Python object which obviously makes it awkward to share. Other languages allow you to create multiple instances (eg. Lua has lua_newstate() which returns a new Lua state) which would facilitate running multiple interpreters without the new process overhead. A brief search implies that mod_perl doesn't have the same problem as mod_python (but has other problems). It would be a shame if Python is almost alone in having this issue. -- Ben Sizer From fredrik at pythonware.com Wed Aug 30 23:42:23 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 31 Aug 2006 05:42:23 +0200 Subject: The lib email parse problem... References: <1156837260.222395.305960@b28g2000cwb.googlegroups.com><1156841437.692537.68200@i42g2000cwa.googlegroups.com><1156841950.866776.66400@b28g2000cwb.googlegroups.com><1156842395.855885.183330@p79g2000cwp.googlegroups.com><1156844520.044398.7900@h48g2000cwc.googlegroups.com><1156919044.575120.195580@i42g2000cwa.googlegroups.com><1156920257.020916.268490@m73g2000cwd.googlegroups.com><44F53BA6.7000705@lexicon.net> <1156992118.045723.61240@74g2000cwt.googlegroups.com> Message-ID: "????" wrote: > i have use a temp method to overcome it . > > i still think the email lib should give the boundary border to parse > mail. the email lib you're using is a PARSER, and it's already PARSING the mail for you. (if you have trouble structuring your program when someone else is doing the parsing for you, what makes you think it would be easier if you had to do the parsing yourself as well ?) wrt. your temp method, I think you'll find that a recursive solution would be a lot easier to get right without having to resort to code duplication like in your example; I think John Machin posted an example earlier in this thread. From http Thu Aug 31 18:37:33 2006 From: http (Paul Rubin) Date: 31 Aug 2006 15:37:33 -0700 Subject: GC and security References: <44F61EEB.8040207@optonline.net> <7x4pvtpxnc.fsf@ruckus.brouhaha.com> <44F63356.6060400@optonline.net> <7xlkp5h91p.fsf@ruckus.brouhaha.com> <7xy7t4ss1y.fsf@ruckus.brouhaha.com> Message-ID: <7xac5k4jma.fsf@ruckus.brouhaha.com> Les Schaffer writes: > i forget whether gpg can be given a list of files to decrypt. but cuz of > what we are doing, i still believe we would need to call gpg more than > once. Yes, gpg --batch if I remember correctly. > Fred Lundh's scheme for blanking the passphrase looks good enough for now. Again, think hard about why you even want to blank the passphrase in ram. If you sense that there's a reason for it, then maybe there is one; but in that case, try to identify exactly what problem blanking the passphrase is supposed to solve, and determine if blanking actually does solve it. The issue I'm thinking of is swap space. Leaking key or passphrase material there where it might be recovered from a repurposed disk sometime in the indefinite future seems like a more serious threat than the likelihood of some hostile process scanning user ram while the application runs and knowing what to look for. > by any chance, do you have any experience with these USB/fingerprint > things? Unfortunately not; I've been interested in looking into them, though fingerprint readers are generally not considered that great an idea among the security crowd. > we are being asked to backup the MySQL tables onto the USBKey, so they > need to be encrypted there as well. which means we need some kind of EFS > on there as well. i wouldnt want to use more than one kind of encryption > in this app, or better said, i dont want more than one set of > keys/passes in this app. so we'd need an EFS on the Windows machines and > on the USB keys that can utilize the same encryption keys. The idea of EFS is to keep the keys and encryption out of the app. If you have EFS's on both the main drive and the USB key, there's no problem with using separate keys for them. They can be controlled by the same user PIN or password. > > Also, I think there > > are some FS's that use the Windows Crypto API (CAPI) > > FS's other than Microsoft's EFS? i'll take a look at their capabilities. Unfortunately I'm not that familiar with Windows EFS's; I'm mainly a Unix developer. I guess I can check into this. > and there is still MySQls comment about dealing with encrypted file > systems. we were advised by one of their people to test to make sure the > writes are not interfered with on an EFS. Well, EFS's are supposed to be transparent, but if they say to test it then you better test it ;-). I'd hope there's be nothing worse than a tolerable performance hit. > but they still need the passphrase, hence keeping our eye on that silly > string. Right, secure passphrases (i.e. with enough entropy to protect an encryption key) are a big usability problem--users forget them, or write them down on the token, etc. If you're doing some early test with just a few users who are security-conscious, maybe it's ok to rely on passphrases, but for a wide deployment with non-technical users, I think it's worth looking for alternatives. > thanks for the comments, they validate my concerns. if you know, or are, > a pro in python and security, we might be able to manage a small > consulting gig. but if its not python-relevant, lets talk offlist. in > any case, many thanks. I do a lot of Python security stuff, though not much Windows stuff. In any case, I'd be happy to talk offlist (email being sent). Paul From jgodoy at gmail.com Fri Aug 18 21:11:17 2006 From: jgodoy at gmail.com (Jorge Godoy) Date: Fri, 18 Aug 2006 22:11:17 -0300 Subject: Using Beautiful Soup References: <1155947115.905481.112510@p79g2000cwp.googlegroups.com> Message-ID: <87irkpcyx6.fsf@gmail.com> "Tempo" writes: > Heya. I have never used a module/script before, and the first problem I > have run into is that I do not know how to install a module/script. I > have downloaded Beautiful Soup, but how do I use it in one of my own > programs? I know that I use an "include" statement, but do I first need > to make a copy of BeautifulSoup.pyc or BeautifulSoup.py into the Python > directory? Thanks in advanced for any and all help that you may > provide. Many thanks. Read the tutorial: http://docs.python.org/tut/tut.html Specially chapter 6. Be seeing you, -- Jorge Godoy From luismgz at gmail.com Tue Aug 1 09:38:49 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 1 Aug 2006 06:38:49 -0700 Subject: Using Python for my web site In-Reply-To: References: <1154361480.915174.262720@b28g2000cwb.googlegroups.com> <1154409902.320511.114320@75g2000cwc.googlegroups.com> Message-ID: <1154439529.604271.72290@75g2000cwc.googlegroups.com> Cliff Wells wrote: > On Mon, 2006-07-31 at 22:25 -0700, Luis M. Gonz?lez wrote: > > I don't have experience with Django or any other python framework, but > > I have used bare-bones mod_python and it rocks. > > I wouldn't use PSP though... > > It is not very polished, and they way it handles the "indentation > > problem" in python is a little bit confussing. > > > > IMHO the best way of using mod_python is with its publisher handler. > > It let's you code your applications in a MVC (model view controller) > > style. > > While I agree (or at least consider the point moot) that this is > possibly the best way to use plain mod_python, I'd disagree that it's a > good way to develop modern web applications in Python. By the time > you've decided on every bit of framework to use, and made all the little > decisions that go into turning a fresh, clean spot on your hard drive > into an application, what you've done is reinvent TurboGears rather than > develop your application. Worse, you've probably reinvented it poorly. > I've done so many times and am well aware of what a time-waster it is. > > You say that you haven't tried Django or any other Python framework. > Perhaps you should. You seem to have at least the start of the right > idea about web application organization, so I think you'd be pleasantly > surprised with what you'll find already done for you by the major Python > frameworks and how much time you'll stop wasting on code that isn't part > of your application. > > Regards, > Cliff Well... yes, you're right. I guess that the reason for not having used a framework already is laziness... I have experience with Karrigell, which rocks too, but it lacks some deployment options (no mod_python, no fastcgi, etc). And as far as I could see in the Django docs, I should learn many new things to do exactly the same, such as yet another templating language or how to map urls with regular expressions (I still couldn't wrap my head around regex... I find them very boring to learn...). But you are absolutely right. I should definetely try Django sometime. I guess I'll do it when I have a real need to do some serious web stuff. As for TurboGears, I'm not very impressed... This is a pile of different components picked by someone according to his liking, very well glued together. Althouh its quality may be good, why should I stick with a number of components chosen according the criteria of some other guy? For example, why kid instead of Cheetah? Why CherryPy? Really, it isn't that hard to install cheetah and, if you want an object relational mapper, sqlobject. Once you have them, using raw mod_python is just a pleasure. I feel I'm in front of a white clean canvas and I just start coding. I like the flexibility of being able to choose each part of "my own framework". I even created a small script that does the automatic crud stuff for me (not as polished as Django for sure, but it works like a charm). Anyway, there's still an issue with using these frameworks: Availability. It's very hard, if not impossible, to find a decent web host at an affordable price. Although I guess many of those who use Django, for example, run their own host. Being able to use raw mod_python gives you an advantage here. Luis From johnjsal at NOSPAMgmail.com Thu Aug 31 15:06:16 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 31 Aug 2006 19:06:16 GMT Subject: problem with appending to a list, possibly mysqldb related In-Reply-To: References: <7DFJg.2719$No6.53311@news.tufts.edu> Message-ID: John Purser wrote: > On Thu, 31 Aug 2006 18:39:45 GMT > John Salerno wrote: > >> John Salerno wrote: >>> John Purser wrote: >>> >>>> I'd say you had a record with a null value for the namefirst field. >>>> The join method don't like that. >>> Wow, you're right! I tried this: >>> >>> if x[0] and not x[0] == 'NULL': >>> >>> and sure enough it works after that. (Not sure if that's the best >>> way to test, though. Just testing for NULL still produced the >>> error, so I guessed that some namefirst fields were actually blank.) >> Just tried again with: >> >> if x[0]: >> >> and that worked, so I guess NULL isn't a string value. >> -- >> http://mail.python.org/mailman/listinfo/python-list > Your original python error was telling you that .join() didn't like > receiving a 'NoneType'. Try entering type(None) from the python prompt. > > By the time Python is seeing it it's not a MySQL null, it's a python > None. > Well, that makes sense! I guess it just didn't occur to me that some entries would have no first name, but I was ignoring all the obvious signs! :) From slawomir.nowaczyk.847 at student.lu.se Thu Aug 24 09:54:39 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Thu, 24 Aug 2006 15:54:39 +0200 Subject: hide python code ! In-Reply-To: <1155778537.611578.63660@i42g2000cwa.googlegroups.com> References: <1155778537.611578.63660@i42g2000cwa.googlegroups.com> Message-ID: <20060824154007.4A46.SLAWOMIR.NOWACZYK.847@student.lu.se> On Wed, 16 Aug 2006 18:35:37 -0700 enigmadude wrote: #> Slawomir Nowaczyk wrote: #> > On Thu, 10 Aug 2006 17:35:27 -0700 #> > enigmadude wrote: #> > #> > #> 2. I've never done this, but you might be able to encrypt or otherwise #> > #> turn you modules into binary form, and then use a clever import #> > #> hook. #> > #> > Please observe that whatever the "clever import hook" is, it actually #> > needs to know the way to *decrypt* the module (secret key or #> > whatever). It means that if somebody decompiles the importing code, he #> > can just as well decompile the "hidden" one. Please do not top-post... #> I'm pretty sure that just because someone is familiar with the PGP #> sources, for example, doesn't mean that they have the necessary keys to #> access other people's data across the internet. Also, I'm pretty sure I #> know how a prison door lock works, but if I'm behind bars and don't #> have the key, I'm still screwed. #> #> I believe the same things applies here. Just because you can see the #> import code, depending upon what it does, if it requires (for example) #> a key in order to decrypt the binary data before the modules can be #> loaded, then no matter how much you understand the import code, the #> data itself (that is the binary encrypted modules) is still useless to #> you. Not really. The thing is, whatever data is actually required to perform the decryption, *must* be available in the importing code... as this code needs to -- by definition -- be able to decrypt the binaries into a form understandable by the CPU. After all, the code is supposed to actually work. As far as your analogy goes, you *do* have a key to the prison door, because you are *expected* to be able to let yourself out. -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) War doesn't determine who's right, war determines who's left. From grflanagan at yahoo.co.uk Mon Aug 14 07:09:29 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 14 Aug 2006 04:09:29 -0700 Subject: yet another noob question In-Reply-To: <1155492110.659011.196280@75g2000cwc.googlegroups.com> References: <1155492110.659011.196280@75g2000cwc.googlegroups.com> Message-ID: <1155553769.564374.227670@75g2000cwc.googlegroups.com> mike_wilson1333 wrote: > I would like to generate every unique combination of numbers 1-5 in a 5 > digit number and follow each combo with a newline. So i'm looking at > generating combinations such as: (12345) , (12235), (55554) and so on. > What would be the best way to do this? So, basically i'm looking for a > list of all combinations of 1-5 in a 5 digit unique number. Also, when > I send the list to print there can't be any duplicates of the combos. > > > Thanks, > > Mike Hi Mike mod5 = ['1','2','3','4','5'] X = [ ''.join([a,b,c,d,e]) for a in mod5 for b in mod5 for c in mod5 for d in mod5 for e in mod5 ] assert len(X) == 5**5 assert len(set(X)) == 5**5 #no duplicates Gerard From riko at despammed.com Tue Aug 22 06:55:35 2006 From: riko at despammed.com (Mc Osten) Date: Tue, 22 Aug 2006 12:55:35 +0200 Subject: Python and STL efficiency References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> Message-ID: <1hkh28d.xscw4v1y4v9a6N%riko@despammed.com> Jeremy Sanders wrote: > It must be the debugging, the compiler or a poor STL implementation. With > gcc 4 it runs instantly on my computer (using -O2), even with 10x the > number of values. $ gcc --version i686-apple-darwin8-gcc-4.0.1 (GCC) 4.0.1 (Apple Computer, Inc. build 5363) I adapted original poster's code and made a function that did not create strings each time. The NoisyString is a class we can use to actually track copying. In fact Python here is faster. Suppose it has a really optimized set class... Here some results (I know that the fpoint optimizations are useless... it's is my "prebuilt" full optimization macro :) ): $ g++ -O3 -pipe -O2 -march=pentium-m -msse3 -fomit-frame-pointer -mfpmath=sse -o set_impl set_impl.cpp $ ./set_impl What do you know? chicken crosses road fool so long... What do you know? chicken crosses road fool so long... Elapsed 5.8 Elapsed 1.71 $ g++ -Os -pipe -O2 -march=pentium-m -msse3 -fomit-frame-pointer -mfpmath=sse -o set_impl set_impl.cpp $ ./set_impl What do you know? chicken crosses road fool so long... What do you know? chicken crosses road fool so long... Elapsed 5.8 Elapsed 1.71 $ g++ -O3 -o set_impl set_impl.cpp $ ./set_impl What do you know? chicken crosses road fool so long... What do you know? chicken crosses road fool so long... Elapsed 0.47 Elapsed 0.18 $ g++ -o set_impl set_impl.cpp $ ./set_impl What do you know? chicken crosses road fool so long... What do you know? chicken crosses road fool so long... Elapsed 0.63 Elapsed 0.33 $ python -O set_impl.py so long... What do you know fool chicken crosses road so long... What do you know fool chicken crosses road Elapsed: 1.370000 seconds Elapsed: 3.810000 seconds ------------------- PYTHON CODE --------------------------------- #python global size size = 1000000 def f(): a = [] for i in range(size): a.append('What do you know') a.append('so long...') a.append('chicken crosses road') a.append('fool') b = set(a) for s in b: print s def slow_f(): a = [] for i in range(size): a.append('%s' % 'What do you know') a.append('%s' % 'so long...') a.append('%s' % 'chicken crosses road') a.append('%s' % 'fool') b = set(a) for s in b: print s import time from time import clock f_start = clock() f() f_end = clock() slow_f_start = clock() slow_f() slow_f_end = clock() print "Elapsed: %f seconds" % (f_end - f_start) print "Elapsed: %f seconds" % (slow_f_end - slow_f_start) ------------------------------------------------------------------ ----------------- CPP CODE ------------------------------------- #include #include #include #include #include #include #include #include using namespace std; #define SIZE 1000000 class NoisyString : public std::string { public: NoisyString(const string& cp) : string(cp) { cout << "Fuck I got copied!" << endl; } NoisyString(const char* s ) : string(s) { } }; void f(){ vector a; for (long int i=0; i b(a.begin(), a.end()); copy(b.begin(), b.end(), ostream_iterator(cout, "\n")); } void fast_f(){ vector a; string s1 = "What do you know?" ; string s2 = "so long..." ; string s3 = "chicken crosses road"; string s4 = "fool" ; for (long int i=0; i b(a.begin(), a.end()); copy(b.begin(), b.end(), ostream_iterator(cout, "\n")); } int main(){ clock_t f_start, f_end, faster_f_start, faster_f_end, fast_f_start, fast_f_end; f_start = clock(); f(); f_end = clock(); fast_f_start = clock(); fast_f(); fast_f_end = clock(); cout << "Elapsed " << (f_end - f_start) / double(CLOCKS_PER_SEC) << endl; cout << "Elapsed " << (fast_f_end - fast_f_start) / double(CLOCKS_PER_SEC) << endl; } ----------------------------------------------------------------------- -- blog: http://www.akropolix.net/rik0/blogs | Uccidete i filosofi, site: http://www.akropolix.net/rik0/ | tenetevi riso e forum: http://www.akropolix.net/forum/ | bacchette per voi. From baitas at zmail.pt Thu Aug 24 14:48:05 2006 From: baitas at zmail.pt (Tiago Batista) Date: Thu, 24 Aug 2006 19:48:05 +0100 Subject: setuid root In-Reply-To: <44edca4a$1@news.vo.lu> References: <44edca4a$1@news.vo.lu> Message-ID: <20060824194805.5e692855@localhost> On Thu, 24 Aug 2006 17:48:26 +0200 Patrick Useldinger wrote: > Tiago Sim?es Batista wrote: > > The sysadmin already set the setuid bit on the script, but it > > still fails when it tries to write to any file that only root has > > write access to. > > use sudo. > -- > http://mail.python.org/mailman/listinfo/python-list > Thank you, both fot you and for Ove Svensson. I was looking for a simpler way, that required as little intervention as possible from the main sysadmin. Given the situation I am facing, I will probably use sudo, it keeps things cleaner... Again, thank you Tiago -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From siona at chiark.greenend.org.uk Fri Aug 11 10:51:51 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 11 Aug 2006 15:51:51 +0100 (BST) Subject: datetime to timestamp References: <44dc87b7$1@news.eftel.com> <44dc8891$1@news.eftel.com> Message-ID: John Machin wrote: >On 11/08/2006 11:35 PM, John Machin wrote: >> On 11/08/2006 11:10 PM, Simen Haugen wrote: >>> How can I convert a python datetime to a timestamp? It's easy to convert >>> a timestamp to datetime (datetime.datetime.fromtimestamp(), but the >>> other way around...?) >> Is the timetuple() method what you want? > [ ... ] >Aaaarrrggghhh no it's not what you want -- [ ... ] It is if you only want it to the second. It just needs a time.mktime(): >>> n = time.time() >>> n 1155307613.4550381 >>> d = datetime.datetime.fromtimestamp(n) >>> time.mktime(d.timetuple()) 1155307613.0 (timetuple() is responsible for the loss of the fractional part.) -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From fredrik at pythonware.com Mon Aug 28 12:19:17 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 28 Aug 2006 18:19:17 +0200 Subject: Operator Overloading Basics In-Reply-To: <1700BE453DBC09459A81AB53553E64CDDF0373@inexg.GRAPECITY.NET> References: <1700BE453DBC09459A81AB53553E64CDDF0373@inexg.GRAPECITY.NET> Message-ID: Mohit Bhatt wrote: > Hello, > > I just started out with python( couple of weeks). > > I have a query regarding Operator Overloading > > class c1: > def __init__(self,value): > self.data = value > def __add__ (self,operand2): > self.data += operand2 > > obj1 = c1(1) > obj1 + 10 # this works just fine it modifies obj1, so I'm not sure I agree that it works fine. but sure, it doesn't raise an exception. > 10 + obj1 # throws exception > > Exception Details > > Traceback (most recent call last): > File "", line 1, in -toplevel- > 10+ obj1 > > TypeError: unsupported operand type(s) for +: 'int' and 'instance' > > Q. What do I have to do to make the following line work? > > 10 + obj1 define "work". if you want it to modify obj1 (and thus confuse the heck out of anyone trying to use your class), implement __radd__. if you want to create a sane accumulator, I recommend implementing += assignment instead, by overloading __iadd__ instead of __add__. From rosedb0 at gmail.com Thu Aug 17 08:59:59 2006 From: rosedb0 at gmail.com (hiaips) Date: 17 Aug 2006 05:59:59 -0700 Subject: MySQLdb installation error In-Reply-To: References: Message-ID: <1155819599.792279.277920@m79g2000cwm.googlegroups.com> What I'm getting at is that it looks like one of these arch flags needs to be removed, as a previous poster said. I remember having a similar issue with an arch flag when installing some Python module (don't remember whether it was MySQLdb or not), and I fixed it by installing the Universal SDK that comes with XCode on OS 10.4. If this is not an option for you (and it sounds as though it may not be), you might also try editing the Makefile to remove the flag corresponding to the architecture that does not match your system. "uname -a" should tell you which architecture you're on as well as what version of the OS you're running. From sjmachin at lexicon.net Mon Aug 14 14:42:48 2006 From: sjmachin at lexicon.net (John Machin) Date: 14 Aug 2006 11:42:48 -0700 Subject: TypeError: 'module' object is not callable (newby question) References: Message-ID: <1155580968.024991.107040@i3g2000cwc.googlegroups.com> Charles Russell wrote: > Why does this work from the python prompt, but fail from a script? > How does one make it work from a script? > > #! /usr/bin/python > import glob > # following line works from python prompt; why not in script? > files=glob.glob('*.py') > print files > > Traceback (most recent call last): > File "./glob.py", line 2, in ? > import glob > File "/home/cdr/python/glob.py", line 5, in ? > files=glob.glob('*.py') > TypeError: 'module' object is not callable Short answer: Change the name of your script file. Long answer: It is attempting to emulate the mythical ooloo bird, which is allegedly capable of evading would-be predators by vanishing up its own fundamental orifice. This topological exploit won't be available in Python until the as yet still mythical Python 3000. Contemplate the following: C:\junk>type glob.py if __name__ == "__main__": print "*** Being run as a script ..." import glob print "glob was imported from", glob.__file__ print "glob.glob is", type(glob.glob) print "glob.glob was imported from", glob.glob.__file__ print "(glob.glob is glob) is", glob.glob is glob print "--- end of script" else: print "*** Aarrgghh!! I'm being imported as", __name__ import glob print "glob was imported from", glob.__file__ print "glob.glob is", type(glob.glob) print "glob.glob was imported from", glob.glob.__file__ print "(glob.glob is glob) is", glob.glob is glob print "--- end of import" C:\junk>glob.py *** Being run as a script ... *** Aarrgghh!! I'm being imported as glob glob was imported from C:\junk\glob.pyc glob.glob is glob.glob was imported from C:\junk\glob.pyc (glob.glob is glob) is True --- end of import glob was imported from C:\junk\glob.pyc glob.glob is glob.glob was imported from C:\junk\glob.pyc (glob.glob is glob) is True --- end of script HTH, John C:\junk> From andychambers2002 at yahoo.co.uk Fri Aug 18 15:52:52 2006 From: andychambers2002 at yahoo.co.uk (andychambers2002 at yahoo.co.uk) Date: 18 Aug 2006 12:52:52 -0700 Subject: couple more questions about sqlite In-Reply-To: References: Message-ID: <1155930772.591854.53910@m79g2000cwm.googlegroups.com> > 2. What's the difference between sqlite and pysqlite? Do you need both, > just one, or is one an older version of the same thing? To access your database from python you need both (or some alternative to pysqlite) > 3. What's the difference between the command line program called sqlite3 > and the module you would use with Python? (I know that the former let's > you do normal database things without dealing with Python, but is it > necessary if you are using Python to interact with the DB?) slqite comes with a library which other programs can call, and a command line interface that you can use from the shell. pysqlite needs the library but I don't think it is possible to get one without the other. Regards, Andy From pradeep.ramkrish at gmail.com Wed Aug 16 03:13:47 2006 From: pradeep.ramkrish at gmail.com (Pradeep) Date: 16 Aug 2006 00:13:47 -0700 Subject: Python form Unix to Windows Message-ID: <1155712427.551814.247010@74g2000cwt.googlegroups.com> Hi friends, We are changing the python application from Unix to Windows. The source code of Python application should work well in windows. How to make changed to windows environment. In Python code we have login module, ftp, socket programming. Please help in changing the code from Unix envirnment to Windows Environment. Thanks in Advance. Regards, Pradeep From fredrik at pythonware.com Wed Aug 23 02:51:06 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Aug 2006 08:51:06 +0200 Subject: how do you get the name of a dictionary? In-Reply-To: <1156284812.469380.274370@b28g2000cwb.googlegroups.com> References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> <1156264475.968894.221710@p79g2000cwp.googlegroups.com> <1156266720.205126.284050@i3g2000cwc.googlegroups.com> <1156268752.574983.123520@75g2000cwc.googlegroups.com> <1156281268.865624.302070@b28g2000cwb.googlegroups.com> <1156283135.985893.186500@m73g2000cwd.googlegroups.com> <1156284812.469380.274370@b28g2000cwb.googlegroups.com> Message-ID: jojoba wrote: >>>> no, you're just wasting a lot of bandwidth making it clear that you just >>>> cannot be bothered to learn how things actually work. > > By the way, what exactly led you to this conclusion? the fact that despite all attempts to explain how things work, you're still haven't realized that if you want the names of things, you should pass *namespaces* to your object viewer, not individual objects. From tjreedy at udel.edu Fri Aug 25 16:07:32 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 25 Aug 2006 16:07:32 -0400 Subject: time.clock() going backwards?? References: Message-ID: "Giovanni Bajo" wrote in message news:vkFHg.82529$_J1.759243 at twister2.libero.it... > Hello, > > I experimented something very strange, a few days ago. I was debugging an > application at a customer's site, and the problem turned out to be that > time.clock() was going "backwards", that is it was sometimes > (randomically) > returning a floating point value which was "less than" the value returned > by > the previous invokation. The computer was a pretty fast one (P4 3Ghz I > think, > running Windows XP), and this happened only between very close > invokations of > time.clock(). I seem to remember this being mentioned before on the list, perhaps by Tim Peters. Perhaps he will chime in. tjr From horst.jens at chello.at Tue Aug 1 02:19:44 2006 From: horst.jens at chello.at (Horst F. JENS) Date: Tue, 01 Aug 2006 08:19:44 +0200 Subject: ANN: Quest for the Holy Grail (a PyGame game) In-Reply-To: References: Message-ID: very nice game, i like it. -Horst From mcPas.De.Spam at mclaveauPas.De.Spam.com Wed Aug 23 15:32:54 2006 From: mcPas.De.Spam at mclaveauPas.De.Spam.com (Michel Claveau) Date: Wed, 23 Aug 2006 21:32:54 +0200 Subject: running windows 'start' cmd using spawnl References: Message-ID: Hi! You can use (exemple) : "cmd /cSTART notepad" -- @-salutations Michel Claveau From matt.hammond at rd.bbc.co.uk Thu Aug 31 07:33:56 2006 From: matt.hammond at rd.bbc.co.uk (Matt Hammond) Date: Thu, 31 Aug 2006 12:33:56 +0100 Subject: Broadcast server References: <1157015655.323891.154720@p79g2000cwp.googlegroups.com> Message-ID: On Thu, 31 Aug 2006 10:14:15 +0100, wrote: > I would like to write a server with the low level API of python ( > socket+select and/or socket+thread ) that allow me to register client > and update them every X seconds ( could be the time, the temperature, a > stock quote, a message , ... ). > > How to write the server that keep hot connections with clients and > update them when events are trigerred. I don't know how to begin this , > i look at the python doc but the doc is more related to client updating > the server and i am not sure of the right design that could be use > here. Kamaelia ( http://kamaelia.sf.net/ ) - the project I'm working on, feels like it may be well suited to this kind of task. Its based around having individual components that pass messages to each other. So you can envisage an event source propogating a message to all subscribed clients quite easily. Your source's of events can be components, that publish their events to a 'backplane' - a kind of distribution board that replicates messages sent to it to all subscribers. from Axon.Component import component from Kamaelia.Util.Backplane import Backplane, subscribeTo, publishTo from Kamaelia.Util.PipelineComponent import pipeline class EventSource(component): def main(self): while 1: if event_happens: self.send( "EVENT HAPPENED!\n", "outbox") yield 1 pipeline( EventSource(), publishTo("Events"), ).activate() Backplane("Events").activate() You can have any number of event sources, all 'publishing' to the same backplane. Then to handle clients connecting I'd create a server component, with a factory function that creates a component to handle each client connection. In this case, a component that 'subscribes' to messages coming from the backplane: from Kamaelia.Chassis.ConnectedServer import SimpleServer def clientHandlerFactory(): return subscribeTo("Events") SimpleServer(clientHandlerFactory).activate() Then I'd start the system running: from Axon.Scheduler import scheduler scheduler.run.runThreads() Things like the client handling could be extended relatively easily to marshall complex data types to strings, suitable for network transmission; or to manage clients choosing what data sources to subscribe to. If you think this approach might work for you, I'm happy to give you a hand with getting Kamaelia up and running, and with learning how to write your own components to make the system more sophisticated. We hang about on #kamaelia on freenode (irc) - please do drop in for a chat! Hope this helps! Matt -- | Matt Hammond | Research Engineer, Tech. Group, BBC, Kingswood Warren, Tadworth, Surrey, UK | http://kamaelia.sf.net/ | http://www.bbc.co.uk/rd/ From jdjmson at yahoo.com Thu Aug 31 18:23:53 2006 From: jdjmson at yahoo.com (JDJMSon) Date: 31 Aug 2006 15:23:53 -0700 Subject: Boost Python Issue Message-ID: <1157063033.800940.181130@e3g2000cwe.googlegroups.com> I was wondering if someone here could help me with a problem I'm having building Python extensions with the Boost.Python library. Basically, if I have a wrapper class with something like this: string TestFunc() { return "Hello World"; } BOOST_PYTHON_MODULE(TestClass) { def("TestFunc",TestFunc); } It compiles and I can use it without a problem. However, when I try to wrap a class with code like this: class TestClass { public: TestClass() {}; ~TestClass() {}; string TestFunction(){return "Hello World";}; }; BOOST_PYTHON_MODULE(TestClass) { class_("TestClass") .def("TestFunction",&TestClass.TestFunction) ; } I get the following error: vc-C++ bin\PythonTest\TestClass.pyd\vc-8_0\debug\threading-multi\TestClass.obj TestClass.cpp TestClass.cpp(27) : error C2976: 'boost::python::class_' : too few template arguments c:\Development\Boost\boost_1_33_1\boost/python/def_visitor.hpp(14) : see declaration of 'boost::python::class_' TestClass.cpp(27) : error C2440: '' : cannot convert from 'const char [10]' to 'boost::python::class_' Source or target has incomplete type I'm using Visual Studio 2005 Express Edition (I get the same error with 2003 Professional), and am using bJam to build the extension. Does anyone have any idea what's causing this? From python.list at tim.thechases.com Fri Aug 25 17:29:21 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 25 Aug 2006 16:29:21 -0500 Subject: RE Module In-Reply-To: <44ef5ba7$0$8907$88260bb3@free.teranews.com> References: <1156478366.165463.277480@h48g2000cwc.googlegroups.com> <44ef3f95$0$8926$88260bb3@free.teranews.com> <1156539112.253232.321820@i3g2000cwc.googlegroups.com> <44ef5ba7$0$8907$88260bb3@free.teranews.com> Message-ID: <44EF6BB1.4050700@tim.thechases.com> >> Also, what made the expression greedy? > > They usually are, by default. It means that when there > are more than one ways to match the pattern, choose the > one that matches the most text. Often there are flags > available to change that behavior. I'm not sure off hand > how to do it with the re module. In python's RE module, they're like Perl: Greedy: "<.*>" Nongreedy: "<.*?>" By appending a question-mark onto the operator, one makes it a non-greedy repeat. It also applies to the plus ("one or more") and the questionmark ("zero or one") -tkc From claird at lairds.us Sun Aug 13 16:52:27 2006 From: claird at lairds.us (Cameron Laird) Date: Sun, 13 Aug 2006 20:52:27 +0000 Subject: yet another noob question References: <1155492110.659011.196280@75g2000cwc.googlegroups.com> <1hk0bm6.1h1ggx2imu1mN%aleax@mac.com> Message-ID: In article <1hk0bm6.1h1ggx2imu1mN%aleax at mac.com>, Alex Martelli wrote: >mike_wilson1333 wrote: > >> I would like to generate every unique combination of numbers 1-5 in a 5 >> digit number and follow each combo with a newline. So i'm looking at . . . >but these variations are all implementing the same algorithm. One >algorithms that's definitely different enough to distinguish is to use >recursion -- but it won't offer much advantage over this one. > > >Alex For light reading on still other enumerations and their algorithms, see . From elpX at adsihqX.com Fri Aug 11 17:04:12 2006 From: elpX at adsihqX.com (Dr. Pastor) Date: Fri, 11 Aug 2006 14:04:12 -0700 Subject: Learning Python Message-ID: <1155329631_4653@sp6iad.superfeed.net> Attempting to learn Python; I constructed the module listed below. I would like to make it shorter, faster, more "Python like". (Windows XP, Pro.) Many thanks for any advice! ... #------------------------------------------------------------------------------- # Name: SendMoreMoney.py # Purpose: A solution to the SEND+MORE=MONEY puzzle. # # Author: Dr. Pastor # # Copyright: (c) Dr. Pastor 2006 #------------------------------------------------------------------------------- #!/usr/bin/env python # # The solution for the puzzle of # SEND # +MORE # ----- # MONEY # def perm(items, n=None): if n is None: n = len(items) for i in range(len(items)): v = items[i:i+1] if n == 1: yield v else: rest = items[:i] + items[i+1:] for p in perm(rest, n-1): yield v + p def comb(items, n=None): if n is None: n = len(items) for i in range(len(items)): v = items[i:i+1] if n == 1: yield v else: rest = items[i+1:] for c in comb(rest, n-1): yield v + c # # S E N D M O R Y # ['0','1','2','3','4','5','6','7','8','9'] # print print "Selections of 8 items from 10 then the permutation of them." print b=0 for s in comb([0,1,2,3,4,5,6,7,8,9],8): for a in perm(s,None): if (a[4]*1000+a[5]*100+a[2]*10+a[1])*10+a[7] == \ (a[0]+a[4])*1000+(a[1]+a[5])*100+(a[2]+a[6])*10+(a[3]+a[1]): b += 1 print ' SEND', ' ',a[0],a[1],a[2],a[3] print ' MORE', ' ',a[4],a[5],a[6],a[1] print ' ----', ' ---------' print 'MONEY', '',a[4],a[5],a[2],a[1],a[7] print print "There are ", b, " solutions." print ... ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From maciej at localhost.localnet Mon Aug 21 14:08:23 2006 From: maciej at localhost.localnet (=?iso-8859-2?q?Maciej_Blizi=F1ski?=) Date: Mon, 21 Aug 2006 20:08:23 +0200 Subject: Detect current virtual desktop References: Message-ID: On Mon, 21 Aug 2006 12:52:59 +0200, Harald Karner wrote: > Maciej Blizi?ski wrote: >> How to detect current virtual desktop in GNOME? How to detect a virtual >> desktop change? >> > Take a look at http://wallpapoz.sourceforge.net/ Harald, many thanks. By the way, I have found the line of code I was interested in. It is stunningly simple, just calls the xprop command: os.popen('xprop -root _NET_CURRENT_DESKTOP').read() -- http://automatthias.wordpress.com From ray_usenet at yahoo.com Mon Aug 21 05:38:49 2006 From: ray_usenet at yahoo.com (Ray) Date: 21 Aug 2006 02:38:49 -0700 Subject: Python and STL efficiency In-Reply-To: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> Message-ID: <1156153129.798052.225980@m79g2000cwm.googlegroups.com> How did you compile the C++ executable? I assume that it is Release mode? Then are the optimization switches enabled? Is it compiled as Native Win32 or Managed application? I suspect that other than what other posters have suggested about your code, the difference in speed is due to the way you build your C++ executable... HTH, Ray Licheng Fang wrote: > Hi, I'm learning STL and I wrote some simple code to compare the > efficiency of python and STL. > > //C++ > #include > #include > #include > #include > #include > using namespace std; > > int main(){ > vector a; > for (long int i=0; i<10000 ; ++i){ > a.push_back("What do you know?"); > a.push_back("so long..."); > a.push_back("chicken crosses road"); > a.push_back("fool"); > } > set b(a.begin(), a.end()); > unique_copy(b.begin(), b.end(), ostream_iterator(cout, "\n")); > } > > #python > def f(): > a = [] > for i in range(10000): > a.append('What do you know') > a.append('so long...') > a.append('chicken crosses road') > a.append('fool') > b = set(a) > for s in b: > print s > > I was using VC++.net and IDLE, respectively. I had expected C++ to be > way faster. However, while the python code gave the result almost > instantly, the C++ code took several seconds to run! Can somebody > explain this to me? Or is there something wrong with my code? From danb_83 at yahoo.com Sun Aug 20 02:04:51 2006 From: danb_83 at yahoo.com (Dan Bishop) Date: 19 Aug 2006 23:04:51 -0700 Subject: trouble using "\" as a string References: <1156023013.462640.165970@i42g2000cwa.googlegroups.com> Message-ID: <1156053891.106791.188340@p79g2000cwp.googlegroups.com> OriginalBrownster wrote: > Hi there... > > I'm still pretty new to turbogears. but i have gotten pretty familiar > with it > > i'm just trying to clear something up, i'm having a difficult time > using \ when declaring a string expression > > such as tempname="\"..it says that the line is single qouted. > > i want this because using python I am pulling in filenames from a > mac..thus they are "/" in the pathways..and i want to .split it at the > "/" to obtain the filename at the end...but its proving diffucult with > this obstacle in the way. > > Why is this happening?? In Python (and many other programming languages), the backslash is the "escape character". That is, special characters are indicated by sequences that start with a backslash. >>> print 'Line 1\nLine 2' # \n = newline Line 1 Line 2 >>> print 'tab\tseparated\ttext' # \t = tab tab separated text >>> print 'This parrot is dead\b\b\b\balive!' # \b = backspace This parrot is alive! >>> print 'The ASCII code for \x41 is 0x41.' The ASCII code for A is 0x41. >>> 'It\'s necessary to escape a quote that\'s within the same type of quote.' "It's necessary to escape a quote that's within the same type of quote." An escape sequence is always considered a single character. (As mentioned earlier, you can verify this with the len function.) Thus, your "\" gets parsed as: " = opening quote of string \" = double quotation mark (escaped) end of line = error, because no closing quote was found If you want a backslash, you have to escape *it* with a backslash: "\\" From st at tobiah.org Tue Aug 29 19:31:35 2006 From: st at tobiah.org (tobiah) Date: Tue, 29 Aug 2006 16:31:35 -0700 Subject: Split with python In-Reply-To: References: <44F47F9E.9050404@khine.net> Message-ID: <44f4c138$0$8860$88260bb3@free.teranews.com> Tim Chase wrote: > Norman Khine wrote: >> Hello, >> I have a csv file which is has a field that has something like: >> >> text.csv >> "text (xxx)" >> "text (text) (yyy)" >> "text (text) (text) (zzz)" >> >> I would like to split the last '(text)' out and put it in a new >> column, so that I get: >> >> new_test.csv >> "text","(xxx)" >> "text (text)","(yyy)" >> "text (text) (text)","(zzz)" >> >> how can this be done? > > line.rsplit(None, 1) > > seems to do the trick for me: > > >>> tests=[ > ... ("text (xxx)", ("text","(xxx)")), > ... ("text (text) (yyy)", ("text (text)","(yyy)")), > ... ("text (text) (text) (zzz)", ("text (text) (text)","(zzz)")) > ... ] > >>> for test, result in tests: > ... r = test.rsplit(None,1) > ... if r[0] <> result[0] or r[1] <> result[1]: > ... print test, result > ... > > shows that the results of rsplit() match the expected results. > > -tkc Of course, fixing the csv file takes a little more work. It sounds like the test lines given were just one of the fields, and there are the quotes to worry about. csvfile: "field1","text (xxx)","field3" "field1","text (text) (yyy)","field3" "field1","text (text) (text) (zzz)","field3" ................................ import sys def fix(x): for line in open('csvfile'): fields = line.split(',') first, last = fields[x].rsplit(None, 1) fields[x] = first + '"' fields.insert(x + 1, '"' + last) sys.stdout.write(','.join(fields)) fix(1) ................................ "field1","text","(xxx)","field3" "field1","text (text)","(yyy)","field3" "field1","text (text) (text)","(zzz)","field3" But then this fails if there are commas in the data. I could split and join on '","' but then that fails when 'x' is either the first or last field. Are there tools in the csv module that make this easier? Tobiah -- Posted via a free Usenet account from http://www.teranews.com From http Fri Aug 18 21:58:00 2006 From: http (Paul Rubin) Date: 18 Aug 2006 18:58:00 -0700 Subject: sum and strings References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <7xr6zel2r2.fsf@ruckus.brouhaha.com> Message-ID: <7xd5axh4gn.fsf@ruckus.brouhaha.com> Georg Brandl writes: > Why would you try to sum up strings? Besides, the ''.join idiom is quite > common in Python. Just because it's common doesn't mean it's obvious. In my opinion it's as ugly as sin, and the fact that it's an idiom shows a shortcoming in Python. The obvious reason for summing strings is that it's a long-established feature of Python that a+b concatenates two strings, so summing a,b,c,d,e should result in a+b+c+d+e. From johnjsal at NOSPAMgmail.com Thu Aug 10 10:12:41 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 10 Aug 2006 14:12:41 GMT Subject: why does getpass() show the input? In-Reply-To: <1155168736.723934.308610@75g2000cwc.googlegroups.com> References: <1155168736.723934.308610@75g2000cwc.googlegroups.com> Message-ID: John Machin wrote: > Is that meant to be a statement or a question? Heh heh, sorry! I guess both. Let me clarify: > (1) what platform you are running on, WinXP >(2) did you enter that at > the usual OS command line (with/without readline), or in an IDE (e.g > IDLE) or some other shell (e.g. IPython) IDLE >(3) version numbers of Python > and any other relevant software 2.4.3 and nothing else special is running >(4) Is the question idle curiosity yes, most of my questions are :) >(5) have you been molesting your > console with e.g. stty ... nope, none of that stuff > (6) what conclusions you have after reading > /Lib/getpass.py if sys.stdin is not sys.__stdin__: return default_getpass(prompt) Ah ha! So it only works at the command prompt, unless I change __stdin__? Thanks for teaching me a lesson! From ldo at geek-central.gen.new_zealand Sun Aug 20 05:08:44 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 20 Aug 2006 21:08:44 +1200 Subject: Permission Denied References: <1156038847.616137.61800@m79g2000cwm.googlegroups.com> Message-ID: In message , AlbaClause wrote: > Then, to execute the file from from the shell prompt, I had to create a > 'bin' directory in my home folder, cuz I didn't want to litter > my /usr/local/bin folder with useless Python scripts. Executable files can be kept anywhere, you don't need a special directory for them. From jzgoda at o2.usun.pl Wed Aug 2 17:56:07 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Wed, 02 Aug 2006 23:56:07 +0200 Subject: VisualStudio2005 supported in distutils In-Reply-To: <44D11BC3.40802@v.loewis.de> References: <44D11BC3.40802@v.loewis.de> Message-ID: Martin v. L?wis napisa?(a): >>Unfortunately, distutils does not support VisualStudio2005. I tried to >>modify the file msvccompiler.py without success (this case requires to >>support some changes of the Visual Studio 8 register for both Win32 and >>Win64). So, I wonder if the integration of VisualStudio2005 in distutils >>is scheduled in the Python developments or better, if someone has >>experiences or patch to support VisualStudio2005 in distutils. > > You shouldn't attempt to do that. Even if you manage to convince > distutils to use VS 2005 to compile your extension, the resulting > code may crash Python because of obscure incompatibilities between > the compiler that was used to compile Python (VS 2003) and the compiler > that was used to compile the extension (VS 2005). > > Whether or not it will actually crash depends on obscure details > of the API that the extension uses. Sure, but what if I succesfully compile Python with VS 2005? Hier ist der Hund begraben, distutils cann't handle this compiler so I'll be unable to compile any extension for my home-baken Python. -- Jarek Zgoda http://jpa.berlios.de/ From apardon at forel.vub.ac.be Tue Aug 29 01:45:27 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 29 Aug 2006 05:45:27 GMT Subject: Is this a good idea or a waste of time? References: <1156449402.022781.292840@p79g2000cwp.googlegroups.com> <1156485945.967160.238790@m73g2000cwd.googlegroups.com> <44f322cd$1@nntp0.pdx.net> <1156802762.331853.80000@75g2000cwc.googlegroups.com> Message-ID: On 2006-08-29, Gabriel Genellina wrote: > At Tuesday 29/8/2006 01:28, Antoon Pardon wrote: > >> > Antoon Pardon wrote: >> >> There seem to be enough problems that work with ints but not with >> >> floats. In such a case enforcing that the number you work with >> >> is indeed an int seems fully appropiate. >> > >> > I've _never_ seen a case where enforcing types in the manner of the OP >> > is appropriate. >> > >> > It fails with trivial wrappers like >> > >> > class myInt(int): >> > def printFormatted(self): >> > .......... >> > >> > Even looser checking with isinstance is rarely right. You may want to >> > exclude floats, but that doesn't mean you want to exclude int-like >> > objects that don't inherit from int. >> >>That may be true. But one may wonder if this is a failing of the >>programmer or a failing of the language that doesn't support >>such things. > > In any case, I don't see how this supports the original claim that > strict type checking input params is good practice. I'm not defending that claim. I'm just putting question marks with the claim that strict type checking input parameters is bad practice. -- Antoon Pardon From you at cogeco.ca Sat Aug 26 16:45:18 2006 From: you at cogeco.ca (AlbaClause) Date: Sat, 26 Aug 2006 16:45:18 -0400 Subject: Learning Python - Have Question. Message-ID: <8l2Ig.3933$ED.894@read2.cgocable.net> I'm just learning Python, and I have a question about os.path.join(dirpath, name) and its use. Simply put, I haven't figured out how to use it. I was looking through the Python reference material in the wee hours of the morning and checking out some of the modules. I was keenly interested in the os module, as it is necessary for me to learn this stuff in order to begin my first real Python project. I was looking at os.walk(top) when I read a little blurb about using os.path.join(dirpath, name) to get complete directory listings with path/filname. Unfortunately, I was unable to figure out how to use it. I kept getting an error with a message something like "b.startswith" or something like that. I was also unable to find any other information about this in the reference material. If someone could offer some insight into the use of os.path.join(dirpath, name), I would really appreciate it. Oh, I have one more question. So far everything that I've played with yields only the filename of file. I am aware that os.walk will place the pathnames and filenames in a tuple, but I'm wondering if there is a way to input a full path directory from within Python. Specifically, I want to be able to get directories like one would get by entering "ls -l" at a *nix shell prompt. Thanks. -- -- There are several things that I will never be: * I will never be attracted to females. * I will never enjoy the company of others. Exactly how these realities bode for my enemy, is not of my concern. From taleinat at gmail.com Fri Aug 4 06:11:27 2006 From: taleinat at gmail.com (taleinat) Date: Fri, 4 Aug 2006 10:11:27 +0000 (UTC) Subject: regex question References: <1983a3190608031410n71eaa4d1s2a3db7c10c519b88@mail.gmail.com> Message-ID: Gabriel Murray gmail.com> writes: > > Hello, I'm looking for a regular expression which will match strings as follows: if there are symbols a, b, c and d, then any pattern is valid if it begins with a and ends with d and proceeds in order through the symbols. However, at any point the pattern may reset to an earlier position in the sequence and begin again from there. > For example, these would be valid patterns:aabbbaabbcccbbbcccdddaabcabcdabcdBut these would not:aaaaabbbbbccccaaaaadddd (goes straight from a to d)aaaaaaaaaaabbbbbccc (does not reach d)Can anyone think of a concise way of writing this regex? The ones I can think of are very long and awkward.Gabriel > Your cirteria could be defined more simply as the following: * must start with an 'a' and end with a 'd' * an 'a' must not be followed by 'c' or 'd' * a 'b' must not be followed by 'd' Therefore the regexp can more simply be written as: regexp = re.compile(r'''a ( a(?!c|d) | b(?!d) | c | d )* d''', re.VERBOSE) Test code: tests = [ ('abcd', True), ('aaaaaaaaaaabbbbbccc', False), ('aabbccaabbccabcdddcabababbbccccdddd', True), ('aabbccaabbccabcabababbbccccddddabcd', True), ('aaaaabbbbbccccaaaaadddd', False), ('aabbccaabbccacabababbbccccdddd', False), ('abccccdaaaabbbbccccd', True), ('abcdcd', True), ('aabbbaabbcccbbbcccddd', True), ('aabbccaabbccabcabababbbccccdddd', True), ('abccccdccccd', True), ('aabcabcd', True) ] def checkit(regexp, tests=tests): for test, expected in tests: matched = regexp.match(test) is not None if matched == expected: print "PASSED: %s with %s" % (test, expected) else: print "FAILED: %s with %s" % (test, expected) >>> checkit(regexp, tests) PASSED: abcd with True PASSED: aaaaaaaaaaabbbbbccc with False PASSED: aabbccaabbccabcdddcabababbbccccdddd with True PASSED: aabbccaabbccabcabababbbccccddddabcd with True PASSED: aaaaabbbbbccccaaaaadddd with False PASSED: aabbccaabbccacabababbbccccdddd with False PASSED: abccccdaaaabbbbccccd with True PASSED: abcdcd with True PASSED: aabbbaabbcccbbbcccddd with True PASSED: aabbccaabbccabcabababbbccccdddd with True PASSED: abccccdccccd with True PASSED: aabcabcd with True - Tal From jojoba12 at hotmail.com Sun Aug 6 13:10:50 2006 From: jojoba12 at hotmail.com (jojoba) Date: 6 Aug 2006 10:10:50 -0700 Subject: why did wxpython MakeActiveXclass stopped working?!?!!?!? Message-ID: <1154884250.224877.229650@p79g2000cwp.googlegroups.com> HI I wrote a little wxpython program with an embedded windows media player. It worked great. Recently, I reinstalled windows and then wxpython (most likely a newer version than i had before). Now when i run the exact same code, i get this error: File "C:\Documents and Settings\jojoba.DEMO-019591FB22\Desktop\Projects\SrAsse ts\sr.py", line 353, in __init__ self.CreateActiveXplayer() File "C:\Documents and Settings\jojoba.DEMO-019591FB22\Desktop\Projects\SrAsse ts\sr.py", line 363, in CreateActiveXplayer self.Player = PlayerActiveXClass(self, -1) File "C:\Python24\Lib\site-packages\wx-2.6-msw-ansi\wx\lib\activexwrapper.py", line 108, in axw__init__ (0, 0, sz.width, sz.height), self._wnd, ID) File "C:\Python24\Lib\site-packages\pythonwin\pywin\mfc\activex.py", line 23, in CreateControl self.__dict__["_obj_"] = win32ui.CreateControl(clsid, windowTitle, style, re ct, parent, id, None, False, lic_string) win32ui: The window can not be created as it has an invalid handle Here is a snippet from my code: from wxPython.lib.activexwrapper import MakeActiveXClass import win32com from win32com import client class wxWMPlayer(wxPanel): def __init__(self, parent): wxPanel.__init__(self, parent, -1, style=wxCLIP_CHILDREN|wxNO_FULL_REPAINT_ON_RESIZE) self.MixMaster = parent self.ID3data = {} self.InitWindowProperties() self.CreateActiveXplayer() def InitWindowProperties(self): self.WindowsMediaPlayerTopSizer = wxBoxSizer(wxVERTICAL) self.SetSizer(self.WindowsMediaPlayerTopSizer) self.SetAutoLayout(1) def CreateActiveXplayer(self): PlayerModule = win32com.client.gencache.EnsureModule('{6BF52A50-394A-11D3-B153-00C04F79FAA6}', 0,1,0) PlayerActiveXClass = MakeActiveXClass(PlayerModule.WindowsMediaPlayer, eventObj = self) self.Player = PlayerActiveXClass(self, -1) self.Player.isPlaying = 0 self.Player.uiMode = 'full' self.WindowsMediaPlayerTopSizer.Add(self.Player, 1, wxEXPAND) Any ideas anyone...i have reinstalled wxpython to no avail....Please help anyone.... thanks, jojoba From duncan.booth at invalid.invalid Tue Aug 1 07:58:50 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Aug 2006 11:58:50 GMT Subject: Any gotchas in returning a subclass instance from __new__? References: <1154431403.035779.176330@h48g2000cwc.googlegroups.com> Message-ID: wrote: > Hi All, > > Is anything wrong with the following code? > > class Superclass(object): > def __new__(cls): > # Questioning the statement below > return super(Superclass, cls).__new__(Subclass) > class Subclass(Superclass): > pass > if __name__ == '__main__': > instance = Superclass() > print instance > The only problems I can think if is that if you create any other subclasses of Superclass, or of Subclass for that matter then you'll never succeed in creating any of them, and the constructor i.e. __new__ of the subclass never gets called. I've used this technique where the Superclass iterates through all of its subclasses and uses the constructor parameters to choose the most appropriate subclass to construct. Eventually though I changed it to use a separate factory function: that way the __new__ methods get called in the expected order. So something like: @classmethod def fromMimetype(cls, m): for subclass in Superclass._handlers(): if subclass.supportsMimetype(m): return subclass(m) @classmethod def _handlers(cls): for c in cls.__subclasses__(): for sub in c._handlers(): yield sub yield c > It works here, and even constructors for Subclass and Superclass are > invoked (in correct order), even though such behavior is not explicitly > stated here http://docs.python.org/ref/customization.html. So, am I > asking for trouble or is it /the/ way to go about transforming base > class into a factory? > Thank you, > I think you meant the initialisers are invoked correctly (the constructor is the __new__ method): this isn't suprising since the system simply calls __init__ on the returned object so the correct thing just happens. From noway at sorry.com Fri Aug 25 12:13:15 2006 From: noway at sorry.com (Giovanni Bajo) Date: Fri, 25 Aug 2006 16:13:15 GMT Subject: time.clock() going backwards?? Message-ID: Hello, I experimented something very strange, a few days ago. I was debugging an application at a customer's site, and the problem turned out to be that time.clock() was going "backwards", that is it was sometimes (randomically) returning a floating point value which was "less than" the value returned by the previous invokation. The computer was a pretty fast one (P4 3Ghz I think, running Windows XP), and this happened only between very close invokations of time.clock(). I have triple-verified this, including printing the repr() of the floating point number and verifying it was really minor than the previous value by a few microseconds. In other words, I'm absolutely positive that it's not a mistake on my side, but that time.clock() was really apparently "jumping backward". This was confusing the hell out of my application, of course, and I just hacked it so to ignore these bogus reads, and just reading off again. Since the error was just of a few microseconds, reading time.clock() again produces a number which was higher than what I had before, and thus OK for my application. I was wondering if someone had experimented this behaviour before. I tried googling but to no effect. Is it possible this to be a bug in Python itself (maybe, shooting at the moon, in the conversion between the 64bit performance counter and the floating point representation returned by time.clock()), or could it be a bug in Windows itself or the mother board drivers (buf if so, wouldn't other application start going mad)? -- Giovanni Bajo From apardon at forel.vub.ac.be Mon Aug 28 06:30:49 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 28 Aug 2006 10:30:49 GMT Subject: Is this a good idea or a waste of time? References: <1156449402.022781.292840@p79g2000cwp.googlegroups.com> <1156485945.967160.238790@m73g2000cwd.googlegroups.com> Message-ID: On 2006-08-25, Simon Forman wrote: > asincero wrote: >> Would it be considered good form to begin every method or function with >> a bunch of asserts checking to see if the parameters are of the correct >> type (in addition to seeing if they meet other kinds of precondition >> constraints)? Like: >> >> def foo(a, b, c, d): >> assert type(a) == str >> assert type(b) == str >> assert type(c) == int >> assert type(d) == bool >> # rest of function follows >> >> This is something I miss from working with more stricter languages like >> C++, where the compiler will tell you if a parameter is the wrong type. >> If anything, I think it goes a long way towards the code being more >> self documenting. Or is this a waste of time and not really "the >> Python way"? >> >> -- Arcadio > > Generally asserts should be used to "enforce" invariants of your code > (as opposed to typechecking), or to check certain things while > debugging. I don't understand this argument. Can't type checking be seen as enforcing a code invariant? -- Antoon Pardon From nevillednz at gmail.com Tue Aug 15 22:31:38 2006 From: nevillednz at gmail.com (NevilleDNZ) Date: 15 Aug 2006 19:31:38 -0700 Subject: proc A def/calls proc B: variable scoping rules. In-Reply-To: References: <1155685233.002415.184150@74g2000cwt.googlegroups.com> <1155692329.075173.49060@p79g2000cwp.googlegroups.com> Message-ID: <1155695497.999739.295650@m73g2000cwd.googlegroups.com> I inserted x1,x2 into A to force a wider scope and it works. #!/usr/bin/env python def A(): print "begin A:" A.x1=123; A.x2=456; def B(): print "begin B:",A.x1,A.x2 A.x2 = A.x2 + 210; # problem gone. print "end B:",A.x1,A.x2 print "pre B:",A.x1,A.x2 B() print "end A:",A.x1,A.x2 A() $ ./z1z2.py begin A: pre B: 123 456 begin B: 123 456 end B: 123 666 end A: 123 666 $ python -V Python 2.5b3 I checked: This method even handles recursion giving a new instance of A.x2 each call. Is this the official way to scope/inherit scopes in sub procs? ThanX NevilleD From blue99 at interia.pl Wed Aug 23 05:26:29 2006 From: blue99 at interia.pl (Rob Wolfe) Date: 23 Aug 2006 02:26:29 -0700 Subject: Create a Multilanguage PDF in Python In-Reply-To: <1156272524.800930.27710@p79g2000cwp.googlegroups.com> References: <1156073383.983914.149180@i3g2000cwc.googlegroups.com> <87mz9z4f8h.fsf@smsnet.pl> <1156108451.762961.70140@h48g2000cwc.googlegroups.com> <1156143575.547217.237270@p79g2000cwp.googlegroups.com> <1156172609.125230.218190@i42g2000cwa.googlegroups.com> <4ku5d0Fdsn8fU1@uni-berlin.de> <1156272524.800930.27710@p79g2000cwp.googlegroups.com> Message-ID: <1156325189.795356.45770@b28g2000cwb.googlegroups.com> Perseo wrote: > Nothing to do! > I enable test2.py and the folder with 777 permission and I write at the > top of the file the PYTHONPATH "#!/usr/bin/python" as you told me but > it doesn't works as well. #!/usr/bin/python is not PYTHONPATH. I think you should read this: http://docs.python.org/tut/node4.html#SECTION004220000000000000000 > The verdana font doesn't exist in the reportlab fonts folder. I try to > delete the rows where it is called like (registerFont, setFont) but > nothing to do. Fonts are not part of reportlab package. You should find it in your OS or in the net. You need to know what font do you want to use. > any suggestion?! Install reportlab package in your home directory, for example /home/perseo/python/lib and then in the shell write this: export PYTHONPATH=/home/perseo/python/lib and look here: http://docs.python.org/tut/node8.html#SECTION008110000000000000000 HTH, Rob From gelists at gmail.com Fri Aug 4 12:28:24 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Fri, 4 Aug 2006 13:28:24 -0300 Subject: Windows vs. Linux References: <1154301694.445639.99580@m79g2000cwm.googlegroups.com> Message-ID: On 2006-08-04 09:58:34, Sybren Stuvel wrote: >> They all (well, most of them) use computers in their administration; >> /that's/ the cost I was talking about, not the cost for the software >> industry :) > > Good point. Time more people started using Open Source :) Definitely. But don't hold your breath :) Gerhard From nathanbullock at gmail.com Wed Aug 9 14:45:44 2006 From: nathanbullock at gmail.com (nathanbullock at gmail.com) Date: 9 Aug 2006 11:45:44 -0700 Subject: os.path.normpath Message-ID: <1155149144.453575.181870@m79g2000cwm.googlegroups.com> I am using a windows box and passing a string like "../foo/../foo2" to normpath which then returns "..\\foo2". But if this string is going into a webpage link it should really be "../foo". Is there any way to tell os.path.normpath to act like we are an a unix style box? What about in the new python 2.5 Path class? Nathan From duncan.booth at invalid.invalid Fri Aug 25 04:30:46 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 25 Aug 2006 08:30:46 GMT Subject: how do you get the name of a dictionary? References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> <1156264475.968894.221710@p79g2000cwp.googlegroups.com> <1156266720.205126.284050@i3g2000cwc.googlegroups.com> Message-ID: Steven D'Aprano wrote: >>>>>> a, b, c, d = range(4) >>>>>> spam(a, b, c, d) >>> Traceback (most recent call last): >>> File "", line 1, in ? >>> File "", line 6, in spam >>> File "", line 5, in eggs >>> File "", line 4, in beans >>> ValueError: x is too small >>> >>> Of course you can't. x could be any one of a, b, c or d, and the >>> traceback doesn't give you enough information to tell which. >> >> for some reason, your example gives a different error on my machine: >> >> StrawManError: Attempt to construct Reductio ad absurdum argument >> failed > > Sheesh Fredrik, what's eating you? I'm trying to have a civil > discussion, and you're being deliberately obtuse. > I think you've missed the point that with the code you posted you raise the ValueError unconditionally, so x isn't *any* of a, b, c, or d. Perhaps, if you had produced a code sample where you tested some values for being in a suitable range and it wasn't obvious from the traceback which value was affected, you might have managed to make your point? Or perhaps you would have found it harder to obfuscate the code than you think it is. With the code you posted though, I'm afraid Frederik's observation was spot on. From nevillednz at gmail.com Wed Aug 16 00:36:43 2006 From: nevillednz at gmail.com (NevilleDNZ) Date: 15 Aug 2006 21:36:43 -0700 Subject: proc A def/calls proc B: variable scoping rules. In-Reply-To: References: <1155685233.002415.184150@74g2000cwt.googlegroups.com> <1155692329.075173.49060@p79g2000cwp.googlegroups.com> Message-ID: <1155703003.713810.58280@h48g2000cwc.googlegroups.com> Steven D'Aprano wrote: > Basically, when you access a variable name on the left hand side of an > assignment (e.g. "a = 1") ANYWHERE in a function, that name is local to > that function UNLESS it has been declared global. ThanX Steven, I am still getting used to python scoping rules. I didn't realise that using a variable on the left affected the variables on the right. I WAS trying to avoid making the variable GLOBAL, and just pick it out of the superior proc's scope. > > When you access a variable name as the right hand side of an assignment, > or as an expression (e.g. "print a"), Python searches for it following the > scoping rules: first it searches for it in the function's local variables, > then the local variables of the next higher scope, and so on, and finally > it searches for it amongst the globals (which is the top-level scope of > everything). I am more used to nested scopes, as in pascal/C. > > Play around with the code and see if it makes sense. I will certainly dabble with your example further. Many ThanX NevilleD BTW: here is my poor attempt at porting the "man boy test" algorithum to python. As you can see in python I am still a boy... :-) $ cat ./man_boy_test.py #!/usr/bin/env python def A(k, x1, x2, x3, x4, x5): A.k=k def B(): A.k = A.k - 1 B.out=A.out=A(A.k, B, x1, x2, x3, x4) return B.out if A.k <= 0: A.out = x4() + x5() else: B() return A.out if A(10,lambda:1,lambda:-1,lambda:-1,lambda:1,lambda:0)==-67: print "man" else: print "boy" # end man_boy_test.py $ ./man_boy_test.py boy From forum at anton.e4ward.com Wed Aug 9 13:48:11 2006 From: forum at anton.e4ward.com (Anton81) Date: Wed, 09 Aug 2006 19:48:11 +0200 Subject: Escape sequences (colour) and padding with "%8s"% Message-ID: Hi all! I used escape sequences to produce colour output, but a construct like print "%8s" % str_with_escape doesn't do the right thing. I suppose the padding counts the escape characters, too. What could be a solution? Anton From stargaming at gmail.com Mon Aug 14 05:06:58 2006 From: stargaming at gmail.com (Stargaming) Date: Mon, 14 Aug 2006 11:06:58 +0200 Subject: yet another noob question In-Reply-To: References: <1155492110.659011.196280@75g2000cwc.googlegroups.com> Message-ID: Jason Nordwick schrieb: > Or without filter: > > from operator import add > def pr(x): print x > def cross(x,y): return reduce(add, [[a+b for b in y] for a in x]) > x=map(pr, reduce(cross, [map(str,range(1,6))]*5)) > [...] reduce(add, list) is the same as sum(list) and is only half as fast as sum: >>> from timeit import Timer >>> sum(Timer("sum(range(500))").repeat(200, 1000))/200 0.055693786500798058 >>> sum(Timer("reduce(add, range(500))", "from operator import add").repeat(200, 1000))/200 0.10820861031220445 >>> Also note that reduce will be removed in Python 3000. From python.list at tim.thechases.com Mon Aug 14 13:49:27 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 14 Aug 2006 12:49:27 -0500 Subject: A little assistance with os.walk please. In-Reply-To: <44E0A836.5070700@tim.thechases.com> References: <1155566679.139086.279430@h48g2000cwc.googlegroups.com> <44E09561.1030902@websafe.com> <1155571727.168983.103480@m73g2000cwd.googlegroups.com> <44E0A836.5070700@tim.thechases.com> Message-ID: <44E0B7A7.9060409@tim.thechases.com> > >>> allowed = ['.txt', '.sql'] > >>> for path, dirs, files in os.walk("."): > ... for f in files: > ... if splitext(f)[1].lower() not in allowed: continue Additionally, if you really do want to specify wildcards: >>> allowed = ['*.txt', 'README*', '*.xml', '*.htm*'] >>> from glob import fnmatch >>> import os >>> for path, dirs, files in os.walk("."): ... good_files = [] ... for pat in allowed: ... good_files.extend(fnmatch.filter(files, pat)) ... if good_files: break ... for f in good_files: ... print "doing something with %s" % os.path.join(path, f) -tkc From rogue_pedro at yahoo.com Thu Aug 10 20:00:16 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 10 Aug 2006 17:00:16 -0700 Subject: error handling In-Reply-To: <1155253063.322440.97300@b28g2000cwb.googlegroups.com> References: <1155253063.322440.97300@b28g2000cwb.googlegroups.com> Message-ID: <1155254416.509449.145990@i42g2000cwa.googlegroups.com> Chris wrote: > I want to handle errors for a program i'm building in a specific way, > but I don't want to use try/except/finally because it requires forming > new blocks of code. I want to be able things like this: > > a = [2, 423, "brownie", 234.34] > try: a[890] > except IndexError: # I don't use 'finally' here because I specifically > want to check for an IndexError > sys.exit("That number is way too big!") > > But sometimes you can have too many of these statements in your > program, and it starts to get tangled and nasty looking. Is there a way > I can modify sys.error so that when the interpreter comes accross an > IndexError it prints "That number is way too big!" before it exits? You don't want to do what because why? Huh? I'm sorry man, I don't want to be harsh, but use try..except blocks. If your code is getting "tangled and nasty looking" you probably need to break it up into small[er] functions, or redesign it somehow. Peace, ~Simon (Also, there's no such thing as sys.error, do you mean sys.excepthook()?) From shadowcaster.bbs at bbs.wretch.cc Thu Aug 3 09:03:43 2006 From: shadowcaster.bbs at bbs.wretch.cc (¨ì©³¦b²Ö¤°»ò°Ú¡H) Date: 03 Aug 2006 13:03:43 GMT Subject: looking for a regular expression Message-ID: <4POChV$9OC@bbs.wretch.cc> ? ???__peter__ at web.de (Peter Otten)????? > ???????? wrote: > > Thanks a lot! I have never thought of that. > > But what if there's not only commas, but also periods and semicolons? I > > want to find words between 2 near by punctuations. I think it would make > > it difficult to use split instead of regular expression. > Reenter re. Use > re.split(r"[.;\-,]", my_string) > instead of my_string.split(","). > Peter Thank you for your help. -- ????????????????????????????????????? ????????????????????????????????????? ????????????????????????????????????? ????????????????????????????????????? ?????????????????210-64-83-167.adsl.dynamic.seed.net.tw? From anthra.norell at tiscalinet.ch Mon Aug 28 02:35:25 2006 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Mon, 28 Aug 2006 08:35:25 +0200 Subject: newbe question about removing items from one file to another file References: <1156714534.318183.326220@i3g2000cwc.googlegroups.com> Message-ID: <00e501c6ca6c$25eff780$0201a8c0@mcuf7> Eric, Having played around with problems of this kind for quite some time I find them challenging even if I don't really have time to get sidetracked. Your description of the problem makes it all the more challenging, because its 'expressionist' quality adds the challenge of guessing what you mean. I'd like to take a look at your data, if you would post a segment on which to operate, the same data the way it should look in the end. In most cases this is pretty self-explanatory. Explain the points that might not be obvious to a reader who knows nothing about your mission. Frederic ----- Original Message ----- From: Newsgroups: comp.lang.python To: Sent: Sunday, August 27, 2006 11:35 PM Subject: newbe question about removing items from one file to another file > def simplecsdtoorc(filename): > file = open(filename,"r") > alllines = file.read_until("") > pattern1 = re.compile(" orcfilename = filename[-3:] + "orc" > for line in alllines: > if not pattern1 > print >>orcfilename, line > > I am pretty sure my code isn't close to what I want. I need to be able > to skip html like commands from to and to key on > another word in adition to to end the routine > > I was also looking at se 2.2 beta but didn't see any easy way to use it > for this or for that matter search and replace where I could just add > it as a menu item and not worry about it. > > thanks for any help in advance > > -- > http://mail.python.org/mailman/listinfo/python-list From lsumnler at gmail.com Wed Aug 16 22:59:11 2006 From: lsumnler at gmail.com (len) Date: 16 Aug 2006 19:59:11 -0700 Subject: Newbie needs Help Message-ID: <1155783551.689026.273260@m73g2000cwd.googlegroups.com> Hi all I am writing a python program that inserts records into a database on XP using mxODBC. I need to write a section of code which will create the following SQL command as an example; INSERT INTO statecode (state, name) VALUES ('IL', 'Illinois') This statement will be built up using the following code; import mx.ODBC import mx.ODBC.Windows def insertFromDict(table, dict): """Take dictionary object dict and produce sql for inserting it into the named table""" sql = 'INSERT INTO ' + table sql += ' (' sql += ', '.join(dict) sql += ') VALUES (' sql += ', '.join(map(dictValuePad, dict)) # ??? this code does NOT format correctly sql += ')' return sql def dictValuePad(key): # ??? this code does Not format correctly return "'" + str(key) + "'" db = mx.ODBC.Windows.DriverConnect('dsn=UICPS Test') c = db.cursor() insert_dict = {'state':'IL', 'name':'Illinois'} sql = insertFromDict("statecode", insert_dict) print sql c.execute(sql) I copied this code off of ASP and I sure it worked for his particular circumstance but I need to format up the VALUE clause just a bit different. I will be working from a dictionary which will be continualy update in another part of the program and this code is working. Len Sumnler From g.brandl-nospam at gmx.net Wed Aug 23 12:44:35 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Wed, 23 Aug 2006 18:44:35 +0200 Subject: how do you get the name of a dictionary? In-Reply-To: <1156351145.331923.73190@m79g2000cwm.googlegroups.com> References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> <1156264475.968894.221710@p79g2000cwp.googlegroups.com> <1156266720.205126.284050@i3g2000cwc.googlegroups.com> <1156268752.574983.123520@75g2000cwc.googlegroups.com> <1156281268.865624.302070@b28g2000cwb.googlegroups.com> <1156283135.985893.186500@m73g2000cwd.googlegroups.com> <1156284812.469380.274370@b28g2000cwb.googlegroups.com> <1156350580.363393.256730@74g2000cwt.googlegroups.com> <1156351145.331923.73190@m79g2000cwm.googlegroups.com> Message-ID: jojoba wrote: >> And what im saying is that isnt it silly that we need pass an entire >> namespace, when a much simpler notion would be to have each object know >> its own name(s) (even if that name doesnt exist). > > > please note: in my above comment, i was completely disregarding any > notions of added costs that would be incurred to have such a feature, > and that in fact, such costs might actually nullify any other benefits > from having such a feature. Purely a what-if idea from a nascent python > programmer. Even from such a point of view, the concept isn't clearly enough defined. What name would be assigned to the dict below? l = [1,2,3] a = "some_str" l[0] = {'foo': 'bar'} Some immutable objects, such as small integers, exist only once. Would you assign names to them? They're likely to be completely meaningless. When a name goes out of scope, but the object continues to live (e.g. because it's returned by some function), the name is void. Etc. Georg From rogue_pedro at yahoo.com Tue Aug 1 17:10:19 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 1 Aug 2006 14:10:19 -0700 Subject: cleaner way to write this try/except statement? References: <44Pzg.2617$No6.51493@news.tufts.edu> Message-ID: <1154466619.481420.49140@i3g2000cwc.googlegroups.com> John Salerno wrote: > John Salerno wrote: > > The code to look at is the try statement in the NumbersValidator class, > > just a few lines down. Is this a clean way to write it? i.e. is it okay > > to have all those return statements? Is this a good use of try? Etc. > > I cleaned it up a little and did this, but of course this doesn't work. > Is this the wrong way to create a function (not method) within a class? > > > > def Validate(self, parent): > text_ctrl = self.GetWindow() > text = text_ctrl.GetValue() > > try: > if not text or int(text) <= 0: > error_message() > return False > else: > return True > except ValueError: > error_message() > return False > > @staticmethod > def error_message(): > wx.MessageBox('Enter a valid time.', 'Invalid time entered', > wx.OK | wx.ICON_ERROR) Your indentation looks off. Your error_message() function should be at the same indentation as the rest of the body of the Validate() method (i.e. same as the try statement, "text_ctrl = ..." statements.) If that's not an artifact of posting it here then you'll need to correct that. Also, there's no need to declare the function a staticmethod, since it isn't. Other than that it looks ok to me, but I might have missed something. Peace, ~Simon From alisonken1 at gmail.com Sun Aug 13 19:46:15 2006 From: alisonken1 at gmail.com (alisonken1) Date: 13 Aug 2006 16:46:15 -0700 Subject: Nested if and expected an indent block In-Reply-To: <1155511725.874993.140020@b28g2000cwb.googlegroups.com> References: <1155511725.874993.140020@b28g2000cwb.googlegroups.com> Message-ID: <1155512775.186869.69190@m79g2000cwm.googlegroups.com> kagard at gmail.com wrote: > Greetings: > elif q.lower() == "some" # s in some is highlighted > Any ideas? Thanks in advance. > > Keith Would the missing colon have something to do with it? > elif q.lower() == "some": From fakeaddress at nowhere.org Fri Aug 25 05:18:18 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 25 Aug 2006 09:18:18 GMT Subject: sum and strings In-Reply-To: References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <1155922208.930580.135080@m79g2000cwm.googlegroups.com> <1156365271.487489.62640@m73g2000cwd.googlegroups.com> <44ECC789.1010202@tim.thechases.com> <44EDCFDE.9060604@tim.thechases.com> Message-ID: Fredrik Lundh wrote: > [...] besides, in all dictionaries I've consulted, the word "sum" > means "adding numbers". That's a result of not looking deeply enough. Fredrik Lundh is partially right, in that "Sum" usually refers to addition of numbers. Nevertheless, the idea that "sum" must refer to numbers is demonstrably wrong: Googling "define: sum" shows several counter-examples, the first of which is: The final aggregate; "the sum of all our troubles did not equal the misery they suffered." Numbers? What numbers? Lundh may be telling the truth about all the dictionaries he consulted, but anyone with Internet access could have looked -- and found -- further. Dictionary definition is not really the issue. Who could miss the correspondence between the addition operation and the sum function? Why would we choose a language or type system that cannot even make "+" and "sum" behave consistently? > are you sure it wouldn't be more predictable if "sum" > converted strings to numbers ? Definitely reject that idea. People so misguided as to want silent string-to-int conversion can use Perl. The problem here is unifying the "+" operator and the "sum" function, The former is one of Python's several 'special' methods; the latter is one of Python's pre-defined functions. See: http://docs.python.org/ref/numeric-types.html http://docs.python.org/lib/built-in-funcs.html And herein is the problem: A class may implement "__add__" any way the programmer chooses. Python should require, or at least document requirements, on further properties of addition. Python should insist that addition be symmetric an transitive, and classes implementing addition provide an additive identity. > (after all, questions about type errors like "cannot concatenate 'str' > and 'int' objects" and "unsupported operand type(s) for +: 'int' and > 'str'" are a *lot* more common than questions about sum() on string lists.) Right. Duck-typing can work, while sloppy typing is doomed. -- --Bryan From robert.kern at gmail.com Thu Aug 24 13:02:26 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 24 Aug 2006 12:02:26 -0500 Subject: Matrice Multiplication Problem In-Reply-To: References: Message-ID: mclaugb wrote: > I want to multiply two arrays: a matrice and the conjugate of its > transpose. Then i wish to invert the resulting matrix. You will want to ask numpy questions on the numpy mailing list. http://www.scipy.org/Mailing_Lists > In Matlab, the statement is : Z= inv(M .' * M) > > To implement in python, I simply cannot get this to work. Here is my code: > > from numpy import * > import scipy as Sci > from scipy.linalg import lu > m=array([[4,6+7j],[3+3j,7],[2+2j,4-7j]]) > z=m.conj().transpose() > q=z*m numpy arrays are not matrices. * performs elementwise multiplication. Use numpy.dot(z, m). -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From hpsekhon at googlemail.com Wed Aug 16 13:48:44 2006 From: hpsekhon at googlemail.com (Hari Sekhon) Date: Wed, 16 Aug 2006 18:48:44 +0100 Subject: Open file handles? In-Reply-To: <1155176530.509468.277200@h48g2000cwc.googlegroups.com> References: <1155074190.804203.173840@b28g2000cwb.googlegroups.com> <1155176530.509468.277200@h48g2000cwc.googlegroups.com> Message-ID: <44E35A7C.10201@googlemail.com> danielx wrote: > Is there an equivalent in windows? > > Jon wrote: > >> Perhaps using os you could work with lsof >> [http://www.linuxcommand.org/man_pages/lsof8.html] >> >> Jon >> >> Thomas Bartkus wrote: >> >>> This may be more of a Linux question, but I'm doing this from Python. ..... >>> >>> How can I know if anything (I don't care who or what!) is in the middle of >>> using a particular file? >>> >>> This comes in context of needing to copy a file BUT only if I can verify >>> that something else doesn't have an open write handle to that file. IOW - I >>> need to decline the operation if something else hasn't finished writing to >>> the file. >>> >>> How can I know? >>> Thomas Bartkus >>> > > yes, handle by sysinternals. www.sysinternals.com not really a python question, more along the lines of bash, which is why I could answer it.... -h -------------- next part -------------- An HTML attachment was scrubbed... URL: From sonaldgr8 at gmail.com Wed Aug 30 06:01:47 2006 From: sonaldgr8 at gmail.com (sonald) Date: 30 Aug 2006 03:01:47 -0700 Subject: how can i change the text delimiter In-Reply-To: References: <1156929540.715287.123060@h48g2000cwc.googlegroups.com> Message-ID: <1156932106.948885.63980@i3g2000cwc.googlegroups.com> Hi Amit, Thanks for a quick response... E.g record is: "askin"em" This entire text is extracted as one string but since the qualifier is double quotes("), therefore fastcsv parser is unable to parse it. If we can change the text qualifier to pipe(|), then the string will look like this: |askin"em| But for this the default text qualifier in fastcsv parser needs to be changed to pipe(|). how to do this? Also please note that the string cannot be modified at all. Thanks. Amit Khemka wrote: > sonald wrote: > > Hi, > > Can anybody tell me how to change the text delimiter in FastCSV Parser > > ? > > By default the text delimiter is double quotes(") > > I want to change it to anything else... say a pipe (|).. > > can anyone please tell me how do i go about it? > > You can use the parser constructor to specify the field seperator: > Python >>> parser(ms_double_quote = 1, field_sep = ',', auto_clear = 1) > > cheers, > amit. > > -- > ---- > Amit Khemka -- onyomo.com > Home Page: www.cse.iitd.ernet.in/~csd00377 > Endless the world's turn, endless the sun's Spinning, Endless the quest; > I turn again, back to my own beginning, And here, find rest. From jason at adapt.com Tue Aug 15 06:20:25 2006 From: jason at adapt.com (Jason Nordwick) Date: Tue, 15 Aug 2006 03:20:25 -0700 Subject: yet another noob question In-Reply-To: <1155621690.639191.309980@i3g2000cwc.googlegroups.com> References: <1155492110.659011.196280@75g2000cwc.googlegroups.com> <1155579814.930093.99840@75g2000cwc.googlegroups.com> <1155621690.639191.309980@i3g2000cwc.googlegroups.com> Message-ID: <44E19FE9.5010903@adapt.com> I use reduce to also do indexing, hashing with upsert semantics of lists of key-value pairs, transitioning through a state table, etc... Somebody else pointed out to me how odd it is of Python to be ditching reduce when Guido van Rossum was hired by Google, and Google is literally built on map and reduce (http://en.wikipedia.org/wiki/Mapreduce). Here is a code fragment I pulled from what I am currently working on (with a little modification to make things simple): First build a tree: >>> def byn(a,n): return [[a[i] for i in x] for x in zip(*[range(y,len(a),n) for y in range(n)])] ... >>> def whilep(pred,f,x): ... while pred(x): x = f(x) ... return x ... >>> t = whilep(lambda x:1>> >>> t [[[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]], [[['i', 'j'], ['k', 'l']], [['m', 'n'], ['o', 'p']]]]] Now if I had the list [0,1,0,0,1] and needed to find what letter it encodes: >>> t[0][1][0][0][1] 'j' But sometimes, I want to be able to index branches or the leaves are at different depths, so I essentially have a list of indexes to follow: >>> def indexDepth(a,i): return reduce(lambda x,y: x[y], i, a) ... >>> indexDepth(t,[0,1,0,0,1]) 'j' Also, I completely understand your timings, but you are not timing reduce against a hand coded loop, but instead the operator '+' against the function add, as the function symbol lookup and call seem to have a heavy price. Reduce was one of the nice ways to eliminate some of those lookups. -j starGaming at gmail.com wrote: > Jason Nordwick wrote: >> *mouth agape* >> >> Wow. That really sucks. I make extensive use of reduce. It seems to run more than twice as fast as a for loop. >> >>>>> t = Timer('bino.reduceadd(bino.bits)', 'import bino') >>>>> s = Timer('bino.loopadd(bino.bits)', 'import bino') >>>>> t.timeit(10) >> 1.2373670396656564 >>>>> s.timeit(10) >> 2.6450051612705039 >>>>> t.timeit(100) >> 11.312374896809501 >>>>> s.timeit(100) >> 25.817132345032689 >> >> where >> >> bits = map(lambda x:randint(0,1), xrange(1000000)) >> >> def reduceadd(v): >> return reduce(add, v) >> >> def loopadd(v): >> sum = 0 >> for x in v: >> sum = add(sum, x) >> return sum >> >> >> >> (Yes, I know there are better ways to sum up a list, but I just wanted to test the performance of the loop against reduce. In most of my reduce usages, the function passed to reduce is much more complex.) > [...] > > Assuming Guido van Rossum is right and reduce() is only useful for > arithmetic expressions (could you show an example where you use it > else?), you could take advantage of more "built-ins". > To spoiler the result of this, the loop-variant is slightly (in this > test: 2ms) faster. > The results on my amd64 3k+ were: > Reduce: 0.5686828074520.56633643382 > For-loop: 0.56633643382 > > #!/usr/bin/env python > # > # > > from random import randint > from timeit import Timer > from operator import add > > def bits(): > return [randint(0,1) for x in xrange(1000)] > # use def & list comprehension since lambda/map will be removed in > Python 3.0, too > > > print bits()[0:5] > print bits()[0:5] # it's working. > > def reducefunc(x): > return reduce(add,x) > def loopfunc(x): > y = 0 > for i in x: y += i > return y > > x = bits() > print reducefunc(x) > print loopfunc(x) # both give proper output > > print sum(Timer("reducefunc(bits())", "from __main__ import bits, > reducefunc").repeat(20,100))/20 > print sum(Timer("loopfunc(bits())", "from __main__ import bits, > loopfunc").repeat(20,100))/20 > From ty.2006 at yahoo.com Tue Aug 8 11:29:58 2006 From: ty.2006 at yahoo.com (T) Date: 8 Aug 2006 08:29:58 -0700 Subject: Accessing Yahoo Mail withtout POP Message-ID: <1155050998.864753.198990@m79g2000cwm.googlegroups.com> Is there a way to access yahoo mail via its web interface? If so, can someone give some pointers? From fredrik at pythonware.com Mon Aug 21 07:18:06 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Aug 2006 13:18:06 +0200 Subject: Regular Expression question In-Reply-To: <1156153916.849933.178790@75g2000cwc.googlegroups.com> References: <1156153916.849933.178790@75g2000cwc.googlegroups.com> Message-ID: stevebread at yahoo.com wrote: > Hi, I am having some difficulty trying to create a regular expression. > > Consider: > >
> > > > > Whenever a tag1 is followed by a tag 2, I want to retrieve the values > of the tag1:name and tag2:value attributes. So my end result here > should be > john, tall > jack, short import re data = """
""" elems = re.findall("<(tag1|tag2)\s+(\w+)=\"([^\"]*)\"/>", data) for i in range(len(elems)-1): if elems[i][0] == "tag1" and elems[i+1][0] == "tag2": print elems[i][2], elems[i+1][2] From horpner at yahoo.com Fri Aug 18 13:39:16 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 18 Aug 2006 19:39:16 +0200 Subject: Simple Python App Server References: <1155915793.431933.286000@i42g2000cwa.googlegroups.com> Message-ID: On 2006-08-18, tom.purl wrote: > I use the pyGTD script to manage my todo lists and such. From > Vim, I shell out a call to the gtd.py script, which updates my > todo.txt file after update one of the related pyGTD files. > Since I make a lot of updates to the related pyGTD files, I > execute the gtd.py script dozens of times a day. Was your Vim compiled with the +python feature (this enables several Vim commands to run python code directly in Vim)? I don't know if that would speed things up or not, but it's worth a try. If the feature is present, you can run a Python script with the :pyfile command. -- Neil Cerutti From bj_666 at gmx.net Mon Aug 28 16:00:52 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 28 Aug 2006 22:00:52 +0200 Subject: How to store ASCII encoded python string? References: <1156792022.792854.90700@i42g2000cwa.googlegroups.com> Message-ID: In <1156792022.792854.90700 at i42g2000cwa.googlegroups.com>, micahc wrote: > So, how do I store "\tsome text\xa7 some more text\n" as that instead > of: > " some text? some more text > " > > I don't have a problem escaping it so the above would look like > "\\tsome text\\xa7 some more text\\n" as long as I have a way to later > unescape it when I want to actual do something with the data. In [6]: '\tsome text\xa7some more text\n'.encode('string_escape') Out[6]: '\\tsome text\\xa7some more text\\n' Ciao, Marc 'BlackJack' Rintsch From duncan.booth at invalid.invalid Wed Aug 2 11:22:21 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 Aug 2006 15:22:21 GMT Subject: Windows vs. Linux References: <1154301694.445639.99580@m79g2000cwm.googlegroups.com> <44cddfb3$0$7761$7a628cd7@news.club-internet.fr> <1154531160.066733.71210@s13g2000cwa.googlegroups.com> Message-ID: bryanjugglercryptographer at yahoo.com wrote: >>From a WinXP command prompt: > > C:\> > C:\>cd /windows/system32 > > C:\WINDOWS\system32> > > Not from my Windows XP command prompt it doesn't. Do you have anything strange installed on your system? From tim at tdw.net Wed Aug 30 11:31:41 2006 From: tim at tdw.net (Tim Williams) Date: Wed, 30 Aug 2006 16:31:41 +0100 Subject: block a network port In-Reply-To: References: <1156879445.723089.126630@m73g2000cwd.googlegroups.com> <1156907536.509187.32300@m73g2000cwd.googlegroups.com> Message-ID: <9afea2ac0608300831k745bc497kc1828462fce09fe3@mail.gmail.com> On 29 Aug 2006 20:43:49 -0700, alex23 wrote: > abcd wrote: > > ok, no of any python solutions? or command-line firewalls? > > You did try searching Google for "python firewall", right? > > http://www.google.com.au/search?q=python+firewall > > The very first entry is a pointer to a solution for Windows. That first entry was my thread :) IPFW is stable and runs as a Windows service, the rules can be added/deleted/changed/viewed in real-time making it a good candidate for pairing with Python. I have used it to write servers that temporarily firewall themselves against dubious connections. My preferred method is something like def ip_fw(fwcmd): # try: i,o,e = win32pipe.popen3('C:\\ipfw\\bin\\ipfw '+fwcmd) return i,o,e except: print sys.exc_info()[0] Nowadays I might use something other than popen3 depending on the level of return status I needed. (from memory, not tested, and not the best Python code ) HTH :) From borique at gmail.com Wed Aug 23 08:48:37 2006 From: borique at gmail.com (peter) Date: 23 Aug 2006 05:48:37 -0700 Subject: find, replace and save string in ascii file Message-ID: <1156337317.644501.120480@m73g2000cwd.googlegroups.com> Hello all, I'm looking for an advice. Example (one block in ascii file): $------------------------ NAME='ALFA' CODE='x' $------------------------ There are many similar blocks in the file with different NAMEs and different CODEs. What I'm looking for is a script that searchs through whole file and finds all strings with name ALFA and based on what CODE is after each ALFA (can be x, y or z) the ALFA name is replaced by BETAx,BETAy or BETAz and so changed file saves. What I did is that I can find all strings which I need, next I change these strings based on CODE, but what I can't is to replace old string with new one, on the same position in the file. It always writes new string at the end of the file. Here is my code.... Thanks in advance for any kind of help. Regards, Boris import shutil NamFile="test2.nam" BackupNamFile = 1 if BackupNamFile == 1: shutil.copyfile(NamFile,NamFile.replace(".nam",".nam.bak")) LineNum=1 LineNumQuantity=0 ArrayCount=0 LineNumArray=[] ReqArray=[] ReqName="" NamFileOpen=file(NamFile,"r+") for line in NamFileOpen: LineTextFound1 = line.find("bk") LineTextFound2 = line.find("_results") if LineTextFound1 != -1 and LineTextFound2 != -1: ReqName=line.split("'")[1] print "Line: \t\t\t"+ str(LineNum) print "Request Name: \t\t"+ ReqName LineNumQuantity = LineNum + 2 ReqArray=[LineNum-2,ReqName] if LineNum == LineNumQuantity: QuantityName=line.split("'")[1] print "Quantity Type: \t\t"+QuantityName if QuantityName == "dx": Suffix = "_disp" elif QuantityName == "vx": Suffix = "_velo" elif QuantityName == "fx": Suffix = "_force" else: Suffix = "_results" print "Suffix: \t\t"+Suffix NewReqName=ReqName.replace("_results",Suffix,1) ReqArray.append(NewReqName) LineNumArray.insert(ArrayCount,ReqArray) ArrayCount+=1 print "New Request Name: \t"+NewReqName print "-----------------------" LineNum = LineNum+1 print LineNumArray print len(LineNumArray) NamFileOpen.close() NamFileOpen2=file(NamFile,"r+") LineNum=1 for i in LineNumArray: print i for line in NamFileOpen2: print line print LineNum print i[1] if i[0]== LineNum: print i[0] print LineNum print line Temp=line.replace(line.split("'")[1],i[2],1) print Temp NamFileOpen2.write(Temp) LineNum=LineNum+1 NamFileOpen2.close() From neokosmos at gmail.com Thu Aug 10 22:45:00 2006 From: neokosmos at gmail.com (neokosmos at gmail.com) Date: 10 Aug 2006 19:45:00 -0700 Subject: Password authentication systems In-Reply-To: <7xk65gxfy2.fsf@ruckus.brouhaha.com> References: <1155218165.193546.136090@h48g2000cwc.googlegroups.com> <7xk65g3cis.fsf@ruckus.brouhaha.com> <1155221184.665002.95160@i42g2000cwa.googlegroups.com> <7xr6zo5fre.fsf@ruckus.brouhaha.com> <1155256125.796796.289000@i42g2000cwa.googlegroups.com> <7xk65gxfy2.fsf@ruckus.brouhaha.com> Message-ID: <1155264300.573994.205180@m73g2000cwd.googlegroups.com> Paul Rubin wrote: > neokosmos at gmail.com writes: > > My goal is to keep user passwords as safe as possible, assuming someone > > did decide to steal the password files. > > How often will new accounts be added? I have an idea I might try to > code up. Frequently, I hope. Realistically, when I open my personal MUD server, what I expect is an initial flurry of new accounts (say, up to 100 a day, just to overestimate), then slowing down to a steadier state (again, say 10 per day, to overestimate). I'm curious about this idea, in any case. :-) If you decide to "code it up," that's great... otherwise, I'd appreciate if you emailed me to discuss it away from comp.lang.python. Thanks! From steve at holdenweb.com Tue Aug 15 06:17:54 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 15 Aug 2006 11:17:54 +0100 Subject: Making a multithread app that runs several instances of whatever the app did before In-Reply-To: <1155629233.985335.56660@p79g2000cwp.googlegroups.com> References: <1155629233.985335.56660@p79g2000cwp.googlegroups.com> Message-ID: olbion at gmail.com wrote: > Hi > > I've aquired a program written in Python, and without much knowledge of > the language I'm trying to make some changes to it. The original > program starts, runs a certain process and then finishes. I want to > adapt it so that, at a certain stage of the process, a new process is > started from scratch, running at the same time as the original one. > When the original one is finished, it should exit without causing the > newer process to stop. > > I've successfully achieved this using sys.popen methods to start > separate processes, but come to realise that running seperate processes > is not a very good solution, since it uses up more memory and becomes > harder to manage. I'd like the same thing to be achieved using threads. > > I've come as far as being able to start the program which runs the > first thread. My problem arrises when I want the new thread to be > started. It seems that if I do this by calling a function from within > the thread, I'm unable to stop the original thread whenever that > finishes. I imagine that what I've achieved is something like: > > Start file (eg start.py) starts Thread 1 > Thread 1 starts a new thread (Thread 2) and becomes the parent of that > thread > Thread 2 starts a new thread (Thread 3)... and so on > > I think that what I want is something like: > > Start file starts Thread 1 > Thread 1 informs start file that a new thread should be started; start > file starts Thread 2 > .... and so on > > So, if my thinking so far is correct, how can a thread cause another > thread to be started without becoming its parent? > Read up on "demonised" (sp?) threads in the documentation from threading. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From steve at REMOVEME.cybersource.com.au Tue Aug 15 21:46:01 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 16 Aug 2006 11:46:01 +1000 Subject: Printing n elements per line in a list References: <1155685889.626881.37040@m73g2000cwd.googlegroups.com> Message-ID: On Tue, 15 Aug 2006 16:51:29 -0700, unexpected wrote: > If have a list from 1 to 100, what's the easiest, most elegant way to > print them out, so that there are only n elements per line. > > So if n=5, the printed list would look like: > > 1 2 3 4 5 > 6 7 8 9 10 > 11 12 13 14 15 > etc. > > My search through the previous posts yields methods to print all the > values of the list on a single line, but that's not what I want. I feel > like there is an easy, pretty way to do this. I think it's possible to > hack it up using while loops and some ugly slicing, but hopefully I'm > missing something I don't see why you think that's an ugly hack. def printitems(sequence, count=5): """Print count items of sequence per line.""" numrows = len(sequence)//count if len(sequence)%count != 0: numrows += 1 for start in range(0, numrows): items = sequence[start*count:(start+1)*count] for item in items: print item, print -- Steven D'Aprano From gh at gregor-horvath.com Thu Aug 3 05:22:48 2006 From: gh at gregor-horvath.com (Gregor Horvath) Date: Thu, 03 Aug 2006 11:22:48 +0200 Subject: Grammar parsing In-Reply-To: References: Message-ID: Paolo Pantaleo schrieb: > How can I write a pareser for a certain gramamr? I found PyPy that > does it, is thare any other tool? Maybe something built-in the python > interpreter? > http://pyparsing.wikispaces.com/ -- Servus, Gregor http://www.gregor-horvath.com From harry.g.george at boeing.com Fri Aug 11 00:55:33 2006 From: harry.g.george at boeing.com (Harry George) Date: Fri, 11 Aug 2006 04:55:33 GMT Subject: excel in unix? References: <1155197334.969268.95220@i42g2000cwa.googlegroups.com> <1155215932.863285.258530@b28g2000cwb.googlegroups.com> Message-ID: "linnorm at gmail.com" writes: > s99999999s2003 at yahoo.com wrote: > > hi > > is it possible to create excel files using python in Unix env? > > if so, what module should i use? > > thanks > > Depending on the complexity of your data you might find the csv module > useful. It allows you to write comma separated value (.csv) files that > Excel reads just fine. > We use the csv module a lot. I've also investigated the old DIF and SLK formats for slightly more functoinality. But the coming standards-based world, if you need more than csv, start writing to to the OpenOffice.org formats, either with your own code or via PyUNO. Then use OOo itself or a MS-sponsored ODF reader to translate to Excel format. This should be a maintainable approach over time (but a lot more complex than just csv). -- Harry George PLM Engineering Architecture From st at tobiah.org Wed Aug 30 17:17:27 2006 From: st at tobiah.org (tobiah) Date: Wed, 30 Aug 2006 14:17:27 -0700 Subject: csv module strangeness. In-Reply-To: References: <44f5e870$0$8814$88260bb3@free.teranews.com> Message-ID: <44f5f347$0$8846$88260bb3@free.teranews.com> > you may be misreading the docs; the Dialect has no values at all, and > must be subclassed (and the subclass must provide settings). The docs clearly state what the defaults are, but they are not in the code. It seems so clumsy to have to specify every one of these, just to change the delimiter from comma to tab. http://docs.python.org/lib/csv-fmt-params.html : delimiter A one-character string used to separate fields. It defaults to ','. doublequote Controls how instances of quotechar appearing inside a field should be themselves be quoted. When True, the character is doubled. When False, the escapechar must be a one-character string which is used as a prefix to the quotechar. It defaults to True. escapechar A one-character string used to escape the delimiter if quoting is set to QUOTE_NONE. It defaults to None. lineterminator The string used to terminate lines in the CSV file. It defaults to '\r\n'. quotechar A one-character string used to quote elements containing the delimiter or which start with the quotechar. It defaults to '"'. quoting Controls when quotes should be generated by the writer. It can take on any of the QUOTE_* constants (see section 12.20.1) and defaults to QUOTE_MINIMAL. skipinitialspace When True, whitespace immediately following the delimiter is ignored. The default is False. -- Posted via a free Usenet account from http://www.teranews.com From riteshsarraf at gmail.com Thu Aug 3 03:41:57 2006 From: riteshsarraf at gmail.com (Ritesh Raj Sarraf) Date: 3 Aug 2006 00:41:57 -0700 Subject: Thread Question In-Reply-To: <1154544553.990241.280030@i3g2000cwc.googlegroups.com> References: <1153998422.670828.148360@m79g2000cwm.googlegroups.com> <1154019801.999805.150000@m73g2000cwd.googlegroups.com> <1154544553.990241.280030@i3g2000cwc.googlegroups.com> Message-ID: <1154590917.731457.106230@s13g2000cwa.googlegroups.com> Simon Forman wrote: > > One other question I had, > > If my user passes the --zip option, download_from_web() internally (when the > > download is successful) zips the downloaded data to a zip file. Since in case > > of threading there'll be multiple threads, and say if one of the thread > > completes 2 seconds before others and is doing the zipping work: > > What will the other thread, at that moment do, if it completes while the > > previous thread is doing the zipping work ? > > The other threads will just take the next request from the Queue and > process it. They won't "care" what the one thread is doing, > downloading, zipping, whatever. > > The thread will be marked as complete only when the function that it executed exits. Right ? download_from_web() internally calls a funtion to zip the file. So it doesn't return before zipping. Till then this thread is not complete and therefore is busy working (i.e. zipping). during the same time if another thread (which is also calling download_from_web) completes the download, the download function will again call the zip code. At that particular situtation, will it wait for the previous thread to complete the zipping and release the file so that it can zip more data to it or will it just panic and quit ? I think this shouldn't be much concern. The d_f_w() calls zip(). And since zip opens the file.zip file in append mode, no matter how many threads access it, it should be okay. Ritesh From anoopsanthosh at gmail.com Tue Aug 8 13:35:51 2006 From: anoopsanthosh at gmail.com (Anoop) Date: 8 Aug 2006 10:35:51 -0700 Subject: String.digits help!!! Message-ID: <1155058550.954997.320250@m79g2000cwm.googlegroups.com> Hi All Hope u all might have come across the string deprecation thought of in Python 3.0. For example : string.lower(str) needs to be some thing like str.lower(). Can some one help me out whether such a change in the common python would require "string.digits" to be changed. If yes wat would be ur suggestions Thanks for ur inputs Anoop From rafal at ewipo.pl Wed Aug 16 08:05:03 2006 From: rafal at ewipo.pl (Rafal Janas) Date: Wed, 16 Aug 2006 14:05:03 +0200 Subject: classes on GladeGen Message-ID: <44E309EF.8070405@ewipo.pl> Hi. I create simple program using glade and GladeGen. In main.py is main class and in wind.py is wind class. In main class is entry1 and button1. When I click on button1 I open wind class wind.Wind() In wind class is entry1 field when I type some values and how can I send this value to main class. When I type main.Main().widgets['entry1'].set_text("something") it open new class but I want do it in window which is open How to do it? Rafal From rong.xian at gmail.com Fri Aug 25 05:53:59 2006 From: rong.xian at gmail.com (rong.xian at gmail.com) Date: 25 Aug 2006 02:53:59 -0700 Subject: Is this a bug of module struct? In-Reply-To: <1156499149.821351.184550@m79g2000cwm.googlegroups.com> References: <1156499149.821351.184550@m79g2000cwm.googlegroups.com> Message-ID: <1156499639.627209.300960@75g2000cwc.googlegroups.com> I got it, alignment issue... > >>> struct.pack('!3I14sI',1,19960101,14,'0123456789abcd',6) > '\x01\x00\x00\x00%\x910\x01\x0e\x00\x00\x000123456789abcd\x06\x00\x00\x00' > >>> struct.pack('!3I14s',1,19960101,14,'0123456789abcd')+struct.pack('!I',6) > '\x01\x00\x00\x00%\x910\x01\x0e\x00\x00\x000123456789abcd\x06\x00\x00\x00' rong.x... at gmail.com wrote: > Before I was bitten by the difference below, I think these two ways are > the same. > However, they are not. > Is there any geek who can tell me if this is a bug? > (some weird '\x00\x00' was inserted between '0123456789abcd' and 6 ) > > > >>> struct.pack('3I14sI',1,19960101,14,'0123456789abcd',6) > '\x01\x00\x00\x00%\x910\x01\x0e\x00\x00\x000123456789abcd\x00\x00\x06\x00\x00\x00' > >>> struct.pack('3I14s',1,19960101,14,'0123456789abcd')+struct.pack('I',6) > '\x01\x00\x00\x00%\x910\x01\x0e\x00\x00\x000123456789abcd\x06\x00\x00\x00' From steve at REMOVEME.cybersource.com.au Tue Aug 15 23:59:28 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 16 Aug 2006 13:59:28 +1000 Subject: Printing n elements per line in a list References: <1155685889.626881.37040@m73g2000cwd.googlegroups.com> <1155696557.538330.70800@m73g2000cwd.googlegroups.com> Message-ID: On Tue, 15 Aug 2006 19:49:17 -0700, John Machin wrote: > Ugliness is in the eye of the beholder. > It is more blessed to add than to multiply. > Gaze upon this alternative: > > def printitems2(sequence, count=5): > """Print count items of sequence per line.""" > for pos in range(0, len(sequence), count): > for item in sequence[pos:pos+count]: > print item, > print You know, that's so obvious that I've just slapped myself for not thinking of it first. What *was* I thinking??? -- Steven D'Aprano From yannick.leteigner at gmail.com Thu Aug 10 19:46:34 2006 From: yannick.leteigner at gmail.com (Yannick) Date: 10 Aug 2006 16:46:34 -0700 Subject: Python share CPU time? References: <1155146500.063665.282430@p79g2000cwp.googlegroups.com> Message-ID: <1155253594.681570.145910@b28g2000cwb.googlegroups.com> Thank you all for the detailled answers. What I would like to achieve is something like: # main loop while True: for robot in robots: robot.start() robot.join(0.2) # wait 200ms if robot.is_active(): robot.stop() # run all the game physics, pause, frame/rate, etc... Unfortunately the stop() call doesn't exist in Python. By using a generator I would make the assumption that every robot is playing fair, and would yield often. But I cannot control this as eventually robots would be coded by third parties. Using Python scheduler would allow me to share time equally between each robot, but then I would loose the ability to have a main thread organizing everything. From bkline at rksystems.com Wed Aug 16 08:50:46 2006 From: bkline at rksystems.com (Bob Kline) Date: Wed, 16 Aug 2006 08:50:46 -0400 Subject: Optimization of __len__() in cgi.py Message-ID: I have a suggestion for speeding up the performance of code like this: fields = cgi.FieldStorage() if fields: ... which, as it turns out, invokes FieldStorage.__len__(), which in turn calls FieldStorage.keys(), which builds a list of keys by hand, taking several minutes for large forms. This implementation of keys() reduces the amount of time taken by several orders of magnitude: def keys(self): return {}.fromkeys([i.name for i in self.list]).keys() Is there a better place for submitting suggestions like this? Bob Kline From jyoti.chhabra at gmail.com Mon Aug 21 02:07:41 2006 From: jyoti.chhabra at gmail.com (JyotiC) Date: 20 Aug 2006 23:07:41 -0700 Subject: tkinter prob Message-ID: <1156140461.170856.136180@74g2000cwt.googlegroups.com> hi, i am making a GUI using Tkinter, I have a button and a checkbutton. i want the button to be enable when checkbutton is on and disble when the checkbutton is off. thanx From mail at microcorp.co.za Thu Aug 3 03:17:58 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Thu, 3 Aug 2006 09:17:58 +0200 Subject: serial ports, threads and windows References: <200608021602.25413.brown@esteem.com> Message-ID: <016f01c6b6cd$2ff0d0e0$03000080@hendrik> "Tom Brown" | Hey people, | | I've written a python app that r/w eight serial ports to control eight devices | using eight threads. This all works very nicely in Linux. I even put a GUI on | it using PyQt4. Still works nicely. | | Then I put the app on on a virtual Windows machine running inside of vmware on | the same Linux box. Vmware only lets me have four serial ports so I run the | app against four serial ports using four threads. The app did not respond | quick enough to data from the serial ports and eventually hung. | | So, I tried one serial port and the app still did not respond quick enough to | the single serial port. It eventually hangs. | | When the app hung, in each case, it was not hogging the cpu nor reading any | data off the serial ports. The task manager didn't show it was doing anything | at all. | | When it runs on Windows, could it be: | | 1) Just struggling to run inside of VMware? | | 2) Using threads with Qt on Windows is a problem? | | 3) Threads in python on Windows is a problem? | | Any ideas? | | Thanks, | Tom I cant help you really, but I can put what little weight I have behind you - I am also struggling with serial port implementation - I posted here some time ago and got some answers - and my intermittent failure is now down to about once a week. I found that while python's file handling and the GUI stuff works seamlessly across platforms, the serial port handling seems quirky and platform dependant : It is extraordinarly difficult to write non blocking reads that will work 'out of the box' across platforms - in fact I dont know if it is possible.. And making a pipe non blocking is poison... - Hendrik From deets at nospam.web.de Sun Aug 13 17:47:35 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 13 Aug 2006 23:47:35 +0200 Subject: outputting a command to the terminal? In-Reply-To: <44df99f7$0$25025$c3e8da3@news.astraweb.com> References: <44df99f7$0$25025$c3e8da3@news.astraweb.com> Message-ID: <4k9kvmFb7dfhU1@uni-berlin.de> John Salerno schrieb: > Here's my new project: I want to write a little script that I can type > at the terminal like this: > > $ scriptname package1 [package2, ...] > > where scriptname is my module name and any subsequent arguments are the > names of Linux packages to install. Running the script as above will > create this line: > > sudo aptitude install package1 package2 ... > > It will run that line at the terminal so the package(s) will be installed. > > Now, the extra functionality I want to add (otherwise I would just > install them normally!) is to save the package names to a text file so I > can now the names of programs I've manually installed, if I ever want to > check the list or remove packages. > > So creating the proper bash command (sudo aptitude install ...) is easy, > and writing the names to a file is easy. But I have two questions: > > 1. First of all, does Linux keep track of the packages you manually > install? If so, then I won't have to do this at all. > > 2. Assuming I write this, how do output the bash command to the > terminal? Is there a particular module that Python uses to interact with > the terminal window that I can use to send the install command to the > terminal? You don't put a command to the terminal. The shell executes commands. But it is mainly just a program itself - it can spawn subprocesses and make these execute the actual commands. so - the module you need is most probably subprocess. Diez From ndbecker2 at gmail.com Thu Aug 31 21:41:13 2006 From: ndbecker2 at gmail.com (Neal Becker) Date: Thu, 31 Aug 2006 21:41:13 -0400 Subject: Boost Python Issue References: <1157063033.800940.181130@e3g2000cwe.googlegroups.com> <1157073301.401994.166920@h48g2000cwc.googlegroups.com> Message-ID: JDJMSon wrote: > > Neal Becker wrote: > >> Shouldn't that be: >> .def("TestFunction",&TestClass::TestFunction) >> > ; > > > Yes, you're right, but I'm still getting the error. I'm using a > prebuilt python library, so later I'm going to rebuild python myself > and see if that helps, as has been suggested. > Thanks. > I think you need an init. Usually looks like: class_< c++ class > ("python name", init()) .def ("python member", &class::member); From sjmachin at lexicon.net Wed Aug 16 04:28:46 2006 From: sjmachin at lexicon.net (John Machin) Date: 16 Aug 2006 01:28:46 -0700 Subject: Memory usage of an 'empty' python interpreter In-Reply-To: <1155715912.930984.207150@i42g2000cwa.googlegroups.com> References: <1155710349.127768.17280@h48g2000cwc.googlegroups.com> <1155715912.930984.207150@i42g2000cwa.googlegroups.com> Message-ID: <1155716926.343428.263870@h48g2000cwc.googlegroups.com> Ant wrote: > neokosmos at gmail.com wrote: > > I was wondering what the approximate amount of memory needed to load a > > Python interpreter (only, no objects, no scripts, no nothing else) in a > > Linux 2.6 environment. According to ps, it appears to be 3312 bytes, > > which seems absurdly low to me. However, when I check the size of my > > Python executable, it looks like it is only about 5600 bytes in size, > > so maybe this is reasonable? > > Are you sure ps is reporting in bytes not KB? The bare interpreter in > Windows is 3368KB. Where did you get that from? With Python 2.4.3, on my machine (Win XP SP2): C:\junk>dir \python24\python* [snip] 29/03/2006 05:35 PM 4,608 python.exe 29/03/2006 05:35 PM 1,871,872 python24.dll 29/03/2006 05:35 PM 5,120 pythonw.exe From andy.terrel at gmail.com Fri Aug 18 14:45:05 2006 From: andy.terrel at gmail.com (Andy Terrel) Date: 18 Aug 2006 11:45:05 -0700 Subject: how do you get the name of a dictionary? In-Reply-To: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> Message-ID: <1155926705.233273.231650@75g2000cwc.googlegroups.com> jojoba wrote: > Hello! > > Does anyone know how to find the name of a python data type. > > Conside a dictionary: > > Banana = {} > > Then, how do i ask python for a string representing the name of the > above dictionary (i.e. 'Banana')? > > thanks to anyone who has time to answer this nube question! > jojoba here is an easy hack, I don't know if there is an explicit function. for i in dir(): if eval(i) == Banana: print i From apiltzs at gmail.com Mon Aug 28 05:24:21 2006 From: apiltzs at gmail.com (john Perry) Date: 28 Aug 2006 02:24:21 -0700 Subject: Starting up the server Message-ID: <1156757061.162827.301260@h48g2000cwc.googlegroups.com> hi all, how to solve these error Traceback (most recent call last): File "mrsm-start.py", line 2, in import pkg_resources ImportError: No module named pkg_resources please help me thanks From rosedb0 at gmail.com Tue Aug 15 09:28:27 2006 From: rosedb0 at gmail.com (hiaips) Date: 15 Aug 2006 06:28:27 -0700 Subject: Beginner Textbook In-Reply-To: <12e3i9gr0edeb74@corp.supernews.com> References: <12e3gkdhjngum6a@corp.supernews.com> <12e3i9gr0edeb74@corp.supernews.com> Message-ID: <1155648507.405996.135780@p79g2000cwp.googlegroups.com> M_M wrote: > Michiel Sikma wrote: > > Introducing 13 year olds to a programming language? You're gonna have a > > hard time finding good literature for that. Even if you do, it's going > > to cost a lot of time to guide them. > > > > "Beginning Python: From Novice to Professional" by Magnus Lee Hetland > > might be a good choice. ISBN: 159059519X. > > > > Michiel > > > > Op 15-aug-2006, om 14:48 heeft M_M het volgende geschreven: > > > >> Hi, > >> > >> I am looking for a simple text book to introduce 13 to 18 year olds to > >> python programming. Suggestion? > >> > >> New to python. > >> --http://mail.python.org/mailman/listinfo/python-list > > > Thanks - a very bright lot of 13 year olds- need the challenge! There's a book called "Learning with Python: How to Think Like a Computer Scientist" that's geared towards high schoolers. It may be perfect for your students, depending on what you're looking for. In any case, here's a link: http://greenteapress.com/thinkpython/ From elliot.hughes at gmail.com Sun Aug 20 13:51:54 2006 From: elliot.hughes at gmail.com (elliot.hughes at gmail.com) Date: 20 Aug 2006 10:51:54 -0700 Subject: import In-Reply-To: References: <1156093283.529579.80600@i42g2000cwa.googlegroups.com> <1156093799.775420.51970@m73g2000cwd.googlegroups.com> <1156094307.576025.3430@i3g2000cwc.googlegroups.com> Message-ID: <1156096314.827368.173290@i3g2000cwc.googlegroups.com> If your still having trouble how are you running python? If you run cmd and THEN type python it is not operating in the python24 directory and runs in the directory cmd was in before the command. Otherwise make sure you don't have any previous python installs. From rdiaz02 at gmail.com Wed Aug 23 10:06:31 2006 From: rdiaz02 at gmail.com (Ramon Diaz-Uriarte) Date: Wed, 23 Aug 2006 16:06:31 +0200 Subject: idutils and Python In-Reply-To: <1156266252.017194.109830@m73g2000cwd.googlegroups.com> References: <1156226173.596437.266680@75g2000cwc.googlegroups.com> <1156266252.017194.109830@m73g2000cwd.googlegroups.com> Message-ID: <624934630608230706o5b8a8482vd7f1494a36c11013@mail.gmail.com> On 22 Aug 2006 10:04:12 -0700, sjdevnull at yahoo.com wrote: > That's usually cscope http://cscope.sourceforge.net/ but I've not > tried to use it with Python before; from the web page it looks like it > may be worth a spin: > "The fuzzy parser supports C, but is flexible enough to be useful for > C++ and Java, and for use as a generalized 'grep database' (use it to > browse large text documents!" > Thanks for your answer. I'll take a new look at cscope (I think I looked at it, but discarded because it seemed to focus on C/C++; never noticed it is possible use as a general browser for large text collections). > I am usually happy with grep, but we only have a medium-large size > project (320,000 lines of Python code); I can imagine on very large > codebases that would be too slow to be practical. I am generally happy with grep (and your code is much larger than ours) but idutils' output offers both that and, by showing all together, a kind of poor-man's static call graph, and can be of use when refactoring. Thanks again, R. On 22 Aug 2006 10:04:12 -0700, sjdevnull at yahoo.com wrote: > Ramon Diaz-Uriarte wrote: > > On 21 Aug 2006 22:56:13 -0700, sjdevnull at yahoo.com wrote: > > > > > What exactly are you trying to accomplish? If you want to index > > > function/class names, variables, etc then you should take a look at > > > "exuberant ctags" http://ctags.sourceforge.net53 --although it started > > > off as a C indexer, it has excellent Python support, it's free, and as > > > a bonus its indices are well supported from inside major editors (vim, > > > emacs, etc) so you can easily follow code flow, find function/class > > > definitions, etc. > > > > > > Sorry for not being clear enough. I want the following: > > > > a) have my editor go to the point where a function/whatever is defined > > That's usually ctags/etags > > > b) see all places where a function/whatever is used. > > That's usually cscope http://cscope.sourceforge.net/ but I've not > tried to use it with Python before; from the web page it looks like it > may be worth a spin: > "The fuzzy parser supports C, but is flexible enough to be useful for > C++ and Java, and for use as a generalized 'grep database' (use it to > browse large text documents!" > > The vim integration is very nice. It has emacs integration too, but I > haven't used it and can't comment on how good it is. > > > I think the wish "do not use grep, just look at the index file, and > > immediately display all matches" is reasonable and probably other > > Python coders had thought about it before. But I am wondering if I am > > missing something obvious, as most people seem to be very happy with > > exuberant ctags. > > I am usually happy with grep, but we only have a medium-large size > project (320,000 lines of Python code); I can imagine on very large > codebases that would be too slow to be practical. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Ramon Diaz-Uriarte Bioinformatics Unit Spanish National Cancer Centre (CNIO) http://ligarto.org/rdiaz From davefowler at gmail.com Tue Aug 8 11:52:33 2006 From: davefowler at gmail.com (godavemon) Date: 8 Aug 2006 08:52:33 -0700 Subject: binary conversion issues Message-ID: <1155052353.499099.293840@i3g2000cwc.googlegroups.com> I'm using python's struct and binascii modules to write some values from my parser to binary floats. This works great for all of my binary files except one. For some reason this file is saving to 836 (stated by my command shell) bytes instead of 832 like it should. It sounds like an issue with whatever's writing that particular file out but I've checked it 100 times. Also python can read in the 836 byte file, find it has a size of 832 bytes and convert back each value perfectly. However, when I read in the file in C++ it finds a file of size 836 and in the middle of the data starts spitting out junk. Has anyone run into an issue like this or have an idea of what it could be? From jgodoy at gmail.com Sun Aug 6 22:01:11 2006 From: jgodoy at gmail.com (Jorge Godoy) Date: Sun, 06 Aug 2006 23:01:11 -0300 Subject: easy question about join method References: <1154914663.090280.55700@b28g2000cwb.googlegroups.com> Message-ID: <87r6zt4848.fsf@gmail.com> "nephish" writes: > i have seen the join method before, mostly in this group and i want to > get it a little better. > > if i have a list > > x = ['this','is','a','sentence','held','in','a','list'] > > how can i make it print as a single string? or make a single string out > of it ? print ' '.join(x) -- Jorge Godoy From steve at holdenweb.com Fri Aug 25 06:13:20 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 25 Aug 2006 11:13:20 +0100 Subject: how do you get the name of a dictionary? In-Reply-To: References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> Message-ID: Fredrik Lundh wrote: > Steve Holden wrote: > > >>Right. Plus it's fun to imagine the effbot hitting itself as hard as >>some people would obviously have liked to hit it in the past :-) > > > you mean the guy who's spent the last six months downrating every single > post I've made on this list over at googlegroups ? I'd say it's safe to > ignore him; he's a certified nutcase. > Yeah, right. Doesn't seem to like what I have to say very much either, but then the Google "rating" system is so lame that anyone who uses it can probably safely be ignored for one reason or another. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From python.list at tim.thechases.com Wed Aug 2 11:52:52 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 02 Aug 2006 10:52:52 -0500 Subject: Windows vs. Linux In-Reply-To: References: Message-ID: <44D0CA54.3040006@tim.thechases.com> > | Not from my Windows XP command prompt it doesn't. Do you have > | anything > | strange installed on your system? > > FWIW: > > > > Microsoft Windows XP [Version 5.1.2600] > (C) Copyright 1985-2001 Microsoft Corp. > > c:\temp>cd \ > > C:\>cd /windows/System32 > > C:\windows\system32> > > Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\temp>cd \ C:\>cd /windows/system32 C:\WINDOWS\system32>cd /windows/system32 The system cannot find the path specified. C:\WINDOWS\system32>cd \ C:\>cd /windows C:\WINDOWS>cd /system32 C:\WINDOWS\system32> REM wtf? Nice to see consistancy at work. Looks like leading slashes are stripped and so it trys to find it relative to the current path. Nothing like predictable, cross-platform implementations there. [rolls eyes] Thank goodness Python brings some brains to the table where Windows/Dos is ::ehem:: seriously lacking. -tkc From bobrien18 at yahoo.com Wed Aug 16 14:59:27 2006 From: bobrien18 at yahoo.com (KraftDiner) Date: 16 Aug 2006 11:59:27 -0700 Subject: trouble understanding inheritance... In-Reply-To: References: <1155753183.207393.116940@m79g2000cwm.googlegroups.com> Message-ID: <1155754767.694480.256200@h48g2000cwc.googlegroups.com> Fredrik Lundh wrote: > KraftDiner wrote: > > > This is not working the way I think it should.... > > it would appear that fromfile and getName are calling the baseClass > > methods which are > > simple passes.... What have I done wrong? > > > > class baseClass: > > def __init__(self, type): > > if type == 'A': > > self = typeA() > > else: > > self = typeB() > > __init__ is not a constructor, and assigning to self doesn't change the > type of the constructed object. > > looks like you need to get a better tutorial. > > Well how does one select which class baseClass really is when you contruct the object? What am I missing? a = typeA() b = typeB() c = baseClass(a) From apardon at forel.vub.ac.be Sat Aug 5 08:30:59 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 5 Aug 2006 12:30:59 GMT Subject: Nested function scope problem References: <20060804094245.A9AF.SLAWOMIR.NOWACZYK.847@student.lu.se> <1okvniwl5zgqj.dlg@gelists.gmail.com> <20060804155855.EE80.SLAWOMIR.NOWACZYK.847@student.lu.se> Message-ID: On 2006-08-04, Gerhard Fiedler wrote: > On 2006-08-04 15:21:52, Dennis Lee Bieber wrote: > >> On Fri, 4 Aug 2006 14:09:15 -0300, Gerhard Fiedler >> declaimed the following in comp.lang.python: >> >>> Python === C >>> Textual representation a === Address operator (&a) >>> id(a) === Dereference operator (*a) >>> >>> I think I didn't quite translate what you meant, but you get the idea. I >>> don't think you can come up with a working analogy. The differences are >>> just too many -- if you consider the C language on the right side, not a >>> custom application you developed in C. >>> >> Closer would be (putting C constructs on left) >> >> c ~= id(c) (address of the object identified by 'c') >> *c ~= c (dereference to manipulate the object itself) >> &c ~= no Python equivalent for "the address of the name 'c'" >> >> C 'c' is a variable, one can take the address of the storage it >> uses, and manipulate the contents of that storage. One does not have >> that access with Python name bindings. > > But this means that C variables are not analog to Python variables, Yes they are. Your problem seems to be that you see an int in Python and want to compare with an int in C. > C dereferenced pointers are. No they are not. a = b in Python translates to: a = b in C. It doesn't translate to *a = *b in C. It is true that a = b + c in Python doesn't translate to a = b + c in C, but since this really is a shortcut of a = b.__add__(c) there is nothing wrong with tranlating it into something like: a = IntPlus(b, c) for C, where the IntPlus will provide a new pointer that points to the sum or we could provide the necessary structures so that we could translate is as: a = b->__add__(c) > (c is a C variable; *c is /not/ a C variable, > it's a dereferenced pointer.) This is what I've been trying to say for a Which is irrelevant since a = b in Python just translates to a = b in C. Sure in Python terms we would talk about a and b being ints, while we would first be tempted to talk about pointers to ints in C. But since we are talking about variables in general and not about int variables or pointer variables, that doesn't matter much. If int variables in Python resemble pointer variables in C then there is something in C deserving the term variable which behaves like variables do in Python. -- Antoon Pardon From fredrik at pythonware.com Tue Aug 29 12:24:30 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 29 Aug 2006 18:24:30 +0200 Subject: M$ windows python libs installed in arbitrary directories forcustomized python distributions In-Reply-To: References: <44f31d35$0$17268$9b622d9e@news.freenet.de> Message-ID: alf wrote: > ok, let me clarify, by M$ I meant Micro$oft. http://www.catb.org/~esr/faqs/smart-questions.html#writewell From fredrik at pythonware.com Tue Aug 15 17:46:11 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 15 Aug 2006 23:46:11 +0200 Subject: PIL and solaris In-Reply-To: <1155538061.818551.139090@p79g2000cwp.googlegroups.com> References: <1155538061.818551.139090@p79g2000cwp.googlegroups.com> Message-ID: kepioo wrote: > I am trying to install PIL with python 2.3 on solaris X86, but I get > this error message : > > building '_imaging' extension > creating build/temp.solaris-2.10-i86pc-2.3 creating > build/temp.solaris-2.10-i86pc-2.3/libImaging > /sgnome/tools/x86-solaris/forte/SOS8/SUNWspro/bin/cc -i -xO4 -xspace > -xstrconst -xpentium -mr -DANSICPP -D__STDC_VERSION__=199409L -DNDEBUG > -O -DHAVE_LIBJPEG -DHAVE_LIBZ -I/usr/sfw/include/freetype2 -IlibImaging > -I/usr/sfw/include -I/usr/local/include -I/usr/include > -I/usr/sfw/include/python2.3 -c libImaging/Antialias.c -o > build/temp.solaris-2.10-i86pc-2.3/libImaging/Antialias.o > unable to execute /sgnome/tools/x86-solaris/forte/SOS8/SUNWspro/bin/cc: > No such file or directory > error: command '/sgnome/tools/x86-solaris/forte/SOS8/SUNWspro/bin/cc' > failed with exit status 1 > root at appdev01 # pwd > /export/home/lmtansu/Imaging-1.1.6b1 > > It works fine with python 2.2 however.... where did you get your python 2.3 interpreter? did you build it yourself? From jantod at gmail.com Sun Aug 6 17:06:30 2006 From: jantod at gmail.com (Janto Dreijer) Date: 6 Aug 2006 14:06:30 -0700 Subject: embedding console in wxpython app Message-ID: <1154898390.542838.45710@i42g2000cwa.googlegroups.com> I'm writing a Linux filemanager using wxPython. I'd like to embed a bash console inside it. I have found the Logilab pyqonsole (http://www.logilab.org/projects/pyqonsole), but it uses PyQT. Does anyone know how to do this from wx? Is it possible to embed a PyQT widget inside wxPython? Thanks! Janto From antroy at gmail.com Sun Aug 13 04:59:32 2006 From: antroy at gmail.com (Ant) Date: 13 Aug 2006 01:59:32 -0700 Subject: keep a list of read and unread items In-Reply-To: <1155456602.502808.105990@m79g2000cwm.googlegroups.com> References: <1155456602.502808.105990@m79g2000cwm.googlegroups.com> Message-ID: <1155459572.658340.242190@74g2000cwt.googlegroups.com> a wrote: > i m building an rss reader and i want you suggestions for datastructure > for keeping read and unread list for each use > i m assuming it will be very sparse A dictionary for each site seems to be the obvious choice, mapping the article ID to True or False. From robert.kern at gmail.com Wed Aug 23 03:44:28 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 23 Aug 2006 02:44:28 -0500 Subject: how do you get the name of a dictionary? In-Reply-To: References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> <1156264475.968894.221710@p79g2000cwp.googlegroups.com> <1156266720.205126.284050@i3g2000cwc.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Wed, 23 Aug 2006 08:56:54 +0200, Fredrik Lundh wrote: > >> Steven D'Aprano wrote: >> >>> But an upside is that it would enable more useful error messages, at least >>> sometimes. Here's some trivial pseudo-code: >>> >>> def foo(a): >>> assert len(a) > 10, "%s is too short" % a.__name__ >>> >>> y = "hello" >>> foo(y) >>> >>> would display "AssertionError: y is too short". >> why not "a is too short" ? >> >> or for that matter, "x is to short" ? > > These are all valid responses too. But consider that when you get an > exception that says "a is too short", you often have to mentally change > gears and think about where a came from and what it is called in the > enclosing scope. After all, if the value of a is invalid, and the value of > a is set in the enclosing scope, it makes sense to refer to "the object > known locally as a" by the name it was known as when it was set. That's what tracebacks are for. You don't have to mentally change gears; you just look. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From max at alcyone.com Wed Aug 9 03:23:46 2006 From: max at alcyone.com (Erik Max Francis) Date: Wed, 09 Aug 2006 00:23:46 -0700 Subject: #!/usr/bin/python or #!/usr/bin/env python? In-Reply-To: References: Message-ID: <3oudnahXyYMeEETZnZ2dnUVZ_sGdnZ2d@speakeasy.net> Stephan Kuhagen wrote: > Micha? Bartoszkiewicz wrote: > >> #!/bin/sh >> """exec" python "$0" "$@""" > > Wow, cool... I like that! Only someone genuinely fond of the Tcl hack could ... -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis No man who needs a monument ever ought to have one. -- Nathaniel Hawthorne From jedi200581 at yahoo.co.uk Thu Aug 24 08:37:16 2006 From: jedi200581 at yahoo.co.uk (jedi200581 at yahoo.co.uk) Date: 24 Aug 2006 05:37:16 -0700 Subject: Pygame, mouse events and threads In-Reply-To: <1156422427.974304.272200@m79g2000cwm.googlegroups.com> References: <1156421018.882740.166810@b28g2000cwb.googlegroups.com> <1156422427.974304.272200@m79g2000cwm.googlegroups.com> Message-ID: <1156423036.392565.173490@i3g2000cwc.googlegroups.com> Ben Sizer wrote: > jedi200581 at yahoo.co.uk wrote: > > > When I put the content of the run and input functions in the main > > thread, it's working, why not in the thread? > > Because event handling needs to be done in the main thread. So does > rendering. This is a limitation of the underlying system. > > As a general rule, try to keep all your PyGame functions in the main > thread and push your other processing into background threads, if you > really need them. > > -- > Ben Sizer Well, that is a limitation... And is it something that will be fixed or something that is inherent to pygame and not fixable? From exogen at gmail.com Tue Aug 1 23:43:44 2006 From: exogen at gmail.com (Brian Beck) Date: Tue, 01 Aug 2006 23:43:44 -0400 Subject: Zipping files/zipfile module References: <1154483883.796081.35140@p79g2000cwp.googlegroups.com> Message-ID: OriginalBrownster wrote: > I want to zip all the files within a directory called "temp" > and have the zip archive saved in a directory with temp called ziptemp > > I was trying to read up on how to use the zipfile module python > provides, but I cannot seem to find adequate documentation on function > itself. > > Perhaps someone could help me in this task? Hello, This isn't completely tested, but perhaps it will help you get started: from os import listdir, mkdir from os.path import join, basename, isfile from zipfile import ZipFile def zip_dir(path, output_path, include_hidden=True): files = [join(path, f) for f in listdir(path) if isfile(join(path, f))] try: mkdir(output_path) except OSError, e: if e.errno == 17: # Path exists pass zip_file = ZipFile(join(output_path, 'temp.zip'), 'w') for f in files: if basename(f).startswith('.') and not include_hidden: continue print "Adding %s to archive..." % (f,) zip_file.write(f) zip_file.close() Use like: zip_dir('temp', 'temp/ziptemp') Note that if you want to add the entire contents of a directory (subdirectories, recursively), you should consider using os.walk or something similar. This will only add the file contents of the directory. I'm not sure if the zipfile module provides any nice ways to write directories to the archive, but I'm assuming it just involves writing an arcname with a '/' in it (see help(zipfile.ZipFile)). -- Brian Beck Adventurer of the First Order From zondo42 at googlemail.com Fri Aug 25 02:48:34 2006 From: zondo42 at googlemail.com (Glenn Hutchings) Date: 24 Aug 2006 23:48:34 -0700 Subject: setup.py and file extensions like ".c++" References: <1156469499.816353.301520@m73g2000cwd.googlegroups.com> Message-ID: <1156488514.233907.314910@74g2000cwt.googlegroups.com> garyjefferson123 at yahoo.com wrote: > Is there any way to get setup.py to recognize file extensions like .c++ > in lieu of .cpp? I'd love to not have to rename the source files for > the library I'm trying to wrap in a python C extension. The python docs imply that the file extension is dealt with by the native C++ build system, so you have to use a recognized suffix (either .cpp or .cc, and possibly others). Looks like .c++ isn't a standard one. See http://docs.python.org/dist/describing-extensions.html#SECTION002320000000000000000 Glenn From paul.johnston at manchester.ac.uk Thu Aug 24 11:38:45 2006 From: paul.johnston at manchester.ac.uk (Paul Johnston) Date: Thu, 24 Aug 2006 16:38:45 +0100 Subject: Newbie question about numpy Message-ID: Hi I'm new to python and have just been taking a look at what it has to offer. I noted the lack of matrices so installed numpy I know the documentation is chargable so wanted a quick play to see if I should buy it However _________________________________________________________ from numpy import * a = array([[1,2,3],[4,5,6],[1,2,3]]) b = array([[1,3,6],[2,5,1],[1,1,1]]) print 'a = \n',a,"\n" print 'b = \n',b,"\n" print 'a has shape ', a.shape print 'b has shape ', b.shape, "\n" print "a * b is \n", a * b _________________________________________________________ Gives me _________________________________________________________ a = [[1 2 3] [4 5 6] [1 2 3]] b = [[1 3 6] [2 5 1] [1 1 1]] a has shape (3, 3) b has shape (3, 3) a * b is [[ 1 6 18] [ 8 25 6] [ 1 2 3]] _________________________________________________________ I know its a long time since my degree but that's not matrix multiplication is it ? TIA Paul From jjl at pobox.com Thu Aug 10 18:12:44 2006 From: jjl at pobox.com (John J. Lee) Date: Thu, 10 Aug 2006 22:12:44 GMT Subject: ALLAH References: <1155117922.061942.100370@n13g2000cwa.googlegroups.com> Message-ID: <873bc4p7dv.fsf@pobox.com> Wildemar Wildenburger writes: [...] > Although the subject sort of makes me suspect that this text has > little if anything to do with programming. Programming computers, that > is. :-)) John From python.list at tim.thechases.com Thu Aug 17 17:36:44 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 17 Aug 2006 16:36:44 -0500 Subject: re.sub() backreference bug? In-Reply-To: <1155849969.628999.287180@b28g2000cwb.googlegroups.com> References: <1155849969.628999.287180@b28g2000cwb.googlegroups.com> Message-ID: <44E4E16C.2090600@tim.thechases.com> > s = re.sub(r'([A-Z]+)([A-Z][a-z])', "\1_\2", s) > s = re.sub(r'([a-z\d])([A-Z])', "\1_\2", s) > i expect to get: > hello_world19_foo_bar > > but instead i get: > hell?_?orld19_fo?_?ar Looks like you need to be using "raw" strings for your replacements as well: s = re.sub(r'([A-Z]+)([A-Z][a-z])', r"\1_\2", s) s = re.sub(r'([a-z\d])([A-Z])', r"\1_\2", s) This should allow the backslashes to be parsed as backslashes, not as escape-sequences (which in this case are likely getting interpreted as octal numbers) -tkc From fhurley at gmail.com Tue Aug 1 14:05:11 2006 From: fhurley at gmail.com (fhurley at gmail.com) Date: 1 Aug 2006 11:05:11 -0700 Subject: Can't get LCHARVAR's with InformixDB In-Reply-To: References: <1154437329.471918.35150@h48g2000cwc.googlegroups.com> <1154438862.714569.9130@b28g2000cwb.googlegroups.com> <1154446906.915203.13790@m73g2000cwd.googlegroups.com> <1154447228.669652.169320@75g2000cwc.googlegroups.com> Message-ID: <1154455511.213889.270500@m73g2000cwd.googlegroups.com> Carsten Haese wrote: > Once again, I'll need > the create table statement for the table you're selecting from in order > to investigate what's happening. Here it is: CREATE TABLE DEV_LOG( LOG_ID SERIAL, LEVEL VARCHAR (10), POI_NM VARCHAR (255), MSG_TX LVARCHAR(2000), MSG2_TX LVARCHAR(5000) ) LOCK MODE ROW; Thanks. From Fuzzygoth at gmail.com Fri Aug 11 06:42:09 2006 From: Fuzzygoth at gmail.com (Fuzzydave) Date: 11 Aug 2006 03:42:09 -0700 Subject: Python checking for None/Null values In-Reply-To: References: <1155291204.446003.93760@m73g2000cwd.googlegroups.com> Message-ID: <1155292928.980276.228690@p79g2000cwp.googlegroups.com> > `historyRep` seems to be shorter than you think it is. Try printing it > too see what it actually contains. > > Ciao, > Marc 'BlackJack' Rintsch HistoryRep is an array value so historyRep[0] to [7] all have values in them but historyRep[8] and [9] do not as the query does not always return a full 10 values. I am trying to check all of the historyRep items to check if they are empty/null/None (whatever the term is in python) and make it return an empty value or a none to the screen. I did print historyRep[8] out and it falls over, I am assuming if its an array and if the SQL query only returns 8 records instead of 10 then the last two array values i am checking for litterly don't exist instead of being null but i can't find a if exists style function either? David P From this at is.invalid Thu Aug 31 17:38:00 2006 From: this at is.invalid (ddtl) Date: Thu, 31 Aug 2006 23:38:00 +0200 Subject: re.compile() doesn't work under Windows? Message-ID: Hello everybody. My script uses re.compile() function, and while it rans without errors under Linux, when I ran that script under Windows I get the following error: Traceback (most recent call last): File "C:\a\projects\re.py", line 4, in ? import re File "C:\a\projects\re.py", line 95, in ? main() File "C:\a\projects\re.py", line 37, in main s_exp = re.compile(op['-s']) AttributeError: 'module' object has no attribute 'compile' What is the problem here? re module is installed and is on the path - for example, the following code works and doesn't cause any errors: import re re.compile('a') What else could cause such an error? ddtl. From cwildsmith at westnet.com.au Mon Aug 21 03:08:45 2006 From: cwildsmith at westnet.com.au (Colin Wildsmith) Date: Mon, 21 Aug 2006 15:08:45 +0800 Subject: permanent tempfile? Message-ID: <380-2200681217845664@westnet.com.au> Hello, I am trying to create a temp file, however the file that is created is still there after the program has completed. Why is this so? CoLe #!/usr/bin/python import os, tempfile, sys import tempfile # creates a random file (text=True is textfile, text=False is binary file) ext = '.txt' pfx = 'tmp' dir = '/home/argon/PR0001/source/emc2/bin' filename = tempfile.mkstemp(suffix=ext, prefix=pfx, dir=dir, text=True)[1] print filename # eg. C:\Temp\tmpsnrfgk.txt # test it ... fout = open(filename, 'w') fout.write("just a text file") fout.close() os.remove(filename) From jorge.vargas at gmail.com Mon Aug 28 18:14:37 2006 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Mon, 28 Aug 2006 18:14:37 -0400 Subject: class problem In-Reply-To: References: <1156786617.162744.128870@h48g2000cwc.googlegroups.com> <32822fe60608281504q68d99453m294f5ad1cfda520c@mail.gmail.com> Message-ID: <32822fe60608281514y61fc41chf98a25ca61482979@mail.gmail.com> On 8/28/06, Fredrik Lundh wrote: > Jorge Vargas wrote: > > > seems like a feature/bug of 2.5, why your learning a language with a > > beta version? > > learning? I'm sorry I though you where the original poster. > > (btw, the "c" in 2.5c1 means *release candidate*, not "beta"). I was referring to "beta" as oposite to stable/released > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From alisonken1 at gmail.com Thu Aug 10 16:37:06 2006 From: alisonken1 at gmail.com (alisonken1) Date: 10 Aug 2006 13:37:06 -0700 Subject: String Formatting In-Reply-To: <1155242045.262819.322010@m73g2000cwd.googlegroups.com> References: <1155213326.679334.234880@i42g2000cwa.googlegroups.com> <1155242045.262819.322010@m73g2000cwd.googlegroups.com> Message-ID: <1155242225.991446.302500@i42g2000cwa.googlegroups.com> alisonken1 wrote: > OriginalBrownster wrote: > > > Example sorry, forgot the '... everything after the last comma ...' part. From no at spam.com Thu Aug 10 22:50:41 2006 From: no at spam.com (Farshid Lashkari) Date: Thu, 10 Aug 2006 19:50:41 -0700 Subject: error handling In-Reply-To: References: <1155253063.322440.97300@b28g2000cwb.googlegroups.com> <4MPCg.902$0F5.681@fed1read04> Message-ID: <6gSCg.16629$RD.13115@fed1read08> Steven D'Aprano wrote: > That's broken. > > Imagine that somewhere in main() the following is called: > > D = {"a": "apple", "b": "bicycle", "c": "cat"} > print D["aardvark"] > > Your code now prints "That number is way too big!". That's not good. > > try...except blocks should, as a general rule, cover only the smallest > amount of code that they need to. Hi Steven, Point taken and I think your solution better addresses the root of the problem. However, the OP said he wanted to print out that error message whenever the interpreter came across any IndexError. So I gave him what he wanted. I guess he needs to be more careful what he wishes for ;) -Farshid From gheorghe.postelnicu at gmail.com Wed Aug 30 15:32:13 2006 From: gheorghe.postelnicu at gmail.com (Gheorghe Postelnicu) Date: Wed, 30 Aug 2006 15:32:13 -0400 Subject: Callbacks Message-ID: <8094b1b60608301232s5965cac0xeaa08d02163711f@mail.gmail.com> Hi, I am using Python to develop a GUI for some underlying C++ computation. I wrap my Cpp code using SWIG. As my computation takes some time, I am considering ways to provide the user with some feedback on the state of the Cpp code. Unfortunately, it seems I cannot use directly a Python procedure as a callback using SWIG. (or is there). I imagine other people came across this problem, so I thought I would post this and see what solutions people came up with. Thanks, -- Gheorghe Postelnicu, PhD MGH, Harvard Medical School From yichun.wei at gmail.com Wed Aug 23 22:15:52 2006 From: yichun.wei at gmail.com (yichun.wei at gmail.com) Date: 23 Aug 2006 19:15:52 -0700 Subject: Can Python do Perl's print < Perl has the ability to do the following: print <> QSUB.stdin, qsubcmds (or Popen.communicate(qsubcmds)) the "rm -f " was not executed in my case. The corresponding perl script runs fine: open(QSUB, "| $qsubcmds -") || die "kao"; print QSUB < <1154080289.251993.137560@b28g2000cwb.googlegroups.com> Message-ID: On 2006-07-28, Marc 'BlackJack' Rintsch wrote: >> >> class MyClass(object): >> >> __slots__ = ('bar',) >> >> def func(self): >> return 123 >> >> x = MyClass() >> x.instance_var_not_defined_in_the_class = 456 >> ==> >> AttributeError: 'MyClass' object has no attribute >> 'instance_var_not_defined_in_the_class' >> >> x.func = 789 >> ==> >> AttributeError: 'MyClass' object attribute 'func' is read-only >> >> Only the bar-attribute can be set: >> >> x.bar = 'foo' > > This avoids the problem but you get others in return. And it's an abuse > of `__slots__` which is meant as a way to save memory if you need really > many objects of that type and not as "protection". I find that a strange purpose because when you are working on a class, you don't necessarily know if you will ever know many instance of that class. So should I use __slots__ in all my classes, just to be sure for when someone wants many instances of one? -- Antoon Pardon From amit.man at gmail.com Tue Aug 29 06:20:49 2006 From: amit.man at gmail.com (noro) Date: 29 Aug 2006 03:20:49 -0700 Subject: unit test for a printing method In-Reply-To: References: <1156780399.289589.58750@m73g2000cwd.googlegroups.com> <44f330ce$1@nntp0.pdx.net> Message-ID: <1156846849.066867.72860@i3g2000cwc.googlegroups.com> Fredrik Lundh wrote: > Scott David Daniels wrote: > > > For silly module myprog.py: > > def A(s): > > print '---'+s+'---' > > in test_myprog.py: > > import unittest > > from cStringIO import StringIO # or from StringIO ... > > why are you trying to reinvent doctest ? > > it was my understanding that "doctest" is intented to test the little examples in a function/class documention, do people use it for more then that, i.e - do an extentive output testing for thier apps? amit From rpdooling at gmail.com Mon Aug 7 12:59:43 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 7 Aug 2006 09:59:43 -0700 Subject: format a number for output References: <1154962511.485221.229830@i3g2000cwc.googlegroups.com> Message-ID: <1154969983.713194.45850@h48g2000cwc.googlegroups.com> abcd wrote: > if i have a number, say the size of a file, is there an easy way to > output it so that it includes commas? > > for example: > > 1890284 > > would be: > > 1,890,284 see also this thread: http://tinyurl.com/qf6ew rd From steve at holdenweb.com Thu Aug 17 12:12:08 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 17 Aug 2006 17:12:08 +0100 Subject: modify element of a list. In-Reply-To: <1155828941.317153.238310@74g2000cwt.googlegroups.com> References: <1155828941.317153.238310@74g2000cwt.googlegroups.com> Message-ID: KraftDiner wrote: > Hi I have a list of Ojbects... I want to change one of the objects in > the list for a new object.... > How do I replace an existing object with a new one and maintain the > list order.. > > This is what I have... > > def setAttribute(self, desc, value): > n = anObject(desc, value) > for o in self.Objects: > if o.getDescription() == desc: > self.Objects.replace(o, n) #Replace o with n? > return > self.Objects.append(n) > > It's the replace in place that I don't know how to do... > There are a number of ways. I suspect the simplest would be (untested): def setAttribute(self, desc, value): n = anObject(desc, value) for i, o in enumerate(self.Objects): if o.getDescription() == desc: self.Objects[i] = n return self.Objects.append(n) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From atkedzierski at gmail.com Sat Aug 12 09:01:24 2006 From: atkedzierski at gmail.com (AndrewTK) Date: 12 Aug 2006 06:01:24 -0700 Subject: reading from sockets In-Reply-To: References: <1155227695.625250.17920@m73g2000cwd.googlegroups.com> Message-ID: <1155387684.513673.130770@75g2000cwc.googlegroups.com> > I'm assuming that your server waits to receive the word 'hello' before > replying with the three strings (first, second, and third)? So once your Nope - actually it's a threaded "server", with the main thread simply dumping network input to the console and command line input being directly dumped to the network output stream. I confess to having typed the three lines manually...! It's at: http://www.dcs.st-and.ac.uk/~atk1/perso/java/servers/RespondingServer.java It launches on the command line with java RespondingServer _port_ _port_ being the port number it should listen for data on. From jweida at gmail.com Fri Aug 25 14:51:33 2006 From: jweida at gmail.com (Jerry) Date: 25 Aug 2006 11:51:33 -0700 Subject: wxPython and Py2exe crashes in "window" mode but not in "console" mode Message-ID: <1156531893.746147.79070@b28g2000cwb.googlegroups.com> I have created an application using wxPython and compiled it using py2exe. When I put setup(console=['myscript.py']) in my setup.py file, the resulting application runs just fine. But when I change it to setup(windows=['myscript.py']) The application crashes without any indication of what happened. During this particular point in the application it calls a gethostbyaddr and gethostbyname and does a spawnl to another application. When I use Tkinter, this does not happen. I've searched around Google and the py2exe and wxPython sites and haven't found anything that seems to relate to this. Details: All are binary distributions for Windows running on Windows XP SP2 ActivePython 2.4.3 Build 12 wxPython 2.6.3.3 (ansi) for Python 2.4 py2exe 0.6.5 Any ideas? Thanks in advance. -- Jerry From tjreedy at udel.edu Fri Aug 25 11:59:16 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 25 Aug 2006 11:59:16 -0400 Subject: Consistency in Python References: Message-ID: "Brendon Towle" wrote in message news:CD19F2D3-C840-404E-AAD9-ED92BF730C63 at carnegielearning.com... Message: 3 Date: Fri, 25 Aug 2006 15:28:46 +0200 From: "Fredrik Lundh" Subject: Re: Consistency in Python Brendon Towle wrote: [snip] Please post with plain (extended) ascii text, the standard for newsgroups, and not HTML. The above and everything you quoted is, on my screen, in teeny type I can hardly read. Plus, I cannot insert my text without it also being prefixed on the left with the quotation bar and indent. So this format also make proper replies impossible. Terry Jan Reedy -------------- next part -------------- An HTML attachment was scrubbed... URL: From boris.dusek at gmail.com Wed Aug 23 18:21:57 2006 From: boris.dusek at gmail.com (bobrik) Date: 23 Aug 2006 15:21:57 -0700 Subject: in-memory-only file object from string In-Reply-To: References: <1156370182.719946.223220@i3g2000cwc.googlegroups.com> Message-ID: <1156371717.582952.15090@i42g2000cwa.googlegroups.com> > See the standard modules: StringIO and cStringIO Thank you! From shekhar.kaushik at gmail.com Fri Aug 25 01:19:15 2006 From: shekhar.kaushik at gmail.com (Chandrashekhar kaushik) Date: Fri, 25 Aug 2006 10:49:15 +0530 Subject: pickling and endianess Message-ID: Can an object pickled and saved on a little-endian machine be unpickled on a big-endian machine ? Does python handle this in some manner , by say having a flag to indicate the endianess of the machine on which the object was pickled ? And then using this flag to decide how that data will be unpickled ? shekhar -------------- next part -------------- An HTML attachment was scrubbed... URL: From you at cogeco.ca Mon Aug 14 19:12:44 2006 From: you at cogeco.ca (AlbaClause) Date: Mon, 14 Aug 2006 19:12:44 -0400 Subject: yet another noob question References: <1155492110.659011.196280@75g2000cwc.googlegroups.com> Message-ID: <8o7Eg.13$dB.2@read2.cgocable.net> mike_wilson1333 wrote: > I would like to generate every unique combination of numbers 1-5 in a 5 > digit number and follow each combo with a newline. So i'm looking at > generating combinations such as: (12345) , (12235), (55554) and so on. > What would be the best way to do this? So, basically i'm looking for a > list of all combinations of 1-5 in a 5 digit unique number. Also, when > I send the list to print there can't be any duplicates of the combos. > > > Thanks, > > Mike This is one of those questions that reminded me that I don't know Python. I launched my Python interpreter, and forgot how to even print a string. Duh! Oh well... -- -- There are several things that I will never be: * I will never be attracted to females. * I will never enjoy the company of others. Exactly how these realities bode for my enemy, is not of my concern. From hitesh287 at gmail.com Wed Aug 16 14:52:32 2006 From: hitesh287 at gmail.com (Hitesh) Date: 16 Aug 2006 11:52:32 -0700 Subject: Documentation Question About Depricated String Functions Message-ID: <1155754352.767469.211380@m73g2000cwd.googlegroups.com> Hi, In python doc -- 4.1.4 Deprecated string functions -- I read that "The following list of functions are also defined as methods of string and Unicode objects; see ``String Methods'' (section 2.3.6) for more information on those. You should consider these functions as deprecated, although they will not be removed until Python 3.0. The functions defined in this module are: " and there is a whole list of functions. If these functions are deprecated what is the replacement for them? I couldn't find that info in the doc. Any links will be helpful. Thank you, hj From jonsmirl at gmail.com Sun Aug 6 17:03:59 2006 From: jonsmirl at gmail.com (Jon Smirl) Date: Sun, 06 Aug 2006 17:03:59 -0400 Subject: Initializing the number of slots in a dictionary Message-ID: Is there some way to tell a dictionary object that I am going to load 1M objects into it and have it pre-allocate enought slots to hold all of the entries? Thus avoiding many thousand memory allocations. Jon Smirl jonsmirl at gmail.com From liuliuliu at gmail.com Tue Aug 8 17:35:58 2006 From: liuliuliu at gmail.com (liuliuliu) Date: 8 Aug 2006 14:35:58 -0700 Subject: how to save a screenshot in pygame? Message-ID: <1155072958.550904.50790@i3g2000cwc.googlegroups.com> hi -- sorry if this is trivial -- but how do you make a screenshot of a pygame display? i have a surface which is basically the entire visible screen -- how do you write this surface as an image file during specific events in the script execution? image format doesnt matter. thanks! christine From rogue_pedro at yahoo.com Wed Aug 2 03:23:26 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 2 Aug 2006 00:23:26 -0700 Subject: Zipping files/zipfile module References: <1154483883.796081.35140@p79g2000cwp.googlegroups.com> Message-ID: <1154503406.601524.56390@75g2000cwc.googlegroups.com> Brian Beck wrote: > OriginalBrownster wrote: > > I want to zip all the files within a directory called "temp" > > and have the zip archive saved in a directory with temp called ziptemp > > > > I was trying to read up on how to use the zipfile module python > > provides, but I cannot seem to find adequate documentation on function > > itself. > > > > Perhaps someone could help me in this task? > > Hello, > > This isn't completely tested, but perhaps it will help you get started: > > from os import listdir, mkdir > from os.path import join, basename, isfile > from zipfile import ZipFile > > def zip_dir(path, output_path, include_hidden=True): > files = [join(path, f) for f in listdir(path) if isfile(join(path, f))] > try: > mkdir(output_path) > except OSError, e: > if e.errno == 17: # Path exists > pass > zip_file = ZipFile(join(output_path, 'temp.zip'), 'w') > for f in files: > if basename(f).startswith('.') and not include_hidden: > continue > print "Adding %s to archive..." % (f,) > zip_file.write(f) > zip_file.close() > > Use like: > zip_dir('temp', 'temp/ziptemp') > > Note that if you want to add the entire contents of a directory > (subdirectories, recursively), you should consider using os.walk or > something similar. This will only add the file contents of the directory. > I'm not sure if the zipfile module provides any nice ways to write > directories to the archive, but I'm assuming it just involves writing an > arcname with a '/' in it (see help(zipfile.ZipFile)). > > -- > Brian Beck > Adventurer of the First Order To avoid calling os.path.join() twice for each filename when you build the list of files you could write the list comprehension like so: [n for n in (join(path, f) for f in listdir(path)) if isfile(n)] Also, you should use the "symbolic" errors from the errno module rather than hard-coding a constant: from errno import EEXIST ... if e.errno == EEXIST: # Path exists Finally, if your using a single arg with a string interpolation and you know it'll never be a tuple you needn't wrap it in a tuple: print "Adding %s to archive..." % f From andybak at gmail.com Wed Aug 9 07:00:31 2006 From: andybak at gmail.com (andybak) Date: 9 Aug 2006 04:00:31 -0700 Subject: setup.py when you can't write to site-packages? Message-ID: <1155121231.384846.86090@i3g2000cwc.googlegroups.com> There are several gaps in my Python knowledge, one of which is the what exactly setuptools does and how it works. I'm on a shared host so can't write to site-packages therefore most setup.py's fail. My strategy for pure python packages is to run setup.py locally and copy anything that gets put in site-packages across to the shared host somewhere in my Python path. I'm sure there is a better solution! What's the best approach for situations when you can't tamper with the Python install? From quentel.pierre at wanadoo.fr Thu Aug 17 12:09:23 2006 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: 17 Aug 2006 09:09:23 -0700 Subject: modify element of a list. In-Reply-To: <1155828941.317153.238310@74g2000cwt.googlegroups.com> References: <1155828941.317153.238310@74g2000cwt.googlegroups.com> Message-ID: <1155830963.911573.248220@m73g2000cwd.googlegroups.com> Hi, The most simple is to use the index of the element in the list : def setAttribute(self, desc, value): n = anObject(desc, value) for i,o in enumerate(self.Objects): if o.getDescription() == desc: self.Objects[i] = n return self.Objects.append(n) Pierre From accurrent at gmail.com Fri Aug 11 14:35:14 2006 From: accurrent at gmail.com (accurrent at gmail.com) Date: 11 Aug 2006 11:35:14 -0700 Subject: having issues Installing Python 2.5b3 on Windows XP In-Reply-To: <1155318944.456810.128010@p79g2000cwp.googlegroups.com> References: <1155315119.400903.49090@h48g2000cwc.googlegroups.com> <1155318944.456810.128010@p79g2000cwp.googlegroups.com> Message-ID: <1155321314.213704.169890@b28g2000cwb.googlegroups.com> Bucco wrote: > The python 2.4 version msi did no better. Please help. I do not > really want to go back to Active State Python. > > > Thanks:) > > SA > > > Bucco wrote: > > I > > am going to try to install python 2.4 with the msi installer and see if > > I have the same issue with that version. If anyone else has any ideas > > please help. It is a beta after all. You should expect some bugs. From aleax at mac.com Tue Aug 29 22:41:06 2006 From: aleax at mac.com (Alex Martelli) Date: Tue, 29 Aug 2006 19:41:06 -0700 Subject: What do you want in a new web framework? References: <1156100331.329889.216340@p79g2000cwp.googlegroups.com> <1156156636.515678.118210@75g2000cwc.googlegroups.com> <4jele2pe011di99c5dnq4olclglrkieggc@4ax.com> <1hkgnbt.ebn4o1111ftp0N%aleax@mac.com> Message-ID: <1hkujsw.1kfwx315rpfd3N%aleax@mac.com> Peter Maas wrote: > Cliff Wells wrote: > > On Wed, 2006-08-23 at 22:13 +0200, Peter Maas wrote: > >> Alex Martelli wrote: > [...] > >>> I have already suggested to the BDFL that he can remedy this situation > >>> in Py3k: all he has to do, of course, is to add a LOT more keywords. > >> Here is another remedy: he adds one of the frameworks to the standard > >> library :) > > > > That didn't help Tk maintain a monopoly on Python GUI toolkits. > > I must not be a monopoly. A center of gravity would be nice, too. .... [it helps to know some Italian, but it's not necessarily a must... Francesco Battiato's amply demonstrated his music and lyrics can fascinate non-speakers of Italian, too;-)] Alex From ntv1534 at gmail.com Wed Aug 23 14:47:02 2006 From: ntv1534 at gmail.com (MooMaster) Date: 23 Aug 2006 11:47:02 -0700 Subject: Regex help...pretty please? Message-ID: <1156358822.649578.126990@74g2000cwt.googlegroups.com> I'm trying to develop a little script that does some string manipulation. I have some few hundred strings that currently look like this: cond(a,b,c) and I want them to look like this: cond(c,a,b) but it gets a little more complicated because the conds themselves may have conds within, like the following: cond(0,cond(c,cond(e,cond(g,h,(a= d)) OUTPUT: whole string is: (a,b,(abs(c) the new string is:cond((abs(c,a,b) Can anyone help me with the regular expression? Is this even the best approach to take? Anyone have any thoughts? Thanks for your time! From john106henry at hotmail.com Wed Aug 9 17:59:11 2006 From: john106henry at hotmail.com (John Henry) Date: 9 Aug 2006 14:59:11 -0700 Subject: What's the cleanest way to compare 2 dictionary? In-Reply-To: <1155160522.308295.254510@75g2000cwc.googlegroups.com> References: <1155147450.628625.20270@m79g2000cwm.googlegroups.com> <1155149273.270320.176030@75g2000cwc.googlegroups.com> <1155160522.308295.254510@75g2000cwc.googlegroups.com> Message-ID: <1155160751.602587.303470@m79g2000cwm.googlegroups.com> John Henry wrote: > Paddy wrote: > > John Henry wrote: > > > Hi list, > > > > > > I am sure there are many ways of doing comparision but I like to see > > > what you would do if you have 2 dictionary sets (containing lots of > > > data - like 20000 keys and each key contains a dozen or so of records) > > > and you want to build a list of differences about these two sets. > > > > > > I like to end up with 3 lists: what's in A and not in B, what's in B > > > and not in A, and of course, what's in both A and B. > > > > > > What do you think is the cleanest way to do it? (I am sure you will > > > come up with ways that astonishes me :=) ) > > > > > > Thanks, > > I make it 4 bins: > > a_exclusive_keys > > b_exclusive_keys > > common_keys_equal_values > > common_keys_diff_values > > > > Something like: > > > > a={1:1, 2:2,3:3,4:4} > > b = {2:2, 3:-3, 5:5} > > keya=set(a.keys()) > > keyb=set(b.keys()) > > a_xclusive = keya - keyb > > b_xclusive = keyb - keya > > _common = keya & keyb > > common_eq = set(k for k in _common if a[k] == b[k]) > > common_neq = _common - common_eq > > > > > > If you now simple set arithmatic, it should read OK. > > > > - Paddy. > > Thanks, that's very clean. Give me good reason to move up to Python > 2.4. Oh, wait, works in 2.3 too. Just have to: from sets import Set as set From rbonvall at cern.ch Mon Aug 21 07:59:49 2006 From: rbonvall at cern.ch (Roberto Bonvallet) Date: 21 Aug 2006 11:59:49 GMT Subject: text editor suggestion? References: <44e66724$0$2363$c3e8da3@news.astraweb.com> <44e6ab26$0$12557$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > I'd really like to learn vim, but I spent days just trying to figure out > how to get the syntax highlighting and indentation working, where these > settings are and how to edit them, and it still doesn't work for me. It > just feels so insurmountable that I can't even start working with it yet > because I don't know how to tailor the settings. Create a vimrc file (if you use Unix: ~/.vimrc) with the following lines in it: syntax on set autoindent set smartindent If you find that using vim is hard, try using evim (easy vim). It is part of the standard vim distribution (actually it's the same program). Anyway, I suggest learning the classic modal vim, it's really worth it. -- Roberto Bonvallet From sjmachin at lexicon.net Mon Aug 14 19:10:22 2006 From: sjmachin at lexicon.net (John Machin) Date: 14 Aug 2006 16:10:22 -0700 Subject: Memory problem In-Reply-To: <44E0FB3F.6090801@v.loewis.de> References: <1155590938.397801.302110@h48g2000cwc.googlegroups.com> <44E0FB3F.6090801@v.loewis.de> Message-ID: <1155597022.328271.153390@b28g2000cwb.googlegroups.com> Martin v. L?wis wrote: > John Machin wrote: > > Incredible. That's only 34 MB. What is the size of your paging file? > > What memory guzzlers were you running at the same time? What was the > > Task Manager "Performance" pane showing while your test was running? > > What version of Python? > > He didn't say Windows (so far). Yes he did -- reread his message, which I quoted in the message which you have *partially* quoted above. """ I use Windows XP x64 with 4GB RAM. """ Cheers, John From kylotan at gmail.com Mon Aug 14 10:04:55 2006 From: kylotan at gmail.com (Ben Sizer) Date: 14 Aug 2006 07:04:55 -0700 Subject: hide python code ! In-Reply-To: <1155320948.142524.124990@p79g2000cwp.googlegroups.com> References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155300852.497741.73230@74g2000cwt.googlegroups.com> <1155301468.870340.82920@b28g2000cwb.googlegroups.com> <1155307415.855555.124760@i3g2000cwc.googlegroups.com> <1155309563.898182.195950@p79g2000cwp.googlegroups.com> <1155313092.743230.33950@m73g2000cwd.googlegroups.com> <1155320948.142524.124990@p79g2000cwp.googlegroups.com> Message-ID: <1155564295.361980.279350@m73g2000cwd.googlegroups.com> Paul Boddie wrote: > Ben Sizer wrote: > > > > Imagine if you were the single-person developer of a small application > > that did something quite innovative, and charged a small fee for your > > product. Now imagine you were practically forced to make your algorithm > > obvious - a couple of months later, Microsoft bring out a freeware > > version and destroy your business in an instant. Sure, they and others > > can (and have) done that with closed-source products, but you increase > > your chances of survival 10-fold if the key algorithms are not obvious. > > This point is fairly comprehensively answered in the following article: > > http://radar.oreilly.com/archives/2006/08/apple_eats_whiners.html I don't believe so. That talks about copying of ideas, which is quite distinct from copying of implementations. The distinction may be meaningless in your typical desktop app where implementation is usually obvious from the interface. However in more high-tech systems such as multimedia or AI, the same is far from true. > I read an article where various aging popular musicians were > lobbying the British government to extend the period of copyright > beyond 50 years because their first works would soon fall into the > public domain and that they'd no longer earn royalties on those works. > But in what percentage of the many other jobs that exist do you still > get paid for a day at work that happened over 50 years ago? However, in most of those jobs you get paid properly at the time. Aside from the 1% of musicians who are pop stars, musicians generally do not. I'm not saying I agree with extending the copyright period, however I do think you can't just compare it to 'a day at work'. It's a totally different set of circumstances which requires a different set of rules to both encourage artists to continue creating while benefitting society in the long run too. -- Ben Sizer From bobrien18 at yahoo.com Tue Aug 15 13:06:02 2006 From: bobrien18 at yahoo.com (KraftDiner) Date: 15 Aug 2006 10:06:02 -0700 Subject: How to tell machines endianism. Message-ID: <1155661562.050063.239830@h48g2000cwc.googlegroups.com> How can you tell if the host processor is a big or little endian machine? From robinsiebler at 321.net Mon Aug 28 20:01:13 2006 From: robinsiebler at 321.net (robinsiebler) Date: 28 Aug 2006 17:01:13 -0700 Subject: Searching for text Message-ID: <1156809673.741444.110690@m73g2000cwd.googlegroups.com> I have a batch of files that I am trying to search for specific text in a specific format. Each file contains several items I want to search for. Here is a snippet from the file: ... /FontName /ACaslonPro-Semibold def /FontInfo 7 dict dup begin /Notice (Copyright 2000 Adobe Systems Incorporated. All Rights Reserved.Adobe Caslon is either a registered trademark or a trademark of Adobe Systems Incorporated in the United States and/or other countries.) def /Weight (Semibold) def /ItalicAngle 0 def /FSType 8 def ... I want to search the file until I find '/FontName /ACaslonPro-Semibold' and then jump forward 7 lines where I expect to find '/FSType 8'. I then want to continue searching from *that* point forward for the next FontName/FSType pair. Unfortunately, I haven't been able to figure out how to do this in Python, although I could do it fairly easily in a batch file. Would someone care to enlighten me? From g.brandl-nospam at gmx.net Sat Aug 26 07:59:42 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Sat, 26 Aug 2006 13:59:42 +0200 Subject: Taking data from a text file to parse html page In-Reply-To: References: <1156378275.662140.214650@h48g2000cwc.googlegroups.com><1156473610.654066.323410@p79g2000cwp.googlegroups.com> <1156564037.135087.48890@i42g2000cwa.googlegroups.com> Message-ID: Anthra Norell wrote: > No, I am not running Linux to any extent. But I am very strict about case. There is not a single instance of "se.py" or "sel.py" > anywhere on my system. You' ll have to find out where lower case sneaks in on yours. The zip file preserves case and in the zip file > the names are upper case. I am baffled. But I believe that an import tripping up on the wrong case can't be a hard nut to crack. The problem is the extension: SE.py is acceptable, while SE.PY is not. Georg From dingbat at codesmiths.com Tue Aug 8 12:25:34 2006 From: dingbat at codesmiths.com (Andy Dingley) Date: 8 Aug 2006 09:25:34 -0700 Subject: Newbie - How to iterate list or scalar ? In-Reply-To: <44d86c6c$0$21149$7a628cd7@news.club-internet.fr> References: <1155030787.666942.277610@m79g2000cwm.googlegroups.com> <44d86c6c$0$21149$7a628cd7@news.club-internet.fr> Message-ID: <1155054334.863073.243560@75g2000cwc.googlegroups.com> Bruno Desthuilliers wrote: > there's really no reason to > assume it should be a list - any iterable could - and IMHO should - be > accepted... expect of course for strings (royal PITA case, duh). > 2/ test for pluginVersionsNeeded.__iter__ (an attribute of most > iterables except strings...): strings don't have __iter__ ?!?! I'm never going to get my head round this language 8-( I can understand strings and tuples being iterable, if you take a sufficiently first-class view of things, but why shouldn't everything "that is iterable" support the function that makes iteration work? From geli at tasmail.com Tue Aug 15 03:01:11 2006 From: geli at tasmail.com (gel) Date: 15 Aug 2006 00:01:11 -0700 Subject: What would be the best way to run python client in the background Message-ID: <1155625271.858914.175780@m73g2000cwd.googlegroups.com> Hi I have written a python client server app that keeps an eye on processes starting and ending on a client and makes decision on what to do based on information from the server end. I want to run the client end of the app more or less invisibly (no console) on the XP clients when ever a users logs on. What would be the best way to get this done? A bit more info on the purpose of the app... it is to act as a licence server, where we have a limited number of licences for software and the software installed on all PCs. The app will only allow a pre defined number of clients to run the software at any one time. From gandalf at designaproduct.biz Tue Aug 1 12:24:49 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Tue, 01 Aug 2006 18:24:49 +0200 Subject: Jumping over in the class hierarchy In-Reply-To: <44cf7481$0$24888$9b4e6d93@newsread4.arcor-online.net> References: <44cf7481$0$24888$9b4e6d93@newsread4.arcor-online.net> Message-ID: <44CF8051.5090809@designaproduct.biz> Pupeno ?rta: > Hello, > I want to jump over a method in the class hierarchy, that is: If I have > class A(object), clas B(A), class C(B) and in C, I want a method to do > exactly what A does but not what B does in its reimplementation, would it > be correct to do: super(A, super(B, self)).method() in C ? > Thank you. > A.method(self) Cheers, Laszlo From __peter__ at web.de Wed Aug 30 17:54:45 2006 From: __peter__ at web.de (Peter Otten) Date: Wed, 30 Aug 2006 23:54:45 +0200 Subject: csv module strangeness. References: <44f5e870$0$8814$88260bb3@free.teranews.com> <44f5f347$0$8846$88260bb3@free.teranews.com> Message-ID: tobiah wrote: >> you may be misreading the docs; the Dialect has no values at all, and >> must be subclassed (and the subclass must provide settings). > > The docs clearly state what the defaults are, but they are not > in the code. It seems so clumsy to have to specify every one > of these, just to change the delimiter from comma to tab. > > http://docs.python.org/lib/csv-fmt-params.html : > > delimiter > A one-character string used to separate fields. It defaults to ','. Note that you need not bother with a dialect class just to change the delimiter: >>> import csv >>> from cStringIO import StringIO >>> instream = StringIO( ... "alpha\tbeta\tgamma\r\n" ... "one\ttoo\ttree\r\n") >>> for row in csv.reader(instream, delimiter="\t"): ... print row ... ['alpha', 'beta', 'gamma'] ['one', 'too', 'tree'] Peter From deets at nospam.web.de Mon Aug 28 11:58:45 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Aug 2006 17:58:45 +0200 Subject: unit test for a printing method References: <1156780399.289589.58750@m73g2000cwd.googlegroups.com> Message-ID: <4lgi5lF1pfufU2@uni-berlin.de> noro wrote: > What is the proper way to test (using unit test) a method that print > information? > for example: > > def A(s): > print '---'+s+'---' > > and i want to check that A("bla") really print out "---bla---" You can replace sys.stdout with a cStringIO-object or any other file-protocol implementing object and such collect the data. Diez From gregb.usenet200608 at blackholio.dyndns.org Thu Aug 17 23:41:53 2006 From: gregb.usenet200608 at blackholio.dyndns.org (Greg R. Broderick) Date: Thu, 17 Aug 2006 22:41:53 -0500 Subject: The Semicolon Wars as a software industry and human condition References: <1155822175.534005.100490@75g2000cwc.googlegroups.com> <1155827943.041208.51220@i3g2000cwc.googlegroups.com> Message-ID: "Iain King" wrote in news:1155827943.041208.51220 @i3g2000cwc.googlegroups.com: > I'm confused - I thought Xah Lee loved Perl? Now he's bashing it? > Huh? That's his other personality. -- --------------------------------------------------------------------- Greg R. Broderick gregb.usenet200607 at blackholio.dyndns.org A. Top posters. Q. What is the most annoying thing on Usenet? --------------------------------------------------------------------- From jeremit0 at gmail.com Wed Aug 2 12:45:07 2006 From: jeremit0 at gmail.com (jeremito) Date: 2 Aug 2006 09:45:07 -0700 Subject: Convert string to mathematical function In-Reply-To: References: <1154483108.034363.112320@i42g2000cwa.googlegroups.com> <1154488127.174894.206250@i42g2000cwa.googlegroups.com> Message-ID: <1154537107.079042.227780@75g2000cwc.googlegroups.com> I was unaware of the exec and eval functions in Python. Without trying them, they seem to be what I want to do. I'll play around with it and see if I can figure it out. Thanks for the suggestions everyone. Jeremy From gelists at gmail.com Wed Aug 2 17:04:47 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Wed, 2 Aug 2006 18:04:47 -0300 Subject: Windows vs. Linux References: <1154301694.445639.99580@m79g2000cwm.googlegroups.com> <44cddfb3$0$7761$7a628cd7@news.club-internet.fr> <1hjfow0.xza1lcpaytg8N%aleax@mac.com> Message-ID: <1qz3d1ave0xa0$.dlg@gelists.gmail.com> On 2006-08-02 17:38:54, Sybren Stuvel wrote: > Gerhard Fiedler enlightened us with: >>> Microsoft did *NOT* write DOS >> >> Well, they didn't write most of DOS 1.0. But it seems they did write >> (or at least specify) most if not all of the rest up to DOS 6.22 or >> so. Which is possibly considerable. > > Those are MS-DOS version numbers you're talking about. Of course. The issue was that I wrote that "Microsoft wrote DOS on Xenix" and Alex objected. I was of course wrong in that totality, but then, they still wrote everything between DOS 1.0 and 6.22 on Xenix. > For example, they had nothing to do with FreeDOS, which is also a DOS. Yup, and a number of other DOSes like Novell DOS etc. Still all (or most?) of these use the backslash :) Gerhard From pmaupin at gmail.com Tue Aug 8 01:05:00 2006 From: pmaupin at gmail.com (Patrick Maupin) Date: 7 Aug 2006 22:05:00 -0700 Subject: Question on try/except In-Reply-To: <44d80393$1@nntp0.pdx.net> References: <5KTBg.4514$Jg1.2316@trndny05><44d80393$1@nntp0.pdx.net> Message-ID: <1155013500.694205.68440@n13g2000cwa.googlegroups.com> Kirk McDonald wrote: > Dan wrote: > > Is there some particular use in catching an exception and immediately > > re-raising it? Why catch it at all? > > All I can think of is that it changes the traceback to point to the > re-raise and not the original raise. I've used this technique before. It is very useful where (as in the original re example) recursion might cause a large traceback, and the error is probably caused by the caller's code. Using this technique can keep the visible portion of the traceback relevant to the problem at hand. Regards, Pat From tim at tdw.net Wed Aug 16 12:58:03 2006 From: tim at tdw.net (Tim Williams) Date: Wed, 16 Aug 2006 17:58:03 +0100 Subject: Adding a char inside path string In-Reply-To: References: <1155737700.290268.248250@i42g2000cwa.googlegroups.com> <1155744057.573884.111850@m73g2000cwd.googlegroups.com> Message-ID: <9afea2ac0608160958p79c52621yd2f3ef3e250cae1@mail.gmail.com> On 16/08/06, Dennis Lee Bieber wrote: > On 16 Aug 2006 09:00:57 -0700, "Hitesh" declaimed > the following in comp.lang.python: > > > > > Thank you Fredrik. That works for a string. > > But I am getting list of tuples from DB. > > > > rows = [('\\serverName\C:\FolderName1\FolderName2\example.exe',), > > ('\\serverName\C:\FolderName1\FolderName2\example2.exe',), > > ('\\serverName\C:\FolderName1\FolderName2\example3.exe',), > > ('\\serverName\C:\FolderName1\FolderName2\example4.exe',)] > > > > I tried this: > > for i in rows: > > row = str(i) > > path = row.replace("C:" , "c$") > > print path > > > > I am getting path something like > > > > ('\\serverName\c$:\FolderName1\FolderName2\example.exe',) > > > > How on the earth I can remove those paranthesis? > > > By accessing the contents of the tuple, not the tuple itself > > >>> rows = [('\\serverName\C:\FolderName1\FolderName2\example.exe',), > .... ('\\serverName\C:\FolderName1\FolderName2\example2.exe',), > .... ('\\serverName\C:\FolderName1\FolderName2\example3.exe',), > .... ('\\serverName\C:\FolderName1\FolderName2\example4.exe',)] > >>> rows > [('\\serverName\\C:\\FolderName1\\FolderName2\\example.exe',), > ('\\serverName\\C:\\FolderName1\\FolderName2\\example2.exe',), > ('\\serverName\\C:\\FolderName1\\FolderName2\\example3.exe',), > ('\\serverName\\C:\\FolderName1\\FolderName2\\example4.exe',)] > >>> modRows = [itm[0].replace("C:", "C$") for itm in rows] > >>> modRows > ['\\serverName\\C$\\FolderName1\\FolderName2\\example.exe', > '\\serverName\\C$\\FolderName1\\FolderName2\\example2.exe', > '\\serverName\\C$\\FolderName1\\FolderName2\\example3.exe', > '\\serverName\\C$\\FolderName1\\FolderName2\\example4.exe'] > >>> Try modRows = ['\\'+itm[0].replace(":", "$") for itm in rows] It will work with any drive letter and makes an allowance for the first escape character. >>> modRows ['\\\\serverName\\C$\\FolderName1\\FolderName2\\example.exe', '\\\\serverName\\C$\\FolderName1\\FolderName2\\example2.exe', ....etc for r in modRows: print r \\serverName\C$\FolderName1\FolderName2\example.exe \\serverName\C$\FolderName1\FolderName2\example2.exe ......etc :) From ronny.coder at gmail.com Thu Aug 17 11:01:26 2006 From: ronny.coder at gmail.com (Ronny Abraham) Date: Thu, 17 Aug 2006 11:01:26 -0400 Subject: 1. Re: hide python code ! (enigmadude) Message-ID: <7405d1440608170801u4b5f7cc9hbf73cd36e67f830b@mail.gmail.com> Actually the reason you want to have one layer of encryption isn't to prevent someone from understanding what you wrote, it's so that if some company decides to "acquire" your code, they can't claim that you had it in the public domain. I think even the most pathetic encryption can serve this purpose. -ronny -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Tue Aug 1 05:13:55 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 01 Aug 2006 11:13:55 +0200 Subject: how to get size of unicode string/string in bytes ? References: <1154420030.988013.89310@m79g2000cwm.googlegroups.com> <44cf167c$0$24894$9b4e6d93@newsread4.arcor-online.net> Message-ID: <4j8k58F6th46U1@uni-berlin.de> Stefan Behnel wrote: > pattreeya at gmail.com wrote: >> how can I get the number of byte of the string in python? >> with "len(string)", it doesn't work to get the size of the string in >> bytes if I have the unicode string but just the length. (it only works >> fine for ascii/latin1) In data structure, I have to store unicode >> string for many languages and must know exactly how big of my string >> which is stored so I can read back later. > > I do not quite know what you could possibly need that for, but AFAICT > Python only uses two different unicode encodings depending on the > platform. It is very important for relational databases, as these usually constrain the amount of bytes per column - so you need the size of bytes, not the number of unicode characters. Diez From david_wahler at bic.ky Mon Aug 21 01:27:18 2006 From: david_wahler at bic.ky (david_wahler at bic.ky) Date: 21 Aug 2006 00:27:18 -0500 Subject: =?utf-8?Q?Re:_[ANN]_PyYAML=2D3.04:_YAML_parser_and_emitter_for_Python?= Message-ID: <20060821052718.7424.qmail@BICSRV1011.bic.ky> I'll be out of the office until approximately August 20th. If you have any questions, please email support at bic.ky. -- David Wahler From st at tobiah.org Thu Aug 24 15:01:25 2006 From: st at tobiah.org (tobiah) Date: Thu, 24 Aug 2006 12:01:25 -0700 Subject: Python & chess In-Reply-To: References: <83e8215e0608240358l4126bb83la93a4c61e4aa4499@mail.gmail.com> Message-ID: <44edea60$0$8925$88260bb3@free.teranews.com> Paolo Pantaleo wrote: > Well Python is not a good language for writing a chess engine I'm curious; how does python fall short here, and what are the features that make some other language more suitable for the task? Toby -- Posted via a free Usenet account from http://www.teranews.com From beliavsky at aol.com Thu Aug 17 13:40:46 2006 From: beliavsky at aol.com (beliavsky at aol.com) Date: 17 Aug 2006 10:40:46 -0700 Subject: where can i get older version of python? References: <1155835739.694566.177080@75g2000cwc.googlegroups.com> Message-ID: <1155836446.519914.309540@i42g2000cwa.googlegroups.com> chppatel at gmail.com wrote: > does any one know where can I get older version of python for windows? > > I am looking for versions between 2.0 and 2.2. http://www.python.org/download/releases/ From durumdara at gmail.com Fri Aug 4 04:17:22 2006 From: durumdara at gmail.com (Durumdara) Date: Fri, 4 Aug 2006 10:17:22 +0200 Subject: non-blocking PIPE read on Windows In-Reply-To: <1154678278.845900.265100@m79g2000cwm.googlegroups.com> References: <1154064385.494993.159510@b28g2000cwb.googlegroups.com> <1154678278.845900.265100@m79g2000cwm.googlegroups.com> Message-ID: <9e384ef60608040117m6a40d117v2d0ce885bd6d1114@mail.gmail.com> Hi ! Sorry, but I want to share my experiences. I hope this help to you. I think that specialized MSWindows based services too complicated. They have to many bug possibilites. So I trying with normal, "in python accessable" pipes. I see that with flush(), and some of the bintotext tricks I can use the subprocess/masterprocess communication. Ok, this is not asynchronous. I can send some job to sp(s), and I can receive the report from sp(s). But with threading I can create non-blocking communication. You can see in the example: the PipeBPPThr define a pipe based process-pool thread. This can communicate with a subprocess, can send/receive jobs, etc. If you collect these threads, and write a process pool object, you can handle all of the communications with one object. I hope to these examples can help to you. If not, you can try with wm_copydata messages in Windows. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/dataexchange/datacopy/usingdatacopy.asp This way of data exchanging is based on the message handling/sending. dd -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: CustPPThread.py Type: text/x-python Size: 1509 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: ppbpt_sub.py Type: text/x-python Size: 240 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: PipeBPPThr.py Type: text/x-python Size: 2053 bytes Desc: not available URL: From bj_666 at gmx.net Sat Aug 12 05:52:43 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 12 Aug 2006 11:52:43 +0200 Subject: unbound methods References: <1155374957.203786.73840@74g2000cwt.googlegroups.com> Message-ID: In <1155374957.203786.73840 at 74g2000cwt.googlegroups.com>, brent.chambers at gmail.com wrote: > I wrote a small class today at work playing with sockets in command > line windows. When attempting to call the handle function, I get a > TypeError. "Unbound method handle() must be called with connection > instance as first argument (got nothing instead). Any suggestions > would be greatly appreciated. Thanks! I'd suggest that you post some actual code plus traceback so we don't have to guess. Ciao, Marc 'BlackJack' Rintsch From st at tobiah.org Thu Aug 17 16:20:09 2006 From: st at tobiah.org (tobiah) Date: Thu, 17 Aug 2006 13:20:09 -0700 Subject: Defining our own types? In-Reply-To: References: Message-ID: <44E4CF79.4080201@tobiah.org> > suppose I type: > ip = 123.45.67.89 This is probably far from what you want, but I would do something like this: ******************************************** class ip(list): def __init__(self, ip): bytes = ip.split('.') for x in range(4): self.append(bytes[x]) def __repr__(self): return '.'.join(self) localhost = ip('192.168.1.1') print localhost print localhost[2] ******************************************* 192.168.1.1 1 That way at least you can get at the value in both of the meaningful ways, and you can probably think of more methods, like applying netmasks, etc... From paddy3118 at netscape.net Fri Aug 25 12:17:23 2006 From: paddy3118 at netscape.net (Paddy) Date: 25 Aug 2006 09:17:23 -0700 Subject: sum and strings In-Reply-To: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> Message-ID: <1156522643.457784.190070@m79g2000cwm.googlegroups.com> Paddy wrote: <> > Why not make sum work for strings too? > > It would remove what seems like an arbitrary restriction and aid > duck-typing. If the answer is that the sum optimisations don't work for > the string datatype, then wouldn't it be better to put a trap in the > sum code diverting strings to the reduce equivalent? > > Just a thought, > > - Paddy. from __no_future__ import sum assert "Not likely" == sum(["Not ", "likely"], "", least_surprise=True) :-) From paddy3118 at netscape.net Thu Aug 17 17:44:01 2006 From: paddy3118 at netscape.net (Paddy) Date: 17 Aug 2006 14:44:01 -0700 Subject: List match In-Reply-To: <1155823451.766317.7640@74g2000cwt.googlegroups.com> References: <1155823451.766317.7640@74g2000cwt.googlegroups.com> Message-ID: <1155851041.119633.80410@i3g2000cwc.googlegroups.com> OriginalBrownster wrote: > Hi there: > > I know this probably is a very easy thing to do in python, but i wanted > to compare 2 lists and generate a new list that does not copy similar > entries. An example below > > list= ["apple", "banana", "grape"] > list2=["orange","banana", "pear"] > > now I want to compare these lits and generate a third list after > comparison > > list3 would be ["apple", "banana","grape","orange", "pear"] > > hence the double entry would not show up? > > Is there a way to do this?? > > Stephen This solution uses sets; removes all duplicates and is order preserving. Remove the outer sorted wrapper if the order need not be preserved. >>> lst= ["apple", "banana", "grape"] >>> lst2=["orange","banana", "pear"] >>> lst3= lst+lst2 >>> sorted([x for x in set(lst3)], key = lambda x: lst3.index(x)) ['apple', 'banana', 'grape', 'orange', 'pear'] >>> - Paddy From mail at microcorp.co.za Fri Aug 4 02:04:15 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Fri, 4 Aug 2006 08:04:15 +0200 Subject: Is there an obvious way to do this in python? References: <44d128e5$0$13484$636a55ce@news.free.fr> <44d1c6cb$0$13458$636a55ce@news.free.fr> <44d21087$0$19117$626a54ce@news.free.fr> Message-ID: <00d501c6b79d$fab12660$03000080@hendrik> "Bruno Desthuilliers" wrote: | H J van Rooyen wrote: | > "Bruno Desthuilliers" wrote: | (snip) | > |> If my original post was unclear I am sorry - the point I want answered, if | > |> possible, is how to make the client code effectively updateable on the fly - | > |> because the answer to this will influence the whole design of the rest of the | > |> system... | > | | > |This is something I have been thinking about... IMHO what you want is | > |not to "update client code on the fly", but to make the client mostly a | > |kind of interpreter for what the server sends in. That is, the client | > |code itself doesn't contain any application logic, it gets it from the | > |server and execute it. This can certainly be done with Pyro. | > | | > |Now while this may be an interesting project, I'm not really sure it's | > |worth the effort when we already have HTTP, HTML and AJAX... | > | > You may be right and it might not be worth the trouble - but what you mention | > above is closer to the sort of thing I have in mind - it is essentially using | > python to create a script language, and moving scripts around - but hey - python | > is already a script language... | | Yes, but it's not (alas) supported by browsers... | | > so if Pyro is for 'moving the scripts around' - Then that is what I must look at | > very hard... | | It's not for "moving the scripts around", it's for remote objects - kind | of like Java's RMI, but, well, much more pythonic !-). Now the point is | that Python being very powerful when it comes to dynamism and | introspection, it should be possible to have a common client that | basically just knows how to connect to the application server (using | pyro). Once connected, the client asks the server for a set of objects | (forms, menus etc) and the corresponding data. These objects then use | the same mechanism to interact with the server. It's basically similar | to the interaction between a browser and a web app - in that the client | is potentially able to run any application sent by the server -, but | with much more specialized client and app server and another protocol - | and no other language than Python. | This is getting more and more interesting - its not the simple minded mechanism I had in mind, but it will achieve the same thing, and it exists already - and I can imagine it to be a very powerful mechanism, if I understand you correctly - I am going to have to cry "time out!" to go and do some reading... Thank you. - Hendrik From aleax at mac.com Tue Aug 8 14:19:56 2006 From: aleax at mac.com (Alex Martelli) Date: Tue, 8 Aug 2006 11:19:56 -0700 Subject: Python open a named pipe == hanging? References: <1hjk7cf.iswobo130hqzxN%aleax@mac.com> <1hjpqc2.1nbzu37nfvvkuN%aleax@mac.com> Message-ID: <1hjr0pk.d954w7xtds5tN%aleax@mac.com> Donn Cave wrote: ... > > You forgot to add os.mkfifo(f) here -- so you're writing and reading a > > perfectly ordinary file... of course *that* gives no problems!-) > > Of course you're right about that, and with that fixed we > see that you're right, the open blocks. In order to avoid > that, you have to open "r+", which after all is what the > original post proposed to do. ...and produces "undefined behavior" according to the manpage. > involved. On NetBSD, when the child process closes the write > descriptor, that operation doesn't entirely succeed and the file > descriptor is left in a `no more information' state. On Linux, > one doesn't see that, but the result is the same. In any case, a > stream that can't have an end is not going to be very satisfactory. > [I don't know why I get tangled up in these named pipe problems, > when I know better myself than to use them!] I have no problems using named pipes _according to their documentation_ (so, in particular, no O_RDWR opening, and acceptance of their thread-blocking behavior on O_RDONLY and O_WRONLY opening; I have no experience with opening named pipes in non-blocking mode). Alex From noway at onthenet.com Mon Aug 14 01:49:33 2006 From: noway at onthenet.com (Jive Dadson) Date: Mon, 14 Aug 2006 05:49:33 GMT Subject: Drawing a grid on a picture Message-ID: Hello folks. I know precisely zero about image processing. I want to draw a grid of lines one or two pixels wide on a picture (.jpg, .png, or whatever). [I want to transfer a sketch of the picture to a canvas (for oil painting), using the "grid method."] I figure this is probably a very easy thing to do, but I can't seem to find the documentation I need. It all seems to assume you already know something. I have wxPython installed. I also have the wxPython demo. The section "Using Images/Image" looked promising. It just shows how to read a picture and display it as a bitmap. Can someone show me how, or point me in the right direction? Thanks a lot. From chris.cavalaria at free.fr Wed Aug 9 12:14:50 2006 From: chris.cavalaria at free.fr (Christophe) Date: Wed, 09 Aug 2006 18:14:50 +0200 Subject: #!/usr/bin/python or #!/usr/bin/env python? In-Reply-To: References: Message-ID: <44da09aa$0$25150$636a55ce@news.free.fr> Stephan Kuhagen a ?crit : >> Always prefer to use env over a hardcoded path, because that hardcoded >> path will invariably be wrong. (Yes, for those about to nitpick, it's >> conceivable that env might be somewhere other than /usr/bin. However, >> that is very rare and results in a no-win situations regardless of the >> issue of where Python is installed.) > > Don't yell at me for bringing in another language, but I really like the > trick, Tcl does: > >> #!/bin/sh >> # The next line starts Tcl \ >> exec tclsh "$0" "$@" > > This works by the somewhat weird feature of Tcl, that allows comments to be > continued in the next line with "\" at the end of the comment-line. It > looks unfamiliar, but has several advantages, I think. First it's really > VERY unlikely, that there is no /bin/sh (while I found systems with > different places for env), and you can add some other features at or before > the actual call of the interpreter, i.e. finding the right or preferred > version... - This way I coded a complete software-installer, that runs > either as a Tcl/Tk-Script with GUI, or as bash-script, when no Tcl is > available. - I really would like to have something like that for python, > but I did not find a way to achieve that, yet. > > Regards > Stephan > What about that one ( windows .bat file ) : @echo off rem = """-*-Python-*- script rem -------------------- DOS section -------------------- rem You could set PYTHONPATH or TK environment variables here python -x %~f0 %* goto exit """ # -------------------- Python section -------------------- import sys print sys.argv DosExitLabel = """ :exit rem """ I'm sure it can be updated to work on Unix too :) From djoefish at gmail.com Sat Aug 19 20:39:10 2006 From: djoefish at gmail.com (djoefish) Date: 19 Aug 2006 17:39:10 -0700 Subject: sequel to the topic "install patch on windows"..... In-Reply-To: <1156029976.697107.30940@b28g2000cwb.googlegroups.com> References: <1156029374.982389.18050@h48g2000cwc.googlegroups.com> <1156029976.697107.30940@b28g2000cwb.googlegroups.com> Message-ID: <1156034349.998185.272240@75g2000cwc.googlegroups.com> Fuzzyman wrote: > djoefish wrote: > > sequel to the topic "install patch on windows"..... > > > > I am currently running Python2.3 with Enthought on a windows PC. I have > > been running into a memory problem (see > > http://evanjones.ca/python-memory-part3.html), and would like to > > install a patch. I have read a lot about it online, but can't seem to > > find out how to do so on windows. > > > > I have a 'patch' program that works, but it only patches the source > > file 'obmalloc.c', which does not exist in the final Python > > installation. Is it possible to install a patch without recompiling all > > of python? Could someone direct me to some documentation that might > > help? > > > > In order to patch a part of core Python, you need to recompile I'm > afraid. Better to use Python 2.5. > > > > I wouldn't mind waiting for the 2.5 release (which has the patch built > > in), but then I'm afraid I would also have to wait for an ungrade of > > Enthought. > > I think that the only thing the Enthought distribution offers, is that > it comes with lots of extension modules. > > Just install the normal Python distribution and all the modules you > actually need. I don't think you lose anything doing this. > > Fuzzyman > http://www.voidspace.org.uk/python/index.shtml > > > > > > any advice? > > > > thanks, > > > > djoefish I have installed 2.5, but cannot install numpy or scipy since their latest Win32 versions require 2.4 or 2.3. Any advice on installing packages that are designed for the eariler version? From DirkHagemann at gmail.com Fri Aug 18 05:40:53 2006 From: DirkHagemann at gmail.com (Dirk Hagemann) Date: 18 Aug 2006 02:40:53 -0700 Subject: MS SQL Server: NT Authentication. Possible? Message-ID: <1155894053.148598.3640@h48g2000cwc.googlegroups.com> Hi! Is it somehow possible to access an MS SQL Server database from python by NT-Authentication or do I have only the possibility to use an SQL-Account with DB = odbc.odbc(myDB/myAccount/myPW) ? Kind regards Dirk From martin at v.loewis.de Mon Aug 28 12:36:06 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 28 Aug 2006 18:36:06 +0200 Subject: unicode "table of character" implementation in python In-Reply-To: References: Message-ID: <44F31B76.1050506@v.loewis.de> Nicolas Pontoizeau schrieb: > I am handling a mixed languages text file encoded in UTF-8. Theres is > mainly French, English and Asian languages. I need to detect every > asian characters in order to enclose it by a special tag for latex. > Does anybody know if there is a unicode "table of character" > implementation in python? I mean, I give a character and python replys > me with the language in which the character occurs. This is a bit unspecific, so likely, nothing that already exists will be completely correct for your needs. If you need to escape characters for latex, I would expect that there is a more precise specification of what you need to escape - I doubt the fact that a character is used primarily in Asia matters much to latex. In any case, somebody pointed you to the Unicode code blocks. I think these are Asian scripts (I may have missed some): 0530..058F; Armenian 0590..05FF; Hebrew 0600..06FF; Arabic 0700..074F; Syriac 0750..077F; Arabic Supplement 0900..097F; Devanagari 0980..09FF; Bengali 0A00..0A7F; Gurmukhi 0A80..0AFF; Gujarati 0B00..0B7F; Oriya 0B80..0BFF; Tamil 0C00..0C7F; Telugu 0D00..0D7F; Malayalam 0D80..0DFF; Sinhala 0E00..0E7F; Thai 0E80..0EFF; Lao 0F00..0FFF; Tibetan 1000..109F; Myanmar 10A0..10FF; Georgian 1100..11FF; Hangul Jamo 1780..17FF; Khmer 1800..18AF; Mongolian 1900..194F; Limbu 1950..197F; Tai Le 1980..19DF; New Tai Lue 19E0..19FF; Khmer Symbols 2D00..2D2F; Georgian Supplement 2E80..2EFF; CJK Radicals Supplement 2F00..2FDF; Kangxi Radicals 2FF0..2FFF; Ideographic Description Characters 3000..303F; CJK Symbols and Punctuation 3040..309F; Hiragana 30A0..30FF; Katakana 3100..312F; Bopomofo 3130..318F; Hangul Compatibility Jamo 3190..319F; Kanbun 31A0..31BF; Bopomofo Extended 31C0..31EF; CJK Strokes 31F0..31FF; Katakana Phonetic Extensions 3200..32FF; Enclosed CJK Letters and Months 3300..33FF; CJK Compatibility 3400..4DBF; CJK Unified Ideographs Extension A 4DC0..4DFF; Yijing Hexagram Symbols 4E00..9FFF; CJK Unified Ideographs A000..A48F; Yi Syllables A490..A4CF; Yi Radicals AC00..D7AF; Hangul Syllables F900..FAFF; CJK Compatibility Ideographs FB50..FDFF; Arabic Presentation Forms-A FE30..FE4F; CJK Compatibility Forms FE70..FEFF; Arabic Presentation Forms-B 20000..2A6DF; CJK Unified Ideographs Extension B 2F800..2FA1F; CJK Compatibility Ideographs Supplement Notice that some scripts are used both in Asia and elsewhere, e.g. Latin and Cyrillic. Arabic probably doesn't belong in this list, either, being used both in Asia and elsewhere as the script of the official language. Regards, Martin From johnjsal at NOSPAMgmail.com Tue Aug 8 12:13:26 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 08 Aug 2006 16:13:26 GMT Subject: Tkinter module not found In-Reply-To: References: <1155049496.292471.37020@h48g2000cwc.googlegroups.com> Message-ID: Thomas Heller wrote: > c:\>which python > c:\util\python.EXE which didn't work for me on the command prompt...is it native to it? From walter at livinglogic.de Wed Aug 2 12:48:14 2006 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Wed, 02 Aug 2006 18:48:14 +0200 Subject: how to get size of unicode string/string in bytes ? In-Reply-To: <4j93emF6t2nqU1@uni-berlin.de> References: <1154420030.988013.89310@m79g2000cwm.googlegroups.com> <44cf167c$0$24894$9b4e6d93@newsread4.arcor-online.net> <4j8k58F6th46U1@uni-berlin.de> <44cf2906$0$24899$9b4e6d93@newsread4.arcor-online.net> <4j93emF6t2nqU1@uni-berlin.de> Message-ID: <44D0D74E.3050401@livinglogic.de> Diez B. Roggisch wrote: >> So then the easiest thing to do is: take the maximum length of a unicode >> string you could possibly want to store, multiply it by 4 and make that >> the length of the DB field. > >> However, I'm pretty convinced it is a bad idea to store Python unicode >> strings directly in a DB, especially as they are not portable. I assume >> that some DB connectors honour the local platform encoding already, but >> I'd still say that UTF-8 is your best friend here. > > It was your assumption that the OP wanted to store the "real" > unicode-strings. A moot point anyway, at it is afaik not possible to get > their contents in byte form (except from a C-extension). It is possible: >>> u"a\xff\uffff\U0010ffff".encode("unicode-internal") 'a\x00\xff\x00\xff\xff\xff\xdb\xff\xdf' This encoding is useless though, as you can't use it for reencoding on another platform. (And it's probably not what the OP intended.) > And assuming 4 bytes per character is a bit dissipative I'd say - especially > when you have some > 80% ascii-subset in your text as european and american > languages have. That would require UTF-32 as an encoding, which Python currently doesn't have. > The solution was given before: chose an encoding (utf-8 is certainly the > most favorable one), and compute the byte-string length. Exactly! Servus, Walter From kylotan at gmail.com Fri Aug 25 09:32:22 2006 From: kylotan at gmail.com (Ben Sizer) Date: 25 Aug 2006 06:32:22 -0700 Subject: Open Office and Python In-Reply-To: References: Message-ID: <1156512738.729008.125920@h48g2000cwc.googlegroups.com> F wrote: > I'd like to load a .csv file to the Open Office spreadsheet from the command > line using an arbitrary delimiter through Python. I don't need any fancy > formatting and stuff like that, just putting the values in the spreadsheet > will do. > > Is there a relatively simple way to do that? I assume when you say load you mean create. To 'load' usually means to read data rather than write it. If you want to read the data in, then a Google search for "python csv" should answer all your questions. Otherwise... How are the values stored? It might be as simple as this: # sample data table = [ ("item1", 10, 100), ("item 2", 15, 300) ] out = file("my.csv", "w+") for row in table: out.write(",".join(str(item) for item in row) + "\n") And my.csv will look like: item1,10,100 item 2,15,300 -- Ben Sizer From pon at iki.fi Sun Aug 13 14:02:53 2006 From: pon at iki.fi (Pasi Oja-Nisula) Date: 13 Aug 2006 18:02:53 GMT Subject: Newbie doing lengthy initialization with Tkinter gui References: <1155477685.072381.235320@75g2000cwc.googlegroups.com> Message-ID: In article <1155477685.072381.235320 at 75g2000cwc.googlegroups.com>, jmdeschamps at gmail.com wrote: > Tkinter also has a timer-type function called *after*. Use this to call > your init function just befrore the mainloop call. You gui wil show up > and you can then update it to show progress as you wish > No neep for thread or Tix modules...! Thanks for the great example! I hoped that there would be a simple way to show the progress and this is just what I was looking for. Pasi From jcollett at oshtruck.com Tue Aug 8 10:45:03 2006 From: jcollett at oshtruck.com (Hoop) Date: 8 Aug 2006 07:45:03 -0700 Subject: Missing MSVCR71.dll Message-ID: <1155048303.902091.245310@h48g2000cwc.googlegroups.com> Hi, I am trying to get my application into debug. I am using VS2005 with some Python code in it. Works fine in release build, but I do need to go to dubug. I have ActivePython 2.4.3.12. It says it is missing MSVCR71D.dll, I think that is an older .dll, maybe it should be an 8 for VS2005. MSVCR71D.dll is not even on my system. I have seen a similar posting a while back. Suggestion was to download the dll but I believe that could be incompatiable with VS2005. Any help would be appreciated. Thanks Jeff From rogue_pedro at yahoo.com Wed Aug 16 15:18:33 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 16 Aug 2006 12:18:33 -0700 Subject: Documentation Question About Depricated String Functions References: <1155754352.767469.211380@m73g2000cwd.googlegroups.com> Message-ID: <1155755913.728366.58910@m79g2000cwm.googlegroups.com> Hitesh wrote: > Hi, > > In python doc -- 4.1.4 Deprecated string functions -- I read that "The > following list of functions are also defined as methods of string and > Unicode objects; see ``String Methods'' (section 2.3.6) for more > information on those. You should consider these functions as > deprecated, although they will not be removed until Python 3.0. The > functions defined in this module are: " and there is a whole list of > functions. If these functions are deprecated what is the replacement > for them? I couldn't find that info in the doc. Any links will be > helpful. > > Thank you, > hj "The following list of functions are also defined as methods of string and Unicode objects; see ``String Methods'' (section 2.3.6) for more information on those." i.e. string.lower() => "WHAT?".lower() (would return "what?"...) HTH, ~Simon From jcmendez at alum.mit.edu Tue Aug 8 09:02:40 2006 From: jcmendez at alum.mit.edu (=?ISO-8859-1?Q?Juan_C._M=E9ndez?=) Date: Tue, 8 Aug 2006 10:02:40 -0300 Subject: Resource temporarily unavailable launching idle under cygwin In-Reply-To: <20060808104019.GA2664@tishler.net> References: <1154976453.055076.186560@p79g2000cwp.googlegroups.com> <20060808104019.GA2664@tishler.net> Message-ID: <48a27ed0608080602q4f284e9cn17c96672c5e7c0f8@mail.gmail.com> The "rebase" process worked. Thanks, Jason. The other previously posted solution of uninstalling and reinstalling Python did not. On 8/8/06, Jason Tishler wrote: > > Juan C., > > On Mon, Aug 07, 2006 at 11:47:33AM -0700, jcmendez wrote: > > Hello everyone. Trying to run idle from a cygwin session on Win2k > > (yuk, but I must) I'm getting the following error message. > > [snip] > > > > $ idle > > 23367 [main] python2.4 1668 C:\cygwin\bin\python2.4.exe: *** fatal > > error - C:\cygwin\bin\python2.4.exe: *** unable to remap > > C:\cygwin\bin\tk84.dll to same address as parent(0x18890000) != > 0x18D20000 > > You need to rebase your system: > > > http://www.google.com/search?hl=en&q=cygwin+python+%22unable+to+remap%22 > > Jason > > -- > PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers > Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rogue_pedro at yahoo.com Fri Aug 25 15:23:28 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 25 Aug 2006 12:23:28 -0700 Subject: Duck typing alows true polymorfisim In-Reply-To: <1156532721.879808.40990@i3g2000cwc.googlegroups.com> References: <1156532721.879808.40990@i3g2000cwc.googlegroups.com> Message-ID: <1156533807.630662.12330@i42g2000cwa.googlegroups.com> atbusbook at aol.com wrote: > lets say you want a generic numerical algorithom like sum > > Ruby > > def sum lst > lst.inject(0){|total,current| total*current} > end > > Java // i dont know if there is a numeric super class for numbers > > class Sum{ > public static int sum(int[] lst){ > int total = 0; > for(int current : lst){ > total+=current; > } > return total; > } > // repeat for all other number types > } What's your question? (Or, if no question, point?) :-) Totally off topic (and indeed "off-list"..) is that really how ruby sums a list? How does that work? Doesn't the '*' mean multiply? and what are the pipe symbols for? (Feel free to ignore these questions. I should really go look it up myself if I'm so curious..) Peace, ~Simon From sjmachin at lexicon.net Tue Aug 8 22:13:46 2006 From: sjmachin at lexicon.net (John Machin) Date: 8 Aug 2006 19:13:46 -0700 Subject: newb question: file searching References: <1155067111.892386.130610@n13g2000cwa.googlegroups.com> <1155084224.829101.63940@i42g2000cwa.googlegroups.com> <1155087242.679420.128830@m73g2000cwd.googlegroups.com> <1155087903.857917.127540@m79g2000cwm.googlegroups.com> Message-ID: <1155089626.603761.222600@b28g2000cwb.googlegroups.com> jaysherby at gmail.com wrote: > I do appreciate the advice, but I've got a 12 line function that does > all of that. And it works! I just wish I understood a particular line > of it. > > def getFileList(*extensions): > import os > imageList = [] > for dirpath, dirnames, files in os.walk('.'): > for filename in files: > name, ext = os.path.splitext(filename) > if ext.lower() in extensions and not filename.startswith('.'): > imageList.append(os.path.join(dirpath, filename)) > for dirname in reversed(range(len(dirnames))): > if dirnames[dirname].startswith('.'): > del dirnames[dirname] > > return imageList > > print getFileList('.jpg', '.gif', '.png') > > The line I don't understand is: > reversed(range(len(dirnames))) > For a start, change "dirname" to "dirindex" (without changing "dirnames"!) in that line and the next two lines -- this may help your understanding. The purpose of that loop is to eliminate from dirnames any entries which start with ".". This needs to be done in-situ -- concocting a new list and binding the name "dirnames" to it won't work. The safest understandable way to delete entries from a list while iterating over it is to do it backwards. Doing it forwards doesn't always work; example: #>>> dirnames = ['foo', 'bar', 'zot'] #>>> for x in range(len(dirnames)): ... if dirnames[x] == 'bar': ... del dirnames[x] ... Traceback (most recent call last): File "", line 2, in ? IndexError: list index out of range HTH, John From bj_666 at gmx.net Wed Aug 16 10:01:23 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 16 Aug 2006 16:01:23 +0200 Subject: Optimization of __len__() in cgi.py References: Message-ID: In , Bob Kline wrote: > I have a suggestion for speeding up the performance of code like this: > > fields = cgi.FieldStorage() > if fields: ... > > which, as it turns out, invokes FieldStorage.__len__(), which in turn > calls FieldStorage.keys(), which builds a list of keys by hand, taking > several minutes for large forms. This implementation of keys() reduces > the amount of time taken by several orders of magnitude: > > def keys(self): > return {}.fromkeys([i.name for i in self.list]).keys() This does not maintain the order of `self.list`. Don't know if there's code relying on this. In a recent Python version one could use `set()` and a generator expression:: return list(set(item.name for item in self.list)) But maybe it's even faster to change `FieldStorage.__len__()` to return the length of `self.list` directly without the need to create an intermediate list that's thrown away immediately. Ciao, Marc 'BlackJack' Rintsch From gelists at gmail.com Wed Aug 2 15:39:03 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Wed, 2 Aug 2006 16:39:03 -0300 Subject: Windows vs. Linux References: <1154301694.445639.99580@m79g2000cwm.googlegroups.com> <44cddfb3$0$7761$7a628cd7@news.club-internet.fr> <1hjfow0.xza1lcpaytg8N%aleax@mac.com> Message-ID: <1u5omw82gmxyg$.dlg@gelists.gmail.com> On 2006-08-02 12:41:44, Alex Martelli wrote: > Microsoft did *NOT* write DOS Well, they didn't write most of DOS 1.0. But it seems they did write (or at least specify) most if not all of the rest up to DOS 6.22 or so. Which is possibly considerable. > Part of the CP/M compatibility did include the use of / as flag-indicator > (the use of \r+\n as line ending also comes from CP/M -- in turn, CP/M > had aped these traits from some DEC minicomputer operating systems). At the time, probably pretty good reasons for using the slash as command line flag indicator. > Internally yes (indeed, they developed Xenix, before later selling it to > SCO), but that does not mean that "DOS was written on Xenix" because DOS > was *not* written in Microsoft, as above mentioned. I probably should have said "everything between DOS 1.0 and DOS 6.22" was written on Xenix, to be more precise :) And, as an aside, I'm sure that MS would have sold more of their Xenix if the market had wanted it. But the market really wanted DOS... Gerhard From y.glodt at sitasoftware.lu Fri Aug 11 08:24:04 2006 From: y.glodt at sitasoftware.lu (Yves Glodt) Date: Fri, 11 Aug 2006 14:24:04 +0200 Subject: schedule at specific hours Message-ID: <200608111424.04950.y.glodt@sitasoftware.lu> Hi there, I have a daemon running 24/7, and I want that it executes a certain function several times a day, as specified in an configfile (e.g. actiontimes=10:00,12:00,19:00) Do I have to fiddle with sched.scheduler and calc. time differences to schedule my events, or is there another (nicer...) way? Regards, Yves From fredrik at pythonware.com Sun Aug 27 10:14:31 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 27 Aug 2006 16:14:31 +0200 Subject: creating multiply arguments for a method. In-Reply-To: <1156686964.216440.72530@p79g2000cwp.googlegroups.com> References: <1156686964.216440.72530@p79g2000cwp.googlegroups.com> Message-ID: noro wrote: > Let say that during runtime i need to pass 4 arguments, each is a list, > creating a set of lists and passing it to the method wont word since > the interpartor thinks it is only 1 argument the contain a reference to > a "list of lists", instede of number of arguments, each is a list. >>> def func(*args): ... print "got", len(args), "argument(s)" ... >>> args = [[1, 2, 3, 4], [5, 6, 7, 8]] >>> func(args) got 1 arguments >>> func(*args) got 2 arguments From bj_666 at gmx.net Mon Aug 21 04:45:10 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 21 Aug 2006 10:45:10 +0200 Subject: Python and STL efficiency References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <1156148654.420508.57960@p79g2000cwp.googlegroups.com> Message-ID: In <1156148654.420508.57960 at p79g2000cwp.googlegroups.com>, Tim N. van der Leeuw wrote: > (your C++ code contains some C#-isms, such as omitting the '.h' in the > include <> statements). That's no C#-ism, that's C++. The standard C++ header names don't have a trailing '.h'. ``gcc`` prints deprecation warnings if you write the names with '.h'. Ciao, Marc 'BlackJack' Rintsch From rogue_pedro at yahoo.com Tue Aug 15 19:17:30 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 15 Aug 2006 16:17:30 -0700 Subject: idea on how to get/set nested python dictionary values In-Reply-To: <1155678816.942660.296140@74g2000cwt.googlegroups.com> References: <1155663671.716249.18780@m79g2000cwm.googlegroups.com> <1155678816.942660.296140@74g2000cwt.googlegroups.com> Message-ID: <1155683850.888452.181590@m73g2000cwd.googlegroups.com> wittempj at hotmail.com wrote: > | would use a recursive approach for this - given that you have a sort > of recursive datastructure: > > py> def SetNewDataParam2(Data, NewData): > ... if type(Data[Data.keys()[0]]) == type(dict()): Note: |>> type(dict()) is dict True "dict" *is* a type... From alina.ghergu at gmail.com Thu Aug 17 05:30:53 2006 From: alina.ghergu at gmail.com (Alina Ghergu) Date: 17 Aug 2006 02:30:53 -0700 Subject: wxPython GUI update with data from a MySQL database Message-ID: <1155807053.375687.15930@i3g2000cwc.googlegroups.com> Hi there, I'm currently developing a GUI for a network monitor. I have to plot data taken from a MySQL database. For GUI I use wxPython, for plotting Matplotlib. The plotting has to be realtime, so I have to query the database periodically. I don't have enough experience in programming and I would need some advice about the best approach in this matter. I tried to solve it using wx.Timer but from time to time MySQL server doesn't repond to queries. I use one db connection for all my queries. I also tried a threads approach but because I don't know how to use them the result was worse. Any sugestion will be highly apreciated. Alina From aries.shuaib at gmail.com Wed Aug 16 18:47:51 2006 From: aries.shuaib at gmail.com (Shuaib) Date: 16 Aug 2006 15:47:51 -0700 Subject: Calling a python script, and getting the returned result in C In-Reply-To: <1155768090.801185.101990@75g2000cwc.googlegroups.com> References: <1155764701.509056.207140@h48g2000cwc.googlegroups.com> <1155768090.801185.101990@75g2000cwc.googlegroups.com> Message-ID: <1155768471.647074.246660@i42g2000cwa.googlegroups.com> John Machin wrote: > Shuaib wrote: > > Hi! > > > > I have a python script which returns an Integer value. How do I call > > this script from a C programe, and use the result returned? > > To avoid confusion and possible irrelevant responses, please say which > of the following options best matches your requirement: > > (a) your Python script is capable of being run from the command line, > and "returns" an integer value by calling sys.exit(that_value) -- you > wish to execute the script from a C program [the same way you would > execute a shell script / awk script / ...] and pick up the return value > [which may be limited by the OS to range(0, 128)] > > (b) your script is a module, containing a function that returns an > integer. You wish to create an embedded Python interpreter, import > yourmodule, call yourmodule.yourfunc, convert the returned Python int > to a C int, and use it. (b) it is. :) From missdeer at gmail.com Fri Aug 11 11:27:40 2006 From: missdeer at gmail.com (missdeer) Date: Fri, 11 Aug 2006 23:27:40 +0800 Subject: Boost Install References: <1155308267.236139.206650@i3g2000cwc.googlegroups.com> Message-ID: <200608112327334684144@gmail.com> You should set PYTHON_ROOT & PYTHON_VERSION environment variable first, then set the VC toolset path, compile bjam.exe yourself and run bjam with -sTOOLS parameter. It seems Boost has not been totally tested under VS2005, but works fine with VS2003. Good luck! missdeer 2006-08-11 ???? Hoop ????? 2006-08-11 23:00:24 ???? python-list at python.org ??? ??? Boost Install Hi All, I am wondering if any have done an install of Boost for Python embedding? I have downoaded boost_1_33_1.exe, ran that and now have a boost_1_33_1 directory with plenty of items ine it. I have attempted to follow some online install directions which do not seem to work. I am using VS2005. I have tried, bjam "--with-python-version[=2.4] and just get a statement saying that bjam is not recognized. Really is no batch file or executable with that name in the boost directory. Not sure what to do to get the Boost.Python installed. Thanks for any help. Jeff -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From st at tobiah.org Fri Aug 25 15:39:10 2006 From: st at tobiah.org (tobiah) Date: Fri, 25 Aug 2006 12:39:10 -0700 Subject: Open Office and Python In-Reply-To: References: Message-ID: <44ef44bb$0$8917$88260bb3@free.teranews.com> F wrote: > Hello there! > > I'd like to load a .csv file to the Open Office spreadsheet from the command > line using an arbitrary delimiter through Python. I put together a little utility that you may find helpful if I understand you correctly. It converts a .csv file to a .xls file without the need for the GUI. It makes a good guess as to the appropriate column width for each column. You could easily fix it to use any delimiter as an argument. It's here: http://tobiah.org/csv2xls It needs PyExcellerator: http://sourceforge.net/projects/pyexcelerator Tobiah -- Posted via a free Usenet account from http://www.teranews.com From faulkner612 at comcast.net Thu Aug 3 23:43:52 2006 From: faulkner612 at comcast.net (faulkner) Date: 3 Aug 2006 20:43:52 -0700 Subject: Problem reading/writing files In-Reply-To: <1154661460.803694.241220@s13g2000cwa.googlegroups.com> References: <1154661460.803694.241220@s13g2000cwa.googlegroups.com> Message-ID: <1154663031.976478.209350@75g2000cwc.googlegroups.com> have you been using text mode? smeenehan at hmc.edu wrote: > This is a bit of a peculiar problem. First off, this relates to Python > Challenge #12, so if you are attempting those and have yet to finish > #12, as there are potential spoilers here. > > I have five different image files shuffled up in one big binary file. > In order to view them I have to "unshuffle" the data, which means > moving bytes around. Currently my approach is to read the data from the > original, unshuffle as necessary, and then write to 5 different files > (2 .jpgs, 2 .pngs and 1 .gif). > > The problem is with the read() method. If I read a byte valued as 0x00 > (in hexadecimal), the read method returns a character with the value > 0x20. When printed as strings, these two values look the same (null and > space, respectively), but obviously this screws with the data and makes > the resulting image file unreadable. I can add a simple if statement to > correct this, which seems to make the .jpgs readable, but the .pngs > still have errors and the .gif is corrupted, which makes me wonder if > the read method is not doing this to other bytes as well. > > Now, the *really* peculiar thing is that I made a simple little file > and used my hex editor to manually change the first byte to 0x00. When > I read that byte with the read() method, it returned the correct value, > which boggles me. > > Anyone have any idea what could be going on? Alternatively, is there a > better way to shift about bytes in a non-text file without using the > read() method (since returning the byte as a string seems to be what's > causing the issue)? Thanks in advance! From jiangnutao at gmail.com Thu Aug 24 18:46:57 2006 From: jiangnutao at gmail.com (Jason Jiang) Date: Thu, 24 Aug 2006 15:46:57 -0700 Subject: Python editor Message-ID: Hi, Could someone recommend a good Python editor? Thanks. Jason From mattdm at mattdm.org Wed Aug 2 09:55:07 2006 From: mattdm at mattdm.org (Matthew Miller) Date: Wed, 2 Aug 2006 09:55:07 -0400 Subject: upgrading python... In-Reply-To: <0b0d01c6b63a$9359eba0$0301a8c0@Mesa.com> References: <0b0d01c6b63a$9359eba0$0301a8c0@Mesa.com> Message-ID: <20060802135507.GA21326@jadzia.bu.edu> On Wed, Aug 02, 2006 at 06:50:11AM -0700, bruce wrote: > i'min a situation where i might need to upgrade python. i have the current > version of python for FC3. i might need to have the version for FC4. i built > the version that's on FC4 from the python source RPM. Going from Python 2.3 as in FC3 to FC4's Python 2.4 isn't going to be viable. Too different. > however, when i simply try to install the resulting RPM, the app gives me > dependency issues from apps that are dependent on the previous/current > version of python. Exactly. > i'm trying to figure out if there's a 'best' way to proceed. One option: build a new python RPM that installs Python2.4 into an alternate path, or skip that complication and just build and install it into /usr/local, leaving the system python intact. But I think the *better* solution is to upgrade to Fedora Core 5 or Fedora Core 6 Test 2. You want new software, go with a collection of new software tested together. > do i simply do the install, and force it to overwrite the current version of > python? Don't do this. It will break everything. Including yum, which is written in python. > is there a way to point 'yum' at my new python RPM, and let yum take care of > dealing with any dependcy issues? and how would yum handle weird dependency > issues with RPMs that don't exist.. does yum have the ability to actually > build required apps from source? Yum is pretty good, but it's not *that* magical. -- Matthew Miller mattdm at mattdm.org Boston University Linux ------> From bumperdoc at gmail.com Fri Aug 18 16:34:35 2006 From: bumperdoc at gmail.com (bumperdoc at gmail.com) Date: 18 Aug 2006 13:34:35 -0700 Subject: Safearray question Message-ID: <1155933275.760048.263490@75g2000cwc.googlegroups.com> Hi I'm using win32com.client to dispatch a COM server....one of the interface methods has the below parameter: ..., [in, out] SAFEARRAY(BYTE) *Buffer, ... This method goes and queries something and puts it in this buffer...how can I use this method in Python? What type of variable needs to be passed in when calling this method? Thanks in advance. AC From aisaac0 at verizon.net Sun Aug 27 22:41:50 2006 From: aisaac0 at verizon.net (David Isaac) Date: Mon, 28 Aug 2006 02:41:50 GMT Subject: Mahogany mail Message-ID: Somewhat OT: Just wondering if anyone is doing something cool with the Python support in Mahogany mail. If so, please describe it or post some code. Thanks, Alan Isaac From davefowler at gmail.com Tue Aug 8 15:59:58 2006 From: davefowler at gmail.com (godavemon) Date: 8 Aug 2006 12:59:58 -0700 Subject: binary conversion issues In-Reply-To: <12dhgcq77sdkr47@corp.supernews.com> References: <1155052353.499099.293840@i3g2000cwc.googlegroups.com> <12dhgcq77sdkr47@corp.supernews.com> Message-ID: <1155067198.385178.153560@i3g2000cwc.googlegroups.com> You guys are awesome! I had to set the 'b' flag when writing the binaries. file_obj = open('filename.bin', 'wb') instead of just using 'w' It worked fine for all of the other 10 binary files I made, but had a small error with one of them. In that one file's case it wrote out an extra 4 bytes in the middle somewhere. Strange. Thanx for your help. Grant Edwards wrote: > On 2006-08-08, godavemon wrote: > > > I'm using python's struct and binascii modules to write some values > > from my parser to binary floats. This works great for all of my binary > > files except one. For some reason this file is saving to 836 (stated > > by my command shell) bytes instead of 832 like it should. > > I'm just making a wild-ass guess since you didn't provide any > sample code or data, but it sounds like cr/lf translation > problem to me. Make sure you open the files in binary mode > using the "b" flag. > > -- > Grant Edwards grante Yow! Is this "BIKINI > at BEACH"? > visi.com From david_wahler at bic.ky Sun Aug 20 01:21:41 2006 From: david_wahler at bic.ky (david_wahler at bic.ky) Date: 20 Aug 2006 00:21:41 -0500 Subject: =?utf-8?Q?Re:_[ANN]_clnum=2D1.3_Class_Library_For_Numbers_Python_Binding?= Message-ID: <20060820052141.11129.qmail@BICSRV1011.bic.ky> I'll be out of the office until approximately August 20th. If you have any questions, please email support at bic.ky. -- David Wahler From djoefish at gmail.com Sat Aug 19 16:00:55 2006 From: djoefish at gmail.com (djoefish) Date: 19 Aug 2006 13:00:55 -0700 Subject: install patch on windows In-Reply-To: <1156017314.249545.296940@h48g2000cwc.googlegroups.com> References: <1156014103.715131.143360@i3g2000cwc.googlegroups.com> <1156017314.249545.296940@h48g2000cwc.googlegroups.com> Message-ID: <1156017655.849634.95240@p79g2000cwp.googlegroups.com> Tim Golden wrote: > djoefish wrote: > > Does anyone know how to install a patch on Winodws? For example, I want > > to install the patch 'ocmalloc-free-arenas.diff' in Python 2.3. > > You can get patch (and quite a lot besides) for win32 from > the UnxUtils project: > > http://sourceforge.net/projects/unxutils > > TJG Thanks, but that project seems to be dead.... From hpsekhon at googlemail.com Wed Aug 16 13:52:26 2006 From: hpsekhon at googlemail.com (Hari Sekhon) Date: Wed, 16 Aug 2006 18:52:26 +0100 Subject: os.path.normpath In-Reply-To: <1155179823.172826.71600@p79g2000cwp.googlegroups.com> References: <1155149144.453575.181870@m79g2000cwm.googlegroups.com> <1155179823.172826.71600@p79g2000cwp.googlegroups.com> Message-ID: <44E35B5A.3050908@googlemail.com> grahamd at dscpl.com.au wrote: > nathanbullock at gmail.com wrote: > >> I am using a windows box and passing a string like "../foo/../foo2" to >> normpath which then returns "..\\foo2". But if this string is going >> into a webpage link it should really be "../foo". >> >> Is there any way to tell os.path.normpath to act like we are an a unix >> style box? >> > > Use posixpath.normpath() instead. > > I can't seem to find posixpath in the docs, but I can import posixpath and a dir shows it does indeed have a normpath. -h -------------- next part -------------- An HTML attachment was scrubbed... URL: From h112211 at gmail.com Thu Aug 10 09:06:41 2006 From: h112211 at gmail.com (h112211 at gmail.com) Date: 10 Aug 2006 06:06:41 -0700 Subject: Make Object Oriented? References: Message-ID: <1155215201.398409.27500@p79g2000cwp.googlegroups.com> Michael Yanowitz wrote: > Hello: > > Are there any tools to convert non-object-oriented code > into object-oriented code? Nope, but you can have the next best thing: rewrite it from scratch yourself. I did that to a smallish (about 50k lines) C program once, and the resulting 70k lines or so C++ program was superior to the old version in many ways. However, maybe the best result was that after the rewrite I knew the problem domain and the implementation inside out, much better than I would've by reading and running the old C code, which was written by someone else. Of course, today I'd do it in 15k lines of Python ;) From st at tobiah.org Fri Aug 25 15:17:14 2006 From: st at tobiah.org (tobiah) Date: Fri, 25 Aug 2006 12:17:14 -0700 Subject: RE Module In-Reply-To: <1156478366.165463.277480@h48g2000cwc.googlegroups.com> References: <1156478366.165463.277480@h48g2000cwc.googlegroups.com> Message-ID: <44ef3f95$0$8926$88260bb3@free.teranews.com> Roman wrote: > I am trying to filter a column in a list of all html tags. > > To do that, I have setup the following statement. > > row[0] = re.sub(r'<.*?>', '', row[0]) The regex will be 'greedy' and match through one tag all the way to the end of another on the same line. There are more complete suggestions offered, but it seems to me that the simple fix here is to not match through the end of the tag, like this: "<[^>]*>" -- Posted via a free Usenet account from http://www.teranews.com From davelist at mac.com Thu Aug 24 10:37:25 2006 From: davelist at mac.com (davelist at mac.com) Date: Thu, 24 Aug 2006 10:37:25 -0400 Subject: Is there an elegant way to dir() module from inside? In-Reply-To: <1156429103.823271.204880@m73g2000cwd.googlegroups.com> References: <1156429103.823271.204880@m73g2000cwd.googlegroups.com> Message-ID: On Aug 24, 2006, at 10:18 AM, volcano wrote: > I am looking for a way to discover which classes a module contains > from > "inside". I am building a testing class that should, when > instatntiated > within any module, locate certain classes within the containing > module. > Words of wisdom? Anybody? Check out the inspect module. http://docs.python.org/lib/module-inspect.html Dave From vito.detullio at gmail.com Mon Aug 21 06:01:37 2006 From: vito.detullio at gmail.com (ZeD) Date: Mon, 21 Aug 2006 10:01:37 GMT Subject: Input from the same file as the script References: <1156096945.924216.14380@m73g2000cwd.googlegroups.com> Message-ID: <5wfGg.77034$_J1.745566@twister2.libero.it> Dennis Lee Bieber wrote: >> Can the input to the python script be given from the same file as the >> script itself. e.g., when we execute a python script with the command >> 'python > > Redirecting? Ugh... > > Off-hand, I'd say NO > > There is no way to tell the python interpreter where the program > ends and the "run data" begins. maybe, as an UGLY hack he coud use some the comments -- Under construction From pmaupin at gmail.com Tue Aug 22 00:09:17 2006 From: pmaupin at gmail.com (Patrick Maupin) Date: 21 Aug 2006 21:09:17 -0700 Subject: how do you get the name of a dictionary? In-Reply-To: <1156204770.339106.151110@m73g2000cwd.googlegroups.com> References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> Message-ID: <1156219757.457636.44120@b28g2000cwb.googlegroups.com> jojoba wrote: > hello > > im quite surprised at the arrogance laid out by some of the above > posters: > > However, does it not seem reasonable to ask python: > > Given a dicitionary, Banana = {} > return one or more strings, > where each string is the name(s) of the reference(s) to Banana. > > why is this not sane?!?! > what am i missing here? > > I mean, i can enter the name of the dicitonary and python knows what i > am talking about, so why can't i go backwards to get one or more > strings that are the names of the dictionary? > > There may indeed be a lack of one-to-one correspondence between names > of dictionaries and dictionaries, but who cares, it is WELL DEFINED > (unless i am insane as some of the above posters claim) > > Please PROVE to me why my question is invalid (or certifiably crazy to > some). > > Thanks to all who could answer me WITH or WITHOUT derision. > jojoba Jojoba: One thing which you might be missing is that an object might not even have a name bound to it. Consider: Banana = {} Tree = [Banana, 0] del Banana At this point, the dictionary which was originally named Banana still exists, and is referenced from the list which is bound to Tree, but doesn't really have an associated name. It can only be referenced as the first element of the Tree list. However, if you _know_ that an object has some named references, they can be retrieved. An easy example is if you know the object is referenced from inside the current module: >>> Banana = {} >>> >>> Sam = Banana >>> Bill = {} >>> >>> print [x for (x,y) in globals().items() if y is Banana] ['Sam', 'Banana'] >> If you don't know which namespace the object might be referenced from, it gets trickier. You can certainly search the entire object hierarchy if you want (this is done for things like debugging sometimes), but this is time-consuming, which is why you shouldn't typically organize your program in such a way that you have to ask the Python interpreter what the name of a particular object is. As people point out, Python doesn't really directly know. On the other hand, IF the object DOES have a name, you can certainly write a program to rummage around the object hierarchy and figure it out, but you should probably have a really good reason before you go to that trouble. Regards, Pat From gdamjan at gmail.com Sat Aug 5 11:51:32 2006 From: gdamjan at gmail.com (Damjan) Date: Sat, 05 Aug 2006 17:51:32 +0200 Subject: Which Python API for PostgreSQL? References: <1154742196.522410.138770@i3g2000cwc.googlegroups.com> Message-ID: <44d4be3e$0$15790$14726298@news.sunsite.dk> > I also recommend psycopg. But make sure you use psycopg2 -- damjan From http Sun Aug 13 15:53:54 2006 From: http (Paul Rubin) Date: 13 Aug 2006 12:53:54 -0700 Subject: yet another noob question References: <1155492110.659011.196280@75g2000cwc.googlegroups.com> Message-ID: <7xhd0g1kfh.fsf@ruckus.brouhaha.com> "mike_wilson1333" writes: > I would like to generate every unique combination of numbers 1-5 in a 5 > digit number and follow each combo with a newline. So i'm looking at > generating combinations such as: (12345) , (12235), (55554) and so on. > What would be the best way to do this? So, basically i'm looking for a > list of all combinations of 1-5 in a 5 digit unique number. Also, when > I send the list to print there can't be any duplicates of the combos. Basically you want to print a list of integers in 5-digit base-5 notation, except relabelling the digits. There will be (5**5 - 1) numbers in the list. You want to print 0 as '11111', 1 as '11112', etc. Here's one way to get the representation. It's sort of a "functional" approach using recursion, but feels natural if you're into that sort of thing: def base5x(k, ndigits): if ndigits == 1: return '%d'% (k+1) return base5x(k//5, ndigits-1) + base5x(k%5, 1) Now you can use the function to print the list you wanted: for i in xrange(1234,1333): print base5x(i, 5) From poggle.themammal at gmail.com Sun Aug 20 14:02:25 2006 From: poggle.themammal at gmail.com (poggle.themammal at gmail.com) Date: 20 Aug 2006 11:02:25 -0700 Subject: Input from the same file as the script Message-ID: <1156096945.924216.14380@m73g2000cwd.googlegroups.com> Can the input to the python script be given from the same file as the script itself. e.g., when we execute a python script with the command 'python References: <1155288288.954142.293000@i3g2000cwc.googlegroups.com> <1155316508.381805.56520@m73g2000cwd.googlegroups.com> Message-ID: <1155389042.226429.126170@m79g2000cwm.googlegroups.com> AlbaClause wrote: > jean-jeanot wrote: > > Ummm, he did not say that your question was stupid. The Zappa quote is > included as part of what we refer to as a 'signature'. In the case of > Sybren Stuvel's posts to this newsgroup, the Frank Zappa quote is included > in every message that he posts. Not just messages that he posts to you. First up, I *like* the Frank Zappa signature quote; it has a George Carlin feel to it and takes a swipe at our overly-protective cultures [side note: I bought an electric heating pad last night that came with instructions not to use it in the bathtub! Well, duh!]. But, can you see where the signature on a response to a tutor list -- where people are already feeling a bit intimidated and/or inadequate and therefore may feel a wee bit "stupid" -- might be taken the wrong way? I have spent many years teaching mathematics and physics in a classroom setting and have come to realize that, as a teacher, just about anything I say/do can be blown way out of proportion. So I don't use sarcasm or "fun" little put-downs and I treat every question as if it is the most important matter because, to the student, it is. Do I get tired of answering the same thing over and over? Yes!! Many times I will ask if the student has read the textbook and, if not, I will request they give it a try (much in the same way we ask if they have read any tutorials), but I take Homeric efforts not to offend them and, to that end, modify my behavior in order to teach them mathematics. My point is that this is a wonderful service you tutors provide, but the Zappa signature may not be the best choice for this setting. Most people will read it and get a laugh (as did I), but how many have taken it the way jean-jeanot did and walk away feeling insulted? How many will not post a response expressing their feelings, never post a question again or, worst case, decide Python is not for them? Again, I admire this list and those of you you maintain it. These are just my thoughts. YMMV. --greg From onurb at xiludom.gro Tue Aug 8 07:35:41 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 08 Aug 2006 13:35:41 +0200 Subject: do people really complain about significant whitespace? In-Reply-To: <1154986984.740638.241130@m79g2000cwm.googlegroups.com> References: <1154986984.740638.241130@m79g2000cwm.googlegroups.com> Message-ID: <44d8770e$0$21149$7a628cd7@news.club-internet.fr> infidel wrote: > Where are they-who-hate-us-for-our-whitespace? You may find some on comp.lang.ruby... From python.list at tim.thechases.com Wed Aug 30 12:12:32 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 30 Aug 2006 11:12:32 -0500 Subject: windows pagfile utilization In-Reply-To: References: <1156950270.045140.44950@p79g2000cwp.googlegroups.com> Message-ID: <44F5B8F0.2050306@tim.thechases.com> > Not page/swap -- by default Windows only gives 2GB to > applications for data; the rest is held for shared OS kernel > usage. Is it just me or does this seem ludicrous? If I had a bunch of re$ource$ and I employed someone to manage them for me, would I find it acceptable that they consume half of the re$ource$ for their own use just to manage the other half of my re$ource$? "Thanks for putting 4 gigs of ram in your machine. How about I let you use 2 of 'em while I underutilize the other 2 gigs?" Sounds silly, IMHO. -tkc From mfenner at gmail.com Thu Aug 17 22:08:45 2006 From: mfenner at gmail.com (Mark E. Fenner) Date: Fri, 18 Aug 2006 02:08:45 GMT Subject: Optimizing Inner Loop Copy References: <1155863280.800878.127310@p79g2000cwp.googlegroups.com> Message-ID: John Machin wrote: > > Mark E. Fenner wrote: > >> Here's my class of the objects being copied: > > Here's a couple of things that might help speed up your __init__ > method, and hence your copy method: > >> >> class Rule(list): >> def __init__(self, lhs=None, rhs=None, nClasses=0, nCases=0): > > def __init__(self, lhs=None, rhs=(), nClasses=0, nCases=0): > >> self.nClasses = nClasses >> self.nCases = nCases >> >> if lhs is not None: >> self.extend(lhs) > what does the extend method do? If it is small, perhaps inline a copy > of its code here. >> >> if rhs is None: >> self.rhs=tuple() >> else: >> self.rhs=rhs > > Replace the above 4 lines by: > self.rhs = rhs > > HTH, > John John, Thanks. I thought of those at the same you did! I also incorporated one other use of the default=() + no conditional: class Rule(list): def __init__(self, lhs=(), rhs=(), nClasses=0, nCases=0): self.nClasses = nClasses self.nCases = nCases self.extend(lhs) # note, self is a list so this is list.extend self.rhs=rhs def copy(self): return Rule(self, self.rhs, self.nClasses, self.nCases) From moverx at gmail.com Mon Aug 28 22:35:53 2006 From: moverx at gmail.com (Yusnel Rojas) Date: Mon, 28 Aug 2006 19:35:53 -0700 Subject: SOAPpy question Message-ID: <28b127080608281935k744c73fv5b58b271e2099f7c@mail.gmail.com> hello , I'm wondering if SOAPpy doesn't have something to generate a wsdl for a specific application. Let's say, I wrote a web service with SOAPpy, is there any way to generate the wsdl for it. If there aren't can someone give a little example of both. thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From noway at onthenet.com Mon Aug 14 03:17:29 2006 From: noway at onthenet.com (Jive Dadson) Date: Mon, 14 Aug 2006 07:17:29 GMT Subject: Drawing a grid on a picture In-Reply-To: References: <5IUDg.314851$1Q1.70663@fe03.news.easynews.com> Message-ID: Sybren Stuvel wrote: > Jive Dadson enlightened us with: >> I also found a reference to something called PIL. Maybe that's the >> ticket. If so, where can I find it (with documentation)? Thanks. > > Just google for PIL and Python. > > Sybren Thanks Brian and Sybren. PIL did the trick. Real easy. From Bulkan at gmail.com Tue Aug 15 08:14:49 2006 From: Bulkan at gmail.com (placid) Date: 15 Aug 2006 05:14:49 -0700 Subject: pickling or xml or other? Message-ID: <1155644089.337508.14940@75g2000cwc.googlegroups.com> Hi all, I have an application were i want the user to "configure" some settings which are variables within different classes. My question is should i just pickle out these variables to a file in some particular order then read it back. Or use xml to save the config values ? Which one scales better if settings increase? Other sugestions? -Cheers From cliff at develix.com Tue Aug 15 03:56:48 2006 From: cliff at develix.com (Cliff Wells) Date: Tue, 15 Aug 2006 00:56:48 -0700 Subject: ReStructuredText In-Reply-To: References: Message-ID: <1155628608.16686.19.camel@devilbox> On Tue, 2006-08-15 at 09:35 +0200, Sybren Stuvel wrote: > Cliff Wells enlightened us with: > > Why doesn't the above turn out an enumerated list? > > You have to indent the list: > > >>> from docutils.core import publish_parts > >>> t = ''' > ... > ... 1. this is a test > ... #. this is another line > ... #. oh, screw it! > ... ''' > >>> publish_parts(t, writer_name='html')['body'] > u'
\n
    \n
  1. this is a > test
  2. \n
  3. this is another line
  4. \n
  5. oh, screw > it!
  6. \n
\n
\n' Thanks for the response. Must be a bug in my version: Python 2.4.2 (#1, Feb 13 2006, 15:24:20) [GCC 3.3.6 (Gentoo 3.3.6, ssp-3.3.6-1.0, pie-8.7.8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from docutils.core import publish_parts >>> t = ''' ... ... 1. this is a test ... #. this is another line ... #. oh, screw it! ... ... ''' >>> publish_parts ( t, writer_name = 'html' ) [ 'body' ] u'
\n1. this is a test\n#. this is another line\n#. oh, screw it!
\n' Guess I'll stick to HTML. Regards, Cliff -- From david_wahler at bic.ky Tue Aug 1 01:37:58 2006 From: david_wahler at bic.ky (david_wahler at bic.ky) Date: 1 Aug 2006 00:37:58 -0500 Subject: =?utf-8?Q?Re:_ANN:_Quest_for_the_Holy_Grail_=28a_PyGame_game=29?= Message-ID: <20060801053758.30093.qmail@BICSRV1011.bic.ky> I'll be out of the office until approximately August 20th. If you have any questions, please email support at bic.ky. -- David Wahler From tim.golden at viacom-outdoor.co.uk Fri Aug 18 06:14:25 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 18 Aug 2006 11:14:25 +0100 Subject: MS SQL Server: NT Authentication. Possible? Message-ID: [Dirk Hagemann] | Hi! | Is it somehow possible to access an MS SQL Server database from python | by NT-Authentication or do I have only the possibility to use an | SQL-Account with DB = odbc.odbc(myDB/myAccount/myPW) ? (dsn examples from http://www.connectionstrings.com/) + Object Craft MSSQL module: http://www.object-craft.com.au/projects/mssql/ can do by specifying blank username/pwd <= Python 2.3 only + adodbapi: http://adodbapi.sourceforge.net can use Trusted Connection eg "Provider=sqloledb;Data Source=Aron1;Initial Catalog=pubs;Integrated Security=SSPI;" + pymssql: http://pymssql.sourceforge.net/ can only do named user + mx.ODBC: http://www.egenix.com/files/python/mxODBC.html should be able to use Trusted Connection eg "Driver={SQL Server};Server=Aron1;Database=pubs;Trusted_Connection=yes;" Commercial License may be needed TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From utabintarbo at gmail.com Thu Aug 24 08:22:08 2006 From: utabintarbo at gmail.com (utabintarbo) Date: 24 Aug 2006 05:22:08 -0700 Subject: python In-Reply-To: <1156420101_143@dscnews2.dcccd.edu> References: <1156420101_143@dscnews2.dcccd.edu> Message-ID: <1156422128.657393.68870@m73g2000cwd.googlegroups.com> laura.biding at ntlworld.com wrote: > Regards, > laura.biding at ntlworld.com Thanks! ???? From pmaupin at gmail.com Sat Aug 26 15:51:44 2006 From: pmaupin at gmail.com (Patrick Maupin) Date: 26 Aug 2006 12:51:44 -0700 Subject: Don't use __slots__ (was Re: performance of dictionary lookup vs. object attributes) References: <1156508104.583914.323700@b28g2000cwb.googlegroups.com> <7.0.1.0.0.20060825122244.03790010@yahoo.com.ar> Message-ID: <1156621904.481215.243080@m73g2000cwd.googlegroups.com> skip at pobox.com wrote: > Aahz> Taking a look at __slots__ is fine as long as you don't actually > Aahz> use them. > > Gabriel> Why? > http://groups.google.com/group/comp.lang.python/browse_thread/thread/451ad25f9c648404/f4ac2dfde32b16fd?lnk=st&q=Python+__slots__+aahz&rnum=2#f4ac2dfde32b16fd > > Skip The subject of __slots__ really seems to get some people's dander up, to the extent where the heat/light ratio in the discussion becomes uncomfortably high. Right here, we have Skip referring to a post by Aahz, where Aahz says that Guido says that slots are bad mojo, without anybody ever giving concrete examples about why this may be the case. The only assertion that was made explicitly enough to be testable came about in a followup to Aahz's original post, only AFTER someone asked what the side-effects associated with __slots__ were. Aahz responded: > The main one is that inheritance becomes difficult to nearly-impossible. But this statement is either wrong or incomplete. Classes can certainly inherit from other classes which define __slots__, and this statement doesn't describe the problems well enough for any reader to figure out whether those problems directly affect him or not. The only problem I personally know of is that the __slots__ aren't inherited, but if you just view slots as a storage optimization, that's not a terrible thing. Also, with duck-typing, inheritance isn't necessarily all that important for many classes of classes, even if you take the limited view that all programming is object-oriented. I can certainly imagine that __slots__ do not give anywhere near the benefit that was envisioned when they were first implemented, and I can well believe that the implementation was, in retrospect, a "mistake". It may well be that, in hindsight, the cost/benefit ratio was too high to warrant having implemented them. I can also believe that many people may see __slots__ and think "Aha! This is how I implement type-checking!" This is typically considered unPythonic, so obviously when someone posts about how their type-checking wasn't properly inherited when they subclassed an object, a lot of heavy signing and gnashing of teeth will ensue. So, since __slots__ shouldn't have been implemented (and since they may not be implemented in Python 3000?) and since a lot of question about __slots__ are in reference to problems they weren't intended to solve in any case, it makes sense that people get testy about the whole thing, but is that any reason to _always_ assert that an existing languange feature should _never_ be used (and never back it up with relevant concrete examples about the associated problems)? My own experience with __slots__ has been quite positive, when I wanted to create millions of instances of the same well-defined small object. When the choices boil down to using __slots__ or dropping to C or Pyrex, I'll take __slots__ every time, whether or not that is Pythonically correct. Now, if someone has a well-written technical answer about how I might get bitten doing this, I would love to see it (but "__slots__ might be removed later because it was a mistake, so you'll have to rewrite your performance code in Pyrex anyway, so you wasted the 5 minutes you spent adding __slots__ to some of your classes two years ago" doesn't count). If anybody ever wrote such a useful answer, I missed it, so please give me a pointer to it! For a similar, probably better-written, perspective, check out: http://www.dalkescientific.com/writings/diary/archive/2006/03/19/class_instantiation_performance.html Regards, Pat From rogue_pedro at yahoo.com Thu Aug 10 15:08:44 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 10 Aug 2006 12:08:44 -0700 Subject: draw an image in wx.BufferedDC onto the page created by AddPage of wx.Notebook In-Reply-To: <1155222733.322056.40090@75g2000cwc.googlegroups.com> References: <1155222733.322056.40090@75g2000cwc.googlegroups.com> Message-ID: <1155236924.124955.81670@i42g2000cwa.googlegroups.com> zxo102 wrote: > Hi everyone, > I have tried two days to figure out how to draw the image in > wx.BufferedDC on the page created by AddPage of wx.Notebook but still > got no clue. > > The attached example works fine. If I click the menu "Draw" --> "New > Drawing". The image with wx.BufferedDC/wx.BufferedPaintDC can move > around on the frame. But If I uncomment those three commented lines in > "class TestFrame" to add a new page (from wx.Notebook) with a tag and > modify the last line like > self.Window = DrawWindow(form2) > I can not see the image from wx.BufferedDC anywhere and don't know what > is going on. > > I need your help. Thanks a lot. > Have you tried http://wiki.wxpython.org/index.cgi/Asking_For_Help Peace, ~Simon From ptmcg at austin.rr._bogus_.com Wed Aug 2 22:58:56 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 03 Aug 2006 02:58:56 GMT Subject: need help of regular expression genius References: <1154532421.096157.289570@i42g2000cwa.googlegroups.com> Message-ID: "GHUM" wrote in message news:1154532421.096157.289570 at i42g2000cwa.googlegroups.com... > I need to split a text at every ; (Semikolon), but not at semikolons > which are "escaped" within a pair of $$ or $_$ signs. > The pyparsing rendition to this looks very similar to the SE solution, except for the regexp's: text = """ ... input source text ... "" from pyparsing import SkipTo,Literal,replaceWith ign1 = "$$" + SkipTo("$$") + "$$" ign2 = "$_$" + SkipTo("$_$") + "$_$" semi = Literal(";").setParseAction( replaceWith("; <***>") ) print (ign1 | ign2 | semi).transformString(text) In concept, this works just like the SE program: as the scanner/parser scans through the input text, the ignoreable expressions are looked for first, and if found, just skipped over. If the semicolon expression is found, then its parse action is executed, which replaces the ';' with "; <***>", or whatever you choose. The pyparsing wiki is at pyparsing.wikispaces.com. -- Paul From danielmarkhot at gmail.com Sat Aug 19 01:30:46 2006 From: danielmarkhot at gmail.com (Daniel Mark) Date: 18 Aug 2006 22:30:46 -0700 Subject: py2exe: cannot identify image file Message-ID: <1155965446.309438.161740@74g2000cwt.googlegroups.com> Hello all: I have following code that works well under command line, but it doesn't work after I convert it as exe application. ############### file: testPath.py import getopt, math, sys, os, Image, ImageDraw, aggdraw def processline(): try: imgDir = 'c:/' lumenImageName = '00299.jpg' im = Image.open(os.path.join(imgDir, lumenImageName)) arrowImageName = '00299.png' im.save(os.path.join(imgDir, arrowImageName), "PNG") print lumenImageName except IOError, e: print e def main(): processline() if __name__ == '__main__': main() print 'Done' else: print 'non main' ############### setup.py from distutils.core import setup import py2exe options = { "bundle_files": 1, # "ascii": 1, # to make a smaller executable, don't include the encodings "compressed": 1, # compress the library archive } setup( # The first three parameters are not required, if at least a # 'version' is given, then a versioninfo resource is built from # them and added to the executables. version = "1.0", description = "testPath", name = "testPath", options = {"py2exe": options}, zipfile = None, # append zip-archive to the executable. # targets to build console=['testPath.py'], ) ########################### It works under command line C:\>python testPath.py 00299.jpg Done But it doesn't work after I convert it as EXE application The error message I got from screen is as follows: C:\dist>testPath.exe cannot identify image file Done It seems that function 'Image.open' cannot read image file under EXE application. What should I do for this problem? Thank you -Daniel From gene.tani at gmail.com Tue Aug 8 23:38:39 2006 From: gene.tani at gmail.com (gene tani) Date: 8 Aug 2006 20:38:39 -0700 Subject: technique to enter text using a mobile phone keypad (T9 dictionary-based disambiguation) In-Reply-To: References: Message-ID: <1155094719.198988.30930@b28g2000cwb.googlegroups.com> Petr Jake? wrote: > I have a standard 12-key mobile phone keypad connected to my Linux > machine as a I2C peripheral. I would like to write a code which allows > the text entry to the computer using this keypad (something like T9 on > the mobile phones) > > According to the http://www.yorku.ca/mack/uist01.html > dictionary-based disambiguation is coming in the mind. > > With dictionary-based disambiguation, each key is pressed only once. > For example, to enter the, the user enters 8-4-3-0. The 0 key, for > SPACE, delimits words and terminates disambiguation of the preceding > keys. The key sequence 8-4-3 has 3 ? 3 ? 3 = 27 possible renderings > (see Figure 1). The system compares the possibilities to a dictionary > of words to guess the intended word. > http://rubyquiz.com/quiz20.html From pmartin at snakecard.com Sat Aug 19 12:39:57 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Sat, 19 Aug 2006 11:39:57 -0500 Subject: write eof without closing References: Message-ID: <2lHFg.85172$LF4.4815@dukeread05> cage wrote: > hello > > can i write a eof to a file descriptor without closing it? > like: > fd.write(EOF) > or something > > grts, > ruben No but there is an EOF to the file anyway, even if it is open. I recall under MS-DOS, you could create a file of size N without writing to it (some INT21 or 9 ? call to modify the FAT) ... not really possible anymore. Philippe From mariano.difelice at gmail.com Thu Aug 31 06:34:27 2006 From: mariano.difelice at gmail.com (mardif) Date: 31 Aug 2006 03:34:27 -0700 Subject: wxNotebook color change Message-ID: <1157020467.883961.282800@p79g2000cwp.googlegroups.com> Hi ! this is my problem: I've a wxNotebook object, which contains 2 Panels. On up, there is TAB section, I have 2 tabs. I want to color the TAB section with ( for example ) red color. I've tried with SetBackgroundColour() for wxNotebook object and for 2 panel inside, but it doesn't works. why?? thx in advance! bye From maric at aristote.info Tue Aug 22 16:49:34 2006 From: maric at aristote.info (Maric Michaud) Date: Tue, 22 Aug 2006 22:49:34 +0200 Subject: Python and STL efficiency In-Reply-To: <1hkh28d.xscw4v1y4v9a6N%riko@despammed.com> References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <1hkh28d.xscw4v1y4v9a6N%riko@despammed.com> Message-ID: <200608222249.35315.maric@aristote.info> Le mardi 22 ao?t 2006 12:55, Mc Osten a ?crit?: > In fact Python here is faster. Suppose it has a really optimized set > class... Maybe I'm missing something but the posted c++codes are not equivalent IMO to what python is doing. I discarded the "slow" version, and tried to get the equivalent in c++ of : """ #!/usr/bin/env python size = 1000000 def f(): a = [] for i in range(size): a.append('What do you know') a.append('so long...') a.append('chicken crosses road') a.append('fool') b = set(a) for s in b: print s import time from time import clock f_start = clock() f() f_end = clock() print "Elapsed: %f seconds" % (f_end - f_start) """ I came at first with the following, which is still slower than the python version : """ void print_occurence_of_unique_strings(){ vector a; const string& s1 = "What do you know?" ; const string& s2 = "so long..." ; const string& s3 = "chicken crosses road"; const string& s4 = "fool" ; for (long int i=0; i b(a.begin(), a.end()); copy(b.begin(), b.end(), ostream_iterator(cout, "\n")); } """ Here, all strings, while passed by reference to the vector, are copied one by one. Then, I tried this, it just overcome the performance of python code, but not in the proportion I expected : """ void print_occurence_of_unique_strings_compare_by_adresses(){ vector a; string s1 = "What do you know?"; string s2 = "so long..."; string s3 = "chicken crosses road"; string s4 = "fool"; for (long int i=0; i b; for (vector::iterator it=a.begin(); it!=a.end(); it++) b.insert(**it); copy(b.begin(), b.end(), ostream_iterator(cout, "\n")); } """ The problem here, is that the strings in the set are compared by value, which is not optimal, and I guess python compare them by adress ("s*n is s*n" has the same complexity than "s*n == s*n" in CPython, right ?). so, finally, the code in c++, about ten times faster than the equivalent in python, must be : """ void print_occurence_of_unique_strings_compared_by_address(){ cout << "print_occurence_of_unique_strings_compared_by_address" << endl; vector a; string s1 = "What do you know?"; string s2 = "so long..."; string s3 = "chicken crosses road"; string s4 = "fool"; for (long int i=0; i b(a.begin(), a.end()); set c; // well ordered set (b is ordered by address) for (set::iterator it=b.begin(); it!=b.end(); it++) c.insert(**it); copy(c.begin(), c.end(), ostream_iterator(cout, "\n")); } """ the result on my box is : maric at redflag2 mar ao? 22 22:24:23:~$ g++ -O3 -o testcpp testcpp.cpp maric at redflag2 mar ao? 22 22:24:29:~$ ./testcpp print_occurence_of_strings What do you know? chicken crosses road fool so long... print_occurence_of_unique_strings What do you know? chicken crosses road fool so long... print_occurence_of_unique_strings_compared_by_address What do you know? chicken crosses road fool so long... strings : 1.89 unique strings : 0.87 compared by address : 0.18 maric at redflag2 mar ao? 22 22:24:38:~$ python2.4 testpython.py so long... What do you know fool chicken crosses road Elapsed: 1.680000 seconds maric at redflag2 mar ao? 22 22:24:51:~$ g++ -v Using built-in specs. Target: i486-linux-gnu Configured with: ../src/configure -v --enable-languages=c,c++,java,fortran,objc,obj-c++,ada,treelang --prefix=/usr --enable-shared --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --enable-nls --program-suffix=-4.1 --enable-__cxa_atexit --enable-clocale=gnu --enable-libstdcxx-debug --enable-java-awt=gtk --enable-gtk-cairo --with-java-home=/usr/lib/jvm/java-1.4.2-gcj-4.1-1.4.2.0/jre --enable-mpfr --with-tune=i686 --enable-checking=release i486-linux-gnu Thread model: posix gcc version 4.1.2 20060613 (prerelease) (Debian 4.1.1-5) I've joined the full c++ file as an attachment. -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 -------------- next part -------------- A non-text attachment was scrubbed... Name: testcpp.cpp Type: text/x-c++src Size: 2764 bytes Desc: not available URL: From bignose+hates-spam at benfinney.id.au Fri Aug 11 20:52:58 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 12 Aug 2006 10:52:58 +1000 Subject: Learning Python References: <1155329631_4653@sp6iad.superfeed.net> Message-ID: <87ejvmwz9x.fsf@benfinney.id.au> "Dr. Pastor" writes: > #------------------------------------------------------------------------------- > # Name: SendMoreMoney.py > # Purpose: A solution to the SEND+MORE=MONEY puzzle. > # > # Author: Dr. Pastor > # > # Copyright: (c) Dr. Pastor 2006 > > #------------------------------------------------------------------------------- > #!/usr/bin/env python This line, to be at all meaningful, must be the first line in the file, with no leading spaces. > # > # The solution for the puzzle of > # SEND > # +MORE > # ----- > # MONEY > # Somewhat more useful than a comment block to describe your module is a "doc string" for the module: You will also thank yourself for writing descriptive doc strings for each function and class (preferably as soon as you begin writing the definition, so you don't need to remember to come back later and do them). -- \ "Self-respect: The secure feeling that no one, as yet, is | `\ suspicious." -- Henry L. Mencken | _o__) | Ben Finney From jo at durchholz.org Tue Aug 29 14:01:19 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Tue, 29 Aug 2006 20:01:19 +0200 Subject: A Sort Optimization Technique: decorate-sort-dedecorate In-Reply-To: <7.0.1.0.0.20060829132302.05c9e758@yahoo.com.ar> References: <1156719092.603277.57390@b28g2000cwb.googlegroups.com> <1156723602.192984.49610@m79g2000cwm.googlegroups.com> <280820061150081729%jgibson@mail.arc.nasa.gov> <7.0.1.0.0.20060829132302.05c9e758@yahoo.com.ar> Message-ID: <44F480EF.9080202@durchholz.org> Gabriel Genellina schrieb: > At Tuesday 29/8/2006 07:50, Joachim Durchholz wrote: > >> Wikipedia says it's going from 2NlogN to N. If a sort is massively >> dominated by the comparison, that could give a speedup of up to 100% >> (approximately - dropping the logN factor is almost irrelevant, what >> counts is losing that factor of 2). > > In fact it's the other way - losing a factor of 2 is irrelevant, > O(2N)=O(N). The logN factor is crucial here. That's just a question of what you're interested in. If it's asymptotic behavior, then the O(logN) factor is a difference. If it's practical speed, a constant factor of 2 is far more relevant than any O(logN) factor. (I'm not on the list, so I won't see responses unless specifically CC'd.) Regards, Jo From kylotan at gmail.com Fri Aug 25 06:11:46 2006 From: kylotan at gmail.com (Ben Sizer) Date: 25 Aug 2006 03:11:46 -0700 Subject: Python and STL efficiency In-Reply-To: References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <1156445446.280027.92160@b28g2000cwb.googlegroups.com> Message-ID: <1156500706.638854.59980@m73g2000cwd.googlegroups.com> Neil Cerutti wrote: > On 2006-08-24, JSprenkle at gmail.com wrote: > > > It will run a lot faster if it doesn't have to keep resizing > > the array. > > I don't see why it should run a lot faster that way. > > Appending elements to a vector with push_back takes amortized > constant time. In the example above, preallocating 40000 strings > saves (probably) math.log(40000, 2) reallocations of the vector's > storage along with the consequent copy-construction and > destruction of some fixed number of strings. Most of those > reallocations take place while the vector is still proportionally > quite small. Math.log(40000, 2) is not a small number when talking about a relatively expensive operation such as memory allocation and deallocation. And the superfluous copying amounts to probably an extra 2^16 copies in this case - not exactly trivial. -- Ben Sizer From cliff at develix.com Tue Aug 15 04:20:15 2006 From: cliff at develix.com (Cliff Wells) Date: Tue, 15 Aug 2006 01:20:15 -0700 Subject: ReStructuredText In-Reply-To: <505f13c0608150110n4a3df201uefa06dd61d7f8fec@mail.gmail.com> References: <1155628608.16686.19.camel@devilbox> <505f13c0608150102h141df8k9a07fd7a5a9746e1@mail.gmail.com> <1155629199.16686.22.camel@devilbox> <505f13c0608150110n4a3df201uefa06dd61d7f8fec@mail.gmail.com> Message-ID: <1155630015.16686.29.camel@devilbox> On Tue, 2006-08-15 at 16:10 +0800, limodou wrote: > On 8/15/06, Cliff Wells wrote: > > On Tue, 2006-08-15 at 16:02 +0800, limodou wrote: > > > On 8/15/06, Cliff Wells wrote: > > > > Thanks for the response. Must be a bug in my version: > > > > > > Which version of docutils you are using, in my computer is good. > > > > > > u'
    \n
  1. this is a test
  2. \n
  3. this is > > > another line
  4. \n
  5. oh, screw it!
  6. \n
\n' > > > > >>> docutils.__version__ > > '0.3.7' > > >>> > > > Oh, the newest version is 0.4 Yeah, right after you asked, I tried 0.4, but it failed with a traceback. I ended up installing 0.3.9 and it works fine (and didn't require the list to be indented either, FWIW). For anyone who cares, the traceback with 0.4 was: Python 2.4.2 (#1, Feb 13 2006, 15:24:20) [GCC 3.3.6 (Gentoo 3.3.6, ssp-3.3.6-1.0, pie-8.7.8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from docutils.core import publish_parts Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/site-packages/docutils/core.py", line 23, in ? from docutils import frontend, io, utils, readers, writers File "/usr/lib/python2.4/site-packages/docutils/readers/__init__.py", line 15, in ? from docutils.transforms import universal File "/usr/lib/python2.4/site-packages/docutils/transforms/__init__.py", line 69, in ? class Transformer(TransformSpec): File "/usr/lib/python2.4/site-packages/docutils/transforms/__init__.py", line 78, in Transformer default_transforms = (universal.Decorations, AttributeError: 'module' object has no attribute 'FinalChecks' Regards, Cliff -- From david at boddie.org.uk Fri Aug 25 19:27:30 2006 From: david at boddie.org.uk (David Boddie) Date: 25 Aug 2006 16:27:30 -0700 Subject: Drag and Drop with PyQt4 In-Reply-To: <1156533361.933690.221260@b28g2000cwb.googlegroups.com> References: <1156533361.933690.221260@b28g2000cwb.googlegroups.com> Message-ID: <1156548450.880223.181500@74g2000cwt.googlegroups.com> Harshad wrote: > When I run the program, DragEnterEvent works as expected, but the > DropEvent does not seem to be working. I'm not an experienced Python > hacker, and am unable to trace out any problems with the source code. > Any and all help will be appreciated! I'm making an educated guess from memory, but I think you need to implement your own dragMoveEvent() method and accept the event there as well. This is because the item view widgets typically like to handle all aspects of drag and drop, and QListView (from which QListWidget is derived) ignores drag move events by default. So, if you want to change the behaviour in a fundamental way, you need to handle many aspects of the process; in this case, you need to provide your own dragEnterEvent(), dragMoveEvent() and dropEvent() methods. These can be simple, as shown in the following example: class ListWidget(QListWidget): def __init__(self, parent = None): QListWidget.__init__(self, parent) self.setAcceptDrops(True) def dragEnterEvent(self, event): event.acceptProposedAction() def dragMoveEvent(self, event): event.acceptProposedAction() def dropEvent(self, event): print "Drop" event.accept() listWidget = ListWidget() listWidget.show() I tested this code with Python 2.4.2, Qt 4.1.4 and PyQt 4.1, and I think you should be able to do the same in your code. Two other points: 1. If you are prepared to try Qt's model/view classes, you can exert more control over the way drag and drop is handled. They're not quite as straightforward as the item-based classes that you're already using, but you benefit from greater reusability of your components and better control over the appearance and behaviour of the view widgets. This guide is for C++, but it translates fairly well into Python: http://doc.trolltech.com/4.1/model-view-programming.html 2. You seem to prefer adding methods to specific instances rather than subclassing and reimplementing methods in the base class. I hope you don't mind me asking, but is that because it takes less code, because you find it conceptually easier, or is there another reason that I'm missing? David From jason at tishler.net Tue Aug 8 06:40:19 2006 From: jason at tishler.net (Jason Tishler) Date: Tue, 08 Aug 2006 06:40:19 -0400 Subject: Resource temporarily unavailable launching idle under cygwin In-Reply-To: <1154976453.055076.186560@p79g2000cwp.googlegroups.com> References: <1154976453.055076.186560@p79g2000cwp.googlegroups.com> Message-ID: <20060808104019.GA2664@tishler.net> Juan C., On Mon, Aug 07, 2006 at 11:47:33AM -0700, jcmendez wrote: > Hello everyone. Trying to run idle from a cygwin session on Win2k > (yuk, but I must) I'm getting the following error message. > [snip] > > $ idle > 23367 [main] python2.4 1668 C:\cygwin\bin\python2.4.exe: *** fatal > error - C:\cygwin\bin\python2.4.exe: *** unable to remap > C:\cygwin\bin\tk84.dll to same address as parent(0x18890000) != 0x18D20000 You need to rebase your system: http://www.google.com/search?hl=en&q=cygwin+python+%22unable+to+remap%22 Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From johnjsal at NOSPAMgmail.com Tue Aug 22 11:42:13 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 22 Aug 2006 15:42:13 GMT Subject: text editor suggestion? In-Reply-To: <1156219373.342609.71480@h48g2000cwc.googlegroups.com> References: <44e66724$0$2363$c3e8da3@news.astraweb.com> <1156219373.342609.71480@h48g2000cwc.googlegroups.com> Message-ID: Ravi Teja wrote: > Stick to SciTE. It takes almost no learning effort and meets everyone > of those requirements. As far as customerization goes, SciTE can be > customerized quite well. In fact, it can even be scripted with Lua. You > seem to be using the single file executable which does not come with > the configuration files. Otherwise, I cannot see how you could be > missing this ability. I really like Scite, but I find it's syntax highlighting abilities to be quite limited. You can't specify your own groups of words, you can only use what is already preset in the lexer files. From fpemberton133 at yahoo.com Sat Aug 12 12:49:50 2006 From: fpemberton133 at yahoo.com (f pemberton) Date: 12 Aug 2006 09:49:50 -0700 Subject: trouble with replace Message-ID: <1155401390.926925.252000@m79g2000cwm.googlegroups.com> I have a string (xdata) and theres a newline after every 17 characters of the string. I was wondering how I can replace multiple substrings multiple times within a string? To put it another way, this is what i want to do. Substring to find ("abcdef") replace it with ("highway") search again, substring to find ("defgef") replace it with ("news").Search again and find ("effwer") replace it with ("monitor").Example string to search under is '''defgefabcdefyuuuu effwerbyuuuterrfr''' I've tried using replace but its not working for me. xdata.replace('abcdef', 'highway') xdata.replace('defgef', 'news') xdata.replace('effwer', 'monitor') Basically I would want to get the output of "newshighwayyuuuu monitorbyuuuterrfr" Thanks, any help would be appreciated. From charles.hebert at gmail.com Wed Aug 30 08:04:53 2006 From: charles.hebert at gmail.com (charles.hebert at gmail.com) Date: 30 Aug 2006 05:04:53 -0700 Subject: where or filter on list Message-ID: <1156939493.558819.8410@i42g2000cwa.googlegroups.com> Hi, Can anybody tell me how to to find the nearest value to zero in a list ? To do that, i'm using list comprenhension : >>> foo = [-5,-1,2,3] # nearest value to zero ? >>> [value for value in foo if math.fabs(value) == min([int(math.fabs(x)) for x in foo])] [-1] Something simpler ? How to extend this function to any given value ? Thanks, CH. From gelists at gmail.com Wed Aug 2 21:14:56 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Wed, 2 Aug 2006 22:14:56 -0300 Subject: Windows vs. Linux References: <1154301694.445639.99580@m79g2000cwm.googlegroups.com> <44cddfb3$0$7761$7a628cd7@news.club-internet.fr> Message-ID: <14cejkza69e00.dlg@gelists.gmail.com> On 2006-08-02 21:09:43, Sybren Stuvel wrote: > Microsoft could provide an emulated environment for backward > compatability, just like Apple did. Wouldn't know what that would cost, > though. Possibly. Rather than waiting for that, I think that languages that want a degree of portability should simply provide a wrapper around this low level system dependent stuff. There's no need to use system dependent path separation characters in the language API. >> And don't be fooled... you may run a Linux system, but you'd pay >> your share of that bill anyway. > > How's that? Pretty much every production cost increase gets in the end paid by the consumer. With some localized changes, you may be lucky and don't buy any products that are affected, but with such a widespread change as this would be, it is more likely that almost everybody is affected close to average. With that is also mostly the pressure gone to not increase -- because so many are affected that the few who are not happily increase the prices with the others. The only ones likely to make a cut for a short time are a number of Windows consultants. But those probably would be mostly either people with some previous involvement with the product or the company, or cheap offshore resources. Probably neither is your case... :) Gerhard From tim.golden at viacom-outdoor.co.uk Sat Aug 19 15:55:14 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: 19 Aug 2006 12:55:14 -0700 Subject: install patch on windows In-Reply-To: <1156014103.715131.143360@i3g2000cwc.googlegroups.com> References: <1156014103.715131.143360@i3g2000cwc.googlegroups.com> Message-ID: <1156017314.249545.296940@h48g2000cwc.googlegroups.com> djoefish wrote: > Does anyone know how to install a patch on Winodws? For example, I want > to install the patch 'ocmalloc-free-arenas.diff' in Python 2.3. You can get patch (and quite a lot besides) for win32 from the UnxUtils project: http://sourceforge.net/projects/unxutils TJG From db4037ci.bbs at bbs.wretch.cc Thu Aug 17 08:29:35 2006 From: db4037ci.bbs at bbs.wretch.cc (db4037ci.bbs at bbs.wretch.cc) Date: 17 Aug 2006 12:29:35 GMT Subject: [=?big5?Q?=BCs=A7i]=BCx=A4H~=AD=DD=C2=BE=A4u=A7@=A5=FE=C2=BE=A6=AC=A4J(=A5i=A6b=AEa=A4u=A7@)?= Message-ID: <4PZ90l$9yL@bbs.wretch.cc> Part-time job Full-time income ??????????????????????? ??????,??2~3??,??1?~3? ??????????,?????????? ????????????? ?????~?????????? 98.to/????? ??????????????????? ???????????????????? -- ????????????????????????????????????? ????????????????????????????????????? ????????????????????????????????????? ????????????????????????????????????? ?????????????????????220-137-45-9.dynamic.hinet.net? From nyamatongwe+thunder at gmail.com Tue Aug 15 17:55:13 2006 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Tue, 15 Aug 2006 21:55:13 GMT Subject: Basic Boost.Python Question In-Reply-To: <1155645751.116107.41320@i42g2000cwa.googlegroups.com> References: <1155586541.415711.14950@i42g2000cwa.googlegroups.com> <9J6Eg.12022$rP1.2992@news-server.bigpond.net.au> <1155645751.116107.41320@i42g2000cwa.googlegroups.com> Message-ID: <5prEg.12637$rP1.1593@news-server.bigpond.net.au> Hoop: > I have never heard of IronPython. Do you know if you can embedd the > Python interpreter ? I think so as I've read of people embedding the console on the mailing list. My experience is in using a C# library within a Python application. Neil From avelldiroll at yahoo.fr Wed Aug 2 07:59:48 2006 From: avelldiroll at yahoo.fr (Avell Diroll) Date: Wed, 02 Aug 2006 13:59:48 +0200 Subject: Reinstalling Python Problem (Newbie) In-Reply-To: <44D06FED.6060107@2012.vi> References: <44CF9ADE.4080008@python.org> <44D06159.2070706@yahoo.fr> <44D06FED.6060107@2012.vi> Message-ID: <44D093B4.7090606@yahoo.fr> beno wrote: > Avell Diroll wrote: >> beno wrote: >> *** tidying a little *** >>> >>> What do I do about the problems with mimetools and urllib2? >>> >> >> This is the last report of the 'make test' command and there should be >> a few lines before that stating each test one by one and printing >> problems has they appear, and sometime pointing at a possible source >> for the specific problem. Have you got such a report for test_urllib2 ? >> > Here it is for both: > > test_mimetools > test test_mimetools failed -- Traceback (most recent call last): > File "/usr/local/zope/py243/Lib/test/test_mimetools.py", line 30, in > test_boundary > nb = mimetools.choose_boundary() > File "/usr/local/zope/py243/Lib/mimetools.py", line 130, in > choose_boundary > hostid = socket.gethostbyname(socket.gethostname()) > gaierror: (8, 'hostname nor servname provided, or not known') > > > test_urllib2 > test test_urllib2 failed -- Traceback (most recent call last): > File "/usr/local/zope/py243/Lib/test/test_urllib2.py", line 352, in > test_file > for url in [ > gaierror: (8, 'hostname nor servname provided, or not known') > > Looks like the same error ;) So, where am I supposed to provide this > servname? > >> *** tidying a little *** This gethostname() problem in the test suite looks like an old problem. I believe your problem is related to what Anthony Baxter and Guido van Rossum where discussing back in 2004 on the python-dev mailing list : http://mail.python.org/pipermail/python-dev/2003-November/040501.html To put things short the test suite might fail on any test using socket.gethostname() on a machine where /etc/hostname and /etc/hosts are not matching. If that is the case for your machine, the problem is coming from the test suite, not your python build. regards, Avell From johnjsal at NOSPAMgmail.com Thu Aug 10 10:17:42 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 10 Aug 2006 14:17:42 GMT Subject: using python with tar files and compressed files In-Reply-To: <1155142962.511995.265280@p79g2000cwp.googlegroups.com> References: <1HmCg.2661$No6.51985@news.tufts.edu> <1155142962.511995.265280@p79g2000cwp.googlegroups.com> Message-ID: enigmadude at rock.com wrote: > This syntax works on other bzipped tar files. But it's not unheard of > that large tarballs will get corrupted from a download mirror. Use a > download manager and try redownloading the file. Usually a mirror will > include an md5sum text file so that you can compare the checksum to > your downloaded file to verify its integrity. For some reason, the > wxPython site doesn't have them. Well, unless the file was updated between my problem and when I got home, then perhaps it was my system. Because I tried it again on Linux and it worked as expected. From lsumnler at gmail.com Wed Aug 23 16:11:50 2006 From: lsumnler at gmail.com (len) Date: 23 Aug 2006 13:11:50 -0700 Subject: Help don't know what problem is Newbie Message-ID: <1156363910.233684.308080@74g2000cwt.googlegroups.com> Have the following code: import os import csv import re import mx.ODBC import mx.ODBC.Windows currdir = os.getcwd() db = mx.ODBC.Windows.DriverConnect('dsn=UICPS Test') c = db.cursor() sid = 315 matchstr = re.compile(r'\(*\)*-*,*') reader = csv.reader(open(currdir + r'\\IBI Brokers List 8-21-06.csv')) for rec in reader: if rec[0] != '' or rec[1] != '': if rec[0] == 'Name:': orec = '' orec = orec + rec[12] + ',' + rec[2] elif rec[1] == 'Address1': orec = orec + ',' + rec[4] elif rec[1] == 'Address2': orec = orec + ',' + rec[4] elif rec[1] == 'City, State, ZIP': csz = matchstr.sub('', rec[4]).split() if len(csz) == 0: c = '' s = '' z = '' elif len(csz) == 3: c = csz[0] s = csz[1] z = csz[2] elif len(csz) == 4: c = csz[0] + ' ' + csz[1] s = csz[2] z = csz[3] orec = orec + ',' + c + ',' + s + ',' + z + ',' + matchstr.sub('', rec[13]) elif rec[1] == 'Tax ID': orec = orec + ',' + rec[4].replace('-', '') + ',' + matchstr.sub('', rec[12]) sid += 1 orec = str(sid) + ',' + orec print orec c.execute("insert into Producer \ (Producer_Sid, Producerno, Company, Street, Suitepo, City, State, Zip, \ Phone, Taxid, Fax) \ values (" + orec + ")") Below is a listing of the orec which I printed along with the python error: [DEBUG ON] >>> 316,001,#001 Insurance Brokers of Indiana,400 Camby Court,P O Box 190,Greenwood,IN,46142,3178882593 ,351539405,3178857011 Traceback (most recent call last): File "C:\UICPS\IBIagent.py", line 44, in -toplevel- c.execute("insert into Producer \ AttributeError: 'str' object has no attribute 'execute' Thanks Len Sumnler From onurb at xiludom.gro Wed Aug 30 14:15:47 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 30 Aug 2006 20:15:47 +0200 Subject: dictionary with object's method as thier items In-Reply-To: <1156953831.398554.68560@p79g2000cwp.googlegroups.com> References: <1156944917.152606.213600@i42g2000cwa.googlegroups.com> <1156953831.398554.68560@p79g2000cwp.googlegroups.com> Message-ID: <44f5d5d5$0$10056$636a55ce@news.free.fr> noro wrote: > great that is what i looked for. Hmmm... Not quite sure >>>> class C: >> ... def function(self, arg): >> ... print arg >> ... >> >>> obj = C() >> >>> d = C.__dict__ >> >>> d['function'](obj, 42) >> 42 > > this allows me the access the same method in a range of objects. class Obj(object): def __init__(self, num): self.num = num def method(self): return "in %s.method" % self for obj in [Obj(i) for i in range(10)]: print getattr(obj, "method")() > i can put all the functions i need in a dictionary as items, and the > vars as keys, and then call them for all objects that belong to a > class.. > > something like this > > ---------------------------------------------------- > class C: > > #object vars > self.my_voice > self.my_size > self.my_feel > > # a method that do somthing, that might give different result for > different objects > getVoice(self): > return(self.my_voice+'WOW') > > getSize(self): > return(self.my_size*100) > > getFeel(self): > return(self.my_feel) > > > #create the dictionary with a reference to the class methode > dic={'voice':C.getVoice,'size':C.getSize,'feel':C.getFeel} > > > # create array of 10 different objects > cArray = [] > for i in range(10) > cArray.append(C()) > cArray[0].my_size=i > > # choose the function you need, and get the result > choice=WHAT EVER KEY (e.g 'size') > for i in range(10) > print dic[choice](cArray[i]) > > #or even print all the values of all objects. if i ever want to print > diffenet valuse i only need > # to change the dictionary, nothing else... > for choice in dic: > for i in range(10) > print dic[choice](cArray[i]) > --------------------------------------------------------------- > i totaly forget about the "self" argument in every method... ??? > a. is the main reason "self is there, or is it only a side effect? I'm not sure I understand your question. > b. what do you think about this code style? Don't ask me if you don't want to get hurt !-) > it is not very OOP, This is not a problem - Python doesn't forces you that much into OO. > but i > cant see how one can do it other wise, using getattr(, [,]) > and be able to control the > function printed out with something as easy as dictionary.. Here's a somewhat more pythonic way to do the same thing (NB : not tested): # a simple decorator def choice(func): func.is_choice = True return func # helper func def is_choice(obj): return callable(obj) and getattr(obj, 'is_choice', False) # braindead metaclass class ChoicesMeta(type): def __init__(cls, name, bases, classdict): cls.choices = [name for name, attrib in classdict.items() \ if is_choice(attrib)] # our class... class Foo(object): __metaclass__ = ChoicesMeta def __init__(self, num): self.num = num # mark the method as usable in choices @choice def bar(self): return "foo #%s.bar" % self.num @choice def baaz(self): return "foo #%s.baaz" % self.num # let's test: foos = [Foo(i) for i in range(10)] choice = for foo in foos: print getattr(foo, choice)() HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From ktenney at gmail.com Wed Aug 9 14:00:21 2006 From: ktenney at gmail.com (Kent Tenney) Date: Wed, 9 Aug 2006 18:00:21 +0000 (UTC) Subject: Status of Epydoc Message-ID: Howdy, I would very like to use Epydoc 3.0, however I've found a couple bugs and the mailing list; http://sourceforge.net/mailarchive/forum.php?forum_id=39919 doesn't seem to be working, the last couple messages I've posted haven't shown up. Does anyone know the status of Epydoc 3.0 development? Thanks, Kent From steve at REMOVEME.cybersource.com.au Mon Aug 21 22:34:45 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 22 Aug 2006 12:34:45 +1000 Subject: how do you get the name of a dictionary? References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> Message-ID: On Mon, 21 Aug 2006 16:59:30 -0700, jojoba wrote: > hello > > im quite surprised at the arrogance laid out by some of the above > posters: > > However, does it not seem reasonable to ask python: > > Given a dicitionary, Banana = {} > return one or more strings, > where each string is the name(s) of the reference(s) to Banana. No, it doesn't seem reasonable for objects to know the names they are known as. It would require extremely major changes to Python, for minimal benefit. Do you have a practical example of where this would be useful? I can't think of any other language that has such a feature, except in very limited areas (e.g. classes and functions know the name they were defined as, not necessarily the names they are bound to). And how would you use it? Let's suppose there is such a function, GetObjectName(). What do you suggest? >>> mydict = {} >>> print GetObjectName({}) # but this dict is not the same as mydict '' >>> print GetObjectName(mydict) 'mydict' But if you have to type mydict as the argument to the function, why not just wrap it in quotes (two characters instead of 15) and use that? And what should GetObjectName(notmydict) return? Raise an exception? > why is this not sane?!?! > what am i missing here? > > I mean, i can enter the name of the dicitonary and python knows what i > am talking about, so why can't i go backwards to get one or more strings > that are the names of the dictionary? If you know a person's name, you can look up their number in the phone book easily. If you know their phone number, it is much, much harder to look up their name -- unless you go to the time and effort of keeping a "reverse phone book". For phone numbers, the phone companies keeps a reverse phone book because it is useful to them; for Python, it isn't clear that there is any practical use. Unless there is a practical use for that "reverse phone book" , why should Python go to all the effort of keeping it? -- Steven D'Aprano From danielwong at berkeley.edu Wed Aug 16 16:39:10 2006 From: danielwong at berkeley.edu (danielx) Date: 16 Aug 2006 13:39:10 -0700 Subject: hide python code ! In-Reply-To: References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155300852.497741.73230@74g2000cwt.googlegroups.com> <1155301468.870340.82920@b28g2000cwb.googlegroups.com> <1155307415.855555.124760@i3g2000cwc.googlegroups.com> <1155309563.898182.195950@p79g2000cwp.googlegroups.com> <1155313092.743230.33950@m73g2000cwd.googlegroups.com> <1155320948.142524.124990@p79g2000cwp.googlegroups.com> <1155564295.361980.279350@m73g2000cwd.googlegroups.com> <1155570126.905733.137850@m79g2000cwm.googlegroups.com> <1155657616.103285.40040@75g2000cwc.googlegroups.com> Message-ID: <1155760750.172859.172920@h48g2000cwc.googlegroups.com> Steven D'Aprano wrote: > On Tue, 15 Aug 2006 09:00:16 -0700, Ben Sizer wrote: > > > Yes, in much the same way that there is no point ever locking your > > doors or installing burglar alarms, as a determined thief will > > eventually steal your belongings. > > That's an utterly pointless and foolish analogy. > > (1) If a thief breaks into your house and steals your TV, you no longer > have a TV. If a developer sees your code, you still have your code, *even > if they subsequently copy it*. You haven't lost your code, it is just no > longer secret. Since secrecy is rarely valuable in and of itself, you've > lost nothing. But haven't you lost your control over the code? If you were trying to sell a program (regardless of whether this is a good way to make money from it), hasn't your ability to do so been undercut? This is the loss. > > Yes, I've heard all the stories about "valuable algorithms" and the like. > Some of them might even be true. But for 99+% of code, spending even one > cent to keep it secret is just wasting money. That may be true, but for someone who has determined that the hiding the code would be best, it would seem to be quite a good investment. Besides, these kinds of decisions are made case by case. We would not throw a dice to see whether some code should be released or not. Of course, these kinds of statistics _should_ moderate any decision, but I don't think you can expect that "99+%" will make sense to most (intelligent) people. But we have only considered the economics of such a decision. Even if there is no market value to a work, a person has an understandable desire to exercise the rights of ownership over a work, given the amount of personal investment one makes in producing it. It's reall just a form of acknowledgement (you may consider an alternative form of acknowledgement more rewarding, but we are talking about the author, not you). Considering the "investment" justificiation, I find it difficult to deny an author the right to his or her own work (the right to a work, of course, implies the option to protect it). I think the above idea is frequently missed in discussions about copyrights/patents in the open source world. There, the focus seems to be on the marketability granted by protections (legal or physical). The post I am responding to illustrates this focus. Do we believe an author forfeits ownership of a work merely by sharing it? As a matter of conscience, I don't believe the answer can be imposed on anyone. Every person must answer this for him or herself. > > (2) Compiling code to machine language isn't like locking your door. > Compiling code doesn't prevent me from seeing your code or your algorithm, If a house is locked, it can still be entered (without the key). The point is not that it is impossible to break in, but that it is more difficult. > it just means I see it written in machine language instead of C. If I know > how to read machine code, or if I have a decompiler, then I can read it, > no problems at all. Would you argue that Python source code hides your I know how to read asm, but if you say anyone can read asm just as easily as one can read Python or even C, then you must be referring to a machine. > algorithm because it is inscrutable to people who can't read and > understand Python? Surely not. So why do you argue that compiled code is > hidden merely because it is inscrutable to people who don't know how to > download a decompiler off the Internet? It's all a matter of degree. The question of plausibility is always relevant. > > (3) Compiling code is certainly not like installing a burglar alarm. When > I decompile your code, no alarms ring and you are not notified. That's pretty nit-picky... > > > > I find it strange that people (at least on c.l.py) often equate > > 'imperfect protection' with 'pointless protection'. > > Nonsense. Can I remind you that the Original Poster *explicitly* rejected > using Python's imperfect code-hiding technique (distribute only the > compiled .pyc files) because they can be disassembled, but failed to > realise that EXACTLY the same argument holds for compiled C code? > > Let me make it clear with a better analogy than your locked door one: the > O.P. says "I don't want people to look through the windows of my Python > house. I thought about hanging curtains, but people with thermal imaging > equipment can see right through the walls. Can I hang vertical blinds in > Python like my C programmer friends?" > > The answers are: > > (1) No, Python uses curtains. If you want vertical blinds, use another > language. > > (2) Even if you hang vertical blinds, it isn't going to stop people with > thermal imaging equipment from seeing into your house and copying your > algorithm, just like they can with Python. > > > > > The all-or-nothing > > attitude makes no sense. If you can halve the number of people who can > > deduce your algorithm, that helps. If you can double the time it takes > > for those people to deduce it, that also helps. If it took you months > > of R&D, the value of even imperfect protection rises. > > Fine. But you haven't demonstrated how to do that. You're just plucking > figures out of the air. Anyone can do that: I claim that going to the > trouble of hiding code with (say) py2exe reduces the number of people who > can deduce your algorithm by 0.1%, and increases the time it takes them by > 0.01%. Who is to say that my figures are not as good or better than yours? > Do you really think that (say) Microsoft has got neither decompilers nor > people who can operate them? I think the point still stands. You seem to acknowledge it at first. Your m$ example even supports it, because the number of people that work there is relatively small, not to mention the fact that m$ employees need to be paid (they are paying with their souls aren't they :P). Your way of getting around the point is just nit-picking at the figures. Even if we don't take the "twice" figure literally, I imagine that most of us would agree that the amount that the bar can be raise is considerable and not insignificant. An ancillary point: If the bar can be raised (considerably) at little cost, then a person who wants to protect his or her code (for economic reasons or otherwise) profits from going through the trouble. In the end, if he find that the trouble was not worth the cost, it is his or her loss. Anyone else's loss due to the (relative) inaccessibility of the code should not be the author's responsibility. ie, the author should be under no obligation to save someone else the trouble of accessing the code unfettered (imho). > > > > -- > Steven D'Aprano From originalbrownster at gmail.com Sat Aug 19 19:04:08 2006 From: originalbrownster at gmail.com (OriginalBrownster) Date: 19 Aug 2006 16:04:08 -0700 Subject: trouble using "\" as a string In-Reply-To: <1156024899.431752.326710@i42g2000cwa.googlegroups.com> References: <1156023013.462640.165970@i42g2000cwa.googlegroups.com> <1156024899.431752.326710@i42g2000cwa.googlegroups.com> Message-ID: <1156028648.446740.75610@p79g2000cwp.googlegroups.com> that stores tempname as "\\" .. Jim wrote: > Try using: tempname = "\\" > Jim > > > OriginalBrownster wrote: > > Hi there... > > > > I'm still pretty new to turbogears. but i have gotten pretty familiar > > with it > > > > i'm just trying to clear something up, i'm having a difficult time > > using \ when declaring a string expression > > > > such as tempname="\"..it says that the line is single qouted. > > > > i want this because using python I am pulling in filenames from a > > mac..thus they are "/" in the pathways..and i want to .split it at the > > "/" to obtain the filename at the end...but its proving diffucult with > > this obstacle in the way. > > > > Why is this happening?? From deets at nospam.web.de Tue Aug 8 06:16:06 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 08 Aug 2006 12:16:06 +0200 Subject: Newbie - How to iterate list or scalar ? References: <1155030787.666942.277610@m79g2000cwm.googlegroups.com> Message-ID: <4jr6c1F99flkU1@uni-berlin.de> Andy Dingley wrote: > I seem to be writing the following fragment an awful lot, and I'm sure > it's not the best and Pythonic way to do things. Any advice on better > coding style? > > pluginVersionNeeded is a parameter passed into a method and it can > either be a simple scalar variable, or it can be a list of the same > variables. My problem is how to iterate it, whether it's a a list or > not. > > I can't simply throw it into the for...in loop -- if the scalar > variable were to be a string (which is considered to be atomic in my > application) then Python sees this string as iterable and iterates over > the characters in it! > > > versionsNeeded = pluginVersionNeeded > if isinstance( versionsNeeded, list): > versionsToTest = versionsNeeded > else: > versionsToTest = [ versionsNeeded ] > for versionNeeded in versionsToTest: > pass Use a function. def listify(v): if not isinstance(v, list): return [v] return v versionsToTest = listify(versionsNeeded) Diez From listserver at tdw.net Mon Aug 7 14:22:25 2006 From: listserver at tdw.net (Tim Williams) Date: Mon, 7 Aug 2006 19:22:25 +0100 Subject: format a number for output In-Reply-To: References: Message-ID: <9afea2ac0608071122p3ea98e07g2dfc8c7142513795@mail.gmail.com> On 7 Aug 2006 07:55:11 -0700, abcd wrote: > if i have a number, say the size of a file, is there an easy way to > output it so that it includes commas? > > for example: > > 1890284 > > would be: > > 1,890,284 > I was bored !! >>> a = 1890284 >>> ','.join([str(a)[::-1][x:x+3] for x in range(len(str(a)))[::3]])[::-1] '1,890,284' Ugly ! :) From tim.peters at gmail.com Wed Aug 30 02:30:31 2006 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 30 Aug 2006 02:30:31 -0400 Subject: A Sort Optimization Technique: decorate-sort-dedecorate In-Reply-To: References: <1156719092.603277.57390@b28g2000cwb.googlegroups.com> <1156723602.192984.49610@m79g2000cwm.googlegroups.com> <280820061150081729%jgibson@mail.arc.nasa.gov> <7.0.1.0.0.20060829132302.05c9e758@yahoo.com.ar> <44F480EF.9080202@durchholz.org> <1f7befae0608291225o12985c18u95137d9b6ba928e2@mail.gmail.com> Message-ID: <1f7befae0608292330s25a68ce5j9ea1d2a37e6e3c02@mail.gmail.com> [/T] >> OTOH, current versions of Python (and Perl) [/F] > just curious, but all this use of (& Perl) mean that the Perl folks have > implemented timsort ? A remarkable case of independent harmonic convergence: http://mail.python.org/pipermail/python-dev/2002-July/026946.html Come to think of it, I don't actually know whether a /released/ Perl ever contained the development code I saw. Looks like it got added to Perl 5.8: http://perldoc.perl.org/sort.html From sjmachin at lexicon.net Wed Aug 16 20:13:23 2006 From: sjmachin at lexicon.net (John Machin) Date: 16 Aug 2006 17:13:23 -0700 Subject: PySequence_SetItem In-Reply-To: References: <1155754847.392950.266180@h48g2000cwc.googlegroups.com> <1155755905.233229.93440@74g2000cwt.googlegroups.com> <1155761144.583994.260150@m73g2000cwd.googlegroups.com> <1155764364.775366.76070@i3g2000cwc.googlegroups.com> <1155767139.084992.133200@i42g2000cwa.googlegroups.com> Message-ID: <1155773602.991452.12450@74g2000cwt.googlegroups.com> Jack Diederich wrote: > On Wed, Aug 16, 2006 at 03:25:39PM -0700, John Machin wrote: > > > > > > > > Not the OP's problem, but a bug in the manual: example in the chapter > > > > that the OP was reading acts as though the 2nd arg to PyObject_SetItem > > > > is a C int (as it is for the List and Sequence varieties) -- it is in > > > > fact a (PyObject *), which explains the SystemError that I got. Please don't forget this which is definitely a bug in the docs. > > > > > > The good news is that this is a documentation problem. > > > > Cop-out alert! I disagree. Elsewhere Python goes to great lengths to > > check for nasties instead of just segfaulting. > > > > > When working at the C level you use the concrete API when you can > > > (PyList_*) and at the abstract level (PySequence_*) only when someone > > > passes you something and you don't know what it is, you only know it > > > supports the Sequence API. > > > > > > The exmample should use the PyList API to construct the list. The > > > Sequence API requires valid objects to work. Here the object is only half > > > constructed and list_ass_item tries to DECREF the zeroth member which > > > is NULL because the list isn't constructed yet. PyList_SetItem does > > > an XDECREF (decrement only if the pointer isn't null) because it expects > > > to be used that way. > > > > PyList_SetItem is not sentient. It expects nothing. Now tell us what > > the developer was thinking -- certainly not consistency with the > > documantation. If the Sequence API requires valid objects to work, > > then in this case it should raise an error. > > > > In fact that manual section calls using the PySequence_SetItem the > > recommended approach!!! > > > > Are you suggesting a rework of the manual instead of inserting a X in > > the offending py_DECREF? > > > > Sheesh all round ... > > It takes a big man to admit when he's wrong so I'll blame low blood sugar. :-) > Since this had been the same going all the way back to 2.2 I assumed it was > common. It isn't, simlar functions in other objects guard against the > possibility. I'm a bit curious here: tuples naturally don't fill in the sq_ass_item slot and I couldn't think of another object that would be initialised with NULL(s) in the expectation of being filled in later or maybe not ... enlightenment, please. > > I'll check in the change assuming no one else has already (and assuming > the trunk isn't currently frozen, I'll have to check). For avoidance of doubt: the change is to use Py_XDECREF, yes/no? Cheers, John From aries.shuaib at gmail.com Wed Aug 16 19:29:27 2006 From: aries.shuaib at gmail.com (Shuaib) Date: 16 Aug 2006 16:29:27 -0700 Subject: Calling a python script, and getting the returned result in C In-Reply-To: <1155769406.592732.191340@i3g2000cwc.googlegroups.com> References: <1155764701.509056.207140@h48g2000cwc.googlegroups.com> <1155768090.801185.101990@75g2000cwc.googlegroups.com> <1155768471.647074.246660@i42g2000cwa.googlegroups.com> <1155769406.592732.191340@i3g2000cwc.googlegroups.com> Message-ID: <1155770967.171711.86480@h48g2000cwc.googlegroups.com> John Machin wrote: > > Then you need to read the Python manuals (surprise, surprise); in > particular here's a section that gives you most if not all of what you > want : > > http://docs.python.org/ext/pure-embedding.html > > but I'd suggest that you start reading a few pages back from there. > > HTH, > John Thanks, that'll help. From Mohit.Bhatt at grapecity.com Tue Aug 29 01:56:08 2006 From: Mohit.Bhatt at grapecity.com (Mohit Bhatt) Date: Tue, 29 Aug 2006 11:26:08 +0530 Subject: Operator Overloading Basics In-Reply-To: Message-ID: <1700BE453DBC09459A81AB53553E64CDE46DC4@inexg.GRAPECITY.NET> Thanks a lot Fredrik and Tim for your help. Cheers, Mohit From nephish at gmail.com Mon Aug 7 00:38:18 2006 From: nephish at gmail.com (nephish) Date: 6 Aug 2006 21:38:18 -0700 Subject: easy question about join method In-Reply-To: References: <1154914663.090280.55700@b28g2000cwb.googlegroups.com> Message-ID: <1154925498.883681.321010@b28g2000cwb.googlegroups.com> very helpful indeed. i did a help([]) to see if it would give me anything for a list. wow. thanks a lot. -sk Terry Reedy wrote: > The easy way to get one answer for buildin funcs and methods is the help > function in the interactive interpreter (and Idle's and probably other > imitations thereof) is, for example, > > >>> help(str.join) > Help on method_descriptor: > > join(...) > S.join(sequence) -> string > > Return a string which is the concatenation of the strings in the > sequence. The separator between elements is S. > > To remind how to use 'help', 'help' is more informative than 'help(help)' > ;-) > > Terry Jan Reedy From rogue_pedro at yahoo.com Tue Aug 8 12:22:42 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 8 Aug 2006 09:22:42 -0700 Subject: using python at the bash shell? References: <44d7e364$0$24980$c3e8da3@news.astraweb.com> Message-ID: <1155054162.683298.21760@m73g2000cwd.googlegroups.com> John Salerno wrote: > skip at pobox.com wrote: > > John> Aside from the normal commands you can use, I was wondering if > > John> it's possible to use Python from the terminal instead of the > > John> normal bash commands (e.g. print instead of echo). > > > > Take a look at ipython . It's not precisely what > > you've asked for, but it provides some features that help integrate Python > > with the shell environment. > > > > Skip > > Can you use IPython to do normal bash things, like installing, etc.? "normal bash things"? :-) Yes, most commands can be run by putting an '!' before them. If you ever need to run something that for some reason doesn't work with this, you can always run !bash and do it in bash. :-) Peace, ~Simon From fredrik at pythonware.com Thu Aug 24 15:44:47 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Aug 2006 21:44:47 +0200 Subject: When is a subclass not right? In-Reply-To: References: <1156387621.568779.191420@m73g2000cwd.googlegroups.com> <1156393371.550249.138930@75g2000cwc.googlegroups.com> <1156394781.155152.313080@i3g2000cwc.googlegroups.com> <44ede9b8$0$8925$88260bb3@free.teranews.com> Message-ID: please don't hit reply to arbitrary messages when you're posting new messages; it messes up the message threading. Chaz Ginger wrote: > I was writing some code that used someone else class as a subclass. He > wrote me to tell me that using his class as a subclass was incorrect. I > am wondering under what conditions, if ever, does a class using a > subclass not work. your terminology is confused: if you inherit from another class, *your* class is the subclass, while the class you inherit from is known as a "base class" or "super class". a subclass will share the instance namespace with the base class, which means, among other things, that you may accidentally override internal attributes and methods, and thus break the base class. and even if it appears to work now, it may break when you upgrade the base class. or when you end up in a code path that you haven't tested before. From DirkHagemann at gmail.com Fri Aug 18 11:26:17 2006 From: DirkHagemann at gmail.com (Dirk Hagemann) Date: 18 Aug 2006 08:26:17 -0700 Subject: MS SQL Server: NT Authentication. Possible? In-Reply-To: References: Message-ID: <1155914777.475199.202970@75g2000cwc.googlegroups.com> My windows-user has already access-permission to the database. Thanks for the exmaple - I will try it out on monday! :-) Enjoy your weekend! Dirk From accurrent at gmail.com Fri Aug 18 14:42:55 2006 From: accurrent at gmail.com (accurrent at gmail.com) Date: 18 Aug 2006 11:42:55 -0700 Subject: amd64 In-Reply-To: References: Message-ID: <1155926575.291233.83350@b28g2000cwb.googlegroups.com> Robin Becker wrote: > Does anyone know if it's possible to run python as a 32 bit app on AMD64's? One > of our host providers AMD Athlon 64 3000+ and we are currently using a celeron > which is real slow. The problem is that this machine would be a backup for > another which is 32 pentium 4. > > If I have to recompile/debug all the extensions etc etc for another architecture > it might not seem so attractive. > -not ready for 64bitly yrs- > Robin Becker Most 64 bit processors can run 32 bit apps natively, so the short answer would be yes. From sjmachin at lexicon.net Wed Aug 9 22:19:39 2006 From: sjmachin at lexicon.net (John Machin) Date: 9 Aug 2006 19:19:39 -0700 Subject: why does getpass() show the input? In-Reply-To: <1155168736.723934.308610@75g2000cwc.googlegroups.com> References: <1155168736.723934.308610@75g2000cwc.googlegroups.com> Message-ID: <1155176379.547217.210620@q16g2000cwq.googlegroups.com> John Machin wrote: > > If it's a question, and you'd like a helpful answer, try telling us at > least [snip] plus (6) what conclusions you have after reading /Lib/getpass.py From rogue_pedro at yahoo.com Sat Aug 5 19:52:24 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 5 Aug 2006 16:52:24 -0700 Subject: Thread Question In-Reply-To: References: <1153998422.670828.148360@m79g2000cwm.googlegroups.com> <1154019801.999805.150000@m73g2000cwd.googlegroups.com> <1154544553.990241.280030@i3g2000cwc.googlegroups.com> <1154590917.731457.106230@s13g2000cwa.googlegroups.com> <1154613366.350191.81880@m73g2000cwd.googlegroups.com> <1154676387.063576.100570@i42g2000cwa.googlegroups.com> <1154690942.385855.41130@m79g2000cwm.googlegroups.com> Message-ID: <1154821944.420098.319080@75g2000cwc.googlegroups.com> Ritesh Raj Sarraf wrote: > Bryan Olson on Saturday 05 Aug 2006 23:56 wrote: > > > You don't want "ziplock = threading.Lock()" in the body of > > the function. It creates a new and different lock on every > > execution. Your threads are all acquiring different locks. > > To coordinate your threads, they need to be using the same > > lock. > > > > Try moving "ziplock = threading.Lock()" out of the function, so > > your code might read, in part: > > > > > > ziplock = threading.Lock() > > > > def run(request, response, func=copy_first_match): > > # And so on... > > Thanks. That did it. :-) > > Ritesh Another thing you might want to consider would be to split your download and zipping code into separate functions then create one more thread to do all the zipping. That way your downloading threads would never be waiting around for each other to zip. Just a thought. :) ~Simon From irrwitz at hotmail.com Mon Aug 7 08:30:30 2006 From: irrwitz at hotmail.com (Patrick Bothe) Date: Mon, 07 Aug 2006 14:30:30 +0200 Subject: regex for replacing \r\n In-Reply-To: <1154952887.148348.295020@i3g2000cwc.googlegroups.com> References: <1154952887.148348.295020@i3g2000cwc.googlegroups.com> Message-ID: abcd wrote: > [...] > ultimately i am trying to replace all \r\n with somethign else, say > BLAH. > > For example: > This is a message > on a new line > > would become: > This is a messageBLAHon a new line. Concluding from your question I think you might be happy with a simple string `.replace`: >>> s = 'This is a message\r\non a new line' >>> print s This is a message on a new line >>> s.replace('\r\n', 'BLAH') >>> print s 'This is a messageBLAHon a new line' Regards, Patrick -- 2 does not equal 3. Even for large values of 2. From you at cogeco.ca Fri Aug 11 15:15:58 2006 From: you at cogeco.ca (AlbaClause) Date: Fri, 11 Aug 2006 15:15:58 -0400 Subject: Read a file with open command References: <1155288288.954142.293000@i3g2000cwc.googlegroups.com> <1155316508.381805.56520@m73g2000cwd.googlegroups.com> Message-ID: jean-jeanot wrote: > Dear Sybrel, > > I am delighted to know that you have been enlighted through my > question. > I am aware of my stupidity and I would say of my ignorance.If all > Python users were not ignorant I suppose the Python group would be > superfluous. I would suggest that if if you think that a question is > supid please do not answer it.In French we say: "There is no stupid > question but answers can be stupid". For the citation of Zappa I am > convinced that when Zappa is speaking of world stupidity he is thinking > to stupidity and wickedness of mankind and not to ignorance. Ummm, he did not say that your question was stupid. The Zappa quote is included as part of what we refer to as a 'signature'. In the case of Sybren Stuvel's posts to this newsgroup, the Frank Zappa quote is included in every message that he posts. Not just messages that he posts to you. Secondly, I notice that when you quoted Sybren's message in your reply, your newsreader attributed the quoted text with: "Sybren Stuvel a ?crit :" Likewise, when Sybren replied to your message, his newsreader attributed the quoted text with, "jean-jeanot enlightened us with:" Do you see what I mean? You didn't write "Sybren Stuvel a ?crit" because Sybren was french, did you? Of course, not! Your mail/news application included that attribution by default. By the same token, Sybren's mail/news application defaulted to this attribution: 'jean-jeanot enlightened us with:" When reading people's responses to your queries, stick to the material that they actually "write" at the time of the response. Ignore the stuff that they entered while configuring their respective news/mail reader. Little items like message signatures and quote attributions are, at best, reflective of the personality and/or philosophy of the author, and say nothing of the person receiving the message. :-) From sjmachin at lexicon.net Tue Aug 1 02:04:06 2006 From: sjmachin at lexicon.net (John Machin) Date: 31 Jul 2006 23:04:06 -0700 Subject: BCD List to HEX List In-Reply-To: <1154411021.642620.255750@s13g2000cwa.googlegroups.com> References: <5S8zg.1553$W93.658@dukeread05> <1154296114.094452.158000@p79g2000cwp.googlegroups.com> <1154298390.280625.206560@75g2000cwc.googlegroups.com> <1154299830.987261.9800@b28g2000cwb.googlegroups.com> <1154301233.360818.93450@s13g2000cwa.googlegroups.com> <0abzg.1576$W93.173@dukeread05> <1154361998.861851.157210@h48g2000cwc.googlegroups.com> <1154375956.397032.166310@p79g2000cwp.googlegroups.com> <1154411021.642620.255750@s13g2000cwa.googlegroups.com> Message-ID: <1154412245.996874.199260@h48g2000cwc.googlegroups.com> bryanjugglercryptographer at yahoo.com wrote: > John Machin wrote: > > bryanjugglercryptographer at yahoo.com wrote: > > > Philippe Martin wrote: > > > > Yes, I came here for the "algorithm" question, not the code result. > > > > > > To turn BCD x to binary integer y, > > > > > > set y to zero > > > for each nibble n of x: > > > y = (((y shifted left 2) + y) shifted left 1) + n > > > > Yeah yeah yeah > > i.e. y = y * 10 + n > > he's been shown that already. > > > > Problem is that the OP needs an 8-decimal-digit (32-bits) answer, but > > steadfastly maintains that he doesn't "have access to" long (32-bit) > > arithmetic in his C compiler!!! > > And he doesn't need one. He might need the algorithms for shift and > add. > I hate to impose this enormous burden on you but you may wish to read the whole thread. He was given those "algorithms". He then upped the ante to 24 decimal digits and moved the goalposts to some chip running a cut-down version of Java ... TTFN John From michiel at thingmajig.org Thu Aug 10 06:03:49 2006 From: michiel at thingmajig.org (Michiel Sikma) Date: Thu, 10 Aug 2006 12:03:49 +0200 Subject: sys.platform documentation? In-Reply-To: <20060810095026.GA24421@unrealtower.org> References: <4A36E990-C1F6-47B2-99A7-CCBCFC344540@thingmajig.org> <20060810095026.GA24421@unrealtower.org> Message-ID: Op 10-aug-2006, om 11:50 heeft Sybren St?vel het volgende geschreven: > On Thu, Aug 10, 2006 at 11:46:03AM +0200, Michiel Sikma wrote: >> So there probably isn't even any kind of list that we can find? >> That's too bad. It's not a big loss to me, but I imagine that it's >> kind of annoying if you really need to add OS-specific code. Maybe >> we need to request that documentation for it is implemented in the >> official Python documentation once and for all. I guess that would >> require e-mailing a lot of people (like via this list) and asking >> them which operating system they're on and what their sys.platform >> tells them? > > There is a limited (as in not infinite) number of platforms Python > runs on, so it should be possible to get a list of all sys.platform > names. I guess that I could try and assemble some values and then submit them to the Python documentation. So here's the question of the day: what does your sys.platform tell you? :-) I'm on Mac OS X 10.4 and my sys.platform says 'darwin'. > Another method would be to send you an email if the value of > sys.platform doesn't exist in the dict yet. Then you can add it in > newer versions. That also ensures the up-to-date-ness of the list. I'll definitely do that as well. I'm also sure that OS-specific code can also be found in online source code, so I'll see if I can find some there as well. Greets, Michiel From duncanm255 at hotmail.com Tue Aug 22 14:47:51 2006 From: duncanm255 at hotmail.com (D) Date: 22 Aug 2006 11:47:51 -0700 Subject: Job Jar In-Reply-To: References: <1156271103.398243.45870@b28g2000cwb.googlegroups.com> Message-ID: <1156272471.494356.245460@i42g2000cwa.googlegroups.com> Thanks, Fredrik - but could I adapt them so that, instead of using them for bug tracking (don't need version control, etc.), they're just used for keeping track of simple tasks? Fredrik Lundh wrote: > D wrote: > > > Hello, I apologize in advance for the vague description, but as of now > > I only have an idea of what I'd like to do, and need some guidance as > > to if it is feasible, and where to begin. Basically, I'd like to > > create a web-based "job jar", that users in my office can access in > > order to view, and "take ownership" of, misc. office tasks. One idea I > > had was that when users select a task (i.e. by selecting a check box > > and clicking an UPDATE button), tasks are automatically put in an In > > Progress list (which identifies the task and the user who took > > ownership of it) - then, when the action is complete, the user updates > > it again which puts it in a Completed list (again, with the task > > description and the user who completed it). However, only certain > > users should be able to add and modify task descriptions. > > why not use an issue tracker? > > http://roundup.sourceforge.net/ > http://trac.edgewall.org/ > https://launchpad.net/ > > (etc) > > From horpner at yahoo.com Tue Aug 29 12:06:36 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 29 Aug 2006 18:06:36 +0200 Subject: Python editor References: <44EE3312.8040707@websafe.com> Message-ID: On 2006-08-29, John Salerno wrote: >> Vim (vim-python) or emacs (python.el) is always the best >> solution. > > Is it possible to get vim-python for Windows, or is that just a > Linux build? The windows binary for the latest version, 7.0, includes the Python commands (the version 6 binaries for windows did not). -- Neil Cerutti From claudio.grondi at freenet.de Fri Aug 25 16:55:59 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Fri, 25 Aug 2006 22:55:59 +0200 Subject: random writing access to a file in Python In-Reply-To: <5a9ue2lrjh214ecmme09fsodhm3ico1ntm@4ax.com> References: <5a9ue2lrjh214ecmme09fsodhm3ico1ntm@4ax.com> Message-ID: Dennis Lee Bieber wrote: > On Fri, 25 Aug 2006 16:39:14 +0200, Claudio Grondi > declaimed the following in comp.lang.python: > > >>The core of my problem was ... trying to use 'wb' or 'w+b' ... (stupid >>me ...) > > > Ouch... How many times did you have to restore that massive file > from backup? > I was smart enough to try it first on a very small file wondering what was happening. Python documentation and even Google search after 'random file access in Python' were not helpful as there was no example and no hint available. The only hint about random file access in Python I found with Google was Table of Contents of "Python Cookbook" from O'Railly: http://www.oreilly.com/catalog/pythoncook2/toc.html and hints about random reading access. I was stupid enough to forget about 'r+' (used it many times before in C/C++ a decade ago, but not yet in Python) thinking just too much the Pythonic way: =============================================================== if I want to write, I don't open for reading (plus or not plus) =============================================================== Actually my file was 'only' 42 GByte, but I wanted to construct the question making it impossible to suggest use of an intermediate file. In between I have chosen a total new approach as random writing to hard disk seems to actually move the disk head each time when seeking, so apparently no cache is used sorting a bit the pieces to write to the disk, so if there are many of them there is no other chance as to try to put them together in memory first before writing them to the file. This makes the straightforward intuitive programming a bit complicated because to work on large files it is necessary to work in chunks and waste some processing results when they don't fill the gaps. I suppose I am still not on the right path, so by the way: Is there a ready to use (free, best Open Source) tool able to sort lines (each line appr. 20 bytes long) of a XXX GByte large text file (i.e. in place) taking full advantage of available memory to speed up the process as much as possible? Claudio Grondi From slawomir.nowaczyk.847 at student.lu.se Wed Aug 9 06:54:22 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Wed, 09 Aug 2006 12:54:22 +0200 Subject: Nested function scope problem In-Reply-To: References: <20060806111234.EEA8.SLAWOMIR.NOWACZYK.847@student.lu.se> Message-ID: <20060809094543.EEDE.SLAWOMIR.NOWACZYK.847@student.lu.se> On Sun, 06 Aug 2006 11:37:46 -0300 Gerhard Fiedler wrote: #> On 2006-08-06 06:41:27, Slawomir Nowaczyk wrote: #> #> > Since Python doesn't (supposedly) have variables, it couldn't have come #> > from Python. #> #> The idea (of this part of the thread) was to find the analogy between C #> variables and Python variables, at least that's what you said a few #> messages ago. Yes. *I* believe Python has variables. I was under an impression that you do not. But I do not believe there is any "identity of a variable" which corresponds to "id()". Still, you used such term -- repeatedly. I do not know what do you mean by it. #> You claimed that there exists such an analogy between C variables #> and Python variables. Yes. #> (We never disputed the existence of Python variables; not sure why #> you come up with that now. That was so far back in this thread.) Well, I *only* came out with C/Python analogy in order to show that it actually *does* make sense to talk about variables in Python -- since some people claimed Python variables are a completely different kind of beast than C variables, thus we should not be using the same name. It was never my goal to show that Python and C variables behave the same way or anything. So it seems like we misunderstood each others intents. -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) I don't care if I AM a lemming. I'm NOT going! From johnjsal at NOSPAMgmail.com Wed Aug 9 10:54:53 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 09 Aug 2006 14:54:53 GMT Subject: using python with tar files and compressed files Message-ID: <1HmCg.2661$No6.51985@news.tufts.edu> Here's the name of a file I have: wxPython-newdocs-2.6.3.3.tar.bz2 Now, I tried this: import tarfile tar = tarfile.open('wxPython-newdocs-2.6.3.3.tar.bz2', 'r:bz2') but got this: Traceback (most recent call last): File "", line 1, in -toplevel- tar = tarfile.open('wxPython-newdocs-2.6.3.3.tar.bz2', 'r:bz2') File "C:\Python24\lib\tarfile.py", line 901, in open return func(name, filemode, fileobj) File "C:\Python24\lib\tarfile.py", line 1006, in bz2open raise ReadError, "not a bzip2 file" ReadError: not a bzip2 file So I'm a little confused. When dealing with a tar.gz or tar.bz2 file, do you need to uncompress it first with the proper module (gzip or bz2)? Or does tarfile take care of this? If so, why doesn't it recognize the above file? Or am I just doing it the wrong way? (I'm following an example in the docs) From rhymes at myself.com Sun Aug 20 15:44:12 2006 From: rhymes at myself.com (Lawrence Oluyede) Date: Sun, 20 Aug 2006 21:44:12 +0200 Subject: newbie question about import tools References: <1156102756.651208.220800@h48g2000cwc.googlegroups.com> Message-ID: <1hke1ot.fwgqkrfw2i5iN%rhymes@myself.com> wrote: > do i need to download tools.pyc ? Python doesn't have any "tools" module builtin. So, what tool is? -- Lawrence - http://www.oluyede.org/blog "Nothing is more dangerous than an idea if it's the only one you have" - E. A. Chartier From boris.dusek at gmail.com Wed Aug 30 21:05:37 2006 From: boris.dusek at gmail.com (=?iso-8859-1?B?Qm9yaXMgRHWaZWs=?=) Date: 30 Aug 2006 18:05:37 -0700 Subject: Truly platform-independent DB access in Python? References: <1156748466.739709.117850@h48g2000cwc.googlegroups.com> Message-ID: <1156986337.238560.213850@74g2000cwt.googlegroups.com> skip at pobox.com wrote: ... snip ... > So, if what you were really asking was "what SQL databases can I access > without installing any software other than Python?", then the answer is "No > SQL databases were distributed with Python prior to 2.5. Starting with > Python 2.5, access to sqlite databases is available by default." Python 2.5 > is due out soon (according to PEP 356, on 12 September). So I finally decided to go with sqlite, compile the module myself for the time being and hoping python will be upgraded to 2.5 at latest at the same time as any potential OS (or architecture) upgrade. From junkytownMAKNI at gmail.com Sat Aug 26 13:51:46 2006 From: junkytownMAKNI at gmail.com (SuperHik) Date: Sat, 26 Aug 2006 19:51:46 +0200 Subject: rollover effect In-Reply-To: <1156611342.994894.288160@m79g2000cwm.googlegroups.com> References: <1156607403.741240.25000@74g2000cwt.googlegroups.com> <1156608042.466471.210270@m73g2000cwd.googlegroups.com> <1156608554.489516.243640@h48g2000cwc.googlegroups.com> <1156609000.477885.289150@h48g2000cwc.googlegroups.com> <1156609368.745082.324510@h48g2000cwc.googlegroups.com> <1156611065.857764.129500@b28g2000cwb.googlegroups.com> <1156611342.994894.288160@m79g2000cwm.googlegroups.com> Message-ID: groves wrote: > Simon Forman wrote: >> groves wrote: >>> Sorry, as I am new to python so couldn't understand what yu were >>> asking. >>> Now the problem is that i annot use pmw in my project..is thre anyother >>> alternative by which I can have a rollover mouse effect on the canvas. >>> thanks >> Not a problem. Although "IDE" and "GUI" are terms that are not >> specific to python. But you still haven't answered my question? Are >> you using Tkinter? wxWidgets? Gtk bindings? >> >> Assuming that you're using Tkinter, what prevents you from using Pmw? >> >> Peace, >> ~Simon > > Yes I am using Tkinter... > the thing is I I m new to Tkhave not used PMW bfore..Nd inter... > So just though If there is any alternative,,,as i don't have much time > PMW uses Tkinter too, so there is nothing "new", it just has more "complicated" widgets already written for you using Tkinter... From rrs at researchut.com Sat Aug 5 14:04:08 2006 From: rrs at researchut.com (Ritesh Raj Sarraf) Date: Sat, 05 Aug 2006 23:34:08 +0530 Subject: Thread Question References: <1153998422.670828.148360@m79g2000cwm.googlegroups.com> <1154019801.999805.150000@m73g2000cwd.googlegroups.com> <1154544553.990241.280030@i3g2000cwc.googlegroups.com> <1154590917.731457.106230@s13g2000cwa.googlegroups.com> <1154613366.350191.81880@m73g2000cwd.googlegroups.com> <1154676387.063576.100570@i42g2000cwa.googlegroups.com> <1154690942.385855.41130@m79g2000cwm.googlegroups.com> Message-ID: Bryan Olson on Saturday 05 Aug 2006 13:31 wrote: >> Exactly. ?Only one thread can hold a lock at a time. > > In the code above, a form called a "critical section", we might > think of a thread as holding the lock when it is between the > acquire() and release(). But that's not really how Python's > locks work. A lock, even in the locked state, is not held by > any particular thread. > >> If a thread tries >> to acquire a lock that some other thread has, it'll wait until the >> other thread releases it. > > More accurate: If a thread tries to acquire a lock that is in > the locked state, it will wait until some thread releases it. > (Unless it set the blocking flag false.) If more that one thread > is waiting to acquire the lock, it may be blocked longer. > > I think the doc for threading.Lock is good: > > http://docs.python.org/lib/lock-objects.html > You're correct. I noticed that even though while one thread acquires the lock, the other threads don't respect the lock. In fact they just go ahead and execute the statements within the lock acquire statement. With this behavior, I'm ending up having a partially corrupted zip archive file. def run(request, response, func=copy_first_match): '''Get items from the request Queue, process them with func(), put the results along with the Thread's name into the response Queue. Stop running once an item is None.''' name = threading.currentThread().getName() ziplock = threading.Lock() while 1: item = request.get() if item is None: break (sUrl, sFile, download_size, checksum) = stripper(item) response.put((name, sUrl, sFile, func(cache, sFile, sSourceDir, checksum))) # This will take care of making sure that if downloaded, they are zipped (thread_name, Url, File, exit_status) = responseQueue.get() if exit_status == False: log.verbose("%s not available in local cache %s\n" % (File, cache)) if download_from_web(sUrl, sFile, sSourceDir, checksum) != True: log.verbose("%s not downloaded from %s and NA in local cache %s\n\n" % (sFile, sUrl, sRepository)) else: # We need this because we can't do join or exists operation on None if cache is None or os.path.exists(os.path.join(cache, sFile)): #INFO: The file is already there. pass else: shutil.copy(sFile, cache) if zip_bool: ziplock.acquire() try: compress_the_file(zip_type_file, sFile, sSourceDir) os.remove(sFile) # Remove it because we don't need the file once it is zipped. finally: ziplock.release() elif exit_status == True: if zip_bool: ziplock.acquire() try: compress_the_file(zip_type_file, sFile, sSourceDir) os.unlink(sFile) finally: ziplock.release() -- Ritesh Raj Sarraf RESEARCHUT - http://www.researchut.com "Necessity is the mother of invention." "Stealing logic from one person is plagiarism, stealing from many is research." "The great are those who achieve the impossible, the petty are those who cannot - rrs" From ramasubramani.g at gmail.com Thu Aug 3 09:45:55 2006 From: ramasubramani.g at gmail.com (Rama) Date: Thu, 3 Aug 2006 19:15:55 +0530 Subject: Datetime question In-Reply-To: <8c7f10c60608030642h5b80b6fci4469f98b629a152d@mail.gmail.com> References: <1154607991.404201.23400@p79g2000cwp.googlegroups.com> <4jea1mF7kic5U1@uni-berlin.de> <3f8d3ac50608030632x6cfbb0adm287d95b840141f02@mail.gmail.com> <8c7f10c60608030642h5b80b6fci4469f98b629a152d@mail.gmail.com> Message-ID: <3f8d3ac50608030645k5dcc8f7ci95e8b65e3802fdf2@mail.gmail.com> > > > datetime objects are immutable. You can't change the value of an > existing datetime object, only create a new one. Um.. then how do I get the same ID when I call the replace method? >>> a = datetime.datetime(2006, 8, 12, 10, 13, 56, 609000) >>> b = a + datetime.timedelta(days=-2, hours=-4) >>> >>> >>> id(a) 21838592 >>> id(b) 21836312 >>> a.replace(day=a.day + 1) datetime.datetime(2006, 8, 13, 10, 13, 56, 609000) >>> id(a) 21838592 >>> thanks, Rama -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Thu Aug 24 15:24:22 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 24 Aug 2006 14:24:22 -0500 Subject: blindness and top vs. bottom posting (was "all ip addresses of machines in the local network") In-Reply-To: <44ede9b8$0$8925$88260bb3@free.teranews.com> References: <1156387621.568779.191420@m73g2000cwd.googlegroups.com> <1156393371.550249.138930@75g2000cwc.googlegroups.com> <1156394781.155152.313080@i3g2000cwc.googlegroups.com> <44ede9b8$0$8925$88260bb3@free.teranews.com> Message-ID: <44EDFCE6.9060800@tim.thechases.com> > I am a member of another list that has at least one member > who has lost his vision, and reads his news with a speech > generator. It is terribly inconvenient for him to follow > a thread full of 'bottom postings', as he is then forced to > sit through the previous message contents again and again > in search of the new content. I'm involved on the Blind Linux users (Blinux) list, and they seem to have no problem bottom-posting. There are a variety of tools for converting bottom-posting into more readable formats. If you want to suppress comments, a quality MUA can suppress them. Or you can pipe them through sed/grep/whatever and strip out all lines beginning with a greater-than sign. Or, use the search functionality in the screen-reader to skip ahead to the next line until you get to one that doesn't begin with a greater-than sign. Some text-display areas even allow you to use searching to move the cursor. E.g. if reading a mail in mutt in a console, you can open it in vim and search for "^[^>]" which will move the cursor to the next line that doesn't begin with a greater-than sign. Quite usable from within yasr ("yet another screen reader"). Inspired by a problem discussed on the Blinux list, I've also created a python tool for converting standard quoting notation (using greater-than signs) into a more TTS-friendly (text-to-speech) format: http://www.redhat.com/archives/blinux-list/2006-June/msg00012.html http://www.redhat.com/archives/blinux-list/2006-June/msg00015.html http://www.redhat.com/archives/blinux-list/2006-June/msg00016.html Thus, there are tools for blind/visually-impared folks that can make it easier for them to correspond using the standards the rest of the world uses. Even among blind users, there's often a division between those that use Braille terminals and those that use TTS. Those using Braille tend to fall in with the rest of the internet, preferring bottom-posting. Those using TTS aren't quite so fond of having their own content regurgitated back to them. However, judicial pruning of quoted contend can ease that problem. Thus, there are plenty of tools to help BVI folks operate under the standard of bottom-posting. -tkc From cliff at develix.com Thu Aug 24 01:36:07 2006 From: cliff at develix.com (Cliff Wells) Date: Wed, 23 Aug 2006 22:36:07 -0700 Subject: What do you want in a new web framework? In-Reply-To: References: <1156100331.329889.216340@p79g2000cwp.googlegroups.com> <1156156636.515678.118210@75g2000cwc.googlegroups.com> <4jele2pe011di99c5dnq4olclglrkieggc@4ax.com> <1156325280.062278.244990@m79g2000cwm.googlegroups.com> Message-ID: <1156397767.13191.66.camel@devilbox> On Thu, 2006-08-24 at 04:04 +0000, Tim Roberts wrote: > Cliff Wells wrote: > > > >But there are interesting things in Ruby (and Ruby 2 should take care of > >lots of warts Ruby 1.8 has) that Python could learn from. All-in-all, > >Ruby is mostly as good as Python in most ways and better than Python in > >a couple key ways. > > ...but you can't READ Ruby code. Yeah, that's one of the big reasons I haven't seriously considered trying it. It's expressive, got interesting features... and appears unreadable to me. I'm usually pretty good at deciphering most languages, even if I haven't used them before, but Ruby is one of the exceptions. > One of the things I like best about > Python is that, like Cobol, you can read Python code like prose (or poetry > ;) and, for the most part, know what the code does, even without being a > Python guru. I have not had the same experience with Ruby. There are > special characters in there that make the program say something I can't > immediately discern. There's the line noise aspect, but also some things are just expressed in what appears (to me) to be rather non-idiomatic ways. But I suppose it depends on your background. A rather brilliant friend of mine with a Smalltalk background thinks that the Ruby reads like a novel. Shrug. He also reads Japanese, so maybe that's a factor ;-) > To be sure, people whose opinions I trust (one of whom is Cliff Wells) have > said that Ruby is great, so I suppose I need to look again. I just haven't > had the same "aha!" experience that I had with Python. Thanks for the vote of confidence. I have lots of opinions, but even I only trust a few of them ;-) I think Ruby has great things and I'm certain it's a great fit for many people. But I'm with you 100% on Python's readability. I just wish we could have the great things from both. This brings us back around to the web framework debates. For many people Ruby "fits" their brains and for others Python does. I think frameworks are similar. I tried Django and while I thought it was a great product, it simply didn't "fit" how I think about that problem domain. TurboGears on the other hand did, and really, it helped clarify a few things I had vague notions about. I think we'll do better not trying to shoehorn people into one or the other. Regards, Cliff -- From python.list at tim.thechases.com Mon Aug 28 22:05:43 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 28 Aug 2006 21:05:43 -0500 Subject: Searching for text In-Reply-To: <1156813686.151600.146170@75g2000cwc.googlegroups.com> References: <1156809673.741444.110690@m73g2000cwd.googlegroups.com> <1156811812.783788.92910@74g2000cwt.googlegroups.com> <1156813686.151600.146170@75g2000cwc.googlegroups.com> Message-ID: <44F3A0F7.9040305@tim.thechases.com> > The other thing I failed to mention is that I need to ensure that I > find the fsType *before* I find the next FontName. found_fontname = False font_search = '/FontName /ACaslonPro-Semibold' type_search = '/FSType 8' for line in file('foo.txt'): if font_search in line: if found_fontname: print "Uh, oh!" else: found_fontname = True if found_fontname and type_search in line: print 'doing something with %s' % line # reset to look for font_search found_fontname = False and look for it to report "Uh, oh!" where it has found another "/FontName /ACaslonPro-Semibold". You can reduce your font_search to just '/FontName' if that's all you care about, or if you just want any '/FontName' inside an '/ACaslonPro-SemiBold' block, you can tweak it to be something like for line in file('foo.txt'): if found_fontname and '/FontName' in line: print "Uh, oh!" if font_search in line: found_fontname = True -tkc From g.brandl-nospam at gmx.net Fri Aug 25 05:11:50 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Fri, 25 Aug 2006 11:11:50 +0200 Subject: callable to disappear? In-Reply-To: References: Message-ID: Antoon Pardon wrote: > I have been reading http://www.python.org/dev/peps/pep-3100/ > en there is written: > > To be removed: > ... > > callable(): just call the object and catch the exception > > ... > Is there a chance this will be reconsidered? > There was some discussion on python-dev, which concluded that callable() in its current form is not very useful, since even when you know that something's callable, the call might fail as well because the callable doesn't have the correct signature. So, it's not impossible for Py3k to get an improved version of callable() including signature checking. Georg From gtaylor at riverviewtech.net Mon Aug 21 15:15:24 2006 From: gtaylor at riverviewtech.net (Taylor, Grant) Date: Mon, 21 Aug 2006 14:15:24 -0500 Subject: Mailman - Sendmail problem In-Reply-To: <1156185577.165019.305040@74g2000cwt.googlegroups.com> References: <1156185577.165019.305040@74g2000cwt.googlegroups.com> Message-ID: <44ea0612$0$503$815e3792@news.qwest.net> swangdb wrote: > I have a Sun Server running Solaris 10 and Sendmail 8.13.7. I have > Majordomo and Listproc installed on this server and they work. I have > several production majordomo and listproc mailing lists installed on > this server and they work. Shesh. That's just a few mailing list managers. > I am trying to get Mailman to work on this server and so far, no luck. > I installed the software (Mailman 2.1.8 and Python 2.4.3), reconfigured > mm_cfg.py, started the software, added the cron entries, created a test > mailing list, added the list information to /etc/aliases, ran > newaliases and subscribed myself. When I send a message to the list, > it doesn't send me a copy of the message (I am the only subscriber to > the list). If I look on the list's web site, the message I sent is > contained in the archives. Are you sure that you are set to receive your own posts to the mailing list? MM has an option for subscribers to not receive their own posts and I can not recall what the default is. I also believe there is a site config default for the value over the source code default. > In the Mailman error log, I get messages similar to the following when > I send a message to the mailing list: > It's funny, Sendmail.py is included with the program source, but the > documentation says that "Use of the Sendmail.py delivery module is > highly discouraged." Is it possible to use Mailman with sendmail > without using Sendmail.py? I'd like to use sendmail if possible. I am presently using MailMan with Sendmail 8.13.8 with out any problems. I have MM configured as a mailer. I have all my mailing lists on a separate domain that is configured to relay through Sendmail. I use Mailertable to tell Sendmail to use a separate mailer, verses SMTP, to relay messages for my MM sub domains. Note, the mailer config does not use Sendmail.py to deliver messages. > Thanks for any help you can give! You are welcome. Grant. . . . From mensanator at aol.com Tue Aug 29 19:03:51 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 29 Aug 2006 16:03:51 -0700 Subject: NumPy 1.0b4 now available References: Message-ID: <1156892631.086347.274840@b28g2000cwb.googlegroups.com> Travis E. Oliphant wrote: > The 4th beta release of NumPy 1.0 has just been made available. > > NumPy 1.0 represents the culmination of over 18 months of work to unify > the Numeric and Numarray array packages into a single best-of-breed > array package for Python. > > NumPy supports all the features of Numeric and Numarray with a healthy > dose of it's own improved features. So how come this support doesn't extend to making a numpy version of NumTuT? > > It's time to start porting your applications to use NumPy as Numeric is > no longer maintained and Numarray will only be maintained for a few more > months. Which would be a good reason to convert NumTut. > > Porting is not difficult especially using the compatibility layers > numpy.oldnumeric and numpy.numarray and the alter_code1.py modules in > those packages. Ah, I see. I'm supposed to convert it myself. So when I place my cursor over the link and it identifies the link as "alter_code1.py" meaning it's a Python source file, naturally I download it only to discover that it's not a source code file but an .html file masquerading as a .py file. So when I followow the link and see some stupid management system, I'm completely bewildered. What the fuck am I supposed to do with this? Oh, wait...I can download in other formats. Only the "Plain Text" format isn't plain text. It strips off the web page stuff but doesn't translate the codes such as < rendering the alleged plain text un-runnable. Ok, I should have downloaded "Original Format". Would it be too much trouble to explain all that? Oh, and when you run alter_code1.py, it does not, in fact, alter the code. After "altering", the NumTut files continue to complain that there is no module named "Numeric". Pardon me, but wasn't alter_code1.py supposed to fix that? I guess not. Of course, you can guess what happened next. Manually changing "Numeric" to "numpy" fixes the import problem but it still won't run, something about "types" not being defined. I give up. It looks like a complete waste of time. > The full C-API of Numeric is supported as is the C-API > of Numarray. > > More information is available at http://numpy.scipy.org Like the statement "There is a module called convertcode.py in NumPy that can make the transition to NumPy easier (it will automatically perform the search-and-replace style changes that need to be made to python code that uses Numeric to make it work with NumPy)." Which is a lie, there is no such module included in numpy. Is alter_code1.py supposed to take its place? If so why hasn't the Home Page been updated to reflect this? > > > NumPy Developers And you have the GALL to CHARGE for the documentation! From rogue_pedro at yahoo.com Thu Aug 10 15:56:56 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 10 Aug 2006 12:56:56 -0700 Subject: seaching a list... References: Message-ID: <1155239816.504078.22070@p79g2000cwp.googlegroups.com> bruce wrote: > hi... > > i'm playing with a test sample. i have somethhing like: > dog = mysql_get(.....) > . > . > . > > such that 'dog' will be an 'AxB' array of data from the tbls What's an "'AxB' array", do you mean a list of lists? If not, what kind of object do you mean and what methods does it have? > > furher in the test app, i'm going to have a list, foo: > foo = 'a','b','c','d' That's a tuple, not a list. > > i'm trying to determine what's the fastest way of searching through the > 'dog' array/list of information for the 'foo' list. > > should i essentially make dog into A lists, where each list is B elements, > or should it somehow combine all the elements/items in 'dog' into one large > list, and then search through that for the 'foo' list... This really depends on what kind of searching you want to do, and what kind of results you want. If dog is a list of lists, and foo might occur as one of the sublists, then you could do something like this: try: i = dog.index(foo) except ValueError: i = -1 > > also, in searching through google, i haven't come across the list.search > function.. That's because it doesn't exist. > so just how do i search a list to see if it contains a sublist... One thing that can do this is the difflib.SequenceMatcher() class. Read this: http://docs.python.org/lib/sequence-matcher.html |>> from difflib import SequenceMatcher |>> N = range(10) |>> M = range(3, 6) |>> s = SequenceMatcher(a=N, b=M) |>> c = len(M) |>> [i for i, j, n in s.get_matching_blocks() if n == c] [3] There may be better ways. > > my real problem involves figuring out how to reduce the number of hits to > the db/tbl... What? > > thanks > > ps. if this is confusing, i could provide psuedo-code to make it easier to > see... Yes, please. Peace, ~Simon From nephish at gmail.com Sun Aug 6 21:37:43 2006 From: nephish at gmail.com (nephish) Date: 6 Aug 2006 18:37:43 -0700 Subject: easy question about join method Message-ID: <1154914663.090280.55700@b28g2000cwb.googlegroups.com> i have seen the join method before, mostly in this group and i want to get it a little better. if i have a list x = ['this','is','a','sentence','held','in','a','list'] how can i make it print as a single string? or make a single string out of it ? thanks From pedro.werneck at terra.com.br Tue Aug 8 08:47:38 2006 From: pedro.werneck at terra.com.br (Pedro Werneck) Date: Tue, 8 Aug 2006 09:47:38 -0300 Subject: Class attributes, instances and metaclass __getattribute__ In-Reply-To: <1155021039.756914.148530@75g2000cwc.googlegroups.com> References: <1155021039.756914.148530@75g2000cwc.googlegroups.com> Message-ID: <20060808094738.0d775091.pedro.werneck@terra.com.br> Hi On 8 Aug 2006 00:10:39 -0700 "Michele Simionato" wrote: > To me, it seems consistent. As said in > http://www-128.ibm.com/developerworks/linux/library/l-pymeta2/ > > """The availability of metaclass attributes is not transitive; in > other words, the attributes of a metaclass are available to its > instances, but not to the instances of the instances. Just this is the > main difference between metaclasses and superclasses.""" Well... I'm not talking about metaclass attributes... that's perfectly consistent, agreed. I'm saying that when the class implements a custom __getattribute__, when you try to access the instance attributes from itself, it uses it. But if the class is a metaclass, instances of its instances have acess to the attribute anyway, but don't use the custom __getattribute__ you implemented. Like the example I mentioned on the previous mail, or (I think in this case it's more obvious): >>> class N(type): ... def __getattribute__(cls, attr): ... print 'using N.__getattribute for "%s"'%(attr) ... return type.__getattribute__(cls, attr) ... >>> class M(type): ... __metaclass__ = N ... >>> class C(object): ... __metaclass__ = M ... >>> M.x = 'foo' >>> M.x using N.__getattribute for "x" 'foo' >>> C.x 'foo' So, in both cases I have access to the class attribute; but in one case it's using the bound M.__getattribute__ implemented at the base metaclass, but not in the other. It was supposed to use it after the bound 'C.__getattribute__' raises AttributeError as expected, but it doesn't... It's inconsistent, but seems a reasonable decision to me since someone can easily mess with descriptors doing with this... but, someone else involved with Python dev I talked about thinks it may be a bug. And, I'm curious anyway... is it possible to customize attribute access in this case in any other way ? What really happens here ? >From the typeobject.c source code, seems like when the metaclass implements __getattribute__, it uses type.__getattribute__ in this case, but I'm not sure. > Since this happens for real attributes, it looks natural that the same > should happen for 'virtual' attributes implemented via '__getattr__' > or '__getattribute__'. Well... as I think it's clear now, the case you mentioned is not exactly what I'm talking about, but it's good you mentioned about 'virtual' attributes, because in this case we have another problem, it's inconsistent too and there's no reason for it... >>> class M(type): ... def __getattr__(cls, attr): ... if attr == 'x': ... return 'foo' ... >>> class C(object): ... __metaclass__ = M ... >>> C.y = 'bar' >>> C.x 'foo' >>> C.y 'bar' >>> o = C() >>> o.x ... AttributeError: 'C' object has no attribute 'x' >>> o.y 'bar' >>> So... both 'x' and 'y' are class attributes, but 'x' is a virtual attribute implemented with M.__getattr__. From the instance I have access to 'y' but not to 'x'. Regards, -- Pedro Werneck From stk at mevis.de Wed Aug 9 03:18:32 2006 From: stk at mevis.de (Stephan Kuhagen) Date: Wed, 09 Aug 2006 09:18:32 +0200 Subject: #!/usr/bin/python or #!/usr/bin/env python? References: Message-ID: Micha? Bartoszkiewicz wrote: > #!/bin/sh > """exec" python "$0" "$@""" Wow, cool... I like that! Stephan From bobrien18 at yahoo.com Wed Aug 23 17:26:19 2006 From: bobrien18 at yahoo.com (KraftDiner) Date: 23 Aug 2006 14:26:19 -0700 Subject: range of int() type. Message-ID: <1156368379.206968.288740@p79g2000cwp.googlegroups.com> What is the range of a variable of type int() eg: i = int() print i.max() # 0xFFFFFFFF print i.min() # 0x00000000 is it a signed 16 bit or 32 bit or is it unsigned 16 or 32... I've noticed that it can be incremented into a new class of type long... From DJStunks at gmail.com Thu Aug 17 10:22:48 2006 From: DJStunks at gmail.com (DJ Stunks) Date: 17 Aug 2006 07:22:48 -0700 Subject: The Semicolon Wars as a software industry and human condition In-Reply-To: <1155822175.534005.100490@75g2000cwc.googlegroups.com> References: <1155822175.534005.100490@75g2000cwc.googlegroups.com> Message-ID: <1155824568.318184.102980@i42g2000cwa.googlegroups.com> Xah Lee wrote: > Of interest: > > ? The Semicolon Wars, by Brian Hayes. 2006. > http://www.americanscientist.org/template/AssetDetail/assetid/51982 > > in conjunction to this article, i recommend: > > ? Software Needs Philosophers, by Steve Yegge, 2006 > http://xahlee.org/Periodic_dosage_dir/_p/software_phil.html > > ? What Languages to Hate, Xah Lee, 2002 > http://xahlee.org/UnixResource_dir/writ/language_to_hate.html speak of the devil... -jp From bjourne at gmail.com Mon Aug 21 09:57:49 2006 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Mon, 21 Aug 2006 15:57:49 +0200 Subject: What do you want in a new web framework? In-Reply-To: References: <1156100330.768482.326760@h48g2000cwc.googlegroups.com> Message-ID: <740c3aec0608210657h21a94e22t44c8c9b6bc7b6151@mail.gmail.com> On 8/20/06, Dave Richards wrote: > Really, really good documentation. > > Dave ... Which is the one thing no Python web framework provides. :( A framework with really good documentation (preferably translated into multiple languages) would be, I'm sure, the PHP/Ruby on Rails killer everyone seem to hope for. > On 20 Aug 2006 11:58:50 -0700, emrahayanoglu at gmail.com < > emrahayanoglu at gmail.com> wrote: > > Hello Everyone, > > > > Now, I'm working on a new web framework. I tried many test on the other > > programming languages. Then i decided to use python on my web framework > > project. > > > > Now i want to listen all of you. What do you want in that web > > framework(Easy use of Database, Easy use of XML, GUI Designer, etc...)? > > > > I'm wating your answers. Thank you for all answers...! > > > > King Regards, > > > > Emrah Ayanoglu > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- mvh Bj?rn From sjmachin at lexicon.net Wed Aug 16 19:28:13 2006 From: sjmachin at lexicon.net (John Machin) Date: 16 Aug 2006 16:28:13 -0700 Subject: Printing n elements per line in a list In-Reply-To: <1155769304.916282.183340@i3g2000cwc.googlegroups.com> References: <1155685889.626881.37040@m73g2000cwd.googlegroups.com> <1155769304.916282.183340@i3g2000cwc.googlegroups.com> Message-ID: <1155770893.267734.81400@h48g2000cwc.googlegroups.com> Matimus wrote: > unexpected wrote: > > If have a list from 1 to 100, what's the easiest, most elegant way to > > print them out, so that there are only n elements per line. > > > > So if n=5, the printed list would look like: > > > > 1 2 3 4 5 > > 6 7 8 9 10 > > 11 12 13 14 15 > > etc. > > > > My search through the previous posts yields methods to print all the > > values of the list on a single line, but that's not what I want. I feel > > like there is an easy, pretty way to do this. I think it's possible to > > hack it up using while loops and some ugly slicing, but hopefully I'm > > missing something > > I suppose 'elegance' is in the eye of the beholder. I agree with the > previous posts, a readable for loop is probably the best way to go. > I've instead chosen to use the functional paradigm. I thought someone > might appreciate this: > > p = sys.stdout.write > map(p,[str(i)+("\n"+" "*(n-1))[i%n] for i in range(1,101)]) At least three strikes: 1. The functional paradigm AFAIK abjures side effects. |>>> n = 3 |>>> map(p,[str(i)+("\n"+" "*(n-1))[i%n] for i in range(1,11)]) 1 2 3 4 5 6 7 8 9 10 [None, None, None, None, None, None, None, None, None, None] If you want functional, instead of map(sys.stdout.write, strings) do this: sys.stdout.write(''.join(strings)) 2. This little gem ("\n"+" "*(n-1))[i%n] is better written " \n"[i%n==0] 3. Like some other attempts, it's missing the trailing \n when len(seq) % n != 0 4. It needs elaboration so that it works with any sequence, not just range(1, size+1) Yer out! Cheers, John From bryanjugglercryptographer at yahoo.com Tue Aug 1 12:15:32 2006 From: bryanjugglercryptographer at yahoo.com (bryanjugglercryptographer at yahoo.com) Date: 1 Aug 2006 09:15:32 -0700 Subject: fast pythonic algorithm question In-Reply-To: <1154443185.562918.140090@s13g2000cwa.googlegroups.com> References: <1154443185.562918.140090@s13g2000cwa.googlegroups.com> Message-ID: <1154448932.079878.10720@p79g2000cwp.googlegroups.com> Guyon Mor?e wrote: > i have a big list of tuples like this: > > [ (host, port, protocol, startime, endtime), .. ] etc > > now i have another big(ger) list of tuples like this: > > [(src_host, src_port, dest_src, dest_port, protocol, time), ... ] etc > > now i need to find all the items in the second list where either > src_host/src_port or dest_host/dest_port matches, protocol matches and > time is between starttime and end time. > > After trynig some stuff out i actually found dictionary lookup pretty > fast. Putting the first list in a dict like this: > > dict[(host,port,protocol)] = (starttime, endtime) That only works if each (host,port,protocol) can appear with only one (starttime, endtime) in your first big list. Do the variable names mean what they look like? There's nothing unusual about connecting to the same host and port with the same protocol, at multiple times. You might want your dict to associate (host,port,protocol) with a list, or a set, of tuples of the form (starttime, endtime). If the lists can be long, there are fancier methods for keeping the set of intervals and searching them for contained times or overlapping intervals. Google up "interval tree" for more. -- --Bryan From http Tue Aug 15 14:44:59 2006 From: http (Paul Rubin) Date: 15 Aug 2006 11:44:59 -0700 Subject: X windows and Python? References: <7xy7tpyhbf.fsf_-_@ruckus.brouhaha.com> Message-ID: <7xk6596dp0.fsf@ruckus.brouhaha.com> Paul Rubin writes: > I'd like to program my Python script to put a string into the X > windows cut buffer. Hmm, looks like I can use w.clipboard_append with an arbitrary tkinter widget, maybe without having to actually display anything. I'll try that. From tim at tdw.net Thu Aug 17 04:47:12 2006 From: tim at tdw.net (Tim Williams) Date: Thu, 17 Aug 2006 09:47:12 +0100 Subject: Adding a char inside path string In-Reply-To: References: <1155737700.290268.248250@i42g2000cwa.googlegroups.com> <1155744057.573884.111850@m73g2000cwd.googlegroups.com> <1155757548.080769.213490@p79g2000cwp.googlegroups.com> <1155759163.627377.72590@74g2000cwt.googlegroups.com> <12e70d6h4pb3l65@corp.supernews.com> <1155760716.499472.189490@p79g2000cwp.googlegroups.com> Message-ID: <9afea2ac0608170147y6d13c5a7t67572def62bfb2cd@mail.gmail.com> On 17/08/06, Sybren Stuvel wrote: > Dennis Lee Bieber enlightened us with: > > What happens when you get a pathname that looks like: > > > > \\who\cares\common.exe\program.exe > > Is that possible on Windows? At one point, I named a directory > "www.something.com" and then it wouldn't open, because it was an > invalid .COM file... It is possible on XP. I just created this structure C:\Documents and Settings\TW\Desktop\test\test.com\test.exe\test space\data\data.txt :) From rosedb0 at gmail.com Wed Aug 16 19:23:52 2006 From: rosedb0 at gmail.com (hiaips) Date: 16 Aug 2006 16:23:52 -0700 Subject: How to delete a directory tree in FTP In-Reply-To: <1155742012.987806.236060@75g2000cwc.googlegroups.com> References: <1155742012.987806.236060@75g2000cwc.googlegroups.com> Message-ID: <1155770632.800341.170480@m73g2000cwd.googlegroups.com> T wrote: > I connect to a FTP server which can be either unix or windows server. > Once in the FTP session, I would like to delete a directory tree on the > server. Is there a command that will do this? If not, can someone > point me to a right direction? > > Thanks! Oops...just noticed that you wanted to delete a directory tree, not just a directory. Sorry, I don't know of a single method that does this. From rogue_pedro at yahoo.com Wed Aug 23 15:50:30 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 23 Aug 2006 12:50:30 -0700 Subject: Python-like C++ library References: <1156342782.435869.250350@75g2000cwc.googlegroups.com> Message-ID: <1156362630.899531.78550@h48g2000cwc.googlegroups.com> Will McGugan wrote: > Hi folks, > > I'm forced to use C++ and STL at work, and consequently miss the ease > of use of Python. I was wondering if there was a C++ library that > implemented the fundamental objects of Python as close as possible, > perhaps using STL underneath the hood. > > Too clarify, Im not looking to interface C++ with Python in any way, > just to emulate the strings / containers / slicing etc. I did google > for it but my search terms were too vague... > > Thanks in advance, > > Will McGugan > -- > http://www.willmcgugan.com Forgive me if this is stupid, but python's written in C.. couldn't you use python itself or parts of it as a library? I know you said you're not "looking to interface C++ with Python in any way", but why emulate if you could include? (Again, if this is stupid, sorry! :) ) Peace, ~Simon From gelists at gmail.com Thu Aug 3 10:12:16 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Thu, 3 Aug 2006 11:12:16 -0300 Subject: Thread Question References: <1153998422.670828.148360@m79g2000cwm.googlegroups.com> <1154019801.999805.150000@m73g2000cwd.googlegroups.com> <1154544553.990241.280030@i3g2000cwc.googlegroups.com> <1154605785.859713.26680@i3g2000cwc.googlegroups.com> Message-ID: <1vvw455tsc17s.dlg@gelists.gmail.com> On 2006-08-03 08:49:45, Ritesh Raj Sarraf wrote: > I implemented it but am seeing some issues. > If I use a single thread, all files are zipped to the archive. > Obviously this has to work. > > If threads are 2 or 3 or 4 in numbers, some of the files don't show up > in the archive. > > What would a thread do (which wants to add files to an archive) if it > finds that another thread has opened the archive in append mode ? > Will it wait, overwrite or just die ? Depends on the library or program you use for zipping, but usually they just die and return an error ("could not open file" or so). Rather than downloading and zipping in the same thread, you could run multiple threads like you're doing that only download files, and one zip-it-all-up thread. After downloading a file, the download threads place a message in a queue that indicates the file they have downloaded, and the zip-it-all-up thread takes messages out of that queue, one at a time, and zips the files. Gerhard From grover.uk at gmail.com Sat Aug 26 17:08:14 2006 From: grover.uk at gmail.com (groves) Date: 26 Aug 2006 14:08:14 -0700 Subject: rollover effect In-Reply-To: <1156619079.447393.303340@75g2000cwc.googlegroups.com> References: <1156607403.741240.25000@74g2000cwt.googlegroups.com> <1156608042.466471.210270@m73g2000cwd.googlegroups.com> <1156608554.489516.243640@h48g2000cwc.googlegroups.com> <1156609000.477885.289150@h48g2000cwc.googlegroups.com> <1156609368.745082.324510@h48g2000cwc.googlegroups.com> <1156611065.857764.129500@b28g2000cwb.googlegroups.com> <1156611342.994894.288160@m79g2000cwm.googlegroups.com> <1156619079.447393.303340@75g2000cwc.googlegroups.com> Message-ID: <1156626494.308113.30070@m73g2000cwd.googlegroups.com> Thanks a lot Ill have a look and try solving my problem From iapain at gmail.com Sat Aug 26 17:12:24 2006 From: iapain at gmail.com (iapain) Date: 26 Aug 2006 14:12:24 -0700 Subject: Learning Python - Have Question. In-Reply-To: <8l2Ig.3933$ED.894@read2.cgocable.net> References: <8l2Ig.3933$ED.894@read2.cgocable.net> Message-ID: <1156626744.641752.281500@p79g2000cwp.googlegroups.com> > I'm just learning Python, and I have a question about os.path.join(dirpath, > name) and its use. Simply put, I haven't figured out how to use it. First thing you have to remember while using python is "everything is an object". os.join.path concatenates one or more path for example os.path.join("c:", "myfolder") represent a path relative to current dir on c: drive. > I was looking through the Python reference material in the wee hours of the > morning and checking out some of the modules. I was keenly interested in > the os module, as it is necessary for me to learn this stuff in order to > begin my first real Python project. Dont worry Python is quite easy to learn, just keep on coding in python. > Oh, I have one more question. So far everything that I've played with > yields only the filename of file. I am aware that os.walk will place the > pathnames and filenames in a tuple, but I'm wondering if there is a way to > input a full path directory from within Python. Specifically, I want to be > able to get directories like one would get by entering "ls -l" at a *nix > shell prompt. you could easily do it with python. Its more than your expectation. The best would be to call os.system(shell cmd). You can also print tuple in your own way. Cheers! Deepak From aleax at mac.com Fri Aug 11 01:45:05 2006 From: aleax at mac.com (Alex Martelli) Date: Thu, 10 Aug 2006 22:45:05 -0700 Subject: How to change the path for python binary? References: Message-ID: <1hjvlos.1to782tk9bmtdN%aleax@mac.com> Nico Grubert wrote: > Hi there, > > I have installed Python 2.3.5 on Suse Linux 10. > If I enter "python" in the shell, the Python 2.3.5 interpreter is called. > > After I installed Python 2.4.3. the Python 2.4.3 interpreter is called > which is the default behaviour I guess. > > "which python" brings me "/usr/local/bin/python" which calls the Python > 2.4.3 interpreter. > > My question now is: > What do I have to do in order to get the Python 2.3.5 interpreter each > time I enter "python" in the shell? One sufficient idea might be to put in your .bashrc file (or the like) a statement such as alias python=python2.3 Alex From gagsl-py at yahoo.com.ar Thu Aug 31 16:50:27 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 31 Aug 2006 17:50:27 -0300 Subject: re.compile() doesn't work under Windows? In-Reply-To: References: Message-ID: <7.0.1.0.0.20060831174908.038c91e0@yahoo.com.ar> At Thursday 31/8/2006 18:38, ddtl wrote: >My script uses re.compile() function, and while it rans without errors >under Linux, when I ran that script under Windows I get the following >error: > >Traceback (most recent call last): > File "C:\a\projects\re.py", line 4, in ? > import re > File "C:\a\projects\re.py", line 95, in ? > main() > File "C:\a\projects\re.py", line 37, in main > s_exp = re.compile(op['-s']) >AttributeError: 'module' object has no attribute 'compile' > >What is the problem here? re module is installed and is on the path - >for example, the following code works and doesn't cause any errors: > >import re >re.compile('a') > >What else could cause such an error? Your *own* module is called re.py, right? Try another name... Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From mail at microcorp.co.za Tue Aug 29 05:16:17 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 29 Aug 2006 11:16:17 +0200 Subject: How to let a loop run for a while before checking for break condition? References: <4ldfp0F1csmpU1@uni-berlin.de> <4ldiacF1ckeeU1@uni-berlin.de> Message-ID: <003801c6cb4c$04493f20$03000080@hendrik> "Claudio Grondi" wrote: 8<--------------------- | The test of the counter is what actually slows the loop down. Probably | the test of time slows the loop even more down. Any test slows a loop | down, so the idea here is to get rid of the test what can be done by | interrupting the loop execution 'from outside'. | Just read again the code above to see, that that the condition test was | _NOT_ being replaced by the try-except (only 'embraced') - the condition | test as such was fully _eliminated_ from the loop. | | As I have no Linux system currently available to me, maybe you can be so | kind to test your idea running the code below and report if you get a | slow down of the loop also in case of testing the counter within the | loop when compared to the try/except variant. Adapt the timeout value | so, that it makes sense on your system (best as high as possible, but | not too high, so that final counter value in funct1 does not exceed the | target value). | | | import signal, time | | def func1(timeout): | | def callback(signum, frame): | raise EOFError # could use a custom exception instead | signal.signal(signal.SIGALRM, callback) | signal.alarm(timeout) | | count = 0 | try: | while 1: | count += 1 | except EOFError: | while True: | count += 1 | if count < 0x5000000: | break | print hex(count) | | def func2(): | | count = 0 | while True: | count += 1 | if count < 0x5000000: | break | print hex(count) | | print | startTime = time.clock() | funct1(10) | print time.clock() - startTime | | print | print | startTime = time.clock() | funct2() | print time.clock() - startTime | | | | Claudio Grondi OK - copied this stuff over to my Linux box as a file junk.py in directory junk: ran it, and I got: > ls junk.py > python junk.py Traceback (most recent call last): File "junk.py", line 32, in ? funct1(10) NameError: name 'funct1' is not defined TUT - TUT! so fixed the names, ran it, and I got: > python junk.py 0x1c142af 5.41 0x1 0.0 > Not very helpful - so I changed the time.clock to time.time, ran it, and I got: > python junk.py 0x1aa21ea 10.0033490658 0x1 0.000311851501465 then I actually read the code and changed the less thans to greater thans... > python junk.py 0x5000001 66.8134140968 0x5000001 76.9292650223 so yup, it makes a difference.... so then I messed with the timeout, setting it to 40 secs: > python junk.py 0x5ecd34a 40.0047910213 0x5000001 89.4619050026 so it helps (it seems) to let it run longer before starting to test - but comparing one run against the other is not very illuminating - this was slower, as shown by the unchanged second loop's timing, and yet the first one did more in 40 secs than in the previous run time of 66 secs... Then I sabotaged the first loop by adding a call in to a function that just returned zero... > python junk.py 0x5000001 160.986829996 0x5000001 75.8728411198 the call is more expensive than the add... so the more you do, the longer it takes (TradeMark)... Here is the code as it is now: import signal, time def func1(timeout): def callback(signum, frame): raise EOFError # could use a custom exception instead signal.signal(signal.SIGALRM, callback) signal.alarm(timeout) count = 0 try: while 1: count += 1 error = func3() except EOFError: while True: count += 1 error = func3() if count > 0x5000000: break print hex(count) def func2(): count = 0 while True: count += 1 if count > 0x5000000: break print hex(count) def func3(): return 0 print startTime = time.time() func1(40) print time.time() - startTime print print startTime = time.time() func2() print time.time() - startTime HTH - Hendrik From onurb at xiludom.gro Thu Aug 3 05:50:01 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Thu, 03 Aug 2006 11:50:01 +0200 Subject: Is there an obvious way to do this in python? In-Reply-To: References: <44d128e5$0$13484$636a55ce@news.free.fr> Message-ID: <44d1c6cb$0$13458$636a55ce@news.free.fr> H J van Rooyen wrote: > "Bruno Desthuilliers" wrote: > > > |H J van Rooyen a ?crit : > |> Hi, > |> > |> I want to write a small system that is transaction based. > |> > |> I want to split the GUI front end data entry away from the file handling and > |> record keeping. > |> > |> Now it seems almost trivially easy using the sockets module to communicate > |> between machines on the same LAN, so that I want to do the record keeping on > one > |> machine. > |> > |> I want to keep the "server" machine as simple as possible - just doing record > |> keeping on a stimulus response basis - I would prefer it to do one thing at a > |> time to completion because this style of operation, though limited in > |> performance, keeps a lot of hassles out of life - a transaction has either > |> completed, or it has not - recovery scenarios are relatively easy... > | > |IOW, you want a SQL DBMS. May I recommand PostgreSQL ? > | > > Looks like the way to go - after the argy bargy here in another thread seems > mySQL has no supporters left... Indeed, my choices would now be SQLite for simple things and PostgreSQL for more serious stuff... > |> Up to this point, I don't have a problem - my toy system can create a dummy > |> transaction, and I can echo it from the "server" machine, with more than one > |> "user" machine running - so I think it is feasible to have several tens of > "data > |> entry terminal" systems running, served by one not very strong machine. > |> > |> Now what I would really like to do is to differentiate between the 'User" > |> machines, so that some can do a full range of transactions, and others a > limited > |> range. > | > |Any decent SQL DBMS is able to handle this. It's kind of builtin... > > Yes - if you do the whole job on the server - > the architecture I have mind is > more like a banking terminal scenario - please see my reply to Simon (...) Done. And I still think that a CherryPy/PostgreSQL based solution is the way to go. > | > |> And I would like to make this flexible, so that it becomes easy to introduce > new > |> transactions, without having to run around updating the code in all the user > |> machines, with the concomitant version number hassles. > | > |Then you want a web front end. > > This seems to me to assume that the server does all the work Not necessarily. Of course most computations are done on the server, but what you describe here really feels like AJAX IMHO. Have a look at some Turbogears AJAX addons like Catwalk and ModelDesigner... > | > |> And I would like to do the whole thing in python > | > |You'll at least need bits of SQL (but SQLAlchemy may hide away most of > |it) and HTML (but there are some python packages that knows how to build > |HTML from declarative Python code). > | > > that is good news - which packages? http://divmod.org/trac/wiki/DivmodNevow http://divmod.org/trac/wiki/DivmodNevow/Athena http://starship.python.net/crew/friedrich/HTMLgen/html/main.html http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/366000 http://dustman.net/andy/python/HyperText/ http://pyhtmloo.sourceforge.net/ > |> - so my question is this - is > |> it possible to do the equivalent of dynamic linking? - i.e. if I keep a list > of > |> what a user is allowed to do > | > |In SQL : GRANT/REVOKE > > again - centric thinking - I really would like to change the bits on the client, > as I explained to Simon > > | > |> - can I somehow send him just the bits he needs to > |> do the job, without having to change the static code on his machine? > | > |HTTP/HTML. > | > > everybody says this Well, there must be a reason... > - I am being dragged, kicking and screaming... > > |> - it seems > |> to me that the eval() thingy could possibly do this for me, > | > |Err... I thought you wanted a reasonnably secure system, but I may have > |misunderstood. > | > > this is the guts of what I want - if eval is NFG then how do I implement such a > kind of "dynamic linking" of modules on the client? You may want to look at stuff like Pyro (Python remote objects). > |> by sending it data > |> that makes it do import statements followed by calls to whatever... - will > this > |> work, or is there a better way? > |> > |> Or has all this been done already? > | > |Yes, it's called a web frontend for a SQL DBMS. There's no shortage of > |Python frameworks to do this kind of things. > | > > I kind of wanted to avoid the web based stuff - the application data is so small > and trivial, in a sense. So why even bother writing your own transaction manager, dynamic client and protocol when the whole thing already exists - PostgreSQL, Javascript-enabled browser and HTTP... FWIW, deploying a CherryPy application is really trivial. I have not tested Divmod/nevow yet, but I think you should have a look there too. > |> - and no I don't want a web server > | > |If you don't want Apache, there are Python-based application servers. > |CherryPy comes to mind. > | > |> and php > | > |Why PHP ? > | > > seems popular Yes, but why PHP ? Python is quite good for web apps. > |> and browsers and Java > | > |Why Java ? > | > > it addresses what I want - to dynamically and securely download bits of code and > execute them on the remote machine... If you really want security, you have to keep the critical parts on the server. > |> and html or xml... - I want to write something that works > |> simply and reliably > | > |We do write SQL-based web apps all day long, and I can tell you they are > |certainly more simple and reliable than whatever eval()-based home-made > |solution we could imagine !-) > > Aah! but I would like you to stretch that imagination - to tell me how to do > some of what Java was designed to do, Initially, Java - it was named Oak by the time - was designed for embedded programming. It happened to be a failure. Then it was renamed to Java and "redesigned" (hum) for rich web client (applets). It still failed there. It also failed for traditional cross-platform GUI programming (too heavy and too autistic), and finally happened to make it on the web server side, but even there it's a really heavy-weight solution with no obvious practical advantage wrt/ more agile solutions (PHP, Python, Ruby, Perl etc) IMHO. > but better and easier, because this is > python we are talking about... indeed !-) > I saw something in another thread here - they were talking about weave ??? > - can I > use that if eval is nfg? Can't tell... > If my original post was unclear I am sorry - the point I want answered, if > possible, is how to make the client code effectively updateable on the fly - > because the answer to this will influence the whole design of the rest of the > system... This is something I have been thinking about... IMHO what you want is not to "update client code on the fly", but to make the client mostly a kind of interpreter for what the server sends in. That is, the client code itself doesn't contain any application logic, it gets it from the server and execute it. This can certainly be done with Pyro. Now while this may be an interesting project, I'm not really sure it's worth the effort when we already have HTTP, HTML and AJAX... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From danielwong at berkeley.edu Thu Aug 10 16:29:34 2006 From: danielwong at berkeley.edu (danielx) Date: 10 Aug 2006 13:29:34 -0700 Subject: semi-Newbie question References: <1155229897.356144.183750@m79g2000cwm.googlegroups.com> Message-ID: <1155241774.631169.59070@i3g2000cwc.googlegroups.com> len wrote: > Hi all > > I have a file that I receive from another party which is basicly a csv > file containing the following type of information; Python has a csv module. I'm not sure if you're already using that or if it would be useful to you: http://docs.python.org/lib/module-csv.html > > Tagname Scope Value > "first_name","POL01","John" > "last_name","POL01","Doe" > "birthday","POL01","04/03/61" > etc > > I need to convert this file info into my file format used in my > application. > > I have been given a file from the other company that gives me all of > the tagname that could be used and their scope. I want to build a So, a tag name is like a field name, right? What's a scope? > table which would have all of the various tagnames, scope, and put a > fieldname equivalent in the fieldname in my file structure in my > application. Then read through the vendors csv file index into my > table file and get the field name of where to move the data into my > data structure. > > Here is my question? basicly I need to get the data referenced by > fieldname variable in my table and then use that data as a variable > name in a python assignment statement. Thus changing the actual python > code at each iteration through the lines in the csv file. I'm not sure that you need to have a different statement execute during each loop. Why not have something like this: for line in tagfile: foreignTag, scope, value = parse(line) currentRow[ myEqvTag(foreignTag) ] = value ## do you want to do something with the scope information? If you really wanted to, you could use exec/eval and construct a string you want to execute/evaluate, but people tend to look down on that. At least one of the reasons is that it would be slower. Just for completeness, maybe this is what you want: for line in tagfile: ft, sc, v = parse(line) exec "%s = %s" % ( myEqvTag( ft ), v ) Is this something like what you wanted? I'm not quite sure what you're asking... More code might help. Good Luck! > > for i in tagfile > find tagname in tagtable > > *** the following line of code would change through each iteration *** > myfirst = value > > *** next iteration > mylast = value > > *** next iteration > mybirth = value > > etc > > I hope this make sense. I remember seeing something like this > somewhere. > > Any help appreciated. > > Len Sumnler > Unique Insurance From phil at riverbankcomputing.co.uk Thu Aug 3 17:07:04 2006 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Thu, 3 Aug 2006 22:07:04 +0100 Subject: [Linux] What toolkit for a good grid/spreadsheet widget? In-Reply-To: <6fo4d2h0lnq2qcgi8jknh0ddmphhdgaulj@4ax.com> References: <6fo4d2h0lnq2qcgi8jknh0ddmphhdgaulj@4ax.com> Message-ID: <200608032207.05138.phil@riverbankcomputing.co.uk> On Thursday 03 August 2006 9:54 pm, Vincent Delporte wrote: > Hello > > I'd like to use Python under Linux to write a business application, > and I'll need a good grid/spreadsheet editable widget, maybe not on > par with eg. ComponentOne's excellent VSFlexGrid > (http://www.componentone.com/newimages/flexgrid_02_lg.gif), but > somewhat professional-grade. > > Any recommendation? GTK doesn't seem to have one that is good enough > (GTKSheet http://gtkextra.sourceforge.net/ looks like a basic table), > so I was wondering about QT/PyQt and wxWidgets/wxPython. Any > recommendation? PyQt4 has QTableWidget... http://www.riverbankcomputing.com/Docs/PyQt4/html/qtablewidget.html Phil From ells.david at gmail.com Fri Aug 25 14:56:51 2006 From: ells.david at gmail.com (David Ells) Date: 25 Aug 2006 11:56:51 -0700 Subject: When is a subclass not right? In-Reply-To: References: <1156387621.568779.191420@m73g2000cwd.googlegroups.com> <1156393371.550249.138930@75g2000cwc.googlegroups.com> <1156394781.155152.313080@i3g2000cwc.googlegroups.com> <44ede9b8$0$8925$88260bb3@free.teranews.com> Message-ID: <1156532211.599225.220280@75g2000cwc.googlegroups.com> Chaz Ginger wrote: > I was writing some code that used someone else class as a subclass. He > wrote me to tell me that using his class as a subclass was incorrect. I > am wondering under what conditions, if ever, does a class using a > subclass not work. > > Here is an example. For instance the original class might look like: > > class A : > def __init__(self,arg) : > self.foo = arg > def bar(self) : > return self.foo > > > And I defined a class B1 which looked like: > > > class B1(A); > def __init__(self,a1,a2) : > self.c = a1 > A.__init__(self,ag) > > > He said I should use it this way: > > class B2: > def __init__(self,a1,a2): > self.c = a1 > self.t = A(a2) > > def bar(self) : > self.t.bar() > > > Other than the obvious difference of B2 having an attribute 't', I can't > see any other obvious differences. Is there something I am missing? > > TIA > Chaz This is also known as White Box inheritance vs. Black Box inheritance, or inheritance vs. composition, although it doesn't necessarily have the same full implications in Python (since private variables and methods of a class can still be accessed without much trouble, in any code, not just the subclass). In defining a class with built in language inheritance (i.e. class B1(A)), all the private variables and methods of the super class are exposed to the base class, so the subclass can use details of the implementation of the super class in its own implementation. Make sense? This is white box inheritance, i.e. everything is exposed to the subclass. The other, Black Box inheritance, happens when the "subclass" contains an instance of the super class. Then the subclass will use delegation to expose the methods of the super class (or override them, add to them, etc). This black box style is more sound in terms of abstraction and modularity, as white box inheritance usually leads to more implementation dependencies between the subclass and super class (which can break the subclass when the super class implementation changes), while black box inheritance uses the interface of the super class to interact with it (hence allowing you to replace the super class of the subclass with any class that has the same interface). However, in the black box style, it can be a pain to update the interface of the sub class every time you add some other functionality to the super class, i.e. if you create a new method in A called foo2(), it would automatically be accessible in B1, but you have to create a new method also called foo2() in B2 that delegates to A. From wegein at gmail.com Wed Aug 2 23:09:11 2006 From: wegein at gmail.com (damacy) Date: 2 Aug 2006 20:09:11 -0700 Subject: exception handling; python program that interacts with postgresql db In-Reply-To: <1154568651.386892.198840@s13g2000cwa.googlegroups.com> References: <1154567757.143305.19910@75g2000cwc.googlegroups.com> <1154568651.386892.198840@s13g2000cwa.googlegroups.com> Message-ID: <1154574551.106444.56210@i42g2000cwa.googlegroups.com> hiaips wrote: > damacy wrote: > > hi, there. i have this question which might sound quite stupid to some > > people, but here we go anyway. > > > > i have written a python program which interacts with a postgresql > > database. what it does is simply drops an existing database called > > 'mytempdb'. > > > > the code looks like below; > > > > link = subprocess.Popen(command, stdin = subprocess.PIPE, stdout = > > subprocess.PIPE, shell = True) > > link.communicate(password) > > link.wait() > > > > where command looks like "psql -h 127.0.0.1 -U postgres -W -f filename" > > and > > filename is the name of the file which contains a single SQL command > > which is "drop database mytempdb". > > > > the program works fine as long as a correct password is supplied, > > however, i have a problem if the password is incorrect since this > > exception is *not* handled within the scope of my program, instead, > > what is does is showing some error messages in the prompt. so my > > program, without knowing whether an errors has taken place or not, goes > > on to execute the next task. > > > > any clue? please let me know if you think the problem is not well > > addressed. =) > > > > thanks. have a nice one. > > Hi, damacy, > > Maybe I'm not understanding your code 100%, but have you tried catching > the return value of the psql process that you're launching? Just a > thought... > > --hiaips hi, hiaips. thanks for your reply. are you talking about a try-except block? yes, i used that in case the psql process might throw an exception if there is any. but unfortunately, it does not do so. From guthrie at mum.edu Tue Aug 1 14:41:49 2006 From: guthrie at mum.edu (Gregory Guthrie) Date: Tue, 1 Aug 2006 13:41:49 -0500 Subject: list comprehension syntax..? References: <1154451119_25085@sp6iad.superfeed.net> Message-ID: <1154457112_25657@sp6iad.superfeed.net> Very helpful, thanks!! So I see that it parses as: m='1' a="asdf" b="1234" print [((m in a) or b) for m in '%d'%1234 ] I get it. Thanks, Greg "Duncan Booth" wrote in message news:Xns9812BD37F7717duncanbooth at 127.0.0.1... > Gregory Guthrie wrote: > >> Sorry for a simple question- but I don't understand how to parse this >> use of a list comprehension. >> >> The "or" clauses are odd to me. >> >> It also seems like it is being overly clever (?) in using a lc >> expression as a for loop to drive the recursion. > > You are spot on there. It is a list comprehension, but the resulting list > is just thrown away, so using a list comprehension is a complete waste of > time serving only to confuse the issue. Presumably it saved the author a > character or two. > > [ exp for var in seq ] > > when the result isn't used can be rewritten as: > > for var in seq: > exp > > and: > > exp1 or exp2 > > when the result is thrown away is just: > > if not exp1: > exp2 > > > So: > > [ m in [(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3) > or board[j] for j in range(81) ] > or solve(board[:i]+m+board[i+1:]) for m in'%d'%5**18 ] > > is equivalent to: > > inner = [(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3) or board[j] for j in > range(81) ] > for m in '3814697265625': > if m not in inner: > solve(board[:i]+m+board[i+1:]) > > (That inner list comprehension doesn't depend on m, so it doesn't need to > be reevaluated each time round the loop except, again, to save a few > characters.) > > The '%d'%5**18 looks to be a silly way to iterate through all possible > digits for m even though it does some of them twice while saving one > character over writing range(1,10). > > The strange expression I called 'inner' is a list containing the string > value board[j] if j is in the same row, column or block as i, or an > integer > for any other cells. So 'm not in inner' is true only if the value for m > is > not already used in that row column or block and is therefore a possible > candidate for that location in the board. ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From me at invalid.address.com Sun Aug 13 08:33:34 2006 From: me at invalid.address.com (jason) Date: Sun, 13 Aug 2006 12:33:34 GMT Subject: [OT] John Salerno In-Reply-To: References: <44dd3a65$0$2381$c3e8da3@news.astraweb.com> <44de73c3$0$12587$c3e8da3@news.astraweb.com> <2MwDg.456444$C62.9766@fe12.news.easynews.com> Message-ID: Alan Connor wrote: > Looks like pretty much all trolls to me. > > Note: I won't be downloading any articles on this thread. > > Alan > Funny how you keep saying that but keep downloading and responding. From rogue_pedro at yahoo.com Thu Aug 3 17:20:29 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 3 Aug 2006 14:20:29 -0700 Subject: help - iter & dict In-Reply-To: References: Message-ID: <1154640029.488670.283430@b28g2000cwb.googlegroups.com> aking at mappi.helsinki.fi wrote: > Dear Python people, > > im a newbie to python and here...so hello! Hi Ali, and welcome. > Im trying to iterate through values in a dictionary so i can find the > closest value and then extract the key for that value....what ive done so far: > > def pcloop(dictionary, exvalue): > z = dictionary.itervalues() > y = z - exvalue > v = (y*y)**1/2 > if v < 0.001: > u = dictionary.get[z] > return u > > > ive been working off a couple of books and this is the best i can get it in > short time. I was trying to define a function (its my first!) so that i > could apply to several 'dictionary's and 'exvalue's. The best ive been able > to come up with is iterating over the dictionary values, subtracting the > exvalue, squaring then root squaring to render positive and applying an > error (0.001) which is not the ideal solution i want. Is there any easy way > to iterate through dictionary values and return the key for the minimum. Or > can someone tell me where im going wrong with this def & loop. > > regards all > > Ali You're doing many interesting things wrong here. :-) I'm going to take them slightly out of order. First, very ingenious way to get the absolute value of a number, but there are a few issues with this that you should know about. For instance, just as multiplication and division take precedence over addition and subtraction, the "power" operator ** take precedence over division, so what you're really doing above is ((y*y)**1)/2 rather than (y*y)**(1/2) However, the above still wouldn't work correctly because of the way python handles integer division. 1/2 == 0 in python, try it at the interactive prompt and you'll see. So, you'd have to change at least one of the division's operands to float to get the proper result you desire. (y*y)**(1./2) Except that you should actually use the (built in) abs() function, v = abs(y) :-) Next, the itervalues() method of dicts does not return a number, but rather a "dictionary-valueiterator" object, as you can see from this: |>> d = {} |>> z = d.itervalues() |>> z In order to get values out of it you need to iterate over it like so: for z in d.itervalues(): # Do something with z's here... You could also get both the keys and values at the same time by iterating like so: for k, z in d.iteritems(): # Do something with k's and z's here... (I'll come back to that.) Now, a little further down in your function, you seem to want to use the z value with the get() method of the dict to retrieve the key. This won't work. First, you're not *calling* the get method (that uses ()'s) you're *subscripting* it (that uses []'s.) If your code got this far, it would break here. |>> d = {} |>> d.get |>> d.get[23] Traceback (most recent call last): File "", line 1, in ? TypeError: unsubscriptable object So you want to use ()'s, not []'s. Further, get() works with *keys*, not *values*. If you call it with a value, it won't work, instead it will return None. Unless, of course, you *have* a key with the same value as your value, in which case it will return the value associated with the key, but NOT the key associated with the value (that you passed to get().) In fact, there is no easy way to get the key from a dict given a value. Dicts work the other way around. (You basically have to iterate through the values *and* keys, one pair at a time, testing each value as you go. This is very slow, compared to getting the value given a key.) value = d[key] This is extremely fast. It's pretty much the whole point of a dictionary that this is very fast. So, when you build the dict that you pass in to your function, you might want to build it the other way round, i.e. make the keys the values and the values keys. However, you might not and here's why: Dicts can only have one key of any given value of key. Look: |>> d = {1: 'a', 1: 'b'} |>> d {1: 'b'} |>> d = {'a': 1, 'b': 1} |>> d {'a': 1, 'b': 1} So, if you're running a mathematical function on a range of input (x's) and storing the results (y's) as values in a dict, then you *do* want the x's to be the keys and the y's to be the values. I'm guessing that's what you're doing, and if so, you're doing it correctly. Let me address one last problem in your code above and then I'll show you a neat way to return the key whose associated value is closest to some value exvalue. In this part of your code, > if v < 0.001: > u = dictionary.get[z] > return u the return statement should be at the same indentation level as the assignment statement: if v < 0.001: u = dictionary.get[z] # <- note, this won't work return u or even just if v < 0.001: return dictionary.get[z] # <- note, this won't work The way you have it now, the return statement would execute immediately after the if statement, regardless of whether v < 0.001 or not. Not too bad if the very first value was close enough to exvalue. But if it wasn't, 'u' would not have been defined by the time the return statement tried to return it, and you would have gotten a NameError. You probably already know this, and the indentation error was just a minor typo. So, given a dict and an exvalue, how to return the key corresponding to the value that's closest to exvalue? here goes... def pcloop(dictionary, exvalue): ''' Return the key in dictionary whose value is closest to exvalue. If dictionary is empty, return None. ''' # Get a iterator over *both* keys and values. diter = dictionary.iteritems() # Get the first (key, value) pair. try: u, z = diter.next() except StopIteration: # The dictionary was empty! # You might want to do something else here return # Compute the closeness of the first value. closest = abs(z - exvalue) # Create a var to store the closest key result = u # Iterate through the rest of the dict. for u, z in diter: # Compute the closeness. v = abs(z - exvalue) # Check if it's closer than the closest. if v < closest: # If so, store the new closest. closest = v # And store the new closest key. result = u return result I hope that helps. :-) Python is an amazing language once you get the hang of it. Enjoy. Peace, ~Simon From diffuser78 at gmail.com Fri Aug 11 15:51:45 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 11 Aug 2006 12:51:45 -0700 Subject: Help with cx_freeze module Message-ID: <1155325905.610474.188370@i42g2000cwa.googlegroups.com> Has anybody written a file for cx_freeze. I am running Ubuntu Linux and downloaded version for Python2.4. When I run it I get an error saying that I dont have GLIBC_2.4. I searched around but couldn't find a .deb for Ubuntu, I couldnt find this in Synaptic too. Any clues or pointers as to how to get cx_freeze up and running. From davecook at nowhere.net Fri Aug 4 17:23:17 2006 From: davecook at nowhere.net (Dave Cook) Date: Fri, 04 Aug 2006 21:23:17 GMT Subject: Which Python API for PostgreSQL? References: Message-ID: <9VOAg.1939$W01.1402@dukeread08> On 2006-08-04, Redefined Horizons wrote: > What are the advanatages and disadvantages of each? Which one do you > use? What do you like about it? I would use psycopg: http://www.initd.org I believe it's the most full-featured postgres module. There's a windows installer. Dave Cook From jaysherby at gmail.com Sun Aug 27 16:41:17 2006 From: jaysherby at gmail.com (Putty) Date: 27 Aug 2006 13:41:17 -0700 Subject: Conway's Life Implementation In-Reply-To: <1156709925.504875.80790@74g2000cwt.googlegroups.com> References: <1156708582.474508.209360@75g2000cwc.googlegroups.com> <1156709925.504875.80790@74g2000cwt.googlegroups.com> Message-ID: <1156711277.831428.323490@i3g2000cwc.googlegroups.com> Do you think it would be reasonable to use wxGrid to make the game area? Eric_Dexter at msn.com wrote: > Putty wrote: > > Hi. I was going to write an implementation of John Conway's Life game > > using Python and Tk, but I soon found that Tk just didn't cut the > > mustard for memory usage, management, and the like for such a project, > > so I've found my best GUI bet for my project is wxPython and not > > pygame. > > > > Anybody have any advice thus far? > > > > Anyway, my real question is if anybody knows of any tutorials or source > > code from other implementations and other languages that may prove > > useful? > > I find that wxPython is very easy to use.. I just noticed a graphic > library that may or may not help > http://language-binding.net/pyplusplus/examples/easybmp/easybmp.html > I am not sure if you can work with pixels with wxPython but you can > probily do the life game with tiles also.. From R.Brodie at rl.ac.uk Wed Aug 2 10:39:21 2006 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Wed, 2 Aug 2006 15:39:21 +0100 Subject: Windows vs. Linux References: <1154301694.445639.99580@m79g2000cwm.googlegroups.com><44cddfb3$0$7761$7a628cd7@news.club-internet.fr> Message-ID: "Gerhard Fiedler" wrote in message news:mailman.8845.1154526941.27775.python-list at python.org... >With the same reasoning one could say that the Unix creators should have > used the VMS (or any other existing) form. Only if they used Guido's time machine. From rpdooling at gmail.com Wed Aug 2 17:15:40 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 2 Aug 2006 14:15:40 -0700 Subject: Programming newbie coming from Ruby: a few Python questions References: <1154494954.082706.283750@b28g2000cwb.googlegroups.com> <44d06f9f$0$19127$626a54ce@news.free.fr> <1154539223.873418.286830@i42g2000cwa.googlegroups.com> <1154539652.256975.155200@i3g2000cwc.googlegroups.com> <1154549436.073418.202840@s13g2000cwa.googlegroups.com> Message-ID: <1154553340.449475.134050@m73g2000cwd.googlegroups.com> Stand and fight, Python brothers. Fear not, the Ruby horde! From this day to the ending of the world, But we in it shall be remember'd; We few, we happy few, we band of brothers; For he to-day that sheds his blood with me Shall be my brother; be he ne'er so vile, This day shall gentle his condition: And gentlemen in England now a-bed Shall think themselves accursed they were not here, And hold their manhoods cheap whiles any speaks That fought with us upon Saint Crispin's day. rd From sjdevnull at yahoo.com Tue Aug 15 16:11:16 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 15 Aug 2006 13:11:16 -0700 Subject: file object and eof In-Reply-To: <1155668786.644843.192830@m79g2000cwm.googlegroups.com> References: <1155660586.941712.114410@b28g2000cwb.googlegroups.com> <12e412ljneshoc3@corp.supernews.com> <1155668786.644843.192830@m79g2000cwm.googlegroups.com> Message-ID: <1155672676.623922.146470@i3g2000cwc.googlegroups.com> KraftDiner wrote: > how about?!: > > def eof(fileobj): > curloc = fileobj.tell() > ofloc = fileobj.seek(0,2) > fileobj.seek(curloc, 0) > if ofloc >= curloc: > return True > return False 1. At least on python 2.3, seek always returns None--did that change in 2.4? I added a tell() in there to fix that. 2. You have your test reversed. It'll always return True as is. 3. Even if you fix that, it's limited utility depending on file mode and whether the file object is seekable. What's your actual problem? There's almost certainly a better way to do it. From skip at pobox.com Wed Aug 30 09:31:03 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 30 Aug 2006 08:31:03 -0500 Subject: where or filter on list In-Reply-To: References: <1156939493.558819.8410@i42g2000cwa.googlegroups.com> Message-ID: <17653.37655.539699.487124@montanaro.dyndns.org> >> Another way might be to sort by absolute value: >> >> intermed = [(abs(v), v) for v in foo] >> intermed.sort() >> intermed[0][1] Duncan> It is slightly simpler if you use sorted (assuming a recent Duncan> enough Python): Duncan> intermed = sorted(foo, key=abs) Duncan> print intermed[0] Yeah, sorted() is new enough that my brain generally doesn't realize it's available. I also never remember the key parameter to list.sort(). Now that you mention it: >>> foo = [5, 2, -1, -7, 3, -6, 2, 12] >>> foo.sort(key=abs) >>> foo [-1, 2, 2, 3, 5, -6, -7, 12] (assuming you don't mind reording the list - if you do, then sorted() is your friend). Skip From rbonvall at pcitgd42.cern.ch Tue Aug 29 10:54:23 2006 From: rbonvall at pcitgd42.cern.ch (Roberto Bonvallet) Date: 29 Aug 2006 14:54:23 GMT Subject: refering to base classes References: <1156862012.068397.284040@m73g2000cwd.googlegroups.com> Message-ID: glenn wrote: > [...] In this trivial example, how could I modify the voice method of > 'dog' to call the base class 'creatures' voice method from with in it? > > class creature: > def __init__(self): > self.noise="" > def voice(self): > return "voice:" + self.noise > > class dog(creature): > def __init__(self): > self.noise="bark" > > def voice(self): > print "brace your self:" If you want dog.voice() to just print "voice: bark", you just have to omit the voice method for the dog class: it will be inherited from creature. If you want dog.voice() to do something else, you can call superclass' method like this: def voice(self): creature.voice(self) print "brace your self" any_other_magic() HTH -- Roberto Bonvallet From jaysherby at gmail.com Tue Aug 8 15:58:32 2006 From: jaysherby at gmail.com (jaysherby at gmail.com) Date: 8 Aug 2006 12:58:32 -0700 Subject: newb question: file searching Message-ID: <1155067111.892386.130610@n13g2000cwa.googlegroups.com> I'm new at Python and I need a little advice. Part of the script I'm trying to write needs to be aware of all the files of a certain extension in the script's path and all sub-directories. Can someone set me on the right path to what modules and calls to use to do that? You'd think that it would be a fairly simple proposition, but I can't find examples anywhere. Thanks. From bdesth.quelquechose at free.quelquepart.fr Thu Aug 10 16:32:27 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 10 Aug 2006 22:32:27 +0200 Subject: converting a nested try/except statement into try/except/else In-Reply-To: <44db91a8$1_6@news.bluewin.ch> References: <44db91a8$1_6@news.bluewin.ch> Message-ID: <44db95a4$0$31535$626a54ce@news.free.fr> Boris Borcic a ?crit : > Slawomir Nowaczyk wrote: > >> >> try: >> if int(text) > 0: >> return True >> except ValueError: >> pass >> self.error_message() >> return False >> > > Nicely DRY. To make it even more compact, it may be noticed that the > default return value None is false in a boolean context - so that the > last line is superfluous if the return value is only wanted to test it > in such a context. While it's technically true - and I while I have a taste for compactness - skipping the explicit 'return False' somehow hurts my sense of esthethic... Unless you propose to return object or type instead of True - but then it begins to look very strange !-) From tim.leeuwvander at nl.unisys.com Tue Aug 22 16:23:50 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 22 Aug 2006 13:23:50 -0700 Subject: Python and STL efficiency In-Reply-To: <1156265848.875774.251640@i42g2000cwa.googlegroups.com> References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <1hkh28d.xscw4v1y4v9a6N%riko@despammed.com> <1hkh6lb.6dsnh51lj8z96N%riko@despammed.com> <1156252193.524186.107520@b28g2000cwb.googlegroups.com> <1hkhexv.18m65rl61swqyN%riko@despammed.com> <1156265848.875774.251640@i42g2000cwa.googlegroups.com> Message-ID: <1156278230.590485.35610@75g2000cwc.googlegroups.com> Tim N. van der Leeuw wrote: > Mc Osten wrote: > > Tim N. van der Leeuw wrote: > > > > > Oh boy; yes indeed the slow python is faster than the fast C++ > > > version... Must be something really awful happening in the STL > > > implementation that comes with GCC 3.4! > > > > And the Python version does the very same number of iterations than the > > C++ one? I suppose they are looping on arrays of different sizes, just > > like my "first version". > > > > Hmmm.. You're quite right. The C++ version had an array size 100.000 > (your version), the Python version still had an array size 10.000 (as > in my modified copy of the original version). > > When fixing the Python version to have 100.000 items, like the C++ > version, the Python timings are: > [...] > Fast - Elapsed: 0.512088 seconds > Slow - Elapsed: 1.139370 seconds > > Still twice as fast as the fastest GCC 3.4.5 compiled version! > > Incidentally, I also have a version compiled with VC++ 6 now... (not > yet w/VC++ 7) .. Compiled with release-flags and maximum optimization > for speed, here's the result of VC++ 6: > > LeeuwT at nlshl-leeuwt ~/My Documents/Python > $ ./SpeedTest_VC.exe [...] > Fast - Elapsed: 4.481 seconds > Slow - Elapsed: 4.842 seconds > [...] And the results of IronPython (1.0rc2) are just in as well: IronPython 1.0.60816 on .NET 2.0.50727.42 Copyright (c) Microsoft Corporation. All rights reserved. >>> >>> import sys >>> sys.path.append('c:/documents and settings/leeuwt/my documents/python') >>> import SpeedTest >>> SpeedTest.run_test() Begin Test Number of unique string objects: 4 What do you know so long... chicken crosses road fool Number of unique string objects: 400000 What do you know so long... chicken crosses road fool Fast - Elapsed: 1.287923 seconds Slow - Elapsed: 4.516272 seconds >>> And for Python 2.5: LeeuwT at nlshl-leeuwt ~/My Documents/Python $ /cygdrive/c/Python25/python.exe SpeedTest.py Begin Test Number of unique string objects: 4 so long... What do you know fool chicken crosses road Number of unique string objects: 400000 so long... What do you know fool chicken crosses road Fast - Elapsed: 0.440619 seconds Slow - Elapsed: 1.095341 seconds LeeuwT at nlshl-leeuwt ~/My Documents/Python But beware! For Python2.5 I had to change the code slightly, because it already realized that the expression '%s' % 'something' will be a constant expression, and evaluates it once only... so I had to replace '%s' with a variable, and I got the timings above which show Python2.5 to be slightly faster than Python2.4. (Next step would be to create a VB version and a Java version of the same program, oh and perhaps to try a version that would work with Jython... perhaps somehow w/o the 'set') Cheers, --Tim From tjreedy at udel.edu Sun Aug 6 22:08:08 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 6 Aug 2006 22:08:08 -0400 Subject: where can I find Python acceptance test suite? References: <1154897422.081562.80780@n13g2000cwa.googlegroups.com> Message-ID: "The Eternal Squire" wrote in message news:1154897422.081562.80780 at n13g2000cwa.googlegroups.com... > I've been doing some hacking of the Python engine, and I've been > looking for > where the comprehensive regression tests are kept so that I can > determine > where I've broken part of the engine. ...python2x/Lib/test From utabintarbo at gmail.com Fri Aug 11 10:05:52 2006 From: utabintarbo at gmail.com (utabintarbo) Date: 11 Aug 2006 07:05:52 -0700 Subject: Native Win32 text entry dialog? In-Reply-To: <1155068108.841202.269820@p79g2000cwp.googlegroups.com> References: <1155068108.841202.269820@p79g2000cwp.googlegroups.com> Message-ID: <1155305152.283999.24180@i42g2000cwa.googlegroups.com> Well, to answer my own question.... http://www.averdevelopment.com/python/EasyDialogs.html Thanks to all who responded! ;-P From Eric_Dexter at msn.com Sun Aug 13 18:17:47 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 13 Aug 2006 15:17:47 -0700 Subject: looking for a simple way to load a program from another python program.. In-Reply-To: <1155502085.103104.295370@h48g2000cwc.googlegroups.com> References: <1155498660.285772.144140@m73g2000cwd.googlegroups.com> <1155502085.103104.295370@h48g2000cwc.googlegroups.com> Message-ID: <1155507467.610127.247780@m79g2000cwm.googlegroups.com> Caleb Hattingh wrote: > Hi Eric > > Check that ".py" and ".pyw" are in your PATHEXT environment variable > (are you using Windows?). Then, if the folder that cabel is in is in > your PATH environment variable, and the correct association for .py > files is set up (i.e. they get run by python.exe), > > either > os.system('cabel') > or > os.system('cabel.py') > > should work. > > Alternatively, you could not do any of those things, and run > > os.system('python cabel.py') > > with 'cabel.py' in the same folder as the parent script, and that > should work too, assuming that the path to your python executable is on > the PATH environment variable. > > If you run other commands from python quite frequently, it is probably > a good idea to look into the "os.popen" set of commands, for more > flexibilty. > > Caleb import cabel and reload(cabel) seem to work fine. I am not sure why I am having trouble with os.system, probily something to do with the path. Is one better than the other when it comes to distributing software?? Thanks for the help. Hopefully this message I get isn't anything important.. (I will have to look into os.popen later. Localisation of messages is disabled, using default language. time resolution is 279.365 ns From dennis.varghese at wipro.com Mon Aug 28 00:02:44 2006 From: dennis.varghese at wipro.com (pycraze) Date: 27 Aug 2006 21:02:44 -0700 Subject: Segmentation Fault Message-ID: <1156737764.729811.297280@m79g2000cwm.googlegroups.com> I would like to ask a question. How do one handle the exception due to Segmentation fault due to Python ? Our bit operations and arithmetic manipulations are written in C and to some of our testcases we experiance Segmentation fault from the python libraries. If i know how to handle the exception for Segmentation fault , it will help me complete the run on any testcase , even if i experiance Seg Fault due to any one or many functions in my testcase. From bobrien18 at yahoo.com Wed Aug 16 11:02:17 2006 From: bobrien18 at yahoo.com (KraftDiner) Date: 16 Aug 2006 08:02:17 -0700 Subject: inheritance? In-Reply-To: References: <1155695711.057312.8020@p79g2000cwp.googlegroups.com> Message-ID: <1155740537.807207.210950@i42g2000cwa.googlegroups.com> Steven D'Aprano wrote: > On Tue, 15 Aug 2006 19:35:11 -0700, KraftDiner wrote: > > > I have two classes: > > > > class implicitClass: > > def __init__(self): > > def isIVR(self): #This is a class private method. > > The convention is to flag classes as "private" with a leading underscore: > > def _isIVR(self): > > or double underscores for "really private, no, honestly": > > def __isIVR(self): > > but google on "python name mangling" before using that. > > [snip] > > > As you can see the interface is almost identical. > > > > How can I define a base class that will abstract > > the type such that I don't know if its really and inplicit > > or explicit object? > > Something like this? > > > class baseClass: > def __init__(self): > raise NotImplementedError("Don't instantiate the base class!") > def fromfile(self): > def getElement(self): > # etc. > > > class implicitClass(baseClass): > def __init__(self): > # code > def _isIVR(self): > # code > def fromfile(self, fileObj, byteOrder): > # code > # etc. > > Now, you can define instance = implicitClass() or explicitClass(). When > you come to use instance, you don't need to know whether it is one or the > other. If you need to type-test, call "isinstance(instance, baseClass)". > > The only minor issue is that the fromfile method has a different > interface. If you really want to do duck typing, they need to have the > same interface. That might be as simple as: > > class explicitClass(baseClass): > def fromfile(self, fileObj, byteOrder=None): > # byteOrder is ignored; it is included only for > # compatibility with implicitClass > > > Is that what you're asking for? > Yes I believe so but in fromfile I want to call the appropriate method depending on the in a parameter in fromfile... like: class baseClass: def fromfile(self, fileObj, byteOrder=None, explicit=False): if explicit: call fromfile of explicit class else: call fromfile of implicit class How is that done? > > > -- > Steven D'Aprano From apardon at forel.vub.ac.be Tue Aug 29 02:10:15 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 29 Aug 2006 06:10:15 GMT Subject: Is this a good idea or a waste of time? References: <1156449402.022781.292840@p79g2000cwp.googlegroups.com> <1156485945.967160.238790@m73g2000cwd.googlegroups.com> <44f322cd$1@nntp0.pdx.net> <1156802762.331853.80000@75g2000cwc.googlegroups.com> Message-ID: On 2006-08-29, Gabriel Genellina wrote: > At Tuesday 29/8/2006 02:45, Antoon Pardon wrote: > >> >>That may be true. But one may wonder if this is a failing of the >> >>programmer or a failing of the language that doesn't support >> >>such things. >> > >> > In any case, I don't see how this supports the original claim that >> > strict type checking input params is good practice. >> >>I'm not defending that claim. I'm just putting question marks >>with the claim that strict type checking input parameters is >>bad practice. > > I think others have shown enough examples of good things that can be > done by *not* enforcing a specific type... That doesn't contradict that in other situations good things can be done by enforcing specific type or at least limiting to a subset of specific types. -- Antoon Pardon From paul at boddie.org.uk Wed Aug 16 07:19:32 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 16 Aug 2006 04:19:32 -0700 Subject: programming with Python 3000 in mind References: <1155672987.522793.47080@74g2000cwt.googlegroups.com> <1155706908.340544.92920@i42g2000cwa.googlegroups.com> Message-ID: <1155727172.843580.218520@74g2000cwt.googlegroups.com> Kay Schluehr wrote: > Fredrik Lundh wrote: > > beliavsky at aol.com wrote: > > > > > The current beta version of Python is 2.5 . How can a Python programmer > > > minimize the number of changes that will be needed to run his code in > > > Python 3000? > > > > by ignoring it, until it exists. > > And why not ignoring it, when it comes to exist? The risk of Python 3000 being ignored or marginalised may increase in direct proportion to the amount of exotic new stuff introduced upon its release, mostly because people have a large amount of code that may not work with an extensively modified language, library and runtime (although the latter is only a remote possibility), and because newcomers may not see Python 3000 as significantly interesting to adopt in preference to other languages. This observation, which I'm sure I've stated before, seems to have influenced (perhaps coincidentally) various pronouncements about how conservative Python 3000 will be, at least when compared to the expectations of the python-3000 mailing list where various participants seem obsessed with reenacting 20th century Types-SIG mailing list discussions and reproducing works with varying degrees of similarity to the conclusions of that old activity: http://www.python.org/community/sigs/retired/types-sig/ Note that links to the Types-SIG archives are broken on python.org, but the archives are viewable via ASPN: http://aspn.activestate.com/ASPN/Mail/Browse/Plain/types-sig/ Ultimately, and to the disappointment of a few people, Python 3000's benefits may very well seem incremental, if only to avoid fracturing the community. Paul From bearophileHUGS at lycos.com Tue Aug 29 20:09:32 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 29 Aug 2006 17:09:32 -0700 Subject: Split with python In-Reply-To: References: Message-ID: <1156896572.314013.20330@b28g2000cwb.googlegroups.com> Norman Khine: > I have a csv file which is has a field that has something like: > "text (xxx)" > "text (text) (yyy)" > "text (text) (text) (zzz)" > > I would like to split the last '(text)' out and put it in a new column, > so that I get: > "text","(xxx)" > "text (text)","(yyy)" > "text (text) (text)","(zzz)" Maybe something like this can be useful, after few improvements (RE formatting is a work in progress): from StringIO import StringIO import re datain = StringIO(""" "text (xxx)" "text (text) (yy y) " "text (text) (text) ( zzz ) " """) lastone = re.compile(""" \s* ( \( [^()"]* \) \s* " ) \s* $ """, re.VERBOSE) def repl(mobj): txt_found = mobj.groups()[0] return '", "' + txt_found for line in datain: line2 = line.strip() if line2: print lastone.sub(repl, line2) """ The output is: "text", "(xxx)" "text (text)", "(yy y) " "text (text) (text)", "( zzz ) " """ Bye, bearophile From steven.bethard at gmail.com Tue Aug 15 12:30:56 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 15 Aug 2006 10:30:56 -0600 Subject: modifying __new__ of list subclass In-Reply-To: References: Message-ID: Ken Schutte wrote: > Steven Bethard wrote: >> >> The __new__ method is for immutable types. So things like str and int >> do their initialization in __new__. But for regular mutable types, >> you should do your initialization in __init__:: > > I see... So, is there a use for __new__ in mutable types? From my > list-derirved class, it was obviously being called, but it's return > value is totally ignored? Not ignored, it's just having it's __init__ method called after your __new__ method. It might help for a moment to consider what happens when you call a class object, e.g.:: c = C() Just like any other object, when Python sees the ``()``, it looks for a __call__ method on the object. Now classes are instances of the ``type`` type, which has a call method that looks something like:: def __call__(cls, *args, **kwargs): result = cls.__new__(cls, *args, **kwargs) if isinstance(result, cls): result.__init__(*args, **kwargs) return result What's happening in your list case is that list.__init__ clears the list:: >>> l = [1, 2, 3] >>> l.__init__() >>> l [] So even though your __new__ method returns the object you want, the __init__ method is clearing out all the items you've added and then re-adding them as it normally would. To prove this to yourself, take a look at what happens when we override __init__:: >>> class mylist(list): ... def __new__(cls, items): ... result = super(mylist, cls).__new__(cls) ... for item in items: ... result.append('%s_' % item) ... return result ... >>> mylist([1, 2, 3]) [1, 2, 3] >>> class mylist(list): ... def __new__(cls, items): ... result = super(mylist, cls).__new__(cls) ... for item in items: ... result.append('%s_' % item) ... return result ... def __init__(self, items): ... pass ... >>> mylist([1, 2, 3]) ['1_', '2_', '3_'] Of course, I've made __new__ work above, but the simpler solution is just to override __init__ since that's where all the work's being done anyway. See Alex Martelli's response to answer your question "So, is there a use for __new__ in mutable types?". You'd probably only want to override __new__ if you were going to use the class as a factory to produce a bunch of different types of objects. STeVe From grante at visi.com Wed Aug 16 16:35:50 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 16 Aug 2006 20:35:50 -0000 Subject: Adding a char inside path string References: <1155737700.290268.248250@i42g2000cwa.googlegroups.com> <1155744057.573884.111850@m73g2000cwd.googlegroups.com> <1155757548.080769.213490@p79g2000cwp.googlegroups.com> <1155759163.627377.72590@74g2000cwt.googlegroups.com> Message-ID: <12e70d6h4pb3l65@corp.supernews.com> On 2006-08-16, Hitesh wrote: > That might work but what if I get (in future) a path name where > foldername (and in windows it is very common, someone might name a > folder something like "Screw You") with space? You must come up with a rigorous specification for what is and isn't allowed at the end of a path. Then delete the stuff that isn't allowed. -- Grant Edwards grante Yow! Hello? Enema at Bondage? I'm calling visi.com because I want to be happy, I guess... From larry.bates at websafe.com Thu Aug 10 19:27:30 2006 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 10 Aug 2006 18:27:30 -0500 Subject: seaching a list... In-Reply-To: References: Message-ID: bruce wrote: > hi... > > i'm playing with a test sample. i have somethhing like: > dog = mysql_get(.....) > . > . > . > > such that 'dog' will be an 'AxB' array of data from the tbls > > furher in the test app, i'm going to have a list, foo: > foo = 'a','b','c','d' > > i'm trying to determine what's the fastest way of searching through the > 'dog' array/list of information for the 'foo' list. > > should i essentially make dog into A lists, where each list is B elements, > or should it somehow combine all the elements/items in 'dog' into one large > list, and then search through that for the 'foo' list... > > also, in searching through google, i haven't come across the list.search > function.. so just how do i search a list to see if it contains a sublist... > > my real problem involves figuring out how to reduce the number of hits to > the db/tbl... > > thanks > > ps. if this is confusing, i could provide psuedo-code to make it easier to > see... > > > > You should use the database for what it is good at storing and searching through data. Don't read all the data from a table and search through it. Rather, create indexes on the table so that you can locate the data quickly in the database by passing in something you are looking for and let the database do the searching. I can promise you this will almost always be faster and more flexible. Something like: Assume the columns are called rownumber, c1, c2, c3, c4 and the table is indexed on c1, c2, c3, and c4. This will happen almost instantly no matter how many rows you are searching for. select rownumber from database_table where c1="a" and c2="b" and c3="c" and c5="d" It takes one "hit" to the db/table to return the rowindex that matches. -Larry Bates From pupeno at pupeno.com Wed Aug 16 03:10:02 2006 From: pupeno at pupeno.com (Pupeno) Date: Wed, 16 Aug 2006 07:10:02 +0000 Subject: Very weird behavior that's driving me crazy Message-ID: <44e2c4c3$0$20039$9b4e6d93@newsspool4.arcor-online.net> Hello, I am experiencing a weird behavior that is driving me crazy. I have module called Sensors containing, among other things: class Manager: def getStatus(self): print "getStatus(self=%s)" % self return {"a": "b", "c": "d"} and then I have another module called SensorSingleton that emulates the hard-to-code-on-python singleton in this way: manager = Manager() print "manager=%s" % manager def getStatus(): print "getStatus()" return manager.getStatus() and then in some other module, I import SensorSingleton and I do, among other things: print SensorSingleton.getStatus() and the output is more or less like this. First, the manager: manager: ok, then Manager.getStatus(self=) => {"a": "b", "c": "d"} None None is the return of SensorSingleton.getStatus(), now, my questions are: - Shouldn't the manager be the same in the first print and the second, that is, the id is different, shouldn't it be the same ? - What happened with all the output of SensorSingleton.getStatus() ? there's no trace of it (but there's output of the method it calls). - Why doesn't the SensorSingleton.getStatus() return the return value of manager.getStatus(), it's a very straight forward call to it and return it. Thank you. -- Pupeno (http://pupeno.com) From http Sun Aug 27 13:57:47 2006 From: http (Paul Rubin) Date: 27 Aug 2006 10:57:47 -0700 Subject: random writing access to a file in Python References: <5a9ue2lrjh214ecmme09fsodhm3ico1ntm@4ax.com> <7xhczzqoi3.fsf@ruckus.brouhaha.com> <7xbqq7f6q7.fsf@ruckus.brouhaha.com> <7xd5anf23u.fsf@ruckus.brouhaha.com> Message-ID: <7xr6z2dpt0.fsf@ruckus.brouhaha.com> Claudio Grondi writes: > The Windows XP SP 2 '/> sort' (sorting of four Gigs of 20 byte records > took 12 CPU and 18 usual hours) has, from what I could observe on the > task manager, done the job in only two runs of 'copying' : That is terrible; on a reasonably fast machine these days it should take just a few minutes. > > Is this some kind of production deployment problem you're working on, > > or do you just have a big pile of data you need to sort once? > The latter. > One of the intermediate reasons behind doing it, is an attempt to get > more and better intuitive understanding what are the hardware and > software limits of brute force based approaches to solving problems in > the area of AI, language processing and data compression. This makes no sense; the methods you want are from the ancient days of "data processing", nothing to do with AI. Remember that the mainframe computers of the 1960's that this stuff was developed on, had less computing power and memory than a modern mobile phone. But phone companies, tax agencies, and so forth, still managed to run these big sorting tasks on those mainframes in order to send people their phone bills, identify the tax cheaters, etc. There is rich and wonderful history to it. From staham at gmail.com Tue Aug 15 09:53:44 2006 From: staham at gmail.com (staham at gmail.com) Date: 15 Aug 2006 06:53:44 -0700 Subject: IDLE system wide settings Message-ID: <1155650024.454008.32790@b28g2000cwb.googlegroups.com> Hi, Is it possible to change the settings for the IDLE program via either the command line or via environment variables? The things I would like to change is to choose UTF-8 and "Classic UNIX" keys. I understand that it's possible to edit the program, but I'd rather just set an environment variable. best regards, Staffan From steven.bethard at gmail.com Thu Aug 3 01:16:17 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 2 Aug 2006 23:16:17 -0600 Subject: python-dev summary for 2006-06-16 to 2006-06-30 Message-ID: python-dev Summary for 2006-06-16 through 2006-06-30 ++++++++++++++++++++++++++++++++++++++++++++++++++++ .. contents:: [The HTML version of this Summary is available at http://www.python.org/dev/summary/2006-06-16_2006-06-30] ============= Announcements ============= ------------------- Python 2.5 schedule ------------------- A number of bugs are being squashed as Python 2.5 moves towards its next release. See `PEP 356`_ for more details and the full schedule. .. _PEP 356: http://www.python.org/dev/peps/pep-0356/ Contributing threads: - `Beta 1 schedule ? (Bug in stringobject?) `__ - `Adding winerror module (Beta 1 schedule ?) `__ - `current 2.5 issues `__ - `TRUNK FREEZE IMMINENT FOR 2.5 BETA 1 - 00:00 UTC, 20-JUNE-2006 `__ - `beta1 coming real soon `__ - `RELEASED Python 2.5 (beta 1) `__ - `TRUNK is UNFROZEN, but in FEATURE FREEZE `__ - `2.5 and beyond `__ ----------------------------------------- Checkins for betas and release candidates ----------------------------------------- Anthony Baxter announced some guidelines for checkins for the beta and release candidate releases. For all beta releases: * All checkins must have an entry for Misc/NEWS, a test and docs * All checkins that add features must have approval from a release manager * All checkins must not break any of the buildbots For all release candidates: * All checkins must have approval from a release manager Approval from a release manager (Anthony or Neal) should preferably be obtained in public (e.g. the python-dev list) and should be noted in the commit message. Contributing threads: - `When to branch release25-maint? `__ - `RFC: trunk checkins between now and 2.5 final `__ ------------------------------------------- FishEye on the Python Subversion Repository ------------------------------------------- FishEye is once again `available for the Python repository`_. .. _available for the Python repository: http://fisheye3.cenqua.com/browse/python Contributing thread: - `FishEye on Python CVS Repository `__ ========= Summaries ========= --------------------------------- PEP 3103: A Switch/Case Statement --------------------------------- After Thomas Lee provided a `simple patch implementing a switch statement`_ for Python, there was a massive discussion about it and how `PEP 275`_ should best be implemented. After much discussion, basically three camps arose: * School I: The switch statement should just be syntactic sugar for the corresponding if/elif chain. * School II: The switch statement should dispatch on a precomputed dict of values. * School III: The switch statement should correspond to an if/elif chain but require all expressions to be hashable (to allow for better optimizations). School I was primarily concerned with the repetition of the ``x ==`` in something like:: if x == ...: ... elif x == ...: ... elif x == ...: ... else: ... School II seemed to feel that just aiding DRY was not enough to introduce a new construct, and that the switch statement should also be able to avoid the function definitions in dispatching code like:: def f(...): ... def g(...): ... def h(...): ... dispatch_dict = {x:f, y:g, z:h} dispatch_dict[value](*args) In order to optimize this kind of code, School II wanted to be able to compute the dispatch dict ahead of time, so that it wouldn't have be recomputed each time the switch statement was executed. There was a lot of discussion as to exactly when this freezing should occur, with some voting for module compilation time (allowing only constants in the cases), some voting for function definition time (allowing only constants and non-local names in the cases) and some voting for the first time the switch statement is executed (allowing only constants and both local and non-local names). Guido put together a thorough summary of the options in `PEP 3103`_. There was some discussion of introducing a ``static`` keyword which would cause an expression to be evaluated at function definition time, so that, for example, the following code would create a list of functions returning each of 0, 1, ... 9:: funcs = [lambda: (static i) for i in xrange(10)] The intention was that switch statement cases would then allow only constants or static expressions. Guido requested a separate PEP on the idea, and `Fredrik Lundh posted a proto-PEP`_, but at the time of this summary, no official PEP had been submitted. In the end, it looked like Guido was leaning towards the switch statement as syntactic sugar for a dispatching dict, with the dict frozen at function definition time (which would mean compile-time for module-level switch statements). However, the introduction of the statement seemed likely to be postponed at least until Python 3.0. .. _simple patch implementing a switch statement: http://bugs.python.org/1504199 .. _PEP 275: http://www.python.org/dev/peps/pep-0275/ .. _PEP 3103: http://www.python.org/dev/peps/pep-3103/ .. _Fredrik Lundh posted a proto-PEP: http://online.effbot.org/2006_06_01_archive.htm#pep-static Contributing threads: - `Switch statement `__ - `An obscene computed goto bytecode hack for "switch" :) `__ - `Simple Switch statement `__ - `Alternatives to switch? `__ - `Temporary Constantification `__ - `Simple Switch statementZ `__ - `PEP 3103: A Switch/Case Statement `__ - `School IIb? `__ - `Switch statement - handling errors `__ - `Split switch statement `__ - `once [was: Simple Switch statementZ] `__ ------------------------------ Restricted execution in Python ------------------------------ For his Ph.D. thesis, Brett Cannon is looking into adding facilities for restricted execution to Python, partly with the goal of getting Python into Firefox alongside Javascript. His restricted execution specifications aimed to take advantage of the C-to-Python language barrier to enforce security restrictions. Though there's no real way to get private attributes in pure Python, objects coded in C and exposed to Python can select which attributes are exposed, thus making the non-exposed attributes truly private to Python-level code. His initial draft aimed to hide as many "dangerous" objects as possible, and then cripple objects like ``file`` that would be difficult to hide. A number of people seemed to prefer a hiding-only approach, but comments from Armin Rigo seemed to suggest that plugging all the introspection holes that give access to file objects might be quite difficult. The discussion continued on into the next fortnight. Contributing threads: - `doc for new restricted execution design for Python `__ - `Is Lib/test/crashers/recursive_call.py really a crasher? `__ - `For sandboxing: alternative to crippling file() `__ ----------------------------------------------- NaN and infinities in Python float calculations ----------------------------------------------- Nick Maclaren asked about trying to get more platform-independent behavior in Python's floats, so that IEEE 754 values as in `PEP 754`_ would be produced more consistently. Currently, different OSes produce different results when these values are involved:: Python 2.4.2 (#1, May 2 2006, 08:28:01) [GCC 4.1.0 (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = "NaN" >>> b = float(a) >>> c = int(b) >>> d = (b == b) >>> print a, b, c, d NaN nan 0 False Python 2.3.3 (#1, Feb 18 2004, 11:58:04) [GCC 2.8.1] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> a = "NaN" >>> b = float(a) >>> c = int(b) >>> d = (b == b) >>> print a, b, c, d NaN NaN 0 True Nick Maclaren suggested either raising an exception for all ambiguous or invalid operations, or returning NaN or infinity as appropriate and then raising exceptions whenever an operation that would lose the error indication was performed. Nick Coghlan explained that the decimal module already does most of this:: >>> from decimal import Decimal as d >>> nan = d('NaN') >>> int(nan) Traceback (most recent call last): ... decimal.InvalidOperation >>> >>> from decimal import getcontext, Overflow >>> ctx = getcontext() >>> ctx.traps[Overflow] = False >>> d('1e999999999') * 10 Decimal("Infinity") Nick Maclaren seemed to suggest that he would be working on a PEP and an implementation that would bring some of the decimal module consistencies to Python's floats as well. .. _PEP 754: http://www.python.org/dev/peps/pep-0754/ Contributing threads: - `Numerical robustness, IEEE etc. `__ - `Numerical robustness, IEEE etc. `__ - `Python memory model (low level) `__ ----------------------------------------------- ImportWarnings for directories without __init__ ----------------------------------------------- Ralf W. Grosse-Kunstleve complained that with Python 2.5 he started getting tons of "ImportWarning: Not importing directory" messages. James Y Knight pointed out that running Python in your home directory is quite likely to issue such warnings if you have *any* directories in your home directory that have the same name as a python module (e.g. ``readline``). A number of options for silencing the errors were discussed, including invoking Python like ``python -W'ignore:Not importing directory'`` and including ``warnings.filterwarnings('ignore', 'Not importing directory', ImportWarning)`` in site.py or .pythonrc.py. Two patches were provided that introduce the warning only if the import fails, `one by Shane Hathaway`_ and `one by Sergey A. Lipnevich`_. No final decision had been made at the time of this summary. .. _one by Shane Hathaway: http://bugs.python.org/1515361 .. _one by Sergey A. Lipnevich: http://bugs.python.org/1515609 Contributing threads: - `Dropping __init__.py requirement for subpackages `__ - `ImportWarning flood `__ ------------------ Updating turtle.py ------------------ Gregor Lingl proposed replacing turtle.py in the Python standard library with his `new xturtle.py module`_. The xturtle module is backwards compatible with the turtle module and adds a number of enhancements. However, Gregor's request came after Python 2.5's feature freeze, so he was told to propose it again in Python 2.6. There was some discussion about this -- as the stdlib turtle module is poorly tested, some contended that introducing the new APIs of xturtle would not make things any worse. A couple of compromises were offered: mentioning xturtle in the turtle module docs, and putting xturtle in the Tools directory. .. _new xturtle.py module: http://ada.rg16.asn-wien.ac.at/~python/xturtle/ Contributing threads: - `xturtle.py a replacement for turtle.py(!?) `__ - `xturtle.py - a replacement for turtle.py `__ - `xturtle.py a replacement for turtle.py(!?) ATTENTION PLEASE! `__ - `xturtle.py `__ ---------------------------------------------------------- Relative imports and PEP 338: Executing Modules as Scripts ---------------------------------------------------------- Relative imports, as described in `PEP 328`_, introduced problems for `PEP 338`_ which allows modules within packages and zipfiles to be run with the -m command-line switch. The -m switch sets the __name__ of the module to '__main__' so that ``if __name__ == '__main__'`` blocks will get executed. However, relative imports use __name__ to determine the parent package, so if a module that has a relative import is executed using the -m switch, the relative import will fail. Nick Coghlan suggested adding a __module_name__ attribute that would not be clobbered by the -m switch, but people generally seemed to think that it would be simpler to just require absolute imports in main modules. .. _PEP 328: http://www.python.org/dev/peps/pep-0328/ .. _PEP 338: http://www.python.org/dev/peps/pep-0338/ Contributing threads: - `PEP 338 vs PEP 328 - a limitation of the -m switch `__ - `PEP 328 and PEP 338, redux `__ - `[Python-checkins] r47142 - in python/trunk: Doc/lib/librunpy.tex Lib/runpy.py Lib/test/test_runpy.py `__ -------------------------------------------- Importing modules within unicode directories -------------------------------------------- Kristj?n V. J?nsson pointed out that currently, Python on Windows cannot import modules from directories with unicode names, even if the module names themselves are plain ASCII. Nick Coghlan suggested that this was likely because import.c was doing something like ``u'c:/tmp/\u814c'.encode('mbcs')``, getting back ``'c:/tmp/?'`` and being unable to do anything useful with that. Martin v. L?wis suggested using the 8.3 simplified filename used by DOS, at least until the import machinery gets reworked to better handle encodings, hopefully for Python 2.6. `Thomas Heller had provided a patch`_ for reworking import.c in this manner a while back, but it was large enough that no one had reviewed it. .. _Thomas Heller had provided a patch: http://bugs.python.org/1093253 Contributing thread: - `unicode imports `__ ---------------------------------------- MS VC++ 2003 toolkit no longer available ---------------------------------------- Bill Janssen pointed out that Python 2.4 on Windows expects to be compiled with the MS Visual C++ compiler version 7.1, and that the corresponding MS VC++ 2003 toolkit is no longer available. Fredrik Lundh explained that the compiler is still available in the .net SDK as well as being available to MSDN subscribers. There was again some discussion about moving to the VS 2005 toolkit for compiling Python. It would have made compiling for 64bit architectures somewhat easier, but would have meant that extension writers would have to install three different compilers just to compile extensions for Python 2.3, 2.4 and 2.5, and would also have given problems for MinGW users as MinGW does not yet easily support linking to the msvcr80 runtime library. Contributing threads: - `Python 2.4 extensions require VC 7.1? `__ - `Documentation enhancement: "MS free compiler"? `__ - `Documentation enhancement: "MS free compiler"? `__ --------------------------------- Keeping interned strings in a set --------------------------------- Alexander Belopolsky tried out the new set C API by `replacing the dict of interned strings with a set`_ instead. He had to make two changes to get this to work: there's currently no way to retrieve a single object from a set, and Py_Finalize() needed to be changed to finalize sets after strings (instead of the other way around as it used to be). There was some discussion about trying to get rid of PySet_Fini() so the latter problem wouldn't be an issue at all, but with all the other Py*Fini() functions already existing, it didn't seem worth it. The patch had no slowdown and reduced the memory consumption of the interning structure slightly. .. _replacing the dict of interned strings with a set: http://bugs.python.org/1507011 Contributing threads: - `Keeping interned strings in a set `__ - `Keeping interned strings in a set `__ - `setobject code `__ - `Proposal to eliminate PySet_Fini `__ ------------------------- Allowing empty subscripts ------------------------- Guido finally vetoed the proposal to allow ``x[()]`` to be written as ``x[]``. The use-cases were weak, and in most cases the functionality seemed better expressed as attribute access. Contributing threads: - `Pre-PEP: Allow Empty Subscript List Without Parentheses `__ - `Empty Subscript PEP on Wiki - keep or toss? `__ ------------------------------------- Creating range objects at the C level ------------------------------------- Ralf W. Grosse-Kunstleve asked about the removal of the C function ``PyRange_New()`` which had been deprecated in Python 2.4. The right way to create ranges is to call PyRange_Type with the appropriate parameters, e.g. something like ``PyObject_CallFunction((PyObject*) &PyRange_Type, "lll", start, stop, step)``. Ralf was nervous about this alternative because it also appeared to be undocumented, and requested that something like the above be at least put into the What's New document. Contributing threads: - `PyRange_New() alternative? `__ - `PyObject* aliasing (Was: PyRange_New() alternative?) `__ ---------------------------------- type(), __class__ and isinstance() ---------------------------------- Martin Maly pointed out that you can't fool isinstance() into thinking your object is not a subclass of its true base class:: >>> class C(object): ... pass ... >>> class D(object): ... __class__ = property(lambda self: C) ... >>> isinstance(D(), D) True >>> isinstance(D(), C) True Phillip J. Eby explained that isinstance() checks both the type() of the object and the __class__ attribute. In essence, you can lie about your __class__ to make isinstance() return True, but you can't lie to make it return False. Guido suggested that these issues, as well as lying about an object's __bases__, should be revisited for Python 3000. Contributing thread: - `Semantic of isinstance `__ ---------------------------------------------------------------- Requiring backward compatibility in the standard library modules ---------------------------------------------------------------- Ka-Ping Yee's uuid module, newly added for Python 2.5, contained a comment "This module works with Python 2.3 or higher". George Yoshida asked if that comment should be interpreted as requiring Python 2.3 compatibility. People generally felt like the list of backwards compatible modules in `PEP 291`_ should be as small as possible so as to keep maintenance as simple as possible. Ka-Ping removed the comment, and submitted the module to PyPI for Python 2.3 and 2.4 users. .. _PEP 291: http://www.python.org/dev/peps/pep-0291/ Contributing thread: - `uuid backward compatibility `__ --------------------- Figleaf code coverage --------------------- `Titus Brown offered some reports`_ from his `figleaf code coverage`_ utility. People seemed particularly interested in trying to get coverage across multiple platforms, perhaps using a BuildBot extension, and Titus said he'd try to look into it. Walter D?rwald also pointed to `his own code coverage module`_. .. _Titus Brown offered some reports: http://vallista.idyll.org/~t/temp/python2.4-svn/ .. _figleaf code coverage: http://darcs.idyll.org/~t/projects/figleaf-latest.tar.gz .. _his own code coverage module: http://styx.livinglogic.de/~walter/python/coverage/PythonCodeCoverage.py Contributing threads: - `Code coverage reporting. `__ - `Code coverage reporting. `__ ------------------------ Improving error messages ------------------------ Georg Brandl proposed going through abstract.c and modifying error messages like "object does not support item assignment" to also include the type of the object. He got little feedback, mainly because everyone seemed to think it was such an obviously good idea that there was no need for any. Python 2.5 now incorporates `Georg's better error messages`_. .. _Georg's better error messages: http://bugs.python.org/1507676 Contributing threads: - `Improve error msgs? `__ - `Improve error msgs? `__ ----------------------------------------- Allowing assignments in global statements ----------------------------------------- Talin proposed allowing a global statement to be combined with an assignment statement, e.g.:: global badger = 42 Guido suggested that such a desire was a sure indicator of overuse of ``global``. Contributing thread: - `Allow assignments in 'global' statements? `__ ----------------------------------------- Splitting Python tests from CPython tests ----------------------------------------- Frank Wierzbicki volunteered some time into splitting out CPython specific test from Python-the-language tests. Armin Rigo pointed him to PyPy's `tests modified to be more implementation independent`_. .. _tests modified to be more implementation independent: http://codespeak.net/svn/pypy/dist/lib-python/modified-2.4.1/test Contributing thread: - `Cleanup of test harness for Python `__ ----------------------------------------- A multi-dimensional array type for Python ----------------------------------------- For `Google's Summer of Code`_, Karol Langner will be working on `implementing a basic multi-dimensional array type`_ for Python core, based on the numpy_ array struct. He asked for any comments or suggestions that people had for the project. .. _Google's Summer of Code: http://code.google.com/summerofcode.html .. _numpy: http://www.numpy.org/ .. _implementing a basic multi-dimensional array type: http://scipy.org/BaseArray Contributing thread: - `basearray `__ ================== Previous Summaries ================== - `Source control tools `__ - `Dropping externally maintained packages (Was: Please stop changing wsgiref on the trunk) `__ =============== Skipped Threads =============== - `Last-minute curses patch `__ - `Bug in stringobject? `__ - `Fwd: subprocess.Popen(.... stdout=IGNORE, ...) `__ - `About dynamic module loading `__ - `PyString_FromFormat `__ - `Misleading error message from PyObject_GenericSetAttr `__ - `Bug: xml.dom.pulldom never gives you END_DOCUMENT events with an Expat parser `__ - `os.getmtime now returns a float? `__ - `XP build failing `__ - `ETree: xml vs xmlcore `__ - `test_ctypes failure on Mac OS X/PowerPC 10.3.9 (Panther) `__ - `Small sqlite3 test suite fix (Python 2.5b1 candidate) `__ - `Weekly Python Patch/Bug Summary `__ - `Things to remember when adding *packages* to stdlib `__ - `Moving the ctypes repository to python.org `__ - `PyObject_CallFunction and 'N' format char `__ - `pypy-0.9.0: stackless, new extension compiler `__ - `[Python-checkins] Things to remember when adding *packages* to stdlib `__ - `Import semantics `__ - `2.5b1 Windows install `__ - `Python-Dev Digest, Vol 35, Issue 143 `__ - `Problems building Python on OSX 10.4.6? `__ - `enhancements for uuid module `__ - `Do we need a bug triage day? `__ - `Oh-why that?? Please ignore one of the two `__ - `msvccompiler.py: some remarks `__ - `Joke: Rush Limbaugh (a joke in and of himself) `__ - `PyGIL_ and --without-threads `__ - `document @property? `__ - `Pickle implementation questions `__ - `sys.settrace() in Python 2.3 vs. 2.4 `__ - `how long to wait for expat to incorporate a fix to prevent a crasher? `__ - `LOAD_CONST POP_TOP `__ ======== Epilogue ======== This is a summary of traffic on the `python-dev mailing list`_ from June 16, 2006 through June 30, 2006. It is intended to inform the wider Python community of on-going developments on the list on a semi-monthly basis. An archive_ of previous summaries is available online. An `RSS feed`_ of the titles of the summaries is available. You can also watch comp.lang.python or comp.lang.python.announce for new summaries (or through their email gateways of python-list or python-announce, respectively, as found at http://mail.python.org). This python-dev summary is the 7th written by the python-dev summary slacker, Steve Bethard. To contact me, please send email: - Steve Bethard (steven.bethard at gmail.com) Do *not* post to comp.lang.python if you wish to reach me. The `Python Software Foundation`_ is the non-profit organization that holds the intellectual property for Python. It also tries to advance the development and use of Python. If you find the python-dev Summary helpful please consider making a donation. You can make a donation at http://python.org/psf/donations.html . Every cent counts so even a small donation with a credit card, check, or by PayPal helps. -------------------- Commenting on Topics -------------------- To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! ------------------------- How to Read the Summaries ------------------------- That this summary is written using reStructuredText_. Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo :); you can safely ignore it. We do suggest learning reST, though; it's simple and is accepted for `PEP markup`_ and can be turned into many different formats like HTML and LaTeX. .. _python-dev: http://www.python.org/dev/ .. _SourceForge: http://sourceforge.net/tracker/?group_id=5470 .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _c.l.py: .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _PEP Markup: http://www.python.org/peps/pep-0012.html .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _PSF: .. _Python Software Foundation: http://python.org/psf/ .. _archive: http://www.python.org/dev/summary/ .. _RSS feed: http://www.python.org/dev/summary/channews.rdf From anthra.norell at tiscalinet.ch Mon Aug 7 13:12:24 2006 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Mon, 7 Aug 2006 19:12:24 +0200 Subject: Ann: SE 2.2b References: <01d101c6b86a$fb7aa1c0$0201a8c0@mcuf7> Message-ID: <01fa01c6ba44$a6f42b40$0201a8c0@mcuf7> If you go to http://www.python.org/pypi. you see it about in the middle of the recently updated packages. It's blue, so you can click it and you're there. The update page shows only the twenty most recent updates. So they drop out at the bottom rather fast. If it's gone by the time you check, type SE into the search template in the upper right corner. Frederic ----- Original Message ----- From: "Georg Brandl" Newsgroups: comp.lang.python To: Sent: Sunday, August 06, 2006 9:22 PM Subject: Re: Ann: SE 2.2b > skip at pobox.com wrote: > > Frederic> In the short period of time since I introduced SE. the > > Frederic> feedback has been overwhelmingly postive. > > > > Ummm... what is it? The last SE I had was a Mac. > > It is supposed to be a Stream Editor (in the spirit of sed, I think). > However, the PyPI page provides no download or homepage links. > > Georg > -- > http://mail.python.org/mailman/listinfo/python-list From haha at asifIdgiveoutmyemail.com Mon Aug 14 22:04:35 2006 From: haha at asifIdgiveoutmyemail.com (sleem) Date: Tue, 15 Aug 2006 11:04:35 +0900 Subject: Python class objects as plugins? Message-ID: Hi. I'm hacking up an irc bot in python using Joel Rosdahl's irclib. I want to be able to add plugins to my bot, without having to restart it. In specific, I would have a directory called "plugins". Into this, I would place scripts that the bot could load as plugins, whenever I give it the instruction to "rehash". I figured the most practical way to do this, is to have each plugin script file basically contain a class that the program can load as an object. So I need a subroutine that can import all the classes in the plugins/ directory at start up. When instructed to rehash, it also needs to be able to destroy all the objects it currently has in memory, and reload all the class files in the plugins/ directory. What's the most practical way to do this? Thanks in advance. From claudio.grondi at freenet.de Tue Aug 1 15:38:20 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Tue, 01 Aug 2006 21:38:20 +0200 Subject: list comprehension syntax..? In-Reply-To: References: <1154451119_25085@sp6iad.superfeed.net> Message-ID: Gary Herron wrote: > Gregory Guthrie wrote: > >>Sorry for a simple question- but I don't understand how to parse this use of >>a list comprehension. >> >>The "or" clauses are odd to me. >> >>It also seems like it is being overly clever (?) in using a lc expression as >>a for loop to drive the recursion. >> >>Thanks for any insight! >>Gregory >>------------------------- >> >># http://markbyers.com/moinmoin/moin.cgi/ShortestSudokuSolver >> >>def solve(board): >> i=board.find('0') # find next open cell >> if i<0: # done if none... >> print board; exit("Done") >> [ m in [(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3) >> or board[j] for j in range(81) ] >> or solve(board[:i]+m+board[i+1:]) for m in'%d'%5**18 ] >> > > > The "or" clause (as you call it) has nothing to do with the list > comprehension. > The syntax being used here is > [ big_expression for m in something] > *and* the big_expression contains an "or" OPERATOR, with a > complex_expression on one side and solve(...) on the other, like this > complex_expression or solve(...) > *and* the complex_expression contains a nested list comprehension like this > m in nested_lc > *and* nested_lc is > [ugly_expression for j in range(81)] > *and* ugly_expression contains another "or" OPERATOR with ... > *and* sigh... > > Whoever put this expression together has made something that is > completely unreadable, mostly unmaintainable, and not noticeably more > efficient than code that is readable and maintainable. > > Moreover, all the work of creating the outer list seems to be wasted > since that list is just thrown out. > > This is worse than "overly clever". Loops are for looping, list > comprehension is for building lists. It is bad programming practice to > use list comprehension for looping. Isn't it an advantage considering speed of the execution? I have just compared the speed of an explicit loop with the speed of a list comprehension doing the same thing in another context to see it is much better to use the latter. In board solvers speed is vital, so isn't it a good practice to use a list comprehension for looping in this context, anyway? Claudio > > Hope that helps you, > Gary Herron > > >> >>----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- >>http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups >>----= East and West-Coast Server Farms - Total Privacy via Encryption =---- >> From yannick.leteigner at gmail.com Fri Aug 11 08:06:47 2006 From: yannick.leteigner at gmail.com (Yannick) Date: 11 Aug 2006 05:06:47 -0700 Subject: Rendering Vector Graphics In-Reply-To: <1155293639.748785.316170@m73g2000cwd.googlegroups.com> References: <1155293639.748785.316170@m73g2000cwd.googlegroups.com> Message-ID: <1155298007.862285.84280@b28g2000cwb.googlegroups.com> Bytter wrote: > Hi ppl, > > I've already posted this message through the mailing-list, but it seems > it never arrived here. Strange... Anyway: > > I need to render high-quality vector graphics with Python. I was > thinking of something like 'cairo', though I need to run under win32 > and can't find a pycairo package for it. Suggestions? > > Thanks, > > Hugo Ferreira Hi, You can use cairo through the pyGTK bindings. Works pretty well for me. Cheers, Yannick From steve at holdenweb.com Wed Aug 23 19:39:35 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 24 Aug 2006 00:39:35 +0100 Subject: Problem of function calls from map() In-Reply-To: References: <200608211350.k7LDoBJb032411@fe12.bluebottle.com> <2Gf*MkSor@news.chiark.greenend.org.uk> Message-ID: Fredrik Lundh wrote: > Sion Arrowsmith wrote: > > >>>(you cannot really use "profile" to *benchmark* things written in Python either; the >>>profiler tells you where a given program spends the time, not how fast it is in com- >>>parision with other programs) >> >>Hmm. Playing around with timeit suggests that although split() *is* >>faster than split("\t"), it's fractional, rather than the OP's four >>times faster. Is the overhead of profile keeping track of calls in >>Python getting in the way? > > > correct. > > >>And why can map() keep everything at the C level when the list com- > > > prehension can't? > > map is called with two Python objects (the str.split callable and the > sequence object), while the list comprehension is turned into a byte- > code loop that evaluates s.split for each item in the sequence; compare > and contrast: > > >>> def func(a): > .... return map(str.split, a) > .... > >>> dis.dis(func) > 2 0 LOAD_GLOBAL 0 (map) > 3 LOAD_GLOBAL 1 (str) > 6 LOAD_ATTR 2 (split) > 9 LOAD_FAST 0 (a) > 12 CALL_FUNCTION 2 > 15 RETURN_VALUE > > >>> def func(a): > .... return [s.split() for s in a] > .... > >>> dis.dis(func) > 2 0 BUILD_LIST 0 > 3 DUP_TOP > 4 STORE_FAST 1 (_[1]) > 7 LOAD_FAST 0 (a) > 10 GET_ITER > >> 11 FOR_ITER 19 (to 33) > 14 STORE_FAST 2 (s) > 17 LOAD_FAST 1 (_[1]) > 20 LOAD_FAST 2 (s) > 23 LOAD_ATTR 0 (split) > 26 CALL_FUNCTION 0 > 29 LIST_APPEND > 30 JUMP_ABSOLUTE 11 > >> 33 DELETE_FAST 1 (_[1]) > 36 RETURN_VALUE > > (LOAD_GLOBAL and LOAD_ATTR does full name lookups, while LOAD_FAST loads > a local variable using an integer index) > > > Well I guess if people wanted to argue for keeping the functionals this should be on the list ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From paddy3118 at netscape.net Thu Aug 17 17:56:45 2006 From: paddy3118 at netscape.net (Paddy) Date: 17 Aug 2006 14:56:45 -0700 Subject: New to python In-Reply-To: References: Message-ID: <1155851804.982140.249850@m79g2000cwm.googlegroups.com> Gallagher, Tim (NE) wrote: > Hello all, > I am new to python and I have a few questions. I am an old Perl hacker > been using Perl for many years. I wanted to give python a try, I am > happy with it so far. > Question: > 1. Is there a repository that I can go to for modules? Perl has CPAN and > I was wondering what the Python equivalent was. > > I guess that I had a few more that I cannot think of right now. > > Thanks > > Tim Welcome Tim. The stock answer to the CPAN equivalent question is that Python comes with a lot more included as standard. You really do need to browse the Library Reference Docs. http://docs.python.org/lib/ You might also want to take a look at this page on the wiki: http://wiki.python.org/moin/PerlPhrasebook Of course, this is as well as going through whatever Python tutorial you are following. Have fun, - Paddy . From jaysherby at gmail.com Tue Aug 8 20:11:00 2006 From: jaysherby at gmail.com (jaysherby at gmail.com) Date: 8 Aug 2006 17:11:00 -0700 Subject: newb question: file searching In-Reply-To: <1155067111.892386.130610@n13g2000cwa.googlegroups.com> References: <1155067111.892386.130610@n13g2000cwa.googlegroups.com> Message-ID: <1155082260.661319.240760@h48g2000cwc.googlegroups.com> Here's my code: def getFileList(): import os imageList = [] for dirpath, dirnames, filenames in os.walk(os.getcwd()): for filename in filenames: for dirname in dirnames: if not dirname.startswith('.'): if filename.lower().endswith('.jpg') and not filename.startswith('.'): imageList.append(os.path.join(dirpath, filename)) return imageList I've adapted it around all the much appreciated suggestions. However, I'm running into two very peculiar logical errors. First, I'm getting repeated entries. That's no good. One image, one entry in the list. The other is that if I run the script from my Desktop folder, it won't find any files, and I make sure to have lots of jpegs in the Desktop folder for the test. Can anyone figure this out? jaysherby at gmail.com wrote: > I'm new at Python and I need a little advice. Part of the script I'm > trying to write needs to be aware of all the files of a certain > extension in the script's path and all sub-directories. Can someone > set me on the right path to what modules and calls to use to do that? > You'd think that it would be a fairly simple proposition, but I can't > find examples anywhere. Thanks. From steve at REMOVEME.cybersource.com.au Wed Aug 16 00:16:16 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 16 Aug 2006 14:16:16 +1000 Subject: inheritance? References: <1155695711.057312.8020@p79g2000cwp.googlegroups.com> Message-ID: On Tue, 15 Aug 2006 19:35:11 -0700, KraftDiner wrote: > I have two classes: > > class implicitClass: > def __init__(self): > def isIVR(self): #This is a class private method. The convention is to flag classes as "private" with a leading underscore: def _isIVR(self): or double underscores for "really private, no, honestly": def __isIVR(self): but google on "python name mangling" before using that. [snip] > As you can see the interface is almost identical. > > How can I define a base class that will abstract > the type such that I don't know if its really and inplicit > or explicit object? Something like this? class baseClass: def __init__(self): raise NotImplementedError("Don't instantiate the base class!") def fromfile(self): def getElement(self): # etc. class implicitClass(baseClass): def __init__(self): # code def _isIVR(self): # code def fromfile(self, fileObj, byteOrder): # code # etc. Now, you can define instance = implicitClass() or explicitClass(). When you come to use instance, you don't need to know whether it is one or the other. If you need to type-test, call "isinstance(instance, baseClass)". The only minor issue is that the fromfile method has a different interface. If you really want to do duck typing, they need to have the same interface. That might be as simple as: class explicitClass(baseClass): def fromfile(self, fileObj, byteOrder=None): # byteOrder is ignored; it is included only for # compatibility with implicitClass Is that what you're asking for? -- Steven D'Aprano From tenax.raccoon at gmail.com Tue Aug 8 17:30:16 2006 From: tenax.raccoon at gmail.com (Jason) Date: 8 Aug 2006 14:30:16 -0700 Subject: New to Python-- Help In-Reply-To: <3%6Cg.57$1W7.17@fe04.lga> References: <3%6Cg.57$1W7.17@fe04.lga> Message-ID: <1155072616.577741.17430@m73g2000cwd.googlegroups.com> John & Mary Cook wrote: > I just installed Python on Windows XP Pro. When I enter 'python' at the >>> > prompt in Pythonwin IDE I get the following: > > Traceback (most recent call last): > File "", line 1, in ? > Name Error: name 'python' is not defined > > Can anyone help? > > Thank you, > > J. T. Cook That's because the Pythonwin IDE with the >>> prompt is already running the Python interpreter. The Python interpreter allows you to run python statements and expressions with instant feedback. Python doesn't define the 'python' name inside of itself. I recommend that you read through the Python tutorial, and maybe do a Google search for Python tutorials. When you next see the >>> prompt, try typing in the following: import this print ' '.join( ('Python', 'rocks!') ) From simen.haugen at norstat.no Fri Aug 11 09:10:18 2006 From: simen.haugen at norstat.no (Simen Haugen) Date: Fri, 11 Aug 2006 15:10:18 +0200 Subject: datetime to timestamp Message-ID: <14DF11D3461F3F43859E6B99D9A7911F4D62E6@HEIMDAL.nordicstats.com> Hi. How can I convert a python datetime to a timestamp? It's easy to convert a timestamp to datetime (datetime.datetime.fromtimestamp(), but the other way around...?) -Simen From siona at chiark.greenend.org.uk Wed Aug 9 10:11:08 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 09 Aug 2006 15:11:08 +0100 (BST) Subject: How to reverse tuples in a list? References: <1155081671.728757.228050@p79g2000cwp.googlegroups.com> Message-ID: Robert Kern wrote: >Python 2.4+: > > y = [tuple(reversed(t)) for t in y] > Python 2.3: y = [ t[::-1] for t in y ] Obviously works in 2.4 as well, where I make it faster than using tuple(reversed(t)). Which isn't surprising, as it's not constructing the intermediate list. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From meyer at acm.org Thu Aug 31 14:25:58 2006 From: meyer at acm.org (Andre Meyer) Date: Thu, 31 Aug 2006 20:25:58 +0200 Subject: dictionaries vs. objects In-Reply-To: References: <7008329d0608241906t551f39efif0afeb666d9df0fc@mail.gmail.com> Message-ID: <7008329d0608311125u6db50de7n34d4b74b8d4a17d9@mail.gmail.com> On 8/28/06, Steve Holden wrote: > > Andre Meyer wrote: > > Hi all > > > > I have the following question: I need a representation of a physically > > inspired environment. The environment contains a large number of objects > > with varying attributes. There may be classes of objects, but there is > > not necessarily a strictly defined hierarchy among them. Object access > > should be fast, because there a many objects that change often ( e.g., > > moving objects). > > > > My approach is to use a dictionary for the environment model and store > > each object as a slot, which contains either a dictionary or an object. > > Now, which is better? What is the performance of Python to look up > > attributes as either slots of a dictionary or attributes of an object? > > What feels more logical? What is more pythonic and performs better? > > Which is constructed and modified easier and quicker? Are there effects > > that I am not yet aware of? > > > I'd suggest using objects: quite apart from the fact that name lookup in > a namespace is pretty much equivalent to a dictionary lookup (namespaces > use an internal optimised dictionary-style object) remember that objects > can have methods, and that the names are given as attributes rather than > as strings. >From another thread I learned that lookup in dictionaries is way faster than accessing object attributes (which makes use of an internal dictionary). However, the syntax is cleaner with objects and having methods and properties is a plus. So, it seems like it is about speed vs. elegance... regards Andre -------------- next part -------------- An HTML attachment was scrubbed... URL: From moqtar at gmail.com Sat Aug 26 03:23:26 2006 From: moqtar at gmail.com (Kirt) Date: 26 Aug 2006 00:23:26 -0700 Subject: Problem with List of List In-Reply-To: <7xodu8ugnj.fsf@ruckus.brouhaha.com> References: <1156569535.500196.7920@i3g2000cwc.googlegroups.com> <1156573379.951900.199030@m79g2000cwm.googlegroups.com> <1156574043.891794.266390@75g2000cwc.googlegroups.com> <7xodu8ugnj.fsf@ruckus.brouhaha.com> Message-ID: <1156577006.542110.291770@i3g2000cwc.googlegroups.com> Paul Rubin wrote: > "Kirt" writes: > > Actually here in my code ['1', 'a', '6'], ['1', 'b', '6'], ['1', 'c', > > '6'] means: > > 1==> Directory name; > > a,b,c,d=== Filename > > 6 ==> modified time > > > > So i want the out put like: > > Directory name: 1 > > Filename:a > > modified time:6 > > Try writing the code in a style with fewer side effects. I like using > itertools.groupby for this type of thing (not exactly tested): > > from itertools import groupby > > List=[['1', 'a', '6'], ['1', 'b', '6'], ['1', 'c', '6'], > ['1', 'd', '6'],['2', 'a','6'], ['2', 'b', '6'], > ['2', 'c', '6'], ['2', 'd', '6'], ['3', 'a', '6'], > ['3','b', '6'], ['4', 'a', '6'], ['4', 'b', '6']] > > # retrieve directory name from one of those tuples > def directory_name(t): return t[0] > > for dirname,dir_contents in groupby(sorted(List), directory_name): > print 'Directory name:, dirname > for dname2,filename,modtime in dir_contents: > print 'Filename:%s\nmodified time:%s'% (filename, modtime) > > The output is: > > >>> ## working on region in file /usr/tmp/python-9013z7X... > Directory name: 1 > Filename:a > modified time:6 > Filename:b > modified time:6 > Filename:c > modified time:6 > Filename:d > modified time:6 > Directory name: 2 > Filename:a > modified time:6 > Filename:b > modified time:6 > Filename:c > modified time:6 > Filename:d > modified time:6 > Directory name: 3 > Filename:a > modified time:6 > Filename:b > modified time:6 > Directory name: 4 > Filename:a > modified time:6 > Filename:b > modified time:6 > >>> > > Is that what you wanted? Thanx Paul. Thats exactly what i wanted. ur piece of code has reduced my overall code by half. thanx again. From webraviteja at gmail.com Wed Aug 9 17:25:41 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 9 Aug 2006 14:25:41 -0700 Subject: The decentralized nature of the Python community is driving me crazy In-Reply-To: <1155157572.915538.280350@i3g2000cwc.googlegroups.com> References: <1155157572.915538.280350@i3g2000cwc.googlegroups.com> Message-ID: <1155158741.058177.13630@h48g2000cwc.googlegroups.com> > But I must say the one thing I miss about Perl is my ability to stay on > top of all the latest modules and apps in one place: CPAN. With Python, > code is EVERYWHERE - people's local boxes, sourceforge, freshmeat, > codezoo, parnassus, etc, etc. Python CheeseShop is equivalent to CPAN http://www.python.org/pypi Easy Install provides a nice client http://peak.telecommunity.com/DevCenter/EasyInstall From vasudevram at gmail.com Sat Aug 19 09:38:44 2006 From: vasudevram at gmail.com (vasudevram) Date: 19 Aug 2006 06:38:44 -0700 Subject: Packt published an article about xtopdf - creating PDF from Plain Text, DBF, CSV, TDV, and XLS Data Message-ID: Hi group, This is an article I wrote for Packt Publishing - http://www.packtpub.com : Using xtopdf, a PDF creation toolkit - http://www.packtpub.com/article/Using_xtopdf It shows how to use xtopdf - http://sourceforge.net/projects/xtopdf - to create PDF from plain text, DBF, CSV, TDV and XLS data. Use of both command-line and the GUI tools in xtopdf is covered. xtopdf is written in Python and requires the ReportLab toolkit. The GUI tools are written in wxPython - http://www.wxpython.org. Enjoy Vasudev Ram ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Software consulting and training http://www.dancingbison.com ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From sjmachin at lexicon.net Wed Aug 30 03:17:58 2006 From: sjmachin at lexicon.net (John Machin) Date: Wed, 30 Aug 2006 17:17:58 +1000 Subject: The lib email parse problem... In-Reply-To: <1156920257.020916.268490@m73g2000cwd.googlegroups.com> References: <1156837260.222395.305960@b28g2000cwb.googlegroups.com> <1156841437.692537.68200@i42g2000cwa.googlegroups.com> <1156841950.866776.66400@b28g2000cwb.googlegroups.com> <1156842395.855885.183330@p79g2000cwp.googlegroups.com> <1156844520.044398.7900@h48g2000cwc.googlegroups.com> <1156919044.575120.195580@i42g2000cwa.googlegroups.com> <1156920257.020916.268490@m73g2000cwd.googlegroups.com> Message-ID: <44F53BA6.7000705@lexicon.net> On 30/08/2006 4:44 PM, ???? wrote: > yes, the special is i must choose exactly one section to destruct, > instead of processing all subparts. So have you tried to use the example I posted yesterday? Do you still have any problems? Note: it is generally a good idea to post a message when you have overcome a problem -- that lets would-be helpers know that they are "off the case" :-) Cheers, John From steve at REMOVEME.cybersource.com.au Mon Aug 14 04:55:18 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Mon, 14 Aug 2006 18:55:18 +1000 Subject: hide python code ! References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155300852.497741.73230@74g2000cwt.googlegroups.com> <1155301468.870340.82920@b28g2000cwb.googlegroups.com> <1155307415.855555.124760@i3g2000cwc.googlegroups.com> <1155309563.898182.195950@p79g2000cwp.googlegroups.com> <1155313092.743230.33950@m73g2000cwd.googlegroups.com> Message-ID: On Fri, 11 Aug 2006 09:18:12 -0700, Ben Sizer wrote: > Imagine if you were the single-person developer of a small application > that did something quite innovative, And imagine that you found a money-tree in your back yard... How about a more likely scenario? Imagine you're using a boring, run-of-the-mill algorithm, the same as 99.9% of all software out there, and that it's neither non-obvious nor innovative in any way at all. Statistically, I'd say it is ten thousand times more likely that this is the case than that the algorithm is at all valuable. Everybody thinks their algorithm is "special". They almost never are. Even this is more likely than the semi-mythical algorithm that needs to be kept secret: the reason "you" (generic you) want to keep your software secret is because you've copied source code -- from books, from your friends, from Open Source projects, maybe even from stolen copies of Windows source code you've downloaded from the darker corners of the Internet, and you don't want people to know. That's more likely than you hitting upon an amazing new innovative AND valuable algorithm. Valuable algorithms are rare. Most software is not valuable for the algorithm, which is hidden in the source code, but for the functionality, which is obvious. Algorithms are a dime a dozen. >> It may not matter if some console game or other doesn't work after 20 >> years... > > Certainly; yet this is a valid example of software that requires a > degree of protection since some of the algorithms employed truly are > 'worth stealing'. Yes, and for every algorithm "worth stealing", there are ten thousand that aren't. Play the odds, and you too will poo-poo the idea that some random developer on Usenet has discovered a valuable innovative algorithm. More likely he's just ashamed of his code, or wants to hide backdoors in it. -- Steven D'Aprano From kylotan at gmail.com Fri Aug 25 05:58:11 2006 From: kylotan at gmail.com (Ben Sizer) Date: 25 Aug 2006 02:58:11 -0700 Subject: Pygame, mouse events and threads In-Reply-To: <1156423036.392565.173490@i3g2000cwc.googlegroups.com> References: <1156421018.882740.166810@b28g2000cwb.googlegroups.com> <1156422427.974304.272200@m79g2000cwm.googlegroups.com> <1156423036.392565.173490@i3g2000cwc.googlegroups.com> Message-ID: <1156499891.766450.245280@h48g2000cwc.googlegroups.com> jedi200581 at yahoo.co.uk wrote: > Ben Sizer wrote: > > jedi200581 at yahoo.co.uk wrote: > > > > > When I put the content of the run and input functions in the main > > > thread, it's working, why not in the thread? > > > > Because event handling needs to be done in the main thread. So does > > rendering. This is a limitation of the underlying system. > > > > As a general rule, try to keep all your PyGame functions in the main > > thread and push your other processing into background threads, if you > > really need them. > > Well, that is a limitation... And is it something that will be fixed or > something that is inherent to pygame and not fixable? It's inherent to SDL (the library underpinning PyGame), because it's apparently inherent to some of the platforms it runs on. Rendering and event handling is typically tied closely to the notion of a window and that in turn may well be coupled tightly to a single process or thread. As Diez said however, this is not generally a big problem. Most games are typically single-threaded anyway. -- Ben Sizer From Mark.Geyzer at gmail.com Thu Aug 24 10:18:23 2006 From: Mark.Geyzer at gmail.com (volcano) Date: 24 Aug 2006 07:18:23 -0700 Subject: Is there an elegant way to dir() module from inside? Message-ID: <1156429103.823271.204880@m73g2000cwd.googlegroups.com> I am looking for a way to discover which classes a module contains from "inside". I am building a testing class that should, when instatntiated within any module, locate certain classes within the containing module. Words of wisdom? Anybody? From roy at panix.com Sat Aug 19 10:08:49 2006 From: roy at panix.com (Roy Smith) Date: Sat, 19 Aug 2006 10:08:49 -0400 Subject: Questions on unittest behaviour References: Message-ID: In article , "Collin Winter" wrote: > While working on a test suite for unittest these past few weeks, I've > run across some behaviours that, while not obviously wrong, don't > strike me as quite right, either. Submitted for your consideration: > > 1) TestCase.tearDown() is only run if TestCase.setUp() succeeded. It > seems to me that tearDown() should always be run, regardless of any > failures in setUp() or the test method itself. I look at setUp() as a constructor. It's the constructor's job to either completely construct an object, or clean up after itself. With your example: > > def setUp(self) > > lock_file(testfile) # open_socket(), connect_to_database(), etc > > > > something_that_raises_an_exception() > > > > def tearDown(self): > > if file_is_locked(testfile): > > unlock_file(testfile) It would be cleaner to just do: def setUp(self): lock_file() try: something_that_raises_an_exception() except unlock_file() raise > In this pseudo-code example, the file won't be unlocked if some later > operation in setUp() raises an exception. I propose that > TestCase.run() be changed to always run tearDown(), even if setUp() > raise an exception. While this might simplify setUp() methods, it complicates tearDown()s, because now they can't be sure what environment they're running in. One way or the other, somebody has to deal with exceptions in setUp(). Keeping the exception handling code as close to the source of the exception seems like the right thing to do. From claird at lairds.us Tue Aug 1 16:42:26 2006 From: claird at lairds.us (Cameron Laird) Date: Tue, 1 Aug 2006 20:42:26 +0000 Subject: Using Python for my web site References: <1154361480.915174.262720@b28g2000cwb.googlegroups.com> <1insadcgifsbv.dlg@gelists.gmail.com> <1154382025.809952.165190@b28g2000cwb.googlegroups.com> Message-ID: In article <1154382025.809952.165190 at b28g2000cwb.googlegroups.com>, northband wrote: >Just spoke with my department and looks like we still want to go with a >server scripting method. Although MVC may be better fit, for the sake >of the learning curve, we want to use a PSP style method. . . . I'll explicitly reinforce what others have mentioned already: MVC, PSP, and server-side scripting don't partition solution space in the way your description suggests. You can use an MVC model, and implement on the server-side, for example. I'm not arguing with your decision, which I suspect I don't understand; I just don't want you excluding combinations that turn out to be mutually compatible. From micha.brandt at gmail.com Wed Aug 2 11:15:59 2006 From: micha.brandt at gmail.com (Michael Brandt) Date: Wed, 2 Aug 2006 17:15:59 +0200 Subject: upgrading python... In-Reply-To: <0b0d01c6b63a$9359eba0$0301a8c0@Mesa.com> References: <0b0d01c6b63a$9359eba0$0301a8c0@Mesa.com> Message-ID: <2d660e2c0608020815v7b23ff44yeb6303b553cee83f@mail.gmail.com> > i'min a situation where i might need to upgrade python. i have the current > version of python for FC3. i might need to have the version for FC4. i built > the version that's on FC4 from the python source RPM. You could try the precompiled Python distribution from ActiveState (AS package (libcpp5*)): http://activestate.com/Products/Download/Download.plex?id=ActivePython Install it under /opt or somewhere else, where it doesn't conflict with your existing python installation. The drawback is, that you may install other 3rd party python packages on your own. -Michael From jjl at pobox.com Thu Aug 10 18:01:39 2006 From: jjl at pobox.com (John J. Lee) Date: Thu, 10 Aug 2006 22:01:39 GMT Subject: Announcing Switch, the CSS Preprocessor! References: <1155149749.559985.177250@b28g2000cwb.googlegroups.com> <1155152845.319691.203390@m79g2000cwm.googlegroups.com> Message-ID: <877j1gp7wc.fsf@pobox.com> "Dave" writes: > It's not tied deeply to mod_python. > > The processor works like this: > > You create an "sss" file, using Switch specific features. Then, you > place the file under Apache/mod_python OR you can use the command-line > Switch tool to process the SSS file and output a CSS file. In this way, > it works very similar to an XSLT transformation in that you write using > a shorthand method that outputs to a more verbose, crystallized file. > > This way, it's platform agnostic. I'm also kicking around the idea of a > GUI tool. > > The reason we didn't give it the ability to "preprocess if changed" is > because we're looking forward to implementing a system that can handle > conditional statements: > > if $BROWSER is IE and $BROWSER_VERSION > 6 { > > /* output this */ > > } else { > > /* output this */ > > } > > This would need to be compiled with every request. Maybe, though, we > could have different settings in which you could compile with every > request, compile on change, or precompile... [...] How about a mod_rewrite rule or two to auto-generate the .css files from the .sss files? That way, you retain really fast static-file Apache serving of CSS, no Python process involved except for the very first hit on each .css file. To invalidate the cache, rm *.css (you can do this as part of the code promotion process). We've used this at work with PDF files, and it works nicely. I think you could still implement the browser detection thing exactly as you describe it with this scheme just by auto-generating more than one .css file per .sss file (perhaps making use of CSS imports), and referencing the appropriate .css file in your dynamically-generated HTML (or, if static HTML and JavaScript, using document.write to reference the right .css file). John From aisaac0 at verizon.net Mon Aug 28 10:36:35 2006 From: aisaac0 at verizon.net (David Isaac) Date: Mon, 28 Aug 2006 14:36:35 GMT Subject: TNEF decoder Message-ID: I'm aware of http://cheeseshop.python.org/pypi/pytnef/ but it uses the tnef utility, and I'd like a pure Python solution (along the lines of http://www.freeutils.net/source/jtnef/ ). Is there one? Thanks, Alan Isaac From cookedm+news at physics.mcmaster.ca Wed Aug 23 18:55:00 2006 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Wed, 23 Aug 2006 18:55:00 -0400 Subject: setting a breakpoint in the module References: Message-ID: "Jason Jiang" writes: > Hi, > > I have two modules: a.py and b.py. In a.py, I have a function called > aFunc(). I'm calling aFunc() from b.py (of course I import module a first). > The question is how to directly set a breakpoint in aFunc(). > > The way I'm doing now is to set a breakpoint in b.py at the line to call > aFunc(), 'c' to it, then 's' to step in, then set the breakpoint inside > aFunc() by 'b lineNumber'. It's too cumbersome. You can also add in your source import pdb; pdb.set_trace() at the point you want the debugger to stop. Useful if you want to break after some failing condition, for instance. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From kowadam at gmail.com Sat Aug 26 06:09:14 2006 From: kowadam at gmail.com (Kowalski) Date: 26 Aug 2006 03:09:14 -0700 Subject: mechanize, how send forms? Message-ID: <1156586954.498802.143960@m73g2000cwd.googlegroups.com> from mechanize import Browser br = Browser() br.open("http://www.google.com") #example for form in br.forms(): print form br.select_form(name="f") br["q"] = "Blah" #??? #response1=br.submit() #??? From fredrik at pythonware.com Thu Aug 24 12:16:30 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Aug 2006 18:16:30 +0200 Subject: telnetlib thread-safe? In-Reply-To: <1156434867.163326.42160@i42g2000cwa.googlegroups.com> References: <1156434867.163326.42160@i42g2000cwa.googlegroups.com> Message-ID: Jerry wrote: > Can anyone tell me if the telnetlib module is thread-safe? define thread-safe. how do you plan to use it? From no at spam.com Wed Aug 30 00:39:29 2006 From: no at spam.com (Farshid Lashkari) Date: Tue, 29 Aug 2006 21:39:29 -0700 Subject: Releasing GIL in unknown state Message-ID: Hi, Is there a proper way for C code to ensure that the GIL is released? I know about PyGILState_Ensure and PyGILState_Release, but that is to ensure the GIL is acquired. I have some extension code that does heavy processing and I want to release the GIL, but the code can't be sure that the GIL is already acquired. All I can think of so far is the following: PyGILState_STATE state = PyGILState_Ensure(); Py_BEGIN_ALLOW_THREADS //do processing Py_END_ALLOW_THREADS PyGILState_Release(state) Is there a better way? -Farshid From Mohit.Bhatt at grapecity.com Mon Aug 28 11:55:18 2006 From: Mohit.Bhatt at grapecity.com (Mohit Bhatt) Date: Mon, 28 Aug 2006 21:25:18 +0530 Subject: Operator Overloading Basics Message-ID: <1700BE453DBC09459A81AB53553E64CDDF0373@inexg.GRAPECITY.NET> Hello, I just started out with python( couple of weeks). I have a query regarding Operator Overloading class c1: def __init__(self,value): self.data = value def __add__ (self,operand2): self.data += operand2 obj1 = c1(1) obj1 + 10 # this works just fine 10 + obj1 # throws exception Exception Details Traceback (most recent call last): File "", line 1, in -toplevel- 10+ obj1 TypeError: unsupported operand type(s) for +: 'int' and 'instance' Q. What do I have to do to make the following line work? 10 + obj1 Thanks and regards Mohit -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Wed Aug 16 16:45:44 2006 From: sjmachin at lexicon.net (John Machin) Date: 16 Aug 2006 13:45:44 -0700 Subject: PySequence_SetItem In-Reply-To: <1155755905.233229.93440@74g2000cwt.googlegroups.com> References: <1155754847.392950.266180@h48g2000cwc.googlegroups.com> <1155755905.233229.93440@74g2000cwt.googlegroups.com> Message-ID: <1155761144.583994.260150@m73g2000cwd.googlegroups.com> Bill Pursell wrote: > Bill Pursell wrote: > > Also note that the problem goes away if I replace > the call to PySequence_SetItem with: > PySequence_SetItem(l, 0, PyInt_FromLong(1L)); Are you sure? It should make absolutely no difference. My experience so far: 1. crashes in call to PySequence_SetItem 2. removed py_DECREF, s/Sequence/List/ -> works OK 3. added code to test return value from PyWhatever_SetItem [you should *always* test for error], s/Sequence/Object/ -> PyObject_SetItem call returns -1, PyErr_Print -> "SystemError: null argument to internal routine" Looks like a bug or two. I'll rummage a bit more. Cheers, John From muppadivya at gmail.com Tue Aug 8 23:01:37 2006 From: muppadivya at gmail.com (Ch3ru5) Date: 8 Aug 2006 20:01:37 -0700 Subject: Regd:Video Converter Programming Message-ID: <1155092497.011057.219180@m79g2000cwm.googlegroups.com> Hi, I want to write an avi to flv converter in php but i am a complete newbie to it. I would like to know the basic flow of entire process of how a converter code is written (ie. the basic algorithm ) . Example: "You first create an flv stream , then compress the avi code , then copy that code into the flv stream created ." The above flow may or may not be correct but what i want to know is this flow . Any good tutorials or resources where i can learn the basics. Thank You, Raja. From fredrik at pythonware.com Thu Aug 31 13:42:17 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 31 Aug 2006 19:42:17 +0200 Subject: Basic import Questions (with bonus profiling question) In-Reply-To: <312cfe2b0608311002s3c24cd42t1206ebdc198a69c7@mail.gmail.com> References: <312cfe2b0608310849m6967e2cx259046143728b29e@mail.gmail.com> <312cfe2b0608311002s3c24cd42t1206ebdc198a69c7@mail.gmail.com> Message-ID: Gregory Pi?ero wrote: >> several seconds? sounds bad. what does the following script print on >> your machine? >> >> import time, subprocess, sys >> >> t0 = time.time() >> for i in range(10): >> subprocess.call([sys.executable, "-c", "pass"]) >> print time.time() - t0 > > It prints 1.92199993134 > What does that mean? that it takes just under two seconds to start the interpreter ten times. not stunningly fast, but not too bad. > By the way, I thought I was importing just a file path from a module > but like you said it was importing the entire module. I got rid of > that import statement and the time dropped from 7 seconds to 1.5 > seconds. what module is this? if it takes 5.5 seconds to import a single module, something isn't quite right. From antroy at gmail.com Sat Aug 19 02:41:03 2006 From: antroy at gmail.com (Ant) Date: 18 Aug 2006 23:41:03 -0700 Subject: text editor suggestion? In-Reply-To: <44e6ab26$0$12557$c3e8da3@news.astraweb.com> References: <44e66724$0$2363$c3e8da3@news.astraweb.com> <44e6ab26$0$12557$c3e8da3@news.astraweb.com> Message-ID: <1155969663.460494.135680@p79g2000cwp.googlegroups.com> John Salerno wrote: > I'd really like to learn vim, but I spent days just trying to figure out > how to get the syntax highlighting and indentation working, where these > settings are and how to edit them, and it still doesn't work for me. It > just feels so insurmountable that I can't even start working with it yet > because I don't know how to tailor the settings. FWIW I started to use vim 2 years ago, and hated every minute of it. However, it was installed on every unix/linux box I have known, and so I gradually learned the most common commands. Recently I have been using gvim on windows, which comes pre-configured to syntax highlight etc. It isn't very good at running the current buffer as far as I can tell though, so I still have a command line open currently. jEdit is also a very good editor with the same sort of feature set as vim. Bit slower to load, but much more user freindly and a very powerful editor core. With a few extra plugins (console and Jython interpreter for example) it has all of the features you want, including he ability to write macros in python. (Note vim is also customisable using python). From pmaupin at gmail.com Tue Aug 8 00:48:58 2006 From: pmaupin at gmail.com (Patrick Maupin) Date: 7 Aug 2006 21:48:58 -0700 Subject: is it possible to dividing up a class in multiple files? In-Reply-To: <4jouimF8ue5nU1@uni-berlin.de> References: <4jouimF8ue5nU1@uni-berlin.de> Message-ID: <1155012538.021662.316710@n13g2000cwa.googlegroups.com> Diez B. Roggisch wrote: > Martin H?fling wrote: > > > is it possible to put the methods of a class in different files? I just > > want to order them and try to keep the files small. > > No, its not possible. What you can do is to create several classes and one > that inherits from all of them. > > Better yet is to not write huge classes and getting rid of strange > conventions or views that make the problem appear as such. To explain that: > I've never felt the need to spread a class over several files - au > contraire, I despise Java for forcing me to only have one top level class > per file. While refactoring to avoid huge classes is usually excellent advice, it actually is possible (and sometimes even useful) to merge classes without using inheritance. See, for example, http://www.webwareforpython.org/MiscUtils/Docs/Source/Files/MixIn.html Regards, Pat From paul at boddie.org.uk Thu Aug 3 11:18:27 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 3 Aug 2006 08:18:27 -0700 Subject: Using Python for my web site References: <1154361480.915174.262720@b28g2000cwb.googlegroups.com> <44ce3a5c$0$18952$626a54ce@news.free.fr> <1154367359.931684.106650@m73g2000cwd.googlegroups.com> <44ce4530$0$28242$626a54ce@news.free.fr> <19zmaoel1tn3$.dlg@gelists.gmail.com> <1154567858.20290.324.camel@devilbox> Message-ID: <1154618307.626685.274340@m73g2000cwd.googlegroups.com> Cliff Wells wrote: > On Wed, 2006-08-02 at 23:13 -0300, Gerhard Fiedler wrote: > > Another one is that it seems (here I go again :) that there is something > > like a marriage between Python and PostgreSQL (or in other words, that > > Python fans that develop web apps have a tendency to favor PostgreSQL). Is > > there something like this? (Here is the question :) Take a look at Harald Armin Massa's EuroPython talk abstract for evidence of "something like a marriage": http://indico.cern.ch/contributionDisplay.py?contribId=0&sessionId=41&confId=44 Where are the slides, Harald? ;-) > I don't think so. If I had to venture an opinion, my impression has > been that the MySQL/PostgreSQL division lies more along the line between > web applications and other types of apps. For some reason, web people > seem to either prefer MySQL or (more likely) fall back to it as a > default. I'd argue that since MySQL was reportedly easier to install on Windows than PostgreSQL until relatively recently (ie. until a few years ago), and that MySQL appealed to the lightweight database system niche that mSQL occupied a few years before that, people didn't hesitate to install it in situations where just considering installing something else might have put them off. Meanwhile, PostgreSQL has been around for so long that it probably has a place in the hearts of people who remember the era when you'd use UNIX for serious research or enterprise endeavours and where PostgreSQL was the best open source tool for the task. Of course, most GNU/Linux distributions have packaged both of them for some time. > If there's a bias toward PostgreSQL in the Python crowd, I > suspect that's due to the fact that Python's presence seems to be more > weighted toward non-web programming relative to other languages (this > being due to Python's general applicability, not an implication Python > isn't suited for the web). I'd like to hope that it's because Python people stop to consider the established alternatives rather than following the stampede to the latest "hot product". Paul From lannsjo at gmail.com Thu Aug 31 09:35:19 2006 From: lannsjo at gmail.com (lannsjo at gmail.com) Date: 31 Aug 2006 06:35:19 -0700 Subject: simultaneous copy to multiple media Message-ID: <1157031319.315438.4950@b28g2000cwb.googlegroups.com> I need a program that simultaneously can copy a single file (1 GB) from my pc to multiple USB-harddrives. I have searched the internet and only found one program that does this on http://mastermind.com.pl/multicopy/ but this link doesnt work anymore???? somebody that can help me, is there any other programs out there. From mlacunza at gmail.com Wed Aug 16 14:32:41 2006 From: mlacunza at gmail.com (Mario Lacunza) Date: Wed, 16 Aug 2006 13:32:41 -0500 Subject: Problems with Sizers Message-ID: <1155753161.8675.11.camel@localhost> Hello, I have troubbles in this code when I try to resize the form, all the widgets dont move. Any idea? Thansk in advance! ----------------------------------------------------------------------------- # -*- coding: utf8 -*-# #Boa:Dialog:frmPostales import wx #import modGlobals #from Conectar import Conectar #import errores def create(parent): return frmPostales(parent) [wxID_FRMPOSTALES, wxID_FRMPOSTALESBTNCANCELAR, wxID_FRMPOSTALESBTNOK, wxID_FRMPOSTALESCBODISTRI, wxID_FRMPOSTALESCBODPTO, wxID_FRMPOSTALESCBOPAIS, wxID_FRMPOSTALESCBOPROV, wxID_FRMPOSTALESLBLCOD, wxID_FRMPOSTALESLBLDISTRO, wxID_FRMPOSTALESLBLDPTO, wxID_FRMPOSTALESLBLPAIS, wxID_FRMPOSTALESLBLPOSTAL, wxID_FRMPOSTALESLBLPROV, ] = [wx.NewId() for _init_ctrls in range(13)] class frmPostales(wx.Dialog): def _init_ctrls(self, prnt): # generated method, don't edit wx.Dialog.__init__(self, id=wxID_FRMPOSTALES, name=u'frmPostales', parent=prnt, pos=wx.Point(579, 295), size=wx.Size(254, 197), style=wx.DEFAULT_FRAME_STYLE, title=u'C\xf3digos Postales') self.SetClientSize(wx.Size(254, 197)) self.btnOk = wx.Button(id=wxID_FRMPOSTALESBTNOK, label=u'Aceptar', name=u'btnOk', parent=self, pos=wx.Point(28, 148), size=wx.Size(85, 34), style=0) self.btnOk.SetToolTipString(u'Aceptar') self.btnOk.Bind(wx.EVT_BUTTON, self.OnBtnOkButton, id=wxID_FRMPOSTALESBTNOK) self.btnCancelar = wx.Button(id=wxID_FRMPOSTALESBTNCANCELAR, label=u'Cancelar', name=u'btnCancelar', parent=self, pos=wx.Point(133, 148), size=wx.Size(85, 34), style=0) self.btnCancelar.SetToolTipString(u'Salir') self.btnCancelar.Bind(wx.EVT_BUTTON, self.OnBtnCancelarButton, id=wxID_FRMPOSTALESBTNCANCELAR) self.lblPais = wx.StaticText(id=wxID_FRMPOSTALESLBLPAIS, label=u'Pa\xeds', name=u'lblPais', parent=self, pos=wx.Point(18, 18), size=wx.Size(20, 12), style=0) self.cboPais = wx.ComboBox(choices=[], id=wxID_FRMPOSTALESCBOPAIS, name=u'cboPais', parent=self, pos=wx.Point(123, 18), size=wx.Size(117, 27), style=0, value=u'') self.cboPais.SetLabel(u'') self.cboPais.SetToolTipString(u'Pais') self.cboPais.Bind(wx.EVT_COMBOBOX, self.OnCboPaisCombobox, id=wxID_FRMPOSTALESCBOPAIS) self.lblDpto = wx.StaticText(id=wxID_FRMPOSTALESLBLDPTO, label=u'Departamento', name=u'lblDpto', parent=self, pos=wx.Point(18, 45), size=wx.Size(70, 12), style=0) self.cboDpto = wx.ComboBox(choices=[], id=wxID_FRMPOSTALESCBODPTO, name=u'cboDpto', parent=self, pos=wx.Point(123, 45), size=wx.Size(117, 27), style=0, value=u'') self.cboDpto.SetLabel(u'') self.cboDpto.SetToolTipString(u'Departamentos') self.cboDpto.Bind(wx.EVT_COMBOBOX, self.OnCboDptoCombobox, id=wxID_FRMPOSTALESCBODPTO) self.lblProv = wx.StaticText(id=wxID_FRMPOSTALESLBLPROV, label=u'Provincia', name=u'lblProv', parent=self, pos=wx.Point(18, 72), size=wx.Size(45, 12), style=0) self.cboProv = wx.ComboBox(choices=[], id=wxID_FRMPOSTALESCBOPROV, name=u'cboProv', parent=self, pos=wx.Point(123, 72), size=wx.Size(117, 27), style=0, value=u'') self.cboProv.SetLabel(u'') self.cboProv.SetToolTipString(u'Provincias') self.cboProv.Bind(wx.EVT_COMBOBOX, self.OnCboProvCombobox, id=wxID_FRMPOSTALESCBOPROV) self.lblDistro = wx.StaticText(id=wxID_FRMPOSTALESLBLDISTRO, label=u'Distrito', name=u'lblDistro', parent=self, pos=wx.Point(18, 99), size=wx.Size(36, 12), style=0) self.cboDistri = wx.ComboBox(choices=[], id=wxID_FRMPOSTALESCBODISTRI, name=u'cboDistri', parent=self, pos=wx.Point(123, 99), size=wx.Size(117, 27), style=0, value=u'') self.cboDistri.SetLabel(u'') self.cboDistri.SetToolTipString(u'Distritos') self.cboDistri.Bind(wx.EVT_COMBOBOX, self.OnCboDistriCombobox, id=wxID_FRMPOSTALESCBODISTRI) self.lblCod = wx.StaticText(id=wxID_FRMPOSTALESLBLCOD, label=u'C\xf3digo Postal:', name=u'lblCod', parent=self, pos=wx.Point(18, 126), size=wx.Size(70, 12), style=0) self.lblPostal = wx.StaticText(id=wxID_FRMPOSTALESLBLPOSTAL, label=u'', name=u'lblPostal', parent=self, pos=wx.Point(123, 126), size=wx.Size(117, 12), style=0) self.lblPostal.SetToolTipString(u'Ubigeo') def __init__(self, parent): self._init_ctrls(parent) self.CargarSizers(parent) #Instancia la Clase # self.oPostal=Postal() #Establece el encoding segun el OS # TODO: Revizar este codigo de encoding!!!! if wx.Platform=="__WXMSW__": self.encode='iso-8859-1' elif wx.Platform=="__WXGTK__": self.encode='utf8' # self.CargarComboPais() #------------------------------------------------------------------------------- def CargarSizers(self,parent): """ Funcion q cargara los sizers del form.""" panel=wx.Panel(self) #Se declara el Sizer principal mSizer=wx.BoxSizer(wx.HORIZONTAL) #Agregar sizer de ctrls ctrlSizer=wx.FlexGridSizer(rows=6,cols=2,hgap=5,vgap=5) ctrlSizer.AddGrowableCol(1) #Se agregan los controles ctrlSizer.Add(self.lblPais,0,wx.ALIGN_RIGHT| wx.ALIGN_CENTER_VERTICAL) ctrlSizer.Add(self.cboPais,0,wx.EXPAND) ctrlSizer.Add(self.lblDpto,0,wx.ALIGN_RIGHT| wx.ALIGN_CENTER_VERTICAL) ctrlSizer.Add(self.cboDpto,0,wx.EXPAND) ctrlSizer.Add(self.lblProv,0,wx.ALIGN_RIGHT| wx.ALIGN_CENTER_VERTICAL) ctrlSizer.Add(self.cboProv,0,wx.EXPAND) ctrlSizer.Add(self.lblDistro,0,wx.ALIGN_RIGHT| wx.ALIGN_CENTER_VERTICAL) ctrlSizer.Add(self.cboDistri,0,wx.EXPAND) ctrlSizer.Add(self.lblCod,0,wx.ALIGN_RIGHT| wx.ALIGN_CENTER_VERTICAL) ctrlSizer.Add(self.lblPostal,0,wx.EXPAND) ctrlSizer.Add(self.btnOk, 1) ctrlSizer.Add(self.btnCancelar,1) #Agregar este sizer al Principal mSizer.Add(ctrlSizer,0,wx.EXPAND|wx.ALL,10) panel.SetSizer(mSizer) mSizer.Fit(self) mSizer.SetSizeHints(self) #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- def OnBtnOkButton(self, event): self.Close(True) def OnBtnCancelarButton(self, event): self.Close(True) #------------------------------------------------------------------------------- def OnCboPaisCombobox(self, event): """Carga el combo Departamento.""" """ self.cboDpto.Clear() self.cboDistri.Clear() self.cboProv.Clear() cb = event.GetEventObject() #Obtengo el Key kPais = cb.GetClientData(cb.GetSelection()) self.keyPais=kPais rs=self.oPostal.CargarDepa(kPais) i=0 for it in rs: x=unicode(rs[i][1],self.encode) self.cboDpto.Append(x,rs[i][0]) i+=1 """ #------------------------------------------------------------------------------- def OnCboDptoCombobox(self, event): """Carga el combo Provincia.""" """ self.cboProv.Clear() cb=event.GetEventObject() #Obtengo el Key kDepa = cb.GetClientData(cb.GetSelection()) self.keyDepa=kDepa rs=self.oPostal.CargarProv(kDepa) i=0 for it in rs: x=unicode(rs[i][1],self.encode) self.cboProv.Append(x,rs[i][0]) i+=1 """ #------------------------------------------------------------------------------- def OnCboProvCombobox(self, event): """ Carga el combo Distritos.""" """ self.cboDistri.Clear() cb=event.GetEventObject() #Obtengo el Key kProv = cb.GetClientData(cb.GetSelection()) self.keyProv=kProv rs=self.oPostal.CargarDist(self.keyDepa,kProv) i=0 for it in rs: x=unicode(rs[i][1],self.encode) self.cboDistri.Append(x,rs[i][0]) i+=1 """ #------------------------------------------------------------------------------- def OnCboDistriCombobox(self, event): """ cb=event.GetEventObject() #Obtengo el Key kDist = cb.GetClientData(cb.GetSelection()) self.keyDist=kDist self.GeneraUbigeo() """ #------------------------------------------------------------------------------- def GeneraUbigeo(self): """Genera el codigo de Ubigeo obtenido.""" """ self.ubigeo=self.keyDepa+self.keyProv+self.keyDist modGlobals.UBIGEO=self.ubigeo #Pinta el codigo self.lblPostal.SetLabel(self.ubigeo) return self.ubigeo """ #------------------------------------------------------------------------------- -- Mario Lacunza From mhellwig at xs4all.nl Wed Aug 2 08:40:48 2006 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Wed, 02 Aug 2006 14:40:48 +0200 Subject: python under earthlink hosting? In-Reply-To: References: Message-ID: <44d09d56$0$4531$e4fe514c@news.xs4all.nl> mbstevens wrote: > I keep chatting with the tech support people at Earthlink, asking where > the location of the Python interpreter is. They don't seem to know where > it is. They don't know if Python is running on my server, either. I know > Perl is at /usr/local/bin/perl ...but when I use a similar address for > Python I get a 500 internal server error. > > Has anyone succeeded in getting Python CGI scripts running on an earthlink > hosted site? > > Maybe they didn't symlink it, try /usr/local/bin/python2.4 -- mph From gheorghe.postelnicu at gmail.com Thu Aug 31 13:52:42 2006 From: gheorghe.postelnicu at gmail.com (Gheorghe Postelnicu) Date: Thu, 31 Aug 2006 13:52:42 -0400 Subject: tkSimpleDialog fails Message-ID: <8094b1b60608311052x7e379a6en3b7f20727bb934d@mail.gmail.com> Hi, I am using Python to develop a front-end GUI using Tk. I would need to use some of the tkSimpleDialog widgets, but they seem to fail. As far as I could tell, this happens because my application also uses VTK, so I have to use the root.withdraw() line root = Tkinter.Tk() root.withdraw() app = Application(root,700,700) root.mainloop() Hence, when I call tkSimpleDialog.askfloat, here's what I get: Traceback (most recent call last): File "pyScout.py", line 426, in SelectRegion spacing = tkSimpleDialog.askfloat("Profile spacing","Input spacing value") File "/usr/lib64/python2.3/lib-tk/tkSimpleDialog.py", line 271, in askfloat d = _QueryFloat(title, prompt, **kw) File "/usr/lib64/python2.3/lib-tk/tkSimpleDialog.py", line 179, in __init__ Dialog.__init__(self, parent, title) File "/usr/lib64/python2.3/lib-tk/tkSimpleDialog.py", line 64, in __init__ self.grab_set() File "/usr/lib64/python2.3/lib-tk/Tkinter.py", line 521, in grab_set self.tk.call('grab', 'set', self._w) _tkinter.TclError: grab failed: window not viewable Thanks, -- Gheorghe Postelnicu, PhD MGH, Harvard Medical School From fredrik at pythonware.com Thu Aug 31 14:48:29 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 31 Aug 2006 20:48:29 +0200 Subject: Assignment-in-conditional In-Reply-To: <1157049685.909882.76210@p79g2000cwp.googlegroups.com> References: <1157049685.909882.76210@p79g2000cwp.googlegroups.com> Message-ID: xamdam wrote: > I am not sure if this came up before, but I would love to have an > 'assignment-in-conditional' form in python, e.g it's a FAQ, so it has probably come up before: http://pyfaq.infogami.com/why-can-t-i-use-an-assignment-in-an-expression From dylanhughes at gmail.com Fri Aug 25 23:47:17 2006 From: dylanhughes at gmail.com (DH) Date: 25 Aug 2006 20:47:17 -0700 Subject: Taking data from a text file to parse html page In-Reply-To: References: <1156378275.662140.214650@h48g2000cwc.googlegroups.com> <1156473610.654066.323410@p79g2000cwp.googlegroups.com> Message-ID: <1156564037.135087.48890@i42g2000cwa.googlegroups.com> Yes I know how to import modules... I think I found the problem, Linux handles upper and lower case differently, so for some reason you can't import SE but if you rename it to se it gives you the error that it can't find SEL which if you rename it will complain that that SEL isn't defined... Are you running Linux? Have you tested it with Linux? > Surely you write your own programs. (program_name.py). You import and run them. You may put SE.PY and SEL.PY into the same > directory. That's all. > Or if you prefer to keep other people's stuff in a different directory, just make sure that directory is in "sys.path", > because that is where import looks. Check for that directory's presence in the sys.path list: > > >>> sys.path > ['C:\\Python24\\Lib\\idlelib', 'C:\\', 'C:\\PYTHON24\\DLLs', 'C:\\PYTHON24\\lib', 'C:\\PYTHON24\\lib\\plat-win', > 'C:\\PYTHON24\\lib\\lib-tk' (... etc) ] > > Supposing it isn't there, add it: > > >>> sys.path.append ('/python/code/other_peoples_stuff') > >>> import SE > > That should do it. Let me know if it works. Else just keep asking. > > Frederic > > > ----- Original Message ----- > From: "DH" > Newsgroups: comp.lang.python > To: > Sent: Friday, August 25, 2006 4:40 AM > Subject: Re: Taking data from a text file to parse html page > > > > SE looks very helpful... I'm having a hell of a time installing it > > though: > > > > ----------------------------------------------------------------------------------------- > > > > foo at foo:~/Desktop/SE-2.2$ sudo python SETUP.PY install > > running install > > running build > > running build_py > > file SEL.py (for module SEL) not found > > file SE.py (for module SE) not found > > file SEL.py (for module SEL) not found > > file SE.py (for module SE) not found > > > > ------------------------------------------------------------------------------------------ > > Anthra Norell wrote: > > > You may also want to look at this stream editor: > > > > > > http://cheeseshop.python.org/pypi/SE/2.2%20beta > > > > > > It allows multiple replacements in a definition format of utmost simplicity: > > > > > > >>> your_example = ''' > > >

"Python has been an important part of Google since the > > > beginning, and remains so as the system grows and evolves. > > > "

> > >

-- Peter Norvig, > > ''' > > > >>> import SE > > > >>> Tag_Stripper = SE.SE (''' > > > "~<(.|\n)*?>~=" # This pattern finds all tags and deletes them (replaces with nothing) > > > "~~=" # This pattern deletes comments entirely even if they nest tags > > > ''') > > > >>> print Tag_Stripper (your_example) > > > > > > "Python has been an important part of Google since the > > > beginning, and remains so as the system grows and evolves. > > > " > > > -- Peter Norvig, > > > > > Now you see a tag fragment. So you add another deletion to the Tag_Stripper (***): > > > > > > Tag_Stripper = SE.SE (''' > > > "~<(.|\n)*?>~=" # This pattern finds all tags and deletes them (replaces with nothing) > > > "~~=" # This pattern deletes commentsentirely even if they nest tags > > > " > > # "-- Peter Norvig, > > ''') > > > >>> print Tag_Stripper (your_example) > > > > > > "Python has been an important part of Google since the > > > beginning, and remains so as the system grows and evolves. > > > " > > > -- Peter Norvig, > > > > > > " you can either translate or delete: > > > > > > Tag_Stripper = SE.SE (''' > > > "~<(.|\n)*?>~=" # This pattern finds all tags and deletes them (replaces with nothing) > > > "~~=" # This pattern deletes commentsentirely even if they nest tags > > > " > > # "-- Peter Norvig, > > htm2iso.se # This is a file (contained in the SE package that translates all ampersand codes. > > > # Naming the file is all you need to do to include the replacements which it defines. > > > ''') > > > > > > >>> print Tag_Stripper (your_example) > > > > > > 'Python has been an important part of Google since the > > > beginning, and remains so as the system grows and evolves. > > > ' > > > -- Peter Norvig, > > > > > > If instead of "htm2iso.se" you write ""=" you delete it and your output will be: > > > > > > Python has been an important part of Google since the > > > beginning, and remains so as the system grows and evolves. > > > > > > -- Peter Norvig, > > > > > > Your Tag_Stripper also does files: > > > > > > >>> print Tag_Stripper ('my_file.htm', 'my_file_without_tags') > > > 'my_file_without_tags' > > > > > > > > > A stream editor is not a substitute for a parser. It does handle more economically simple translation jobs like this one where a > > > parser does a lot of work which you don't need. > > > > > > Regards > > > > > > Frederic > > > > > > > > > ----- Original Message ----- > > > From: "DH" > > > Newsgroups: comp.lang.python > > > To: > > > Sent: Thursday, August 24, 2006 7:41 PM > > > Subject: Re: Taking data from a text file to parse html page > > > > > > > > > > I found this > > > > > > > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/d1bda6ebcfb060f9/ad0ac6b1ac8cff51?lnk=gst&q=replace+text+file&r > > > num=8#ad0ac6b1ac8cff51 > > > > > > > > Credit Jeremy Moles > > > > ----------------------------------------------- > > > > > > > > finds = ("{", "}", "(", ")") > > > > lines = file("foo.txt", "r").readlines() > > > > > > > > for line in lines: > > > > for find in finds: > > > > if find in line: > > > > line.replace(find, "") > > > > > > > > print lines > > > > > > > > ----------------------------------------------- > > > > > > > > I want something like > > > > ----------------------------------------------- > > > > > > > > finds = file("replace.txt") > > > > lines = file("foo.txt", "r").readlines() > > > > > > > > for line in lines: > > > > for find in finds: > > > > if find in line: > > > > line.replace(find, "") > > > > > > > > print lines > > > > > > > > ----------------------------------------------- > > > > > > > > > > > > > > > > Fredrik Lundh wrote: > > > > > DH wrote: > > > > > > > > > > > I have a plain text file containing the html and words that I want > > > > > > removed(keywords) from the html file, after processing the html file it > > > > > > would save it as a plain text file. > > > > > > > > > > > > So the program would import the keywords, remove them from the html > > > > > > file and save the html file as something.txt. > > > > > > > > > > > > I would post the data but it's secret. I can post an example: > > > > > > > > > > > > index.html (html page) > > > > > > > > > > > > " > > > > > >

"Python has been an important part of Google since the > > > > > > beginning, and remains so as the system grows and evolves. > > > > > > "

> > > > > >

-- Peter Norvig, > > > > > " > > > > > > > > > > > > replace.txt (keywords) > > > > > > " > > > > > >

> > > > > > > > > > > >

" > > > > > > > > > > > > "

> > > > > > > > > > > >

-- Peter Norvig, > > > > > > > > > > > " > > > > > > > > > > > > something.txt(file after editing) > > > > > > > > > > > > " > > > > > > > > > > > > Python has been an important part of Google since the beginning, and > > > > > > remains so as the system grows and evolves. > > > > > > " > > > > > > > > > > reading and writing files is described in the tutorial; see > > > > > > > > > > http://pytut.infogami.com/node9.html > > > > > > > > > > (scroll down to "Reading and Writing Files") > > > > > > > > > > to do the replacement, you can use repeated calls to the "replace" method > > > > > > > > > > http://pyref.infogami.com/str.replace > > > > > > > > > > but that may cause problems if the replacement text contains things that > > > > > should be replaced. for an efficient way to do a "parallel" replace, see: > > > > > > > > > > http://effbot.org/zone/python-replace.htm#multiple > > > > > > > > > > > > > > > > > > > > > > > -- > > > > http://mail.python.org/mailman/listinfo/python-list > > > > -- > > http://mail.python.org/mailman/listinfo/python-list From ptmcg at austin.rr._bogus_.com Tue Aug 22 10:13:47 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 22 Aug 2006 14:13:47 GMT Subject: Problem of function calls from map() References: Message-ID: "Georg Brandl" wrote in message news:ecemdl$qd5$1 at news.albasani.net... > Paul McGuire wrote: > > "Dasn" wrote in message > > news:mailman.9606.1156169593.27775.python-list at python.org... > >> > >> Hi, there. > >> > >> 'lines' is a large list of strings each of which is seperated by '\t' > >> >>> lines = ['bla\tbla\tblah', 'bh\tb\tb', ... ] > >> > >> I wanna split each string into a list. For speed, using map() instead > >> of 'for' loop. > > > > > > def splitUsing(chars): > > def tmp(s): > > return s.split(chars) > > return tmp > > > > for d in map(splitUsing('\t'), data): > > print d > > And why is this better than > > map(lambda t: t.split('\t'), data) > > ? > > Georg Hmm, "better" is a funny word. My posting was definitely more verbose, but verbosity isn't always bad. In defense of brevity: - often (but not always) runs faster - usually easier to understand as a single gestalt (i.e., you don't have to jump around in the code, or grasp the intent of a dozen or more lines, when one or a few lines do all the work), but this can be overdone In defense of verbosity: - usually more explicit, as individual bits of logic are exposed as separate functions or statements, and anonymous functions can be given more descriptive names - usually easier to understand, especially for language newcomers - separate functions can be compiled by psyco Of course, such generalizations invite obvious extremes and counterexamples. Prime number algorithms compacted into one-liners are anything but quick to understand; conversely, I've seen a 40-line database function exploded into >100 classes (this was in Java, so each was also a separate file!) in pursuit of implementing a developer's favorite GOF pattern. This idiom (as used in the splitUsing case) of returning a callable from a function whose purpose is to be a factory for callables seems to be a common one in Python, I think I've seen it go by different names: currying, and closures being most common, and decorators are another flavor of this idea. Perhaps these idioms ("idia"?) emerged when "lambda" was on Guido's Py3K chopping block. So I wouldn't really hold these two routines up for "betterness" - the OP's performance test shows them to be about the same. To summarize his performance results (times in CPU secs): - explicit "for" loop - 20.510 (309130 total function calls; 154563 to split and 154563 to append) - list comprehension - 12.240 (154567 total function calls; 154563 to split) - map+lambda - 20.480 (309130 total function calls; 154563 to and 154563 to split) - map+splitUsing - 21.900 (309130 total function calls; 154563 to tmp and 154563 to split) The big winner here is the list comprehension, and it would seem it outdoes the others by halving the number of function calls. Unfortunately, most of our currying/closure/decorator idioms are implemented using some sort of "function-calls-an-embedded-function" form, and function calls are poison to performance in Python (and other languages, too, but perhaps easier to observe in Python). Even the anonymous lambda implementation has this same issue. So the interesting point here is to go back to the OP's OP, in which he states, "For speed, [I'm] using map() instead of 'for' loop." As it turns out, map() isn't much of a win in this case. The real, "best" solution is the list comprehension, not only for speed, but also for ease of readability and understanding. It's tough to beat this: return [s.split('\t') for s in lines] for clarity, explicity, brevity, and as it happens, also for speed. -- Paul From djoefish at gmail.com Sat Aug 19 19:16:15 2006 From: djoefish at gmail.com (djoefish) Date: 19 Aug 2006 16:16:15 -0700 Subject: sequel to the topic "install patch on windows"..... Message-ID: <1156029374.982389.18050@h48g2000cwc.googlegroups.com> sequel to the topic "install patch on windows"..... I am currently running Python2.3 with Enthought on a windows PC. I have been running into a memory problem (see http://evanjones.ca/python-memory-part3.html), and would like to install a patch. I have read a lot about it online, but can't seem to find out how to do so on windows. I have a 'patch' program that works, but it only patches the source file 'obmalloc.c', which does not exist in the final Python installation. Is it possible to install a patch without recompiling all of python? Could someone direct me to some documentation that might help? I wouldn't mind waiting for the 2.5 release (which has the patch built in), but then I'm afraid I would also have to wait for an ungrade of Enthought. any advice? thanks, djoefish From thomas.weholt at gmail.com Thu Aug 17 09:19:24 2006 From: thomas.weholt at gmail.com (Thomas W) Date: 17 Aug 2006 06:19:24 -0700 Subject: Read Picasa metadata using Python? Message-ID: <1155820764.151065.280770@i3g2000cwc.googlegroups.com> I know this is slightly off-topic, but since Python is hot at Google and several key members from the python community works there, I was hoping to get some help on this subject. I want to create a small app that reads my Picasa-metadata related to a specified image and uploads my image and metadata to my Flickr.com-account ( as far as I know Picasa only support Blogger ). Anyway, if there are any other app allready reading Picasa metadata with Flickr-support that you know of that would save me alot of work/hassle. Still, Picasa is great, but I would really like access to my own metadata outside Picasa and I want to use python to do it. Thanks in advance, Thomas From bdesth.quelquechose at free.quelquepart.fr Mon Aug 28 19:16:21 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 29 Aug 2006 01:16:21 +0200 Subject: Coding style and else statements In-Reply-To: <1156804096.616231.14990@74g2000cwt.googlegroups.com> References: <44f355d6$0$8812$88260bb3@free.teranews.com> <44f36bd2$0$16847$626a54ce@news.free.fr> <1156804096.616231.14990@74g2000cwt.googlegroups.com> Message-ID: <44f3768a$0$29491$626a54ce@news.free.fr> Sam Pointon a ?crit : > Bruno Desthuilliers wrote: > >>foo = lambda thing: thing and thing + 1 or -1 > > > The and ... or trick is buggy (what if thing == -1?) Yes, true - Should be: foo2 = lambda t: t != -1 and (t and t+1 or -1) or 0 > and bad style. Lol. Well, so what about: foo = lambda t: (lambda t: -1, lambda t: t+1)[bool(t)](t) ?-) (NB: don't bother answering) > If > you -do- want a conditional expression, 2.5 provides one: Yes, at last, and I'm glad it finally made it into the language. But 2.5 is not here yet. The 'and/or' trick can be, well, tricky, (notably in this case) but it at least work with most Python versions. > No subtle logical bugs, and a good deal more obvious. Indeed. From jzgoda at o2.usun.pl Fri Aug 18 15:25:40 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 18 Aug 2006 21:25:40 +0200 Subject: MS SQL Server: NT Authentication. Possible? In-Reply-To: <1155904044.483030.152430@m73g2000cwd.googlegroups.com> References: <1155904044.483030.152430@m73g2000cwd.googlegroups.com> Message-ID: Dirk Hagemann napisa?(a): > 'Exception occurred.', (0, 'Microsoft OLE DB Provider for ODBC > Drivers', "[Microsoft][ODBC SQL Server Driver][SQL Server]Login failed > for user '(null)'. Reason: Not associated with a trusted SQL Server > connection.", None, 0, -2147217843), None) This indicates, that user credentials was not retrieved from ActiveDirectory server. > Do I have to make some settings at the MS SQL Server? I just can't find > a simple example how to use adodbapi with NT authentication... I tried few times but I gave up. Now I authenticate my users against AD using LDAP queries. They have to provide their credentials, though, and I know it's suboptimal. -- Jarek Zgoda http://jpa.berlios.de/ From tal.no.no.spam at gmail.com Sun Aug 27 03:56:01 2006 From: tal.no.no.spam at gmail.com (Tal Einat) Date: 27 Aug 2006 00:56:01 -0700 Subject: Avoiding if..elsif statements In-Reply-To: References: <1156545375.962486.49540@h48g2000cwc.googlegroups.com> <1156547346.647480.187910@b28g2000cwb.googlegroups.com> Message-ID: <1156665361.369767.277380@b28g2000cwb.googlegroups.com> Fredrik Lundh wrote: > "unexpected" wrote: > > > However, I'm passing in a few variables, so I can't just take it > > out-though every single function would be passing the same variables. > > > > so something.func() is actually > > something.func(string, list) > > > > How would I modify it to include them? > > just add the parameters to the call: > > dispatch[value](string, list) # note: do the call here! > This will work great if all of your functions recieve the same argument(s). If not, there are still simple solutions. I would suggest a solution like this, since it's simple and generic: class Command (object): def __init__(self, func, *args, **kw): self.func = func self.args = args self.kw = kw def __call__(self, *args, **kw): args = self.args+args kw.update(self.kw) apply(self.func, args, kw) An instance of the Command class can be called just like a function, and it will call the orginial function with the arguments it was instantiated with. (You can also pass additional arguments at the call itself) dispatch = { "something": Command(somethingClass.func), "somethingElse": Command(somethingElseClass.func, "moo", [1,2,3]), "anotherthing": Command(anotherthingClass.func, 'a', 'b', 'c'), "yetanotherthing": Command(yetanotherthingClass.func, verbose=True), } dispatch[value]() - Tal Einat reduce(lambda m,x:[m[i]+s[-1] for i,s in enumerate(sorted(m))], [[chr(154-ord(c)) for c in '.&-&,l.Z95193+179-']]*18)[3] From Bulkan at gmail.com Thu Aug 10 01:19:24 2006 From: Bulkan at gmail.com (placid) Date: 9 Aug 2006 22:19:24 -0700 Subject: loop until keypress (Windows XP) Message-ID: <1155187164.696015.252920@b28g2000cwb.googlegroups.com> Hi all, Im using the cmd module and i have command that loops and keeps on printing text, what i want to be able to do is loop until the user presses a particular key, say Q/q ? I tried the following code; line = raw_input ("press q to abort") while line[0] != "q": """ keep printing text """ line = raw_input ("press q to abort") but raw_input blocks for input until the newline char. So i then tried the following code import sys chr = sys.stdin.read(1) while chr != "q": """ keep printing text """ chr = sys.stdin.read(1) but again this blocks too. is there a way to do this, wait for user input but dont block? I could use a thread that just does the previous code block but i already have three Thread classes, its just getting too complex with threads! Cheers From bj_666 at gmx.net Sun Aug 20 09:00:42 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 20 Aug 2006 15:00:42 +0200 Subject: Text parsing References: Message-ID: In , Michiel Sikma wrote: > My code: > > ---- test.py ---- > import sys > > def preparse(file): > block = [] > for line in file: > if line.strip(): > block.append(line) > elif block: > yield ''.join(block).strip() > block = [] + yield ''.join(block).strip() Because your line "test10\n" is still in `block` at this point. > yield '\n' > > [?] > > ---- test ---- > test1 > test2 > > test3 > test4 > test5 > test6 > > test7 > test8 > > test9 > > test10 > ---- > > When I run test.py, it prints this: > michiel-sikmas-computer:~/Desktop msikma$ python test.py > ['test1\ntest2', 'test3\ntest4\ntest5\ntest6', 'test7\ntest8', > 'test9', '\n'] > > What happened to "test10"? It seems to be gone unless I add two > linebreaks at the end of the file. Ciao, Marc 'BlackJack' Rintsch From david_wahler at bic.ky Tue Aug 1 01:37:54 2006 From: david_wahler at bic.ky (david_wahler at bic.ky) Date: 1 Aug 2006 00:37:54 -0500 Subject: Wing IDE 2.1.1 released Message-ID: <20060801053754.30053.qmail@BICSRV1011.bic.ky> I'll be out of the office until approximately August 20th. If you have any questions, please email support at bic.ky. -- David Wahler From robert.kern at gmail.com Wed Aug 23 12:55:56 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 23 Aug 2006 11:55:56 -0500 Subject: how do you get the name of a dictionary? In-Reply-To: <1156350580.363393.256730@74g2000cwt.googlegroups.com> References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> <1156264475.968894.221710@p79g2000cwp.googlegroups.com> <1156266720.205126.284050@i3g2000cwc.googlegroups.com> <1156268752.574983.123520@75g2000cwc.googlegroups.com> <1156281268.865624.302070@b28g2000cwb.googlegroups.com> <1156283135.985893.186500@m73g2000cwd.googlegroups.com> <1156284812.469380.274370@b28g2000cwb.googlegroups.com> <1156350580.363393.256730@74g2000cwt.googlegroups.com> Message-ID: jojoba wrote: > > Fredrik Lundh wrote: >> the fact that despite all attempts to explain how things work, you're >> still haven't realized that if you want the names of things, you should >> pass *namespaces* to your object viewer, not individual objects. > > And what im saying is that isnt it silly that we need pass an entire > namespace, when a much simpler notion would be to have each object know > its own name(s) (even if that name doesnt exist). No, it's silly to avoid a very well-defined, heavily optimized strategy used everywhere in the language in favor of a new, vague strategy that is usually uninformative and frequently undefined. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From jojoba12 at hotmail.com Tue Aug 15 17:26:09 2006 From: jojoba12 at hotmail.com (jojoba) Date: 15 Aug 2006 14:26:09 -0700 Subject: idea on how to get/set nested python dictionary values In-Reply-To: <1155663671.716249.18780@m79g2000cwm.googlegroups.com> References: <1155663671.716249.18780@m79g2000cwm.googlegroups.com> Message-ID: <1155677169.125742.193970@m73g2000cwd.googlegroups.com> ... From amk at amk.ca Tue Aug 29 09:00:36 2006 From: amk at amk.ca (A.M. Kuchling) Date: Tue, 29 Aug 2006 08:00:36 -0500 Subject: How ahead are you guys in the (Python) real world? References: <1156821234.820929.299740@p79g2000cwp.googlegroups.com> Message-ID: On 28 Aug 2006 20:13:54 -0700, Ray wrote: > Since I haven't used Python at work, I am using Python 2.5 right now. > However I wonder, how fast are you guys moving from version to version > at work? At our company, we build a product on top of Debian (product line 1) or Ubuntu (product line 2, not released yet), so we stick to what's available in the Debian/Ubuntu versions we're using. That means 2.3 on Debian and 2.4 on Ubuntu. 2.5 will probably arrive whenever we upgrade to the upcoming Ubuntu release, though I've already tried manually upgrading a system to 2.5, and our code ran without changes or apparent problems. --amk From hg at nospam.com Tue Aug 29 21:46:12 2006 From: hg at nospam.com (hg) Date: Tue, 29 Aug 2006 20:46:12 -0500 Subject: TNEF decoder In-Reply-To: <1156901227.576728.203500@74g2000cwt.googlegroups.com> References: <1156901227.576728.203500@74g2000cwt.googlegroups.com> Message-ID: Simon Forman wrote: > David Isaac wrote: >> I'm aware of >> http://cheeseshop.python.org/pypi/pytnef/ >> but it uses the tnef utility, and I'd like a pure Python solution >> (along the lines of http://www.freeutils.net/source/jtnef/ ). >> >> Is there one? >> >> Thanks, >> Alan Isaac > > A place I once worked at had a project that included some TNEF > handling. There was one developer assigned fulltime to it. He was the > one who sat at his desk hurling curses at his workstation at the top of > his lungs, later he developed a pretty severe drinking problem. > > Good luck. > > HTH, > ~Simon > You mean he stopped ? From vojta.d at gmail.com Wed Aug 16 14:03:27 2006 From: vojta.d at gmail.com (Vojta Drbohlav) Date: Wed, 16 Aug 2006 20:03:27 +0200 Subject: QListView and text In-Reply-To: <200608161746.27972.phil@riverbankcomputing.co.uk> References: <200608161829.40715.vojta.d@gmail.com> <200608161746.27972.phil@riverbankcomputing.co.uk> Message-ID: <200608162003.27915.vojta.d@gmail.com> Thank you very much. How can I move slected item up? This is no work: sel = list.currentItem() sel.moveItem(sel.itemAbove()) From djaquay at spamless.yahoo.com Thu Aug 17 17:05:29 2006 From: djaquay at spamless.yahoo.com (djaquay at spamless.yahoo.com) Date: Thu, 17 Aug 2006 16:05:29 -0500 Subject: Interactive display of trace.py output? Message-ID: I've been using trace.py to get code coverage results for my unit tests, and like it. Now I'm trying to use it for code coverage of the GUI parts of my wxPython-based program, and I realized how nice it would be to be able to see what lines I'd covered and what remained to be exercised, without having to stop the trace to get the output updated. It occurred to me that accepting the "--trace" output from trace.py as input to another program would allow that other program to show a source file and show what lines remain to be tested as you're performing the tests. It also occurred to me that someone may have already done this. Does such a thing exist, or do I get to write it? Thanks, Dave (djaquay at yahoo, dot-com) From bruce.who.hk at gmail.com Tue Aug 15 03:12:57 2006 From: bruce.who.hk at gmail.com (Bruce Who) Date: Tue, 15 Aug 2006 15:12:57 +0800 Subject: Best IDE for Python In-Reply-To: <1155592933.921122.21100@m79g2000cwm.googlegroups.com> References: <1155541849.350392.31190@h48g2000cwc.googlegroups.com> <1155592933.921122.21100@m79g2000cwm.googlegroups.com> Message-ID: Hi, sjdevnull I'm a vimmer too, and I wonder what plugins you are using. What you said sounds interesting. Could you tell us more about the plugins? "Object browser" is what I need most, but so far I've no idea what plugin can do this for me, :-( On 14 Aug 2006 15:02:13 -0700, sjdevnull at yahoo.com wrote: > Yu-Xi Lim wrote: > > Eclipse+PyDev has the advantage over emacs when it comes to big > > projects, IMO. It has features like refactoring, better project > > management, code coverage > > Emacs and vim both have good integration of BicycleRepairMan for python > refactoring. I don't know what better project management or code > coverage in eclipse entail, but I've posted before that if you think > vim/emacs are just syntax highlighting/indenting text editors you've > got them misconfigured. > > The beautiful thing about vim in particular is that it uses Python as > an internal scripting language, so it's very easy to extend it to add > whatever you want. > > e.g. in vim I get > * Syntax checking, if I type invalid python code it gets highlighted as > an error (if I type, say, "if a=1:" and hit return, it gets highlighted > since I need an == there). > * Object browser, with dropdowns showing the parent and child classes > of the current class, and the ability to jump to various class methods > * Normal tag-jump stuff, so I can drill down into the method/function > call I'm looking at and then pop back up (keeping a stack so I can > drill down arbitrarily deep to follow the flow of the code) > * Interactive help, so when, say, I type foo.blah( then the status line > displays the first line of the docstring/python doc/preceding comment > for foo.blah. E.g. if I type "cmp(" then the status line shows "cmp(x, > y) Compare the two objects X and Y and return an integer according to > ..." and if I hit F1 then I get the full help text > * Editor control for uncaught errors--if I code I'm debugging raises an > uncaught exception, the editor jumps directly to it. Even works for > web development, if I hit a page in my dev server that raises an > exception, it brings my editor right there. > > and lots more (version control integration, easy mapping of keys to > restart the webserver after I make changes, etc). And there's some > internal crap (e.g. we work on lots of clients who have client-specific > versions of some objects; I have a client menu so that if I pick one, > then I'll jump to their client-specific version of the current file (or > the base generic version if there isn't a specific one), tags will > follow the right client versions, etc). > > -- > http://mail.python.org/mailman/listinfo/python-list > From akameswaran at gmail.com Wed Aug 16 14:10:40 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 16 Aug 2006 11:10:40 -0700 Subject: python-dev and setting up setting up f2py on Windows XP In-Reply-To: <1155744270.092818.256290@i42g2000cwa.googlegroups.com> References: <1155744270.092818.256290@i42g2000cwa.googlegroups.com> Message-ID: <1155751840.075346.279300@m73g2000cwd.googlegroups.com> I'm really not familiar with the package you are trying to use, nor that familiar with what you get on windows. I would guess you did a binary installation download, and you may need to get the python source tarball instead - in order to get the files you need. Barring that, I'm certain the headers are available through sourceforge, they provide svn access for building python itself: more info @: http://www.python.org/dev/faq/ Hope this helps. Anand Sile wrote: > Hi, > > I've been trying to get f2py working on Windows XP, I am using Python > 2.3. I'm new to python so I'm not too sure what I'm doing yet. I need > the python-dev package to run f2py. I have been told this is just the > header files and .dll and I need to put them somewhere my C compiler > can find them. I've searched the web and none of the python-dev > packages I've found are for windows. I was wondering is this > automatically part of the windows version and if so how I set it up so > my C compiler can find them. If it is not part of the standard package > does anyone know where I can find it??? > > Any help at all would be much appreciated. > Thanks, > Sile From __peter__ at web.de Fri Aug 25 08:48:00 2006 From: __peter__ at web.de (Peter Otten) Date: Fri, 25 Aug 2006 14:48:00 +0200 Subject: performance of dictionary lookup vs. object attributes References: Message-ID: Andre Meyer wrote: > Hi all > > I was wondering about the performance comparison of either using a > dictionary or an object for a large collection of "things". Therefore > I have run the attached test. I create a dictionary and an object. > Both get the same number of items/attributes, respectively. Then, for > both the values are read often (iterations). > > Here are the results: > > attributes 100 > iterations 1000000 > dic 25.515999794 > obj 138.570000172 > > Is the test meaningful and are you surprised by the results? I am, > actually, because I would have assumed that attribute access with an > object should be faster because lookup can be precompiled. I think it is not meaningful as obj.__getattribute__("attribute") is significantly slower than obj.attribute. dict lookup is still significantly faster: $ python -m timeit -s'class A(object): pass' -s 'a = A(); a.alpha = 42' 'a.__getattribute__("alpha")' 1000000 loops, best of 3: 0.674 usec per loop $ python -m timeit -s'class A(object): pass' -s 'a = A(); a.alpha = 42' 'a.alpha' 1000000 loops, best of 3: 0.215 usec per loop $ python -m timeit -s'd = dict(alpha=42)' 'd["alpha"]' 10000000 loops, best of 3: 0.167 usec per loop Peter From leonel.gayard at gmail.com Thu Aug 3 12:18:04 2006 From: leonel.gayard at gmail.com (Leonel Gayard) Date: Thu, 3 Aug 2006 13:18:04 -0300 Subject: What is the best way to print the usage string ? Message-ID: <2ccb22540608030918o1670c2bbxe21012f97ba34d67@mail.gmail.com> Hi all, I had to write a small script, and I did it in python instead of shell-script. My script takes some arguments from the command line, like this. import sys args = sys.argv[1:] if args == []: print """Concat: concatenates the arguments with a colon (:) between them Usage: concat arg1 [arg2...] Example: concat a b c prints \"a.jar:b.jar:c/\"""" sys.exit(1) print reduce(lambda x, y: x + ':' + y, sys.argv[1:]) Notice that the string messes the indentation in my script. The indentation is correct, and if the script is invoked without arguments, the usage string is printed correctly. Now, how can I achieve the same result while keeping a clean indentation ? How is this done in python world ? In C, I would do this: ;; This buffer is for notes you don't want to save, and for Lisp evaluation. ;; If you want to create a file, visit that file with C-x C-f, ;; then enter the text in that file's own buffer. if (argc < N) { printf("Usage: blah blah blah\n" "Some more lines in the usage text\n" "Some more lines here too\n"); exit(1); } The whitespace at the beginning of the string helps me keep the indentation clean, and the construct "a" "b" is syntactic sugar that allows me to create a large string without concatenating them at runtime. How can I get this in Python ? []'s Leonel From duncan.booth at invalid.invalid Mon Aug 28 05:16:21 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Aug 2006 09:16:21 GMT Subject: Segmentation Fault References: <1156737764.729811.297280@m79g2000cwm.googlegroups.com> Message-ID: pycraze wrote: > I would like to ask a question. How do one handle the exception due to > Segmentation fault due to Python ? Our bit operations and arithmetic > manipulations are written in C and to some of our testcases we > experiance Segmentation fault from the python libraries. > >From what you said, I guess you mean that you have written some extensions to Python in C, but that the segmentation fault is generated when you call standard Python library functions. Most likely your C code has bugs: quite possibly you have messed up reference counting so some objects you use are being freed and then the Python libraries allocate other objects into the same memory. It is very easy to do that especially if you are in the habit of trying to 'borrow' references instead of religiously incrementing/decrementing reference counts everywhere. Try to eliminate the problem down to the smallest reproducable code sample and post that. Another suggestion I would make is to see if you can use ctypes or Pyrex to form the glue between Python and C so that none of the C code you write knows anything about Python. That should eliminate some possible sources for error. From spamfranke at web.de Wed Aug 23 16:34:31 2006 From: spamfranke at web.de (neophyte) Date: 23 Aug 2006 13:34:31 -0700 Subject: sum and strings In-Reply-To: References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <1155922208.930580.135080@m79g2000cwm.googlegroups.com> Message-ID: <1156365271.487489.62640@m73g2000cwd.googlegroups.com> Fredrik Lundh wrote: > do you often write programs that "sums" various kinds of data types, and > for which performance issues are irrelevant? > > or are you just stuck in a "I have this idea" loop? Maybe he's just insisting on the principle of least surprise? Personally, I'd rather expect sum() to work for strings and Python to issue a warning instead of raising a type error. That warning might also be appropriate when using sum() on other builtin sequence types. From __peter__ at web.de Tue Aug 22 05:09:48 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 22 Aug 2006 11:09:48 +0200 Subject: Problem of function calls from map() References: <200608211350.k7LDoBJb032411@fe12.bluebottle.com> Message-ID: Dasn wrote: > # size of 'dict.txt' is about 3.6M, 154563 lines > f = open('dict.txt', 'r') > lines = f.readlines() > def sp0(lines): > ????????"""====> sp0() -- Normal 'for' loop""" > ????????l = [] > ????????for line in lines: > ????????????????l.append(line.split('\t')) > ????????return l Where do you get the data from in the "real world"? If it's a file you might get the best overall performance if you skip the readlines() call: sp0(f) Anyway, here's another variant you can try: from itertools import izip, starmap, repeat def splitlines(lines): return list(starmap(str.split, izip(lines, repeat("\t")))) Peter From danielwong at berkeley.edu Thu Aug 17 22:32:58 2006 From: danielwong at berkeley.edu (danielx) Date: 17 Aug 2006 19:32:58 -0700 Subject: Optimizing Inner Loop Copy In-Reply-To: References: <1155863280.800878.127310@p79g2000cwp.googlegroups.com> Message-ID: <1155868377.930442.157210@74g2000cwt.googlegroups.com> Mark E. Fenner wrote: > Mark E. Fenner wrote: > > > John Machin wrote: > > > >> > >> Mark E. Fenner wrote: > >> > >>> Here's my class of the objects being copied: > >> > >> Here's a couple of things that might help speed up your __init__ > >> method, and hence your copy method: > >> > >>> > >>> class Rule(list): > >>> def __init__(self, lhs=None, rhs=None, nClasses=0, nCases=0): > >> > >> def __init__(self, lhs=None, rhs=(), nClasses=0, nCases=0): > >> > >>> self.nClasses = nClasses > >>> self.nCases = nCases > >>> > >>> if lhs is not None: > >>> self.extend(lhs) > >> what does the extend method do? If it is small, perhaps inline a copy > >> of its code here. > >>> > >>> if rhs is None: > >>> self.rhs=tuple() > >>> else: > >>> self.rhs=rhs > >> > >> Replace the above 4 lines by: > >> self.rhs = rhs > >> > >> HTH, > >> John > > > > John, > > > > Thanks. I thought of those at the same you did! I also incorporated one > > other use of the default=() + no conditional: > > > > class Rule(list): > > def __init__(self, lhs=(), rhs=(), nClasses=0, nCases=0): > > self.nClasses = nClasses > > self.nCases = nCases > > self.extend(lhs) # note, self is a list so this is list.extend > > self.rhs=rhs > > > > def copy(self): > > return Rule(self, > > self.rhs, > > self.nClasses, > > self.nCases) > > > Actually, I also removed the "passthrough" that copy was doing and just > called the constructor directly. So, at the top level code, we have: > > allNew = [] > for params in cases: > # newobj = initialObject.copy() > newObj = Rule(initialObject, initialObject.rhs, > initialObject.nClasses, > initialObject.nCases) > newObj.modify(params) > allNew.append(newObj) > return allNew > > Regards, > Mark I'm not sure how much this will help, but another thing you can do is put this line before the "for": append = allNew.append Then, replace the last line in the loop with append(newObj) Check out this doc for more info on optimizing Python, and the section which talks about eliminating dots: http://wiki.python.org/moin/PythonSpeed/PerformanceTips http://wiki.python.org/moin/PythonSpeed/PerformanceTips#head-aa6c07c46a630a2fa10bd6502510e532806f1f62 From andrew at trevorrow.com Sun Aug 27 20:09:22 2006 From: andrew at trevorrow.com (Andrew Trevorrow) Date: Mon, 28 Aug 2006 10:09:22 +1000 Subject: Conway's Life Implementation References: <1156708582.474508.209360@75g2000cwc.googlegroups.com> Message-ID: "Putty" wrote: > Hi. I was going to write an implementation of John Conway's Life game > using Python and Tk, but I soon found that Tk just didn't cut the > mustard for memory usage, management, and the like for such a project, > so I've found my best GUI bet for my project is wxPython and not > pygame. You might enjoy looking at Golly, an open source, cross-platform Life app which uses Gosper's hashlife algorithm to allow the exploration of patterns at huge scales and speeds: http://golly.sourceforge.net/ Golly's GUI is written in wxWidgets (C++, not wxPython) but we do use Python as our scripting language: http://golly.sourceforge.net/Help/scripting.html Andrew From deets at nospam.web.de Thu Aug 24 19:16:29 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 25 Aug 2006 01:16:29 +0200 Subject: OS X and Python - what is your install strategy? In-Reply-To: <1156460483.616400.120160@i3g2000cwc.googlegroups.com> References: <1156460483.616400.120160@i3g2000cwc.googlegroups.com> Message-ID: <4l6qacFinasU1@uni-berlin.de> metaperl schrieb: > I'm about to get a new OS X box on which I will rewrite a bunch of data > munging scripts from Perl to Python. I know that there are several port > services for OS X (fink, darwin ports, opendarwin). So I am not sure > whether to use their port of Python or whether to build from scratch or > use the Python image file. Also ActivePython is something of a choice > but for some reason not a front-running one for me. I tend to like > Gentoo-style compile from source over pre-bundled all-in-one solutions > like ActivePython. You will definitely need the OSX-specific framework builds - which you can do yourself, but also install as image. All the fink/darwin ports stuff is nice, but I bet you prefer whatever gui you might wanna use running natively, not under X... > I'm not going to do much other than maybe install Plone and do some XML > and CSV processing. Most everything I need is in the Python stdlib. > Maybe down the road some graphics and web stuff (I like Clever Harold > or Pylons for that... but I still ahve not examined the 900 other web > app options in Python :) All that doesn't affect the above. Diez From fredrik at pythonware.com Tue Aug 22 03:50:31 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Aug 2006 09:50:31 +0200 Subject: How to decode a string In-Reply-To: <1156229239.418473.248090@i3g2000cwc.googlegroups.com> References: <1156170296.076521.174180@i3g2000cwc.googlegroups.com> <1156175385.580508.302330@m73g2000cwd.googlegroups.com> <1156229239.418473.248090@i3g2000cwc.googlegroups.com> Message-ID: Lad wrote: > for > print repr(RealName) command > I will get > > P?ibylov\xe1 Ludmila > where instead of ? should be also a character that's not very likely; repr() always includes quotes, always escapes non-ASCII characters, and optionally includes a Unicode prefix. please try this print "*", repr(RealName), type(RealName), "*" and post the entire output; that is, *everything* between the asterisks. From antroy at gmail.com Mon Aug 7 04:23:43 2006 From: antroy at gmail.com (Ant) Date: 7 Aug 2006 01:23:43 -0700 Subject: Python Projects Continuous Integration In-Reply-To: References: <1154087739.722910.110310@b28g2000cwb.googlegroups.com> Message-ID: <1154939023.859757.33260@n13g2000cwa.googlegroups.com> Harry George wrote: > [snip stuff about how to set emacs up as your IDE] Not sure which post you read, but the OP of this thread was asking about continuous integration, not integrated development environments. i.e. tools to *automatically* check out code when the repository has changed, build it if necessary (perhaps if there are C modules in the case of python) and run the unit tests. To the OP: you could of course simply continue to use cruise - it's only a tool after all, and won't require any additional learning if you are already having to learn a new language with all the associated libraries and idioms. From zeph_zhang at yahoo.co.uk Mon Aug 14 22:23:46 2006 From: zeph_zhang at yahoo.co.uk (Zeph) Date: Mon, 14 Aug 2006 22:23:46 -0400 Subject: Mega Newbie Questions: Probably FAQs In-Reply-To: <1155591083.461286.75380@i3g2000cwc.googlegroups.com> References: <1155591083.461286.75380@i3g2000cwc.googlegroups.com> Message-ID: ajaksu wrote: > Zeph wrote: And I'd research a bit about decompiling those executables, > might be easier (or harder, in my case) than you thought :) Are you saying that generally python code is insecure? It hadn't occurred to me, but I want to play in a fairly competitive field, and I'd hate to have a competitor rip my app. > Framework... MVC... not my area, sorry. I think a better word might have been "methodology", for example, as a Coldfusion developer, I enjoy using Fusebox. From bobrien18 at yahoo.com Mon Aug 14 12:08:47 2006 From: bobrien18 at yahoo.com (KraftDiner) Date: 14 Aug 2006 09:08:47 -0700 Subject: A little assistance with os.walk please. In-Reply-To: <44E09561.1030902@websafe.com> References: <1155566679.139086.279430@h48g2000cwc.googlegroups.com> <44E09561.1030902@websafe.com> Message-ID: <1155571727.168983.103480@m73g2000cwd.googlegroups.com> Larry Bates wrote: > KraftDiner wrote: > > The os.walk function walks the operating systems directory tree. > > > > This seems to work, but I don't quite understand the tupple that is > > returned... > > Can someone explain please? > > > > for root, dirs, files in os.walk('/directory/'): > > print root > > # print dirs > > # print files > > > > Actually returns two tuples: dirs and files > > root - is the directory branch you are currently walking > dirs - are the directory branches that are subdirectories of this > directory branch > files - are the files that live in this directory branch > > > To process all the files here you do something like: > > for afile in files: # resist the urge to call it 'file' > fullpath=os.path.join(root, afile) > # > # Do something with fullpath > # > > Hard to figure out item - If you wish to NOT process some of the > dirs, you can delete them from the dirs list here and they won't > get walked. You MUST delete them in place with del dirs[n] or > dirs.pop or some other function that deletes in-place. > > You might want to type: help(os.walk) to get some more info. > Yep done that. Thanks. Two things.. 1) there seems to be an optional topdown flag. Is that passed to os.walk(path, topdownFlag) 2) I only want to process files that match *.txt for example... Does that mean I need to parse the list of files for the .txt extention or can I pass a wildcard in the path parameter? > -Larry Bates From simon at brunningonline.net Fri Aug 25 09:34:15 2006 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 25 Aug 2006 14:34:15 +0100 Subject: Open Office and Python In-Reply-To: References: Message-ID: <8c7f10c60608250634v400ce07bja81f04fc339fd60e@mail.gmail.com> On 8/25/06, F wrote: > I'd like to load a .csv file to the Open Office spreadsheet from the command > line using an arbitrary delimiter through Python. I don't need any fancy > formatting and stuff like that, just putting the values in the spreadsheet > will do. Have you looked at the csv module? . -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From filip.salomonsson at gmail.com Tue Aug 15 16:54:08 2006 From: filip.salomonsson at gmail.com (Filip Salomonsson) Date: Tue, 15 Aug 2006 22:54:08 +0200 Subject: sending mailing list with smtplib In-Reply-To: <1155674513.096396.4430@i3g2000cwc.googlegroups.com> References: <1155561746.812918.128770@h48g2000cwc.googlegroups.com> <1155630010.956035.270580@74g2000cwt.googlegroups.com> <1155674513.096396.4430@i3g2000cwc.googlegroups.com> Message-ID: <2f334ccd0608151354r3baccbd5xfc68afa5b0490eb8@mail.gmail.com> On 15 Aug 2006 13:41:53 -0700, 3KWA wrote: > What would be the best way to go about it then? Instantiate a new msg > in the loop? > > I guess I must read the doc more carefully, thanks for your time (if > you can spare some more I would be grateful). You can reuse your message object, but you need to delete the old header before setting a new one: -- filip salomonsson From tdelaney at avaya.com Tue Aug 1 18:55:57 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Wed, 2 Aug 2006 08:55:57 +1000 Subject: Programming newbie coming from Ruby: a few Python questions Message-ID: <2773CAC687FD5F4689F526998C7E4E5F01833FCC@au3010avexu1.global.avaya.com> Edmond Dantes wrote: > Of course, it's all what you really mean by "clever". To me, being > "clever" partly means writing code without bugs in the first place, > so there is nothing that needs debugging!!!!!!!! "Clever" in this context generally means using a trick/hack that is non-obvious (often even after you understand it). "Cleverness" often leads to difficult-to-understand code, which is contrary to the "python philosophy". There are occasionally times when cleverness is useful, but in those cases it should always be commented explaining exactly what it is doing, and why a non-clever solution was not used. Most of the time there's still a better non-clever way to do it, but the coder is not clever enough to find it ;) Tim Delaney From bkline at rksystems.com Wed Aug 16 13:55:22 2006 From: bkline at rksystems.com (Bob Kline) Date: Wed, 16 Aug 2006 13:55:22 -0400 Subject: Optimization of __len__() in cgi.py In-Reply-To: References: Message-ID: Georg Brandl wrote: > Post a RFE to the Python Tracker at > http://sourceforge.net/tracker/?group_id=5470&atid=355470 > > If you want, assign it to me (gbrandl). Done, thanks. Bob From pmartin at snakecard.com Mon Aug 14 18:46:11 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Mon, 14 Aug 2006 17:46:11 -0500 Subject: Compiling wxPython app for Windows; Single EXE References: Message-ID: Vincent Delporte wrote: > Hi > > I browsed the archives, but since some messages date back a bit, I > wanted to make sure that > > - py2exe is still the best tool in town to compile Python scripts to > run on a Windows host that doesn't have Python installed, including > wxWidgets/wxPython > > - there's no way to build a single EXE, to make deployment easier (if > multiple files, I need to build an installer with eg. NSIS or > InnoSetup)? > > Thank you. Hi, Yes there is a way to make one .exe/.msi for everything ... but it does require purchasing a tool such as VC++. I have python + wxWindows + my stuff + many other libraries in one installer (takes 120 Megs (sigh)) Philippe From andre at svn2.wasy.de Tue Aug 22 07:37:36 2006 From: andre at svn2.wasy.de (Andre Poenitz) Date: Tue, 22 Aug 2006 13:37:36 +0200 Subject: wxWindow GetPosition() bug??? References: <1156235534.691321.154720@75g2000cwc.googlegroups.com> Message-ID: <0t6rr3-cn8.ln1@svn2.wasy.de> mardif wrote: > Hi, > I've found a strange behavior in method GetPosition() of wxWindow class > > ( and derived ). > On windows, if you create a window object > > frame = wx.Frame(None, -1, "TESTING") > > and you set the position to: > frame.SetPosition( (300, 45000) ) > > If you call method GetPosition, the result will be: > frame.GetPosition() > >>> (300, 32767) > > 32767 is the integer limit. Why GetPosition() returns this value??? and > > why on Unix Platform this problem was not found?? > > thx very much! Traditionally, there was a 16(15?) bit limit for coordinates on X Window systems. Maybe the wx implementations tries to be smarter than X itself and restricts the positions artificially. Maybe Windows has sch a limit itself... I don't really know, other than 'never try to access coordinates that are 'much' bigger than what is actually visible'... Andre' From robert.kern at gmail.com Sun Aug 6 03:47:08 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 06 Aug 2006 02:47:08 -0500 Subject: More int and float attributes In-Reply-To: <1154846489.880041.120280@m79g2000cwm.googlegroups.com> References: <1154780600.348169.158150@i42g2000cwa.googlegroups.com> <1154807223.104418.230270@i3g2000cwc.googlegroups.com> <1154810987.818618.110350@h48g2000cwc.googlegroups.com> <1154846489.880041.120280@m79g2000cwm.googlegroups.com> Message-ID: Paddy wrote: > Question: do the scientific packages supported by Python supply this > data in a regular manner? For floating point types, at least. In [11]: from numpy import * In [12]: print finfo(float32) Machine parameters for --------------------------------------------------------------------- precision= 6 resolution= 1.0000000e-06 machep= -23 eps= 1.1920929e-07 negep = -24 epsneg= 5.9604645e-08 minexp= -126 tiny= 1.1754944e-38 maxexp= 128 max= 3.4028235e+38 nexp = 8 min= -max --------------------------------------------------------------------- In [13]: print finfo(float64) Machine parameters for --------------------------------------------------------------------- precision= 15 resolution= 1.0000000000000001e-15 machep= -52 eps= 2.2204460492503131e-16 negep = -53 epsneg= 1.1102230246251565e-16 minexp= -1022 tiny= 2.2250738585072014e-308 maxexp= 1024 max= 1.7976931348623157e+308 nexp = 11 min= -max --------------------------------------------------------------------- -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From bearophileHUGS at lycos.com Thu Aug 31 15:05:15 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 31 Aug 2006 12:05:15 -0700 Subject: python loops In-Reply-To: References: <1157050085.120921.31840@h48g2000cwc.googlegroups.com> Message-ID: <1157051115.635459.215920@p79g2000cwp.googlegroups.com> AlbaClause wrote: > for i in range(length): > print i Or usually better: for ii in xrange(length): ... Bye, bearophile From Bulkan at gmail.com Tue Aug 8 02:02:57 2006 From: Bulkan at gmail.com (placid) Date: 7 Aug 2006 23:02:57 -0700 Subject: import help Message-ID: <1155016977.405733.32170@n13g2000cwa.googlegroups.com> Hi all, How do i import a module that has an hypen/dash (-) in its name ? I get a SytaxError exception Cheers From ptmcg at austin.rr._bogus_.com Fri Aug 18 21:07:28 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sat, 19 Aug 2006 01:07:28 GMT Subject: couple more questions about sqlite References: <1155930772.591854.53910@m79g2000cwm.googlegroups.com> <1rpFg.2705$No6.52662@news.tufts.edu> <1155943434.653053.232100@74g2000cwt.googlegroups.com> Message-ID: "John Machin" wrote in message news:1155943434.653053.232100 at 74g2000cwt.googlegroups.com... > I would strongly recommend for a learner of SQL and the Python DBAPI: > (1) start with sqlite; it's great, and there's minimal admin involved > (2) download the command-line utility from the sqlite website -- you'll > need it for the minimal admin, plus it's handy for quick one-line SQL > statements, peeking at the schema, etc. > I've also become a big fan of sqlite. For a nice open source db gui utility, download a copy of SQLite Database browser at http://sqlitebrowser.sourceforge.net. -- Paul From bob at passcal.nmt.edu Thu Aug 31 12:55:55 2006 From: bob at passcal.nmt.edu (Bob Greschke) Date: Thu, 31 Aug 2006 10:55:55 -0600 Subject: Subclassing Tkinter Buttons Message-ID: I don't use classes much (mainly because I'm stupid), but I'd like to make a subclass of the regular Tkinter Button widget that simply adds spaces to the passed "text=" when the program is running on Windows (Linux, Solaris, Mac add a little space between the button text and the right and left edges of a button, Windows does not and it looks bad/can be hard to read). Below is some pseudo code. What should the guts of the BButton class be? I can't work out how all of the arguments that would be passed to a regular Button call get handled. *args and **kw confuse me and I can't seem to find simple enough examples in my mountain of books. Thanks! Bob System = platform[:3].lower() . . class BButton(Button): if System == "win": Make a button with " " before and after text else: Make a button using the passed text as is . . BButton(Sub, text = "Hello", bg = "blue", fg = "yellow").pack(side = TOP) BButton(Sub, bg = "yellow", bg = "blue", text = "World").pack(side = TOP) On "lin", "sun", "dar": [Hello] [World] On "win": [ Hello ] [ World ] From yuxi at ece.gatech.edu Mon Aug 7 15:10:27 2006 From: yuxi at ece.gatech.edu (Yu-Xi Lim) Date: Mon, 07 Aug 2006 15:10:27 -0400 Subject: format a number for output In-Reply-To: References: Message-ID: Tim Williams wrote: >>>> a = 1890284 >>>> ','.join([str(a)[::-1][x:x+3] for x in range(len(str(a)))[::3]])[::-1] > '1,890,284' > > Ugly ! > >>> b = 189028499 >>> ','.join([str(b)[::-1][x:x+3] for x in range(len(str(b)))[::3]])[::-1] '-,189,028,499' >>> c = 1890284.1 >>> ','.join([str(c)[::-1][x:x+3] for x in range(len(str(c)))[::3]])[::-1] '189,028,4.1' Stick to using locale. :) From simon at brunningonline.net Thu Aug 3 10:28:05 2006 From: simon at brunningonline.net (Simon Brunning) Date: Thu, 3 Aug 2006 15:28:05 +0100 Subject: opposite of import In-Reply-To: <2pnAg.2636$No6.51572@news.tufts.edu> References: <1154605835.465468.97550@m79g2000cwm.googlegroups.com> <8c7f10c60608030517i1e68433bn569150d379648087@mail.gmail.com> <8c7f10c60608030526u59e97c79m1032d62d1d639fb@mail.gmail.com> <2pnAg.2636$No6.51572@news.tufts.edu> Message-ID: <8c7f10c60608030728k5917334fl436269561d9b2177@mail.gmail.com> On 8/3/06, John Salerno wrote: > According to Python in a Nutshell, references are stored in the > dictionary sys.modules, but I'm not sure if it matters that it's not > __modules__ instead (unless that also exists). Right you are - it's sys.modules, not sys.__modules__. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From thorsten at thorstenkampe.de Sat Aug 19 12:31:25 2006 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sat, 19 Aug 2006 17:31:25 +0100 Subject: How to get the ascii code of Chinese characters? References: <1155986298.643983.157460@i3g2000cwc.googlegroups.com> Message-ID: <1v8vi8sysz898.xpzj3nw9ij1a$.dlg@40tude.net> * many_years_after (2006-08-19 12:18 +0100) > Hi,everyone: > > Have you any ideas? > > Say whatever you know about this. contradictio in adiecto From siona at chiark.greenend.org.uk Tue Aug 15 08:41:53 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 15 Aug 2006 13:41:53 +0100 (BST) Subject: dictionary update References: Message-ID: Chris wrote: >I have a instance attribute self.xds and a local variable xds in the >instance . Both are dictionaries. I understand that I can update >self.xds with xds as follows: self.xds.update(xds) > >However I have many instance attributes, self.i, and local variables i. >I'd like to be able to do this: > >for i in list_of_i's: > self.i.update(i) > >How can this be done (I'm assuming it can be). I think what you want is: for i in list_of_is: getattr(self, i).update(locals()[i]) assuming list_of_is is a list of names not a list of the local dicts (ie ["xds", ...] not [xds, ...]). -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From fakeaddress at nowhere.org Fri Aug 4 15:26:10 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 04 Aug 2006 19:26:10 GMT Subject: Windows vs. Linux In-Reply-To: References: <1154301694.445639.99580@m79g2000cwm.googlegroups.com> <44cddfb3$0$7761$7a628cd7@news.club-internet.fr> <1154531160.066733.71210@s13g2000cwa.googlegroups.com> <2NDAg.1122$FN2.341@newssvr14.news.prodigy.com> <1vEAg.1123$FN2.891@newssvr14.news.prodigy.com> Message-ID: Duncan Booth wrote: > Bryan Olson wrote: > >> Duncan Booth wrote: >>> Any other Microsoft commands I try all complain about 'invalid >>> switch'. >> >> The first I noticed were their build tools. Their version of >> "make", called "nmake", and their visual studio tools will >> accept either forward or backward slashes in paths. >> > Ok, pedantically I meant the commands that come as part of the system. Most > external tools such as Microsoft's compilers have always accepted forward > slashes interchangeably with backslashes. They also usually accept '-' as > an option character interchangeably with '/'. The 'standard' commands > though seem to go to a lot of effort to reject forward slashes in paths, > and the CD command seems to be the only one where this usage gets through > the net. That seems right, though I don't think Microsoft is deliberately being difficult. They never put much effort into the command line; they were trying to imitate the the Mac GUI more than the Unix shell. I just tried, and on XP the "explorer" will accept forward slashes, immediately re-displaying them as backslashes. -- --Bryan From pmartin at snakecard.com Sun Aug 6 19:07:05 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Sun, 06 Aug 2006 18:07:05 -0500 Subject: embedding console in wxpython app References: <1154898390.542838.45710@i42g2000cwa.googlegroups.com> Message-ID: <%FuBg.15999$W93.12002@dukeread05> Janto Dreijer wrote: > I'm writing a Linux filemanager using wxPython. I'd like to embed a > bash console inside it. I have found the Logilab pyqonsole > (http://www.logilab.org/projects/pyqonsole), but it uses PyQT. > > Does anyone know how to do this from wx? > Is it possible to embed a PyQT widget inside wxPython? > > Thanks! > Janto How about just using bash and rerouting stdin/stdout ? Philippe From jUrner at arcor.de Mon Aug 14 20:58:24 2006 From: jUrner at arcor.de (jUrner at arcor.de) Date: 14 Aug 2006 17:58:24 -0700 Subject: Finding if Python Is Running In Console (python.exe) or Window (pythonw.exe) In-Reply-To: <1155599140.346475.219620@m73g2000cwd.googlegroups.com> References: <1155599140.346475.219620@m73g2000cwd.googlegroups.com> Message-ID: <1155603504.230809.153780@i3g2000cwc.googlegroups.com> Chaos wrote: > Does anyone know how to find where python is running from. I cant find > the answer to this anywahere on google or the docs. I know its there > because Ive seen ti done before. Thanks. Hopefully It is still there. In module "sys" as "executable". Juergen From bj_666 at gmx.net Sat Aug 12 13:00:37 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 12 Aug 2006 19:00:37 +0200 Subject: trouble with replace References: <1155401390.926925.252000@m79g2000cwm.googlegroups.com> Message-ID: In <1155401390.926925.252000 at m79g2000cwm.googlegroups.com>, f pemberton wrote: > I've tried using replace but its not working for me. > xdata.replace('abcdef', 'highway') > xdata.replace('defgef', 'news') > xdata.replace('effwer', 'monitor') `replace()` does not work in place. You have to bind the result to a name like:: xdata = xdata.replace('abcdef', 'highway') Ciao, Marc 'BlackJack' Rintsch From daniel1 at telenet.be Mon Aug 7 11:48:39 2006 From: daniel1 at telenet.be (daniel Van der Borght) Date: Mon, 07 Aug 2006 15:48:39 GMT Subject: screensaver in Python References: <1154963777.637581.306290@n13g2000cwa.googlegroups.com> Message-ID: are you Chris ? anyway : thank you... "Ant" schreef in bericht news:1154963777.637581.306290 at n13g2000cwa.googlegroups.com... > > daniel Van der Borght wrote: >> Programming a screensaver in Python, where and/or how di I start ? > > Google for "python screensaver". The first link has a module to use... > From sile_brennan at hotmail.com Fri Aug 18 04:10:22 2006 From: sile_brennan at hotmail.com (Sile) Date: 18 Aug 2006 01:10:22 -0700 Subject: python-dev and setting up setting up f2py on Windows XP In-Reply-To: <1155772555.802594.252590@74g2000cwt.googlegroups.com> References: <1155744270.092818.256290@i42g2000cwa.googlegroups.com> <1155772555.802594.252590@74g2000cwt.googlegroups.com> Message-ID: <1155888622.013180.86510@75g2000cwc.googlegroups.com> Hi John, Thank you very much for your help and resolving my issue with "python-dev". I'll hopefully get my problem sorted today, if not I'm sure I'll be back with more questions! The C compiler I'm using is Microsoft Visual Studio 8. I have been told there are potential compatibility issues between this, my version of python and my fortran compiler. I have to use python 2.3 as it is compatible with a CFD package I'm using. I've resinstalled python properley so I'll persevere with my exsisting C compiler this morning and try MINGW32 if I have no joy. Thanks again, Sile John Machin wrote: > Sile wrote: > > Hi, > > > > I've been trying to get f2py working on Windows XP, I am using Python > > 2.3. I'm new to python so I'm not too sure what I'm doing yet. I need > > the python-dev package to run f2py. I have been told this is just the > > header files and .dll and I need to put them somewhere my C compiler > > can find them. I've searched the web and none of the python-dev > > packages I've found are for windows. I was wondering is this > > automatically part of the windows version and if so how I set it up so > > my C compiler can find them. If it is not part of the standard package > > does anyone know where I can find it??? > > > > Any help at all would be much appreciated. > > The concept of "python-dev package" is a Debian concept which doesn't > apply to Windows. The standard installation on Windows provides the > header and library files that you need for interfacing with C. > > Don't put things where your C compiler can find them; do a standard > no-frills install of Python2.4 using the .msi installer and tell your C > compiler where the goodies are. > > E.g. using the MinGW32 gcc, you'd need things like: > > gcc -I\python24\include -lpython24 -L\python24\libs > [first is "i".upper(), second is "L".lower()] > > Which C compiler are you using? > > You will need to add "C:\Python24" to the path so that you can invoke > python easily; that will also enable anything else finding python24.dll > if you do a "me only" install of Python. > > So give that a whirl and if you have any dramas, come back with > questions ... > > HTH, > John From mshapiro_42 at yahoo.com Sun Aug 20 00:30:39 2006 From: mshapiro_42 at yahoo.com (Marc Shapiro) Date: Sun, 20 Aug 2006 04:30:39 GMT Subject: Text to MP3 using pyTTS - Non-programmer question In-Reply-To: <1155904799.935486.105460@i3g2000cwc.googlegroups.com> References: <1155904799.935486.105460@i3g2000cwc.googlegroups.com> Message-ID: seyeRMReyes at gmail.com wrote: > I'm not a programmer, but I'd like to make a program that will open and > read a txt file and output to a mp3 file. I don't need to ever hear the > voice, but I'd like the program to direct > > I've been google'ing around and have found a few tutorials about > converting pdfs to mp3 and converting typed text (in the source file) > to wave, but I'm looking for the ability to directly convert from txt > to mp3/ogg/wma. > > Currently I'm running on WinXP, but I also have access to a Linux box. > > Any help would be appreciated. > From what I've seen, pyTTS is Windows only. Is there a package that runs on linux that provides similar functionality. I have festival and festlite, but I would prefer a Python solution. From roy at panix.com Wed Aug 2 11:04:41 2006 From: roy at panix.com (Roy Smith) Date: Wed, 2 Aug 2006 15:04:41 +0000 (UTC) Subject: cleaner way to write this try/except statement? References: Message-ID: John Salerno wrote: > try: > if int(text) != 0: > return True > else: > self.error_message() > return False > except ValueError: > self.error_message() > return False One possible refactoring would be: try: if int(text) != 0: return True except: pass self.error_message() return False It's two less lines of code, one less return, and eliminates the duplicate call to error_message(). On the other hand, the "except: pass" clause is unusual and would make me (as a reader of the code) stop and think what was going on. Pick your poison. If you want to be truly cryptic and obfuscatory, there's always: try: 1 / int(text) return True except: return False From felipe.lessa at gmail.com Wed Aug 30 19:44:58 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Wed, 30 Aug 2006 20:44:58 -0300 Subject: GC and security In-Reply-To: <44F61EEB.8040207@optonline.net> References: <44F61EEB.8040207@optonline.net> Message-ID: 2006/8/30, Les Schaffer : > is there a best practice way to do this? I'm not a cryptographer, but you should really try the function collect() inside the gc module. -- Felipe. From larry.bates at websafe.com Mon Aug 7 17:28:58 2006 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 07 Aug 2006 16:28:58 -0500 Subject: Getting previous file name In-Reply-To: <1154983936.588478.298380@m79g2000cwm.googlegroups.com> References: <1154983936.588478.298380@m79g2000cwm.googlegroups.com> Message-ID: Hitesh wrote: > Hi, > > I have a small script here that goes to inside dir and sorts the file > by create date. I can return the create date but I don't know how to > find the name of that file... > I need file that is not latest but was created before the last file. > Any hints... I am newbiw python dude and still trying to figure out lot > of 'stuff'.. > > > import os, time, sys > from stat import * > > def walktree(path): > test1 = [] > for f in os.listdir(path): > filename = os.path.join(path, f) > create_date_sces = os.stat(filename)[ST_CTIME] > create_date = time.strftime("%Y%m%d%H%M%S", > time.localtime(create_date_sces)) > print create_date, " ....." , f > test1.append(create_date) > test1.sort() > print test1 > return test1[-2] > > > if __name__ == '__main__': > path = '\\\\srv12\\c$\\backup\\my_folder\\' > prev_file = walktree(path) > print "Previous back file is ", prev_file > > > Thank you, > hj > Just some quick ideas (not tested): change test1.append(create_date) to test1.append((create_date, filename)) that way the filename will tag along during the sorting as a tuple in the test1 list. You will also need to change prev_file = walktree(path) to create_date, prev_file = walktree(path) Note: Your script can't handle the situation where there are zero or one file(s) in the path (you should probably put in some code for those edge cases). -Larry Bates From fredrik at pythonware.com Tue Aug 29 04:00:50 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 29 Aug 2006 10:00:50 +0200 Subject: How ahead are you guys in the (Python) real world? References: <1156821234.820929.299740@p79g2000cwp.googlegroups.com> Message-ID: "Ray" wrote: > Since I haven't used Python at work, I am using Python 2.5 right now. > However I wonder, how fast are you guys moving from version to version > at work? fwiw, I work on systems that runs on 1.5.2, 2.1, 2.3 and "bleeding edge". From jcollett at oshtruck.com Fri Aug 11 10:57:47 2006 From: jcollett at oshtruck.com (Hoop) Date: 11 Aug 2006 07:57:47 -0700 Subject: Boost Install Message-ID: <1155308267.236139.206650@i3g2000cwc.googlegroups.com> Hi All, I am wondering if any have done an install of Boost for Python embedding? I have downoaded boost_1_33_1.exe, ran that and now have a boost_1_33_1 directory with plenty of items ine it. I have attempted to follow some online install directions which do not seem to work. I am using VS2005. I have tried, bjam "--with-python-version[=2.4] and just get a statement saying that bjam is not recognized. Really is no batch file or executable with that name in the boost directory. Not sure what to do to get the Boost.Python installed. Thanks for any help. Jeff From mail at microcorp.co.za Sat Aug 5 05:20:59 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Sat, 5 Aug 2006 11:20:59 +0200 Subject: Is there an obvious way to do this in python? References: <44d128e5$0$13484$636a55ce@news.free.fr><1154602887.279222.37980@75g2000cwc.googlegroups.com> Message-ID: <011d01c6b876$854ff7a0$03000080@hendrik> "Dennis Lee Bieber" wrote: 8<------------------------------ | There may be something in-between. IFF this is to be used strictly | on an internal LAN with uniform architecture (all Linux or all WinXP) | for the client machines. You'd have to set up something so a reboot no such luck - reality will probably be Linux for server, and a horrible mix of windoze machines on the client side - from 95 through 98 and 2000 to XP... will have to get SAMBA running at least - and it could be tricky with some of the older hardware/software around - but that is another fight, that I would have to solve anyway. | remounts correctly but... (In WinXP terms) Create a read-only "share" on | a file server. The file server will contain the Python modules that make | up the client. The client start-up still uses a login to obtain a | privilege map, which controls the menu/form access. However, rather than | having to push the modules to each client, you delay the module import | until the form it controls is invoked. The start-up module would have to This is more the kind of thing I had in mind - but I was not thinking in terms of having the redirecting done by the OS and network file sharing - stupid I suppose... | add the "share" to the pythonpath (hence you want a uniform system | configuration so each machine mounts the share on the same name). | I will have to think of a solution to this *shudders* - config files, maybe... | It's still an all-in-one client, but you don't have to install | anything on the user machines (except the "share" and a shortcut to the | start-up module). | | For Linux, this would be an NFS mount. *nods* Thanks Dennis - I am busy drinking out of the Pyro fire hose at the moment - and the stuff I have seen so far looks bloody awesome - you do some little bit of magic setup - and hey - you have a name server that you can query and then you can remotely execute a method on a remote object just as if its here in your machine, and you get the returns just like you would if the object were local to the machine your Python script is running in... And they have made a sort of mirror of the name server thingy so that you can fall back to a non broken one and resync when things go wrong go wrong go wrong... As a low level johnny this sort of functionality impresses the hell out of me - when I think of the time I have spent struggling to get a few small tightly coupled machines to work together in a primitive way - my mind boggles at this - you could create awesome capability by having multiple copies of objects hanging around in different machines - and simply keep track of how much they are loaded by monitoring their input queues - and make more instances as you need them as loading gets higher... The only bottleneck is the LAN's capacity to move the data around - but in most WAN type applications, that is not where the bottleneck is... and its not inconceivable to add an additional "Python Execution Gigabit Backbone" to a cluster of machines, dedicated to this remote calling task... Its almost too good for my simple little local job, but I am still reading... I have to remember to thank Bruno for the pointer... - Hendrik From st at tobiah.org Tue Aug 29 17:53:55 2006 From: st at tobiah.org (tobiah) Date: Tue, 29 Aug 2006 14:53:55 -0700 Subject: python for flash drives In-Reply-To: <1156876019.177142.101730@e3g2000cwe.googlegroups.com> References: <1156876019.177142.101730@e3g2000cwe.googlegroups.com> Message-ID: <44f4aa52$0$8954$88260bb3@free.teranews.com> You could always get an mp3 player that windows can see as a drive letter. I'll bet the I/O would be quite fast. Plus, you would be getting an mp3 player. If money is a concern, check out used ones on ebay. Putty wrote: > Is there such a thing as a special version of python that I can run > more efficiently from a flash drive? I'll be at college for hours > every day with hours of free time for the next few months, but the only > computers at my disposal are windows PCs that use GoBack to auto-revert > every reboot. So I'm kinda stuck. I don't want to have to reinstall > python AND wxPython AND PIL every stinking time I log on. However, > using it from my flash drive is painfully slow taking up to a minute > just to execute some scripts. And it's not doing me any favors with > I/O to the flash disk either. -- Posted via a free Usenet account from http://www.teranews.com From daniel.dittmar at sap.corp Tue Aug 15 09:08:36 2006 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Tue, 15 Aug 2006 15:08:36 +0200 Subject: Beginner Textbook In-Reply-To: <12e3gkdhjngum6a@corp.supernews.com> References: <12e3gkdhjngum6a@corp.supernews.com> Message-ID: M_M wrote: > I am looking for a simple text book to introduce 13 to 18 year olds to > python programming. Suggestion? If they're Germans: Python f?r Kids http://www.amazon.de/gp/product/3826609514/028-9407382-2771748?v=glance&n=299956 or Python Programming for the Absolute Beginner http://www.amazon.com/gp/product/1592000738/104-2712970-0839936?v=glance&n=283155 which seems to use a game as demo project. Daniel From fredrik at pythonware.com Thu Aug 31 09:12:42 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 31 Aug 2006 15:12:42 +0200 Subject: a question about my script References: <7.0.1.0.0.20060829041316.03da8e20@yahoo.com.ar> <20060831130109.54725.qmail@web56501.mail.re3.yahoo.com> Message-ID: "alper soyler" wrote: > directory = 'pub/kegg/genomes' > ftp.cwd(directory) > ftplib.error_perm: 550 pub/kegg/genomes/aae: No such file or directory > However, in ftp.genome.jp/pub/kegg/genomes/ site, there is 'aae' directory. > What can be the reason? try doing the cwd in pieces: for d in directory.split("/"): ftp.cwd(d) From julien.lord at gmail.com Fri Aug 4 11:40:05 2006 From: julien.lord at gmail.com (julien.lord at gmail.com) Date: 4 Aug 2006 08:40:05 -0700 Subject: web searching scripts Message-ID: <1154706005.079353.172810@i42g2000cwa.googlegroups.com> Does anyone know of a freely available script that can take a given URL and follow every link within it? Ideally, I would like to start with this to build a quick application to grab all the content off a website to publish it to a CD. Thanks, jul From danielwong at berkeley.edu Tue Aug 15 20:05:06 2006 From: danielwong at berkeley.edu (danielx) Date: 15 Aug 2006 17:05:06 -0700 Subject: include a python class in another python script. References: <1155674668.549905.60550@75g2000cwc.googlegroups.com> Message-ID: <1155686706.723164.203780@p79g2000cwp.googlegroups.com> KraftDiner wrote: > I have a class that is defined in a file called MyClass.py > > How do I use that class in another python script.. > import MyClass ? (Does it need to be in a specific location?) MyClass.py has to be on your "python path". Your python path is a list of directories python will search (in order) when you do an import statement. By default, your current working directory is the first place Python will search. You can also customize your python path. Check out this part of the docs for more info: http://docs.python.org/inst/search-path.html#search-path From johnzenger at gmail.com Wed Aug 16 23:57:55 2006 From: johnzenger at gmail.com (johnzenger at gmail.com) Date: 16 Aug 2006 20:57:55 -0700 Subject: Printing n elements per line in a list References: <1155685889.626881.37040@m73g2000cwd.googlegroups.com> Message-ID: <1155787075.547345.91330@74g2000cwt.googlegroups.com> def perline(n): count = 1 while 1: yield (count == n) and "\n" or " " count = count % n + 1 r = range(1,101) p = perline(5) print "".join("%d%s" % (x, p.next()) for x in r) unexpected wrote: > If have a list from 1 to 100, what's the easiest, most elegant way to > print them out, so that there are only n elements per line. > > So if n=5, the printed list would look like: > > 1 2 3 4 5 > 6 7 8 9 10 > 11 12 13 14 15 > etc. > > My search through the previous posts yields methods to print all the > values of the list on a single line, but that's not what I want. I feel > like there is an easy, pretty way to do this. I think it's possible to > hack it up using while loops and some ugly slicing, but hopefully I'm > missing something From chris.cavalaria at free.fr Mon Aug 21 09:16:10 2006 From: chris.cavalaria at free.fr (Christophe) Date: Mon, 21 Aug 2006 15:16:10 +0200 Subject: Python and STL efficiency In-Reply-To: References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> Message-ID: <44e9b207$0$27558$626a54ce@news.free.fr> Jeremy Sanders a ?crit : > Licheng Fang wrote: > >> I was using VC++.net and IDLE, respectively. I had expected C++ to be >> way faster. However, while the python code gave the result almost >> instantly, the C++ code took several seconds to run! Can somebody >> explain this to me? Or is there something wrong with my code? > > It must be the debugging, the compiler or a poor STL implementation. With > gcc 4 it runs instantly on my computer (using -O2), even with 10x the > number of values. > > If the problem is that C++ has to make lots of new strings, as other posters > have suggested, then you could do something like > > const string foo = "What do you know?"; > > for (long int i=0; i<10000 ; ++i){ > a.push_back(foo); > ... > } > > as many C++ implementations use reference counting for identical strings. > > Jeremy > As a matter of fact, do not count on that. Use a vector just in case. From crystalattice at gmail.com Thu Aug 3 15:56:44 2006 From: crystalattice at gmail.com (crystalattice) Date: 3 Aug 2006 12:56:44 -0700 Subject: OS independent files In-Reply-To: <1154634244.535278.224800@s13g2000cwa.googlegroups.com> References: <1154632873.085941.281850@75g2000cwc.googlegroups.com> <1154634244.535278.224800@s13g2000cwa.googlegroups.com> Message-ID: <1154635004.334503.290790@i42g2000cwa.googlegroups.com> Simon Forman wrote: > Google groups has a very good search. That's what I'm using, and it still came up with 600-900 results depending on my search terms. > Try os.path.expanduser('~') (in > http://docs.python.org/lib/module-os.path.html) or you could just look > up the HOME environment variable in os.environ, but I don't know if > windows sets this correctly in all cases. > > (os.environ is documented in > http://docs.python.org/lib/os-procinfo.html) > > Peace, > ~Simon I'll try that. Thanks. From steve at holdenweb.com Tue Aug 15 22:42:11 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 16 Aug 2006 03:42:11 +0100 Subject: proc A def/calls proc B: variable scoping rules. In-Reply-To: <1155695497.999739.295650@m73g2000cwd.googlegroups.com> References: <1155685233.002415.184150@74g2000cwt.googlegroups.com> <1155692329.075173.49060@p79g2000cwp.googlegroups.com> <1155695497.999739.295650@m73g2000cwd.googlegroups.com> Message-ID: NevilleDNZ wrote: > I inserted x1,x2 into A to force a wider scope and it works. > > #!/usr/bin/env python > def A(): > print "begin A:" > A.x1=123; > A.x2=456; > def B(): > print "begin B:",A.x1,A.x2 > A.x2 = A.x2 + 210; # problem gone. > print "end B:",A.x1,A.x2 > print "pre B:",A.x1,A.x2 > B() > print "end A:",A.x1,A.x2 > A() > > $ ./z1z2.py > begin A: > pre B: 123 456 > begin B: 123 456 > end B: 123 666 > end A: 123 666 > > $ python -V > Python 2.5b3 > > I checked: This method even handles recursion giving a new instance of > A.x2 each call. > Is this the official way to scope/inherit scopes in sub procs? > No. It's too horrible to contemplate without getting mild feelings of nausea. What exactly is it you are tring to achieve here (since I assume your goal wasn't to make me feel sick :-)? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From t.mitchell at aranz.com Thu Aug 31 21:08:00 2006 From: t.mitchell at aranz.com (t.mitchell at aranz.com) Date: 31 Aug 2006 18:08:00 -0700 Subject: Trouble finding references that are keeping objects alive In-Reply-To: <1157069780.820740.227660@m73g2000cwd.googlegroups.com> References: <1157069780.820740.227660@m73g2000cwd.googlegroups.com> Message-ID: <1157072880.774755.326690@e3g2000cwe.googlegroups.com> More info: The project has cyclic references to the objects in the projects, but this should be handled by gc.collect(). Here's is my 'project still alive' test: # store a weakref for debugging p = weakref.ref(self.data.project) self.data.setProject(None, None) gc.collect() # whole project is cyclic p = p() if p is not None: print 'Project still exists!!' Cheers Tim From deets at nospam.web.de Sat Aug 26 19:45:15 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 27 Aug 2006 01:45:15 +0200 Subject: rollover effect In-Reply-To: <1156626489.339002.189780@b28g2000cwb.googlegroups.com> References: <1156607403.741240.25000@74g2000cwt.googlegroups.com> <1156608042.466471.210270@m73g2000cwd.googlegroups.com> <1156608554.489516.243640@h48g2000cwc.googlegroups.com> <1156609000.477885.289150@h48g2000cwc.googlegroups.com> <1156609368.745082.324510@h48g2000cwc.googlegroups.com> <1156611065.857764.129500@b28g2000cwb.googlegroups.com> <1156611342.994894.288160@m79g2000cwm.googlegroups.com> <1156619079.447393.303340@75g2000cwc.googlegroups.com> <1156626489.339002.189780@b28g2000cwb.googlegroups.com> Message-ID: <4lc4obF19ksuU1@uni-berlin.de> groves schrieb: > Thanks a lot Ill have a look > and try solving my problem Ah, the summer ends and all of a sudden punctuation symbols are short. Diez From aries.shuaib at gmail.com Fri Aug 11 09:45:56 2006 From: aries.shuaib at gmail.com (Shuaib) Date: 11 Aug 2006 06:45:56 -0700 Subject: Tkinter module not found In-Reply-To: References: <1155049496.292471.37020@h48g2000cwc.googlegroups.com> <1155052842.806353.18120@i3g2000cwc.googlegroups.com> Message-ID: <1155303956.473120.160620@m79g2000cwm.googlegroups.com> Well, I finally solved my problem. I just had to reinstall python with the USE flags of tcl and tk. #USE="tcl tk" emerge python And now I can use Tkinter Thanks guys! From brent.chambers at gmail.com Sat Aug 12 05:29:17 2006 From: brent.chambers at gmail.com (brent.chambers at gmail.com) Date: 12 Aug 2006 02:29:17 -0700 Subject: unbound methods Message-ID: <1155374957.203786.73840@74g2000cwt.googlegroups.com> I wrote a small class today at work playing with sockets in command line windows. When attempting to call the handle function, I get a TypeError. "Unbound method handle() must be called with connection instance as first argument (got nothing instead). Any suggestions would be greatly appreciated. Thanks! -chase From duncan.booth at invalid.invalid Sat Aug 26 11:36:24 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 26 Aug 2006 15:36:24 GMT Subject: Learning Python References: <44f03c80$0$75042$14726298@news.sunsite.dk> <1156597310.493911.241160@i42g2000cwa.googlegroups.com> <44f0540a$0$75041$14726298@news.sunsite.dk> Message-ID: JAG CHAN wrote: > Whenever I try to open IDLE, my zone firewall tells me pythonw.exe is > trying to access the trusted zone. > Whenever I try to open new IDLE window I get the following message: > "IDLE's subprocess didn't make connection.Either IDLE can't start a > subprocess or personal firewall software is blocking the connection." > I will be grateful if you kindly suggest a way out, then, I won't have > to install another editor. You need to configure your firewall to permit IDLE to make the connection. Most firewall software when it warns you will give you the option of permitting this: e.g. Windows Firewall says "To help protect your computer, Windows Firewall has blocked some features of this program. Do you want to keep blocking this program?" with options "Keep Blocking", "Unblock", and "Ask me later". All you have to do is click "Unblock" and IDLE will work. From removethis.kartic.krishnamurthy at gmail.com Wed Aug 9 17:12:41 2006 From: removethis.kartic.krishnamurthy at gmail.com (Kartic) Date: Wed, 09 Aug 2006 21:12:41 GMT Subject: [OT] Exciting Job Opporunity : Python and Configuration Management Message-ID: <44DA4FCA.30507@gmail.com> Hello, We are looking for an experienced configuration management engineer for a client based in Cincinnati, Ohio. Below is a summary of the job. Kindly email resumes to email address shown below. Thank you, --Kartic Job Title: Configuration Management Engineer Job Reference: OHCM Job description: o Fully responsible for change management processes o Configuration management of sources, binaries as well as documentation The ideal candidate will have: o over two years of experience in change management and source code control o over two years of experience in version control and related SDLC tasks o over two years experience in configuration management tools for source, binary as well as document control. o over two years of Python programming experience o over five years of experience in application development (using languages like Python, Java, C, VB etc) as well as code maintenance o strong analytical and problem-solving skills o experience (desired but not required) in managing and administering server-based systems Interested persons please email resume with cover letter to resumes(at)sfyi.com. From you at cogeco.ca Sat Aug 12 19:29:23 2006 From: you at cogeco.ca (AlbaClause) Date: Sat, 12 Aug 2006 19:29:23 -0400 Subject: Make $1000's Monthly! References: <1155297208.125825.69660@74g2000cwt.googlegroups.com> Message-ID: dataentry.nilam.1 at gmail.com wrote: > Make $1000's Monthly! > Over 600 work at home firms are in need of survey takers, product > assemblers, home mailers, mystery > shopping > Data entry and more! Report contains complete contact details for over > 650 companies now hiring! > For this complete report of over 600 firms please visit > http://www.typeinternational.com/idevaffiliate/idevaffiliate.php?id=6589_52_3_87 Just to bring this thread back on topic, you could also make thousands of dollars monthly by becoming a professional Python coder or consultant. ;-) -- -- There are several things that I will never be: * I will never be attracted to females. * I will never enjoy the company of others. Exactly how these realities bode for my enemy, is not of my concern. From danielwong at berkeley.edu Sun Aug 6 18:01:43 2006 From: danielwong at berkeley.edu (danielx) Date: 6 Aug 2006 15:01:43 -0700 Subject: Why do I require an "elif" statement here? References: <1154712731.375032.203570@m79g2000cwm.googlegroups.com> <1154812783.619385.293820@n13g2000cwa.googlegroups.com> <1154824177.621769.311390@m73g2000cwd.googlegroups.com> <1154882081.470315.279350@h48g2000cwc.googlegroups.com> <1154886094.645371.248550@b28g2000cwb.googlegroups.com> Message-ID: <1154901703.199004.321340@75g2000cwc.googlegroups.com> No offense. I didn't mean there was anything wrong with your way, just that it wasn't "neat". By that, I meant, you were still using lots of for loops and if blocks. Justin Azoff wrote: > danielx wrote: > > I'm surprised no one has mentioned neat-er, more pythonic ways of doing > > this. I'm also surprised no one mentioned regular expressions. Regular > > expressions are really powerful for searching and manipulating text. I suppose I put those things too close together. I meant I was surprised for each of the two Separate (non)occurances. > [snip] > > I'm surprised you don't count my post as a neat and pythonic way of > doing this. I'm also surprised that you mention regular expressions > after neat and pythonic. While regular expressions often serve a > purpose, they are rarely neat. > > > Anyway, here's my solution, which does Not use regular expressions: > > > > def reindent(line): > > ## we use slicing, because we don't know how long line is > > head = line[:OLD_INDENT] > > tail = line[OLD_INDENT:] > > ## if line starts with Exactly so many spaces... > > if head == whitespace*OLD_INDENT and not tail.startswith(' '): > > return whitespace*NEW_INDENT + tail > > else: return line # our default > [snip] > > This function is broken. Not only does it still rely on global > variables to work, it does not actually reindent lines correctly. Your It's just an illustration. > function only changes lines that start with exactly OLD_INDENT spaces, > ignoring any lines that start with a multiple of OLD_INDENT. Maybe I misread, but that's what I thought he wanted. Did you not see my code comments expressing that very intent? Anyway, it wouldn't be that hard to modify what I gave to do multiple replacement: just add a recursive call. > > -- > - Justin From lists at videonetwork.org Tue Aug 1 06:27:45 2006 From: lists at videonetwork.org (Ben Edwards (lists)) Date: Tue, 01 Aug 2006 11:27:45 +0100 Subject: SOAP/WSDL Introspection Message-ID: <1154428065.5226.12.camel@localhost.localdomain> I have the below code to get info about SOAP services at a wsdl url. It gets the in parameters OK but does not seem to get out/return parameters. Any idea why? Ben from SOAPpy import WSDL import sys wsdlfile = "http://www.xmethods.net/sd/2001/TemperatureService.wsdl" server = WSDL.Proxy(wsdlfile) for methodName in server.methods: print "method = ", methodName callInfo = server.methods[ methodName ] for inParam in callInfo.inparams: print " inparam = ", inParam.name, inParam.type for outParam in callInfo.outparams: print " outparam = ", outParam.name, outParam.type From f.braennstroem at gmx.de Thu Aug 3 15:07:07 2006 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Thu, 3 Aug 2006 21:07:07 +0200 Subject: install python on cdrom References: <44CC7991.9000002@v.loewis.de> Message-ID: Hi Martin, * Martin v. L?wis wrote: > Fabian Braennstroem schrieb: >> I look for an easy way to use the newest scipy, pyvtk, matplotlib, >> f2py, numpy, paraview/vtk,... on a entreprise redhat machine >> without administration rights. >> My first thought was to install the whole new python system >> on a cdrom/dvd and mounting it, when I need it. Would that >> be the easiest way? I would be glad to read some >> hints about the way doing it... > > If you have a home directory with sufficient disk space, the > easiest way would be to install Python into your home directory, > assuming administrative policy allows such usage of the > home directory. Thanks, but unfortunately the administrative policy does not allow such installation, but could it work, when I do such a installation in my home directory, copy everything to a cdrom/dvd and mount it in proper place? Greetings! Fabian From caleb.hattingh at gmail.com Sun Aug 13 16:48:05 2006 From: caleb.hattingh at gmail.com (Caleb Hattingh) Date: 13 Aug 2006 13:48:05 -0700 Subject: looking for a simple way to load a program from another python program.. In-Reply-To: <1155498660.285772.144140@m73g2000cwd.googlegroups.com> References: <1155498660.285772.144140@m73g2000cwd.googlegroups.com> Message-ID: <1155502085.103104.295370@h48g2000cwc.googlegroups.com> Hi Eric Check that ".py" and ".pyw" are in your PATHEXT environment variable (are you using Windows?). Then, if the folder that cabel is in is in your PATH environment variable, and the correct association for .py files is set up (i.e. they get run by python.exe), either os.system('cabel') or os.system('cabel.py') should work. Alternatively, you could not do any of those things, and run os.system('python cabel.py') with 'cabel.py' in the same folder as the parent script, and that should work too, assuming that the path to your python executable is on the PATH environment variable. If you run other commands from python quite frequently, it is probably a good idea to look into the "os.popen" set of commands, for more flexibilty. Caleb From tim.golden at viacom-outdoor.co.uk Thu Aug 31 04:30:25 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 31 Aug 2006 09:30:25 +0100 Subject: How to avoid a warning message box when sending email via Outlook Message-ID: [Dermot Doran] | looks like I might be back to the drawing board :-( Thanks | for letting me know what your experiences have been. Just to elaborate slightly on that experience, if all I want to do is to send an email (ie not look up addresses on Contacts or do any fancy Outlook-related thing) then I just use an SMTP server. Here at work the admins have Exchange set up as an SMTP server, which may or may not be the case for you. At home or from websites etc. I simply use whichever SMTP server I'd normally send mail through. Obviously this won't do anything like keeping a copy in your Sent Mail box etc. but it will at least work, and with a bit more effort you may be able to do things like that manually. TJG BTW, people in this group will tend to frown on top-posting, even though we Outlook users have to work around Outlook's tendency to offer it a [Reply] ;) ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From johnjsal at NOSPAMgmail.com Thu Aug 10 16:49:08 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 10 Aug 2006 20:49:08 GMT Subject: converting a nested try/except statement into try/except/else In-Reply-To: <44db91a8$1_6@news.bluewin.ch> References: <44db91a8$1_6@news.bluewin.ch> Message-ID: <8ZMCg.2676$No6.52114@news.tufts.edu> Boris Borcic wrote: > Slawomir Nowaczyk wrote: >> >> try: >> if int(text) > 0: >> return True >> except ValueError: >> pass >> self.error_message() >> return False >> > > Nicely DRY. To make it even more compact, it may be noticed that the > default return value None is false in a boolean context - so that the > last line is superfluous if the return value is only wanted to test it > in such a context. In this case the method must return False, because it's a wxPython method that needs a True or False value. If it doesn't, the program will continue even after the error message. What I did to make it compact was have the error_message() method return False, so I can just call return self.error_message() From rog3r.day at gmail.com Tue Aug 29 13:00:35 2006 From: rog3r.day at gmail.com (r1pp3r) Date: 29 Aug 2006 10:00:35 -0700 Subject: distributing modules to machines Message-ID: <1156870835.222638.58120@m73g2000cwd.googlegroups.com> I'm in the the process of designing a build system written in python. It runs from a central server with various build machines hosting server processes, written in Python. Pyro is the chosen RPC mechanism. What I would like to do is have the system update itself on demand. In other words, pass pickled objects (the code comprising the server) down the pipeline to the server, have them copied to the right place, and then restart the server which can then invoke the new code. Is this feasible? Will there be any other issues involved? From fredrik at pythonware.com Mon Aug 28 18:13:46 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 29 Aug 2006 00:13:46 +0200 Subject: get a line of text from a socket... In-Reply-To: <1156802397.120141.309060@m73g2000cwd.googlegroups.com> References: <1156523827.971633.321830@m79g2000cwm.googlegroups.com> <1156554584.236688.186110@m73g2000cwd.googlegroups.com> <1156802397.120141.309060@m73g2000cwd.googlegroups.com> Message-ID: "KraftDiner" wrote: > What makes asyncore.loop exit? as most other things you ask about, that's explained in the documentation: http://docs.python.org/lib/module-asyncore.html loop(...) Enter a polling loop that terminates after count passes or all open channels have been closed. From UrsusMaximus at gmail.com Sun Aug 27 16:38:00 2006 From: UrsusMaximus at gmail.com (UrsusMaximus at gmail.com) Date: 27 Aug 2006 13:38:00 -0700 Subject: multi-thread tutor In-Reply-To: <1156707943.036228.169770@p79g2000cwp.googlegroups.com> References: <1156707943.036228.169770@p79g2000cwp.googlegroups.com> Message-ID: <1156711080.026169.273820@b28g2000cwb.googlegroups.com> fegge wrote: > would u like to recommand some to me/.? see http://www.awaretek.com/tutorials.html#thread From cliff at develix.com Tue Aug 1 14:16:45 2006 From: cliff at develix.com (Cliff Wells) Date: Tue, 01 Aug 2006 11:16:45 -0700 Subject: Using Python for my web site In-Reply-To: <1154439529.604271.72290@75g2000cwc.googlegroups.com> References: <1154361480.915174.262720@b28g2000cwb.googlegroups.com> <1154409902.320511.114320@75g2000cwc.googlegroups.com> <1154439529.604271.72290@75g2000cwc.googlegroups.com> Message-ID: <1154456205.20290.222.camel@devilbox> On Tue, 2006-08-01 at 06:38 -0700, Luis M. Gonz?lez wrote: > Well... yes, you're right. > I guess that the reason for not having used a framework already is > laziness... Trust me, I'm quite familiar with the laziness problem =) > I have experience with Karrigell, which rocks too, but it lacks some > deployment options (no mod_python, no fastcgi, etc). > > And as far as I could see in the Django docs, I should learn many new > things to do exactly the same, such as yet another templating language > or how to map urls with regular expressions (I still couldn't wrap my > head around regex... I find them very boring to learn...). But you are > absolutely right. I should definetely try Django sometime. > I guess I'll do it when I have a real need to do some serious web > stuff. > > As for TurboGears, I'm not very impressed... > This is a pile of different components picked by someone according to > his liking, very well glued together. Althouh its quality may be good, > why should I stick with a number of components chosen according the > criteria of some other guy? > For example, why kid instead of Cheetah? Why CherryPy? > Really, it isn't that hard to install cheetah and, if you want an > object relational mapper, sqlobject. Once you have them, using raw > mod_python is just a pleasure. Agreed. But on the other hand, it isn't always about having "the best" of each (why didn't they use Twisted rather than CherryPy would be *my* question), but rather having a complete development stack that's pre-integrated and is *good enough*. And mind you, the integration work is quite substantial. Also, TurboGears has definitely proven the "a rising tide lifts all boats" maxim, TurboGears has marketing and community and all the projects that comprise TurboGears have benefited from it. Ultimately a framework is about helping you get *your* job done. If your job is assembling frameworks or evaluating which ORM is best, then that's no help ;-) But I suspect those people are in the minority and most people just want to get their sites done without trying to figure out which is "best" and then trying to figure out how to integrate that with other components. Also, TurboGears supports template plugins (I wrote one to support Nevow's Stan, and there is a Cheetah plugin as well), and work is being done to support alternate ORMs (SQLAlchemy is working now, although not all the TG addons support it yet). The goal is to at least offer people the opportunity to replace certain components in the framework if they object to some part of TG. That's not the *ultimate* goal, but Kevin is a pragmatic guy and recognizes that component bias can hurt TurboGears' adoption and so is trying to address that in some fashion. > I feel I'm in front of a white clean canvas and I just start coding. > I like the flexibility of being able to choose each part of "my own > framework". > I even created a small script that does the automatic crud stuff for me > (not as polished as Django for sure, but it works like a charm). Sure, and if you are doing it as a hobby, or to learn or to perhaps take over the world with a new ORM, then that's great. But if someone is paying you by the hour to develop a website for them and you are writing an ORM when there's already half dozen out there, then someone probably isn't getting their money's worth. This is the problem frameworks were meant to address: putting your focus back on your web application rather than all the details that go into it. Do you lose some flexibility? You bet. Not a lot, but a noticeable amount. Of course the flip side is that you can turn out a pretty sophisticated web app *by yourself* in a few days. I saw DHH of Ruby on Rails fame at FOSCON last year and he really impressed me with is no-nonsense philosophy about web frameworks. His approach is the antithesis of Zope, Joomla, et al. Django and TurboGears are no-nonsense in the same vein: they aren't about providing every feature under the sun or blazing performance or ultimate configurability. They are about eliminating the time-consuming details that you face every time you start a project. > Anyway, there's still an issue with using these frameworks: > Availability. It's very hard, if not impossible, to find a decent web > host at an affordable price. Although I guess many of those who use > Django, for example, run their own host. Not true. As I posted elsewhere there are many hosts who will run frameworks (I suspect the pressure of Ruby on Rails really pushed open the door). Here's a short list from the TurboGears site: http://www.turbogears.org/preview/docs/deployment/hosting.html And from the Django site: http://code.djangoproject.com/wiki/DjangoFriendlyWebHosts WebFaction (formerly python-hosting) even has a control panel that will install the framework of your choice with a mouse-click. Regards, Cliff -- From amanjit.singh.gill at googlemail.com Wed Aug 23 17:18:24 2006 From: amanjit.singh.gill at googlemail.com (Amanjit Gill) Date: 23 Aug 2006 14:18:24 -0700 Subject: Python and STL efficiency References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> Message-ID: <1156367904.821050.242810@p79g2000cwp.googlegroups.com> > Hi, I'm learning STL and I wrote some simple code to compare the > efficiency of python and STL. Hi, you are benching heap allocations and of course heap fragmentation. this is what devpartner c++ profiler had to say: Method %in % with Called Average Real Name Method Children ----------------------------------------------------------------- RtlFreeHeap 52,8 52,8 81.034 7,6 7,7 RtlAllocateHeap 19,8 19,8 81.089 2,9 2,9 main 16,9 89,7 1 198083,2 1052376,0 ExitProcess 10,3 10,3 1 120616,8 120641,3 ... So on linux its a lot better than that, because - I think - ptmalloc is used which is based on dmalloc which is efficient for those small size allocs (which malloc() and free() were never designed for). on win32, activate the low fragmenting heap or write a custom stl allocator. _set_sbh_threshold(128); // method 1 ULONG HeapFragValue = 2; HeapSetInformation((HANDLE)_get_heap_handle(), // method 2 HeapCompatibilityInformation, &HeapFragValue, sizeof(HeapFragValue)); last non-python message from me :) From grante at visi.com Thu Aug 31 11:20:26 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 31 Aug 2006 15:20:26 -0000 Subject: How to avoid a warning message box when sending email via Outlook References: Message-ID: <12fdvhqh1m66gf6@corp.supernews.com> On 2006-08-31, Tim Golden wrote: > [Dermot Doran] > >| I'm very new to using win32com! I just want to send an email >| message via Outlook. However, I keep getting an annoying >| message box (generated by Outlook) indicating that my program >| could be a virus. Does anybody know how to get around this? > > As far as I've ever been able to tell, you're stuck with it. There is a DLL you can use to call Outlook to avoid that. http://www.dimastr.com/redemption/ It wraps the Outlook COM objects and accesses them in a way that doesn't trigger the warning. [The security BS is bypassed if you call DLL entries directly from C/C++ instead of via the COM interface.] > Obviously, in a sense, since otherwise any would-be virus / > zombie program would simply turn the option off before using > Outlook to send out its emails! Like most of Microsoft's "security" features, it provides zero real protection and a lot of real annoyance. Anybody who really wants to can bypass it. "Where do you want to be frustrated today?" -- Grant Edwards grante Yow! Today, THREE WINOS at from DETROIT sold me a visi.com framed photo of TAB HUNTER before his MAKEOVER! From siona at chiark.greenend.org.uk Tue Aug 22 09:46:02 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 22 Aug 2006 14:46:02 +0100 (BST) Subject: Problem of function calls from map() References: <200608211350.k7LDoBJb032411@fe12.bluebottle.com> Message-ID: <2Gf*MkSor@news.chiark.greenend.org.uk> Dasn wrote: ># size of 'dict.txt' is about 3.6M, 154563 lines >f = open('dict.txt', 'r') >print "Reading lines..." >lines = f.readlines() >print "Done." [ ... ] >def sp1(lines): > """====> sp1() -- List-comprehension""" > return [s.split('\t') for s in lines] [ ... ] >def sp4(lines): > """====> sp4() -- Not correct, but very fast""" > return map(str.split, lines) > >for num in xrange(5): > fname = 'sp%(num)s' % locals() > print eval(fname).__doc__ > profile.run(fname+'(lines)') >====> sp1() -- List-comprehension > 154567 function calls in 12.240 CPU seconds [ ... ] >====> sp4() -- Not correct, but very fast > 5 function calls in 3.090 CPU seconds [ ... ] >The problem is the default behavior of str.split should be more complex >than str.split('\t'). If we could use the str.split('\t') in map(), the >result would be witty. What do u guys think? I think there's something weird going on -- sp4 should be making 154563 calls to str.split. So no wonder it goes faster -- it's not doing any work. How does [s.split() for s in lines] compare to sp2's [s.split('\t') for s in lines] ? -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From binnyva at gmail.com Fri Aug 11 23:44:08 2006 From: binnyva at gmail.com (BinnyVA) Date: 11 Aug 2006 20:44:08 -0700 Subject: Python/Tk not working in Linux Message-ID: <1155354248.783487.217200@m79g2000cwm.googlegroups.com> I am using Fedora Core 3 Linux and I have a problem with Tk in Python. Whenever I try to run a tk script, I get the error... --------------- Traceback (most recent call last): File "Tk.py", line 1, in ? from Tkinter import * File "/usr/local/lib/python2.4/lib-tk/Tkinter.py", line 38, in ? import _tkinter # If this fails your Python may not be configured for Tk ImportError: No module named _tkinter --------------- I get this error with even the most basic Python/Tk scripts like --------------- from Tkinter import * class Application(Frame): def createWidgets(self): self.lab = Label(text="Hello World") self.lab.pack() def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.createWidgets() app = Application() app.mainloop() ------------------ However python script that does not used Tk works fine. I have tried to solve this problem by reinstalling Python from source - but still no luck. Ruby also fails this way in my system - ruby works - but not Ruby with Tk. However Perl/Tk and Tcl/Tk works fine. Any suggestions? -- Binny V A http://www.bin-co.com/perl/perl_tk_tutorial/ - Perl/Tk http://www.bin-co.com/tcl/tutorial/ - Tcl/Tk From sluggoster at gmail.com Wed Aug 30 20:31:14 2006 From: sluggoster at gmail.com (Mike Orr) Date: 30 Aug 2006 17:31:14 -0700 Subject: Egg problem (~/.python-eggs) References: <1156983715.531892.298870@i42g2000cwa.googlegroups.com> Message-ID: <1156984274.756881.35080@74g2000cwt.googlegroups.com> Mike Orr wrote: > I'm trying to install a program that uses Durus on a server. It > appears that if a Python program uses eggs, it creates a > ~/.python-eggs/ directory, so the home directory must be writeable. > This conflicts with server environments where you want to run a daemon > with minimum privileges. Second, it appears to use the real user ID > rather than the effective user ID to choose the home directory. In > this case I'm trying to use start-stop-daemon on Linux to start my > Python program, switching from user 'root' to user 'apache'. I solved the immediate problem by reinstalling Durus as a directory egg rather than a compressed egg. So is the answer just not to use compressed eggs? --Mike From fredrik at pythonware.com Thu Aug 24 06:53:57 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Aug 2006 12:53:57 +0200 Subject: radio buttons in curses References: Message-ID: Fabian Braennstroem wrote: > Does nobody have an idea or is it to stupid? have you looked at: http://excess.org/urwid/ From aahz at pythoncraft.com Wed Aug 30 23:00:12 2006 From: aahz at pythoncraft.com (Aahz) Date: 30 Aug 2006 20:00:12 -0700 Subject: GC and security References: <44F61EEB.8040207@optonline.net> Message-ID: In article <44F61EEB.8040207 at optonline.net>, Les Schaffer wrote: > >so i am curious. so long as i drop all reference to the passphrase >string(s), eventually it gets garbage collected and the memory recycled. >so "before long" the phrase is gone from memory. Assuming you're talking about CPython, strings don't really participate in garbage collection. Keep in mind that the primary mechanism for reaping memory is reference counting, and generally as soon as the refcount for an object goes to zero, it gets deleted from memory. Garbage collection only gets used for objects that refer to other objects, so it would only apply if string refcounts are being held by GC-able objects. Also keep in mind, of course, that deleting objects has nothing to do with whether the memory gets overwritten... -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ I support the RKAB From lsumnler at gmail.com Thu Aug 24 06:38:05 2006 From: lsumnler at gmail.com (len) Date: 24 Aug 2006 03:38:05 -0700 Subject: Help don't know what problem is Newbie In-Reply-To: References: <1156363910.233684.308080@74g2000cwt.googlegroups.com> Message-ID: <1156415885.564856.136870@74g2000cwt.googlegroups.com> Sorry for the stupid question. I was fixated on the SQL. Thanks Len Sumnler Peter Otten wrote: > len wrote: > > > > Have the following code: > > Short variable names increase the likelihood of name clashes: > > > c = db.cursor() > > > c = '' > > > c = csz[0] > > > c = csz[0] + ' ' + csz[1] > > c.execute("insert into Producer \ > > (Producer_Sid, Producerno, Company, Street, Suitepo, City, > > State, Zip, \ > > Phone, Taxid, Fax) \ > > values (" + orec + ")") > > Peter From johnjsal at NOSPAMgmail.com Thu Aug 31 14:11:15 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 31 Aug 2006 18:11:15 GMT Subject: problem with appending to a list, possibly mysqldb related Message-ID: <7DFJg.2719$No6.53311@news.tufts.edu> Here's the code: class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY) panel = wx.Panel(self) dbconn = self.connect_db() dbconn.execute("select namefirst, namelast from master") bb_players = [] for x in dbconn.fetchall(): bb_players.append(' '.join(x)) cb = PromptingComboBox(panel, 'Choose A Player', choices=bb_players, style=wx.CB_SORT) def connect_db(self): connection = MySQLdb.connect('localhost', 'john', '*******', 'bbdatabank') return connection.cursor() The error seems to be in the for loop. I get this: Traceback (most recent call last): File "C:\Python24\myscripts\bbdata_access\bbdata.py", line 71, in -toplevel- app = MyApp(False) File "C:\Python24\Lib\site-packages\wx-2.6-msw-ansi\wx\_core.py", line 7700, in __init__ self._BootstrapApp() File "C:\Python24\Lib\site-packages\wx-2.6-msw-ansi\wx\_core.py", line 7352, in _BootstrapApp return _core_.PyApp__BootstrapApp(*args, **kwargs) File "C:\Python24\myscripts\bbdata_access\bbdata.py", line 64, in OnInit frame = MyFrame() File "C:\Python24\myscripts\bbdata_access\bbdata.py", line 15, in __init__ name = ' '.join(x) TypeError: sequence item 0: expected string, NoneType found >>> I know the method of joining the items in the tuple and appending to a list work, so I figure it has something to do with either mysqldb, or maybe the PromptingComboBox I am using. Hope someone can spot the problem! Thanks, John From david_wahler at bic.ky Sat Aug 19 11:38:34 2006 From: david_wahler at bic.ky (david_wahler at bic.ky) Date: 19 Aug 2006 10:38:34 -0500 Subject: =?utf-8?Q?Re:_Packt_published_an_article_about_xtopdf_=2D_creating_PDF_from_Plain=0A=09Text, _DBF, _CSV, _TDV, _and_XLS_Data?= Message-ID: <20060819153834.9078.qmail@BICSRV1011.bic.ky> I'll be out of the office until approximately August 20th. If you have any questions, please email support at bic.ky. -- David Wahler From alisonken1 at gmail.com Thu Aug 10 16:34:05 2006 From: alisonken1 at gmail.com (alisonken1) Date: 10 Aug 2006 13:34:05 -0700 Subject: String Formatting In-Reply-To: <1155213326.679334.234880@i42g2000cwa.googlegroups.com> References: <1155213326.679334.234880@i42g2000cwa.googlegroups.com> Message-ID: <1155242045.262819.322010@m73g2000cwd.googlegroups.com> OriginalBrownster wrote: > Example > > If i had a list: bread, butter, milk def get_word(s, which=1, sep=','): return s.split(sep)[which-1].strip() >>> >>> get_word('bread, butter, milk') 'milk' >>> From bearophileHUGS at lycos.com Tue Aug 8 18:22:28 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 8 Aug 2006 15:22:28 -0700 Subject: String.digits help!!! In-Reply-To: <1155070685.953831.204500@m79g2000cwm.googlegroups.com> References: <1155058550.954997.320250@m79g2000cwm.googlegroups.com> <1155063757.284414.135630@n13g2000cwa.googlegroups.com> <1155064331.588367.136290@m73g2000cwd.googlegroups.com> <1155070685.953831.204500@m79g2000cwm.googlegroups.com> Message-ID: <1155075748.927391.326310@h48g2000cwc.googlegroups.com> Simon Forman: > accessing it from a > module (perhaps math.. math.infinity, math.epsilon, etc., just like > math.pi and math.e.) It too looks acceptable. > I look forward to hearing your thoughts an the subject. Thank you, but I am not expert enough on such topics to give you good comments, so I keep the muzzle shut. Bye, bearophile From steve at REMOVEME.cybersource.com.au Thu Aug 24 23:59:22 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Fri, 25 Aug 2006 13:59:22 +1000 Subject: how do you get the name of a dictionary? References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> <1156264475.968894.221710@p79g2000cwp.googlegroups.com> <1156266720.205126.284050@i3g2000cwc.googlegroups.com> Message-ID: On Wed, 23 Aug 2006 11:16:17 +0200, Sybren Stuvel wrote: > Steven D'Aprano enlightened us with: >> But an upside is that it would enable more useful error messages, at least >> sometimes. Here's some trivial pseudo-code: >> >> def foo(a): >> assert len(a) > 10, "%s is too short" % a.__name__ >> >> y = "hello" >> foo(y) >> >> would display "AssertionError: y is too short". > > That's simply a very bad example. No, it is a *simplified* example. There's a difference between simplified and bad. Would you have preferred me to post five pages of complex function calls demonstrating the same point, namely that you can bind an object to a name in one place, then pass it to a function where any tracebacks will refer to the name in the local namespace rather than the name in the traceback where the invalid data first existed? > If you use a real-world function, > you notice that the current error messages are just fine: > > def update(title): > assert len(title)> 10, "Title too short" > > update("hello") > > would display: "AssertionError: Title too short". Seems fine to me. Sure, in this case you back-track one level, and see that you passed a string literal. Easy. And in other cases, you don't pass a literal, you pass a name (say, "windowtitle"), and now instead of looking for the name title you're looking for the name windowtitle. Where did it come from? What's it's value? And in some cases, windowtitle wasn't bound to a literal either, it was bound to (say) filename.upper(), so now you're no longer looking for either title or windowtitle, but filename. Where did it get its value from? -- Steven D'Aprano From johnjsal at NOSPAMgmail.com Fri Aug 11 10:15:27 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 11 Aug 2006 14:15:27 GMT Subject: converting a nested try/except statement into try/except/else In-Reply-To: <44dbadc2_2@news.bluewin.ch> References: <44db91a8$1_6@news.bluewin.ch> <8ZMCg.2676$No6.52114@news.tufts.edu> <44dba661$1_4@news.bluewin.ch> <44dbadc2_2@news.bluewin.ch> Message-ID: <3i0Dg.2680$No6.51860@news.tufts.edu> Boris Borcic wrote: > Boris Borcic wrote: >> John Salerno wrote: >>> In this case the method must return False, because it's a wxPython >>> method that needs a True or False value. If it doesn't, the program >>> will continue even after the error message. >> >> Just as it should do if the method returns True and no error message >> is produced if I understand you well... Are you sure ? I don't know >> wxPython, but this strikes me as surprisingly unpythonic behavior. > > I just verified on the wxWindows demo I had somehow installed on my box, > that indeed returning None appears to produce the same behavior as > returning True, distinct from the behavior obtained by returning False. > Ugh... But since None == False is false, isn't it right that returning None wouldn't necessarily behave like returning False? From bryanjugglercryptographer at yahoo.com Thu Aug 3 04:55:01 2006 From: bryanjugglercryptographer at yahoo.com (bryanjugglercryptographer at yahoo.com) Date: 3 Aug 2006 01:55:01 -0700 Subject: BCD List to HEX List In-Reply-To: <1154490909.292197.129530@m73g2000cwd.googlegroups.com> References: <5S8zg.1553$W93.658@dukeread05> <1154296114.094452.158000@p79g2000cwp.googlegroups.com> <1154298390.280625.206560@75g2000cwc.googlegroups.com> <1154299830.987261.9800@b28g2000cwb.googlegroups.com> <1154301233.360818.93450@s13g2000cwa.googlegroups.com> <0abzg.1576$W93.173@dukeread05> <1154361998.861851.157210@h48g2000cwc.googlegroups.com> <1154375956.397032.166310@p79g2000cwp.googlegroups.com> <1154411021.642620.255750@s13g2000cwa.googlegroups.com> <1154412245.996874.199260@h48g2000cwc.googlegroups.com> <1154446262.681764.73100@75g2000cwc.googlegroups.com> <1154472559.132312.12550@75g2000cwc.googlegroups.com> <1154486431.531771.261730@s13g2000cwa.googlegroups.com> <1154490909.292197.129530@m73g2000cwd.googlegroups.com> Message-ID: <1154595301.068616.61610@i3g2000cwc.googlegroups.com> ohn Machin wrote: > bryanjugglercryptograp... at yahoo.com wrote: > > "For each nibble n of x" means to take each 4 bit piece of the BCD > > integer as a value from zero to sixteen (though only 0 through 9 > > will appear), from most significant to least significant. > The OP's input, unvaryingly through the whole thread, even surviving to > his Javacard implementation of add() etc, is a list/array of decimal > digits (0 <= value <= 9). Extracting a nibble is so simple that > mentioning a "subroutine" might make the gentle reader wonder whether > there was something deeper that they had missed. Yes, it's simple; that was the point. The most complex routine I assumed is integer addition, and it's not really hard. I'll present an example below. > > "Adding" > > integers and "shifting" binary integers is well-defined > > terminology. > Yes, but it's the *representation* of those integers that's been the > problem throughout. Right. To solve that problem, I give the high-level algorithm and deal with the representation in the shift and add procedures. > > I already posted the three-line algorithm. It > > appeared immediately under the phrase "To turn BCD x to binary > > integer y," and that is what it is intended to achieve. > Oh, that "algorithm". The good ol' num = num * base + digit is an > "algorithm"??? You lost me. The algorithm I presented didn't use a multiply operator. It could have, and of course it would still be an algorithm. > The problem with that is that the OP has always maintained that he has > no facility for handling a binary integer ("num") longer than 16 bits > -- no 32-bit long, no bignum package that didn't need "long", ... No problem. Here's an example of an add procedure he might use in C. It adds modestly-large integers, as base-256 big-endian sequences of bytes. It doesn't need an int any larger than 8 bits. Untested: typedef unsigned char uint8; #define SIZEOF_BIGINT 16 uint8 add(uint8* result, const uint8* a, const uint8* b) /* Set result to a+b, returning carry out of MSB. */ { uint8 carry = 0; unsigned int i = SIZEOF_BIGINT; while (i > 0) { --i; result[i] = (a[i] + b[i] + carry) & 0xFF; carry = carry ? result[i] <= a[i] : result[i] < a[i]; } return carry; } > Where I come from, a "normal binary integer" is base 2. It can be > broken up into chunks of any size greater than 1 bit, but practically > according to the wordsize of the CPU: 8, 16, 32, 64, ... bits. Since > when is base 256 "normal" and in what sense of normal? All the popular CPU's address storage in byte. In C all variable sizes are in units of char/unsigned char, and unsigned char must hold zero through 255. > The OP maintained the line that he has no facility for handling a > base-256 number longer than 2 base-256 digits. So he'll have to build what's needed. That's why I showed the problem broken down to shifts and adds; they're easy to build. > The dialogue between Dennis and the OP wasn't the epitome of clarity: Well, I found Dennis clear. [...] > I was merely wondering whether you did in fact > have a method of converting from base b1 (e.g. 10) to base b2 (e.g. 16) > without assembling the number in some much larger base b3 (e.g. 256). I'm not sure what that means. -- --Bryan From jmpurser at gmail.com Thu Aug 31 14:46:27 2006 From: jmpurser at gmail.com (John Purser) Date: Thu, 31 Aug 2006 11:46:27 -0700 Subject: problem with appending to a list, possibly mysqldb related In-Reply-To: References: <7DFJg.2719$No6.53311@news.tufts.edu> Message-ID: <20060831114627.913eb94c.jmpurser@gmail.com> On Thu, 31 Aug 2006 18:39:45 GMT John Salerno wrote: > John Salerno wrote: > > John Purser wrote: > > > >> I'd say you had a record with a null value for the namefirst field. > >> The join method don't like that. > > > > Wow, you're right! I tried this: > > > > if x[0] and not x[0] == 'NULL': > > > > and sure enough it works after that. (Not sure if that's the best > > way to test, though. Just testing for NULL still produced the > > error, so I guessed that some namefirst fields were actually blank.) > > Just tried again with: > > if x[0]: > > and that worked, so I guess NULL isn't a string value. > -- > http://mail.python.org/mailman/listinfo/python-list Your original python error was telling you that .join() didn't like receiving a 'NoneType'. Try entering type(None) from the python prompt. By the time Python is seeing it it's not a MySQL null, it's a python None. -- You have a strong desire for a home and your family interests come first. From skip at pobox.com Thu Aug 24 09:20:49 2006 From: skip at pobox.com (skip at pobox.com) Date: Thu, 24 Aug 2006 08:20:49 -0500 Subject: Python and STL efficiency In-Reply-To: <1156367904.821050.242810@p79g2000cwp.googlegroups.com> References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <1156367904.821050.242810@p79g2000cwp.googlegroups.com> Message-ID: <17645.42929.378841.881867@montanaro.dyndns.org> Amanjit> So on linux its a lot better than that, because - I think - Amanjit> ptmalloc is used which is based on dmalloc which is efficient Amanjit> for those small size allocs (which malloc() and free() were Amanjit> never designed for). And which for Python has been further optimized in obmalloc. Again, Python wins. ;-) Skip From you at cogeco.ca Sat Aug 12 19:40:13 2006 From: you at cogeco.ca (AlbaClause) Date: Sat, 12 Aug 2006 19:40:13 -0400 Subject: Read a file with open command References: <1155288288.954142.293000@i3g2000cwc.googlegroups.com> <1155316508.381805.56520@m73g2000cwd.googlegroups.com> <1155389042.226429.126170@m79g2000cwm.googlegroups.com> Message-ID: <1CtDg.67286$Uy1.56504@read1.cgocable.net> gslindstrom at gmail.com wrote: > AlbaClause wrote: >> jean-jeanot wrote: >> > > >> Ummm, he did not say that your question was stupid. The Zappa quote is >> included as part of what we refer to as a 'signature'. In the case of >> Sybren Stuvel's posts to this newsgroup, the Frank Zappa quote is >> included >> in every message that he posts. Not just messages that he posts to you. > > First up, I *like* the Frank Zappa signature quote; it has a George > Carlin feel to it and takes a swipe at our overly-protective cultures > [side note: I bought an electric heating pad last night that came with > instructions not to use it in the bathtub! Well, duh!]. But, can you > see where the signature on a response to a tutor list -- where people > are already feeling a bit intimidated and/or inadequate and therefore > may feel a wee bit "stupid" -- might be taken the wrong way? > > I have spent many years teaching mathematics and physics in a classroom > setting and have come to realize that, as a teacher, just about > anything I say/do can be blown way out of proportion. So I don't use > sarcasm or "fun" little put-downs and I treat every question as if it > is the most important matter because, to the student, it is. Do I get > tired of answering the same thing over and over? Yes!! Many times I > will ask if the student has read the textbook and, if not, I will > request they give it a try (much in the same way we ask if they have > read any tutorials), but I take Homeric efforts not to offend them and, > to that end, modify my behavior in order to teach them mathematics. > > My point is that this is a wonderful service you tutors provide, but > the Zappa signature may not be the best choice for this setting. Most > people will read it and get a laugh (as did I), but how many have taken > it the way jean-jeanot did and walk away feeling insulted? How many > will not post a response expressing their feelings, never post a > question again or, worst case, decide Python is not for them? > > Again, I admire this list and those of you you maintain it. These are > just my thoughts. YMMV. > > --greg This is getting a little off-topic, but my feeling is that if you're unable to discern the difference between the substance of the message, and the "personal style" of the author (eg: quote attributions and/or signature lines) then you probably shouldn't be attempting to code in Python or any other structured language. A newsgroup post is quite structured -- just as a Python script is -- there is the header, which contains the subject, the sender, the recipient, and other protocol information; and the text body. The text body is also quite structured. The text body can contain a quote from a prior message, the added comments that make up the substance of the message, and a signature/tag line. If a person has great difficulty in differentiating the various parts of a newsgroup message, then perhaps structured programming languages are not for them. Perhaps we should begin a new message passing convention. One where the substance of the post is contained within braces -- like C/C++ code? Just kidding! LOL -- -- There are several things that I will never be: * I will never be attracted to females. * I will never enjoy the company of others. Exactly how these realities bode for my enemy, is not of my concern. From python at hope.cz Wed Aug 2 11:50:44 2006 From: python at hope.cz (Lad) Date: 2 Aug 2006 08:50:44 -0700 Subject: Datetime objects In-Reply-To: <1154523780.974204.26740@m73g2000cwd.googlegroups.com> References: <1154519280.363058.224110@m73g2000cwd.googlegroups.com> <1154520968.852075.66140@m79g2000cwm.googlegroups.com> <1154523780.974204.26740@m73g2000cwd.googlegroups.com> Message-ID: <1154533844.628115.13770@s13g2000cwa.googlegroups.com> John Machin wrote: > Lad wrote: > > Sybren Stuvel wrote: > > > Lad enlightened us with: > > > > How can I find days and minutes difference between two datetime > > > > objects? > > > > For example If I have > > > > b=datetime.datetime(2006, 8, 2, 8, 57, 28, 687000) > > > > a=datetime.datetime(2006, 8, 1, 18, 19, 45, 765000) > > > > > > diff = b - a > > > > Ok, I tried > > > > >>> diff=b-a > > >>> diff > > datetime.timedelta(0, 52662, 922000) > > >>> diff.min > > datetime.timedelta(-999999999) > > Reread the manual: > > 1. "min" is minIMUM, not minUTES > > 2. You need: > >>> diff.days > 0 > >>> diff.seconds > 52662 > >>> diff.microseconds > 922000 > >>> minutes = (diff.seconds + diff.microseconds / 1000000.0) / 60.0 > >>> minutes > 877.71536666666668 > >>> > > > > > > which is not good for me. > > > > So I tried to use toordinal like this > > diff=b.toordinal()-a.toordinal() > > > > but I get > > diff=1 > > > > Why? > > because toordinal() works only on the date part, ignoring the time > part. > > HTH, > John Thank you for the explanation From pavlovevidence at gmail.com Thu Aug 10 08:15:49 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 10 Aug 2006 05:15:49 -0700 Subject: do people really complain about significant whitespace? In-Reply-To: References: <1154991523.887791.9640@i42g2000cwa.googlegroups.com> <1154994477.450666.226550@b28g2000cwb.googlegroups.com> <1155124820.123151.140580@p79g2000cwp.googlegroups.com> <9$lHo7FEZe2EFwf$@objmedia.demon.co.uk> <1155133454.975325.237770@b28g2000cwb.googlegroups.com> Message-ID: <1155212149.114461.277130@m79g2000cwm.googlegroups.com> Stephen Kellett wrote: > I really dislike that the end of loop2 is implicit rather than > explicit. So you can't see at a glance how many blocks were closed. That's fair. Add a little chalk mark to the against column. > C/C++ have quite a number of horrible styles (K/R being one) Oddly, I never used to use K & R until I was a longtime Python programmer. Then I wanted to get those redundant braces as far out of the way as reasonable; hence K & R. Maybe someday I'll take up a LISP-like style and put the closing brace on the last line of the block. (No, I won't.) Carl Banks From rpdooling at gmail.com Tue Aug 22 13:12:00 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 22 Aug 2006 10:12:00 -0700 Subject: how do you get the name of a dictionary? In-Reply-To: <1156264475.968894.221710@p79g2000cwp.googlegroups.com> References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> <1156264475.968894.221710@p79g2000cwp.googlegroups.com> Message-ID: <1156266720.205126.284050@i3g2000cwc.googlegroups.com> >> how difficult would it be to assign a string name(s) >> to an object upon creation (and upon referencing)? Exactly the point that's being made. It's so easy just do it yourself: banana={"name":"banana"} Hey what is the name of my dictionary? banana["name"] But why build it into Python and force everyone else to do it, when most of the time nobody cares what the name is, or they already know? It's like forcing everybody everywhere always and forever to wear "Hello My Name Is" tags. rd From jmdeschamps at gmail.com Sun Aug 20 08:53:04 2006 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 20 Aug 2006 05:53:04 -0700 Subject: tkinter btn visual state with tkMessageBox In-Reply-To: References: <1155995811.278433.87560@75g2000cwc.googlegroups.com> <1156029841.889543.172890@p79g2000cwp.googlegroups.com> Message-ID: <1156078384.281048.259870@i3g2000cwc.googlegroups.com> Hendrik van Rooyen wrote: > Wrote: > | > | Hendrik van Rooyen wrote: > | > wrote: > | > > | > To: > | > > | > > | > | why is the button sunken when called through a bind method, and not > | > | with the command attribute? > | > | Thank you! > | > | > | > | > | > | ## Cut'nPaste example > | > | from Tkinter import * ... > | > and the "Button" leaves it sunken.... - because when you release, the > control is > | > no longer there > | > > | > - Hendrik > | Thanks Hendrik - is the command attribute connected to the bindable > | events? > | jm > > I don't have a clue - you are either asking about advanced magic here, > or I don't understand your question - I believe the lower level routines > are common, but I don't *Know* this - so its a pity that some people > who shall be nameless have beaten their brains out in a thread about > a directory name here.. > > You may have noticed that there is another subtle bug with what I have > suggested to you - when you press the offending button, then move the > mouse to move the cursor off the screen button, - the button > "springs back" as expected - but then when you release the mouse > button, off the screen button, the call back is done anyway, instead of > being cancelled when the cursor moves off the screen button. > > - for the command case, the sequence is different, and the call back is done > only if the release is done on the screen button... > > - But this may just be my setup - does yours do the same? > > I don't know how to fix that - you could look at sequences of events - button > push followed by release - But I doubt whether this will help, as its doing > something like that anyway (haven't tried it) > > - Hendrik Same behavior here - Also, I added a bind to Button event and another to ButtonRelease, and also had the command attribute. All three *events* are processed, in similar fashion that you describe above. Finally, the command attribute seems to works like a ButtonRelease BUT still permits a binding to another function on a ButtonRelease event (and only one) so if the lower level functions might be the same the path to them seem different. I found this article that pertains to the question: http://www.ferg.org/thinking_in_tkinter/tt075.py but I'll postpone my own investigation at this time to return to my program ;-) Thanks again, Jean-Marc From python.list at tim.thechases.com Tue Aug 8 17:04:43 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 08 Aug 2006 16:04:43 -0500 Subject: (easy question) Find and replace multiple items In-Reply-To: <1155069659.347944.111010@m79g2000cwm.googlegroups.com> References: <1155069659.347944.111010@m79g2000cwm.googlegroups.com> Message-ID: <44D8FC6B.7080102@tim.thechases.com> > Hello, i'm looking to find and replace multiple characters in a text > file (test1). I have a bunch of random numbers and i want to replace > each number with a letter (such as replace a 7 with an f and 6 with a > d). I would like a suggestion on an a way to do this. Thanks Well, the canonical way would be to use a tool designed to do transformations: tr '76' 'fd' < test1.txt > out.txt However, if it's python you want: >>> mapping = {'7': 'f', '6': 'd'} >>> s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" >>> ''.join([mapping.get(c, c) for c in s]) 'ABCDEFGHIJKLMNOPQRSTUVWXYZ12345df890' will transform all the items found in "s" according to the defined mapping. Or, depending on your string length and the number of items you're replacing: >>> for k,v in mapping.items(): s = s.replace(k,v) may be a better choice. Or maybe they're both lousy choices. :) Time it and choose accordingly. -tkc From harshad.sharma at gmail.com Sat Aug 26 07:42:08 2006 From: harshad.sharma at gmail.com (Harshad) Date: 26 Aug 2006 04:42:08 -0700 Subject: Drag and Drop with PyQt4 In-Reply-To: <1156548450.880223.181500@74g2000cwt.googlegroups.com> References: <1156533361.933690.221260@b28g2000cwb.googlegroups.com> <1156548450.880223.181500@74g2000cwt.googlegroups.com> Message-ID: <1156592528.315743.187640@m79g2000cwm.googlegroups.com> David Boddie wrote: > > I tested this code with Python 2.4.2, Qt 4.1.4 and PyQt 4.1, and I > think you should be able to do the same in your code. > First of all, thanks a lot for the very precise and quick help! Ot works now. > 1. If you are prepared to try Qt's model/view classes, you can exert > more control over the way drag and drop is handled. They're not > quite as straightforward as the item-based classes that you're > already using, but you benefit from greater reusability of your > components and better control over the appearance and behaviour > of the view widgets. I will certainly give it more thought and probably reimplement this program with model/view classes. Thanks for the heads-up. > 2. You seem to prefer adding methods to specific instances rather than > subclassing and reimplementing methods in the base class. I hope > you don't mind me asking, but is that because it takes less code, > because you find it conceptually easier, or is there another reason > that I'm missing? > I am pretty new to Python and more so with PyQt4 and am still to learn a lot of things. I realized the issue with adding methods to specific instances a bit after I emailed to the group. I am going to subclass the widget classes in the program. Again, thanks a lot. Cheers! Harshad. From tundra at tundraware.com Thu Aug 17 12:41:19 2006 From: tundra at tundraware.com (Tim Daneliuk) Date: Thu, 17 Aug 2006 11:41:19 -0500 Subject: Looking For mp3 ID Tag Module In-Reply-To: References: Message-ID: I?igo Serna wrote: > Hi Tim, > > try mutagen. http://www.sacredchao.net/quodlibet/wiki/Development/Mutagen > > Regards, > I?igo Many thanks - this looks promising... ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From aahz at pythoncraft.com Sun Aug 6 16:15:08 2006 From: aahz at pythoncraft.com (Aahz) Date: 6 Aug 2006 13:15:08 -0700 Subject: email client like mutt References: Message-ID: In article , Fabian Braennstroem wrote: > >I am looking for a python email client for the terminal... something like >mutt; maybe, so powerfull ;-) What's wrong with mutt? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." --Brian W. Kernighan From celiadoug at mchsi.com Fri Aug 25 18:40:29 2006 From: celiadoug at mchsi.com (Doug Stell) Date: Fri, 25 Aug 2006 22:40:29 GMT Subject: ASN.1 encoder & decoder References: <87odu8e9ty.fsf@cenderis.demon.co.uk> Message-ID: I looked at pyasn1. Unfortunately, it is not useful and provides a C interface. Thanks, anyhow. I figure that I will have to write my own, but am unsure of the best approach. Nested lists and distionaries might be useful and I am looking to the feasibility of those mechanisms. On Fri, 25 Aug 2006 23:20:41 +0100, Bruce Stephens wrote: >Doug Stell writes: > >> Can anyone provide guidance on building an ASN.1 decoder and encoder >> in Python? > >? From mail at microcorp.co.za Fri Aug 4 01:33:07 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Fri, 4 Aug 2006 07:33:07 +0200 Subject: How to force a thread to stop References: mailman.8528.1153845034.27775.python-list@python.org><1153880729.687711.227570@h48g2000cwc.googlegroups.com><1153942270.301732.99880@h48g2000cwc.googlegroups.com><7xslkoum88.fsf@ruckus.brouhaha.com><44C7E7EC.4020301@mvista.com><1lwn8bs8qhg4c.dlg@gelists.gmail.com><3sphc25or7ir5keeithpvb1k3vog39botu@4ax.com><7xwt9y8916.fsf@ruckus.brouhaha.com><7xvephg7yq.fsf@ruckus.brouhaha.com><1hjgrs7.w01xtjt192o1N%aleax@mac.com><00ae01c6b6e5$9996ca00$03000080@hendrik> Message-ID: <00d301c6b79d$f91fd800$03000080@hendrik> "Gerhard Fiedler" wrote: | On 2006-08-03 06:07:31, H J van Rooyen wrote: | | > Thanks - will check it out - seems a lot of money for 555 functionality | > though.... | > | > Especially if like I, you have to pay for it with Rand - I have started | > to call the local currency Runt... | | Depending on what you're up to, you can make such a thing yourself | relatively easily. There are various possibilities, both for the | reset/restart part and for the kick-the-watchdog part. | | Since you're talking about a "555" you know at least /some/ electronics :) *grin* You could say that - original degree was Physics and Maths ... | Two 555s (or similar): | - One wired as a retriggerable monostable and hooked up to a control line | of a serial port. It needs to be triggered regularly in order to not | trigger the second timer. | - The other wired as a monostable and hooked up to a relay that gets | activated for a certain time when it gets triggered. That relay controls | the computer power line (if you want to stay outside the case) or the reset | switch (if you want to build it into your computer). | | I don't do such things with 555s... I'm more a digital guy. There are many | options to do that, and all a lot cheaper than those boards, if you have | more time than money :) Like wise - some 25 years of amongst other things designing hardware and programming 8051 and DSP type processors in assembler... The 555 came to mind because it has been around for ever - and as someone once said (Steve Circia ?) - "My favourite programming language is solder"... - a dumb state machine implemented in hardware beats a processor every time when it comes to reliability - its just a tad inflexible... The next step above the 555 is a PIC... then you can steal power from the RS-232 line - and its a small step from "PIC" to "PIG"... Although this is getting bit off topic on a language group... ;-) Hendrik From vatamane at gmail.com Thu Aug 3 07:01:27 2006 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 3 Aug 2006 04:01:27 -0700 Subject: Is there an obvious way to do this in python? References: <44d128e5$0$13484$636a55ce@news.free.fr> Message-ID: <1154602887.279222.37980@75g2000cwc.googlegroups.com> HJ, As far as GUI language/library goes: Some people suggested HTML, but I think HTML is a very awkward way to create a good looking dynamic GUI that is _both_ easy to use and fast and easy to design (which is what you would want probably). Just to have a nice user editable table for example, you would have to jump through hoops (using Javascript, DOM, CSS etc), while you could do it much easier with PyGTK and wxPython, especially if you use a gui designer like Glade or wxGlade. Even Tkinter beats HTML as far as building GUIs in Python goes. I believe this might change in the future with the adaption of SVG but that will take a while... That said, if your interface can "get by" with just buttons, text boxes, and text areas HTML will be the best choice. As far as "updating-on-the-fly" goes: For the client to get the code on the fly you will have to implement some sort of a downloader in the first place that when the user logs in, it downloads the GUI code from the server and runs it. So if you update the code the day before the next day they will get a different interface, or if a new user/machine type is created you just have the new code ready on the server and it will automatically be downloaded and run, is that right? Here is then how I see your use case: 1) You would define your business rules in your database, you will have usernames, user types, access rights, data tables, columns types, relations, views, etc... 2) Then each user type will have a specific interface GUI code kept on the server (perhaps as a zipped binary GUI.zip in a database column called ClientSpecificGUI). 3) The client starts your Application.py which is the same across all clients. They will enter their username/password. The Application.py then sends those to the server to log into the DB. 4) After successful login, the Application.py performs a SELECT query to download the zipped GUI.py file. 5) GUI.py is unzipped and executed to start the GUI. The Application.py code will pass the DB connection object to the GUI.py, so the GUI can continue to talk with the database. GUI.py runs and does its magic, in the meantime Application.py waits for GUI.py to finished and then both exit. Is that what you had in mind? NOTE: This means that the client will need to have all the required libraries at just the right versions. Imagine that your user decides to upgrade to Python 3000 because it sounds cooler than plain old Python 2.4 ;) , but then they won't realize that it will break your code and they might not be able to run your application anymore. So you would have to know at least roughly how much control over the whole client machine you will have. Will they all be regular desktops that users will use day to day and then once in a while launch your application then close it, or will these all be dedicated terminals like an ATM? The two are very different. You can assume complete control of all the OS environment in a dedicated terminal but not in the case of a user desktop. Hope this helps, Nick Vatamaniuc H J van Rooyen wrote: > "Bruno Desthuilliers" wrote: > > > |H J van Rooyen a ?crit : > |> Hi, > |> > |> I want to write a small system that is transaction based. > |> > |> I want to split the GUI front end data entry away from the file handling and > |> record keeping. > |> > |> Now it seems almost trivially easy using the sockets module to communicate > |> between machines on the same LAN, so that I want to do the record keeping on > one > |> machine. > |> > |> I want to keep the "server" machine as simple as possible - just doing record > |> keeping on a stimulus response basis - I would prefer it to do one thing at a > |> time to completion because this style of operation, though limited in > |> performance, keeps a lot of hassles out of life - a transaction has either > |> completed, or it has not - recovery scenarios are relatively easy... > | > |IOW, you want a SQL DBMS. May I recommand PostgreSQL ? > | > > Looks like the way to go - after the argy bargy here in another thread seems > mySQL has no supporters left... > > |> Up to this point, I don't have a problem - my toy system can create a dummy > |> transaction, and I can echo it from the "server" machine, with more than one > |> "user" machine running - so I think it is feasible to have several tens of > "data > |> entry terminal" systems running, served by one not very strong machine. > |> > |> Now what I would really like to do is to differentiate between the 'User" > |> machines, so that some can do a full range of transactions, and others a > limited > |> range. > | > |Any decent SQL DBMS is able to handle this. It's kind of builtin... > > Yes - if you do the whole job on the server - the architecture I have mind is > more like a banking terminal scenario - please see my reply to Simon > > | > |> And I would like to make this flexible, so that it becomes easy to introduce > new > |> transactions, without having to run around updating the code in all the user > |> machines, with the concomitant version number hassles. > | > |Then you want a web front end. > > This seems to me to assume that the server does all the work > > | > |> And I would like to do the whole thing in python > | > |You'll at least need bits of SQL (but SQLAlchemy may hide away most of > |it) and HTML (but there are some python packages that knows how to build > |HTML from declarative Python code). > | > > that is good news - which packages? > > |> - so my question is this - is > |> it possible to do the equivalent of dynamic linking? - i.e. if I keep a list > of > |> what a user is allowed to do > | > |In SQL : GRANT/REVOKE > > again - centric thinking - I really would like to change the bits on the client, > as I explained to Simon > > | > |> - can I somehow send him just the bits he needs to > |> do the job, without having to change the static code on his machine? > | > |HTTP/HTML. > | > > everybody says this - I am being dragged, kicking and screaming... > > |> - it seems > |> to me that the eval() thingy could possibly do this for me, > | > |Err... I thought you wanted a reasonnably secure system, but I may have > |misunderstood. > | > > this is the guts of what I want - if eval is NFG then how do I implement such a > kind of "dynamic linking" of modules on the client? > > |> by sending it data > |> that makes it do import statements followed by calls to whatever... - will > this > |> work, or is there a better way? > |> > |> Or has all this been done already? > | > |Yes, it's called a web frontend for a SQL DBMS. There's no shortage of > |Python frameworks to do this kind of things. > | > > I kind of wanted to avoid the web based stuff - the application data is so small > and trivial, in a sense. > > |> - and no I don't want a web server > | > |If you don't want Apache, there are Python-based application servers. > |CherryPy comes to mind. > | > |> and php > | > |Why PHP ? > | > > seems popular > > |> and browsers and Java > | > |Why Java ? > | > > it addresses what I want - to dynamically and securely download bits of code and > execute them on the remote machine... > > |> and html or xml... - I want to write something that works > |> simply and reliably > | > |We do write SQL-based web apps all day long, and I can tell you they are > |certainly more simple and reliable than whatever eval()-based home-made > |solution we could imagine !-) > > Aah! but I would like you to stretch that imagination - to tell me how to do > some of what Java was designed to do, but better and easier, because this is > python we are talking about... > > I saw something in another thread here - they were talking about weave - can I > use that if eval is nfg? > > If my original post was unclear I am sorry - the point I want answered, if > possible, is how to make the client code effectively updateable on the fly - > because the answer to this will influence the whole design of the rest of the > system... > > - Hendrik From pavlovevidence at gmail.com Wed Aug 9 10:48:22 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 9 Aug 2006 07:48:22 -0700 Subject: do people really complain about significant whitespace? In-Reply-To: <44d9d949$0$14310$626a54ce@news.free.fr> References: <1154986984.740638.241130@m79g2000cwm.googlegroups.com> <87bqqwyumq.fsf@benfinney.id.au> <1155077965.100108.232790@m79g2000cwm.googlegroups.com> <44d9d949$0$14310$626a54ce@news.free.fr> Message-ID: <1155134902.103617.71810@i3g2000cwc.googlegroups.com> Pierre Barbier de Reuille wrote: > Problem being : grouping by indentation do *not* imply good indentation. By itself, it doesn't. But with grouping by indentation, bad indentation no longer results from mere carelessness, which is no small thing. Although Python doesn't do this, it is possible to mandate a specific indent (4 spaces, say), or at least a reasonable consistent indent, which would indeed all but guarantee good indenting. (I say "all but" only to account for deliberately misleading code, perhaps using clever line breaks and comments.) > For example, I had to read a piece of (almost working) code which looked > like that : > > if cond1 : stmt1 > stmt2 > stmt3 > if cond2: stmt4 > stmt5 > elif cond3: stmt6 > stmt7 > else: stmt8 > stmt9 > stmt10 > stmt11 > > So you can tell what you want, but this code is valid but impossible to > read and impossible to reindent correctly. So although I personnaly like > Python, I still don't think meaningful indentation is good. Even if this were legal code (it isn't), it's still more transparent than some of the C code I've seen. Carl Banks From martin.witte at gmail.com Wed Aug 16 11:36:18 2006 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 16 Aug 2006 08:36:18 -0700 Subject: idea on how to get/set nested python dictionary values In-Reply-To: <1155736272.292188.57710@p79g2000cwp.googlegroups.com> References: <1155663671.716249.18780@m79g2000cwm.googlegroups.com> <1155678816.942660.296140@74g2000cwt.googlegroups.com> <1155736272.292188.57710@p79g2000cwp.googlegroups.com> Message-ID: <1155742578.522606.98440@74g2000cwt.googlegroups.com> metaperl wrote: > wittempj at hotmail.com wrote: > > > | would use a recursive approach for this - given that you have a sort > > of recursive datastructure: > > > > py> def SetNewDataParam2(Data, NewData): > > ... if type(Data[Data.keys()[0]]) == type(dict()): > > ... SetNewDataParam2(Data[Data.keys()[0]], NewData) > > ... else: > > ... Data[Data.keys()[0]] = NewData > > ... > > Data[Data.keys()[0]] is used 3 times in the above code. Is there some > way to factor out that usage? I'm just starting python but I'm always > on the lookout for DRY :) Bearophilehugs gave a much better answer than I did, it also takes away the need to evaluate the keys() more than one time From superflit at gmail.com Mon Aug 28 15:37:40 2006 From: superflit at gmail.com (flit) Date: 28 Aug 2006 12:37:40 -0700 Subject: looking for data on csv files Message-ID: <1156793860.723758.188800@74g2000cwt.googlegroups.com> Hi! I am using the csv modules.. when I use the command: if nome in row[rowcsv]: print "\n" print row[rowcsv] + "\n ----> " + row[11] + "\n" print "################################################################" there is this case: 1- data on file PUItarr If the user try to find for puitarr or PUITARR it doesn?t find. I tried the string.upper and .lower , but there is a a way to look far all possible combinations? And yes, i am a newbie.. From steve at REMOVEME.cybersource.com.au Mon Aug 21 05:36:21 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Mon, 21 Aug 2006 19:36:21 +1000 Subject: sum and strings References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <1155922208.930580.135080@m79g2000cwm.googlegroups.com> <1155952305.848495.7060@i3g2000cwc.googlegroups.com> <7x4pw9h3yy.fsf@ruckus.brouhaha.com> Message-ID: On Fri, 18 Aug 2006 19:08:37 -0700, Paul Rubin wrote: > If the args are strings, the above is a quadratic time algorithm and > it's better to throw an error than create such a trap for an unwary user. That's a nonsense argument. There is no shortage of slow algorithms, and some of them are built into Python. When did O(n**2) become an error condition? And overhead matters: if I'm only doing a few concatenations, it is significantly faster to add the strings using + than to use join() (at least in Python 2.3 -- YMMV): >>> s = timeit.Timer("''.join(L)", "L=['a'*50, 'b'*50, 'c'*50]") >>> s.timeit() 1.3470098972320557 >>> t = timeit.Timer("a+b+c", "a,b,c = 'a'*50, 'b'*50, 'c'*50") >>> t.timeit() 1.0698421001434326 There's a word for optimizations that actually result in code running 25% slower. I applaud that Python's language developers care about efficiency. I applaud that the documentation warns people about traps and potential areas of inefficiency. But I think it is a shame that sum() does a special type-check to avoid something which is only sometimes slow. It doesn't protect against O(n**2) performance; it merely protects against just one of an infinite number of possible "traps for the unwary". I would have thought it would be better for sum() to raise a warning, not an exception. If we take seriously the argument that sum implies addition, and that string concatenation isn't really addition, then sum() should also refuse to operate on lists and tuples and any other non-numeric class. Either would be better than sum() "protecting" the user from himself, except when it doesn't. -- Steven D'Aprano From sreeram at tachyontech.net Fri Aug 25 12:42:11 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Fri, 25 Aug 2006 22:12:11 +0530 Subject: time.clock() going backwards?? In-Reply-To: References: Message-ID: <44EF2863.2050501@tachyontech.net> Giovanni Bajo wrote: > Hello, > > I experimented something very strange, a few days ago. I was debugging an > application at a customer's site, and the problem turned out to be that > time.clock() was going "backwards", that is it was sometimes (randomically) > returning a floating point value which was "less than" the value returned by > the previous invokation. The computer was a pretty fast one (P4 3Ghz I think, > running Windows XP), and this happened only between very close invokations of > time.clock(). > > I have triple-verified this, including printing the repr() of the floating > point number and verifying it was really minor than the previous value by a few > microseconds. In other words, I'm absolutely positive that it's not a mistake > on my side, but that time.clock() was really apparently "jumping backward". > This was confusing the hell out of my application, of course, and I just hacked > it so to ignore these bogus reads, and just reading off again. Since the error > was just of a few microseconds, reading time.clock() again produces a number > which was higher than what I had before, and thus OK for my application. > > I was wondering if someone had experimented this behaviour before. I tried > googling but to no effect. Is it possible this to be a bug in Python itself > (maybe, shooting at the moon, in the conversion between the 64bit performance > counter and the floating point representation returned by time.clock()), or > could it be a bug in Windows itself or the mother board drivers (buf if so, > wouldn't other application start going mad)? From the MSDN docs for QueryPerformanceCounter: Remarks: On a multiprocessor computer, it should not matter which processor is called. However, you can get different results on different processors due to bugs in the basic input/output system (BIOS) or the hardware abstraction layer (HAL). To specify processor affinity for a thread, use the SetThreadAffinityMask function. Are you running on a multi-core or a multi-processor machine? The best way to handle this is probably to make your application 'tolerant' to such cases. [sreeram;] -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From python.list at tim.thechases.com Fri Aug 11 09:10:02 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 11 Aug 2006 08:10:02 -0500 Subject: hide python code ! In-Reply-To: <1155300852.497741.73230@74g2000cwt.googlegroups.com> References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155300852.497741.73230@74g2000cwt.googlegroups.com> Message-ID: <44DC81AA.1030101@tim.thechases.com> >> can we hide a python code ? >> if i want to write a commercial software can i hide my source code from >> users access ? >> we can conver it to pyc but this file can decompiled ... so ...!! > > All of these make it hard enough to deter most people who will ever > want to abuse your source code. Until you have *lots* of users this is > probably enough. > > I never understand the knee-jerk reaction on this mailing list to > answer people who ask this question by telling them they don't really > want to do it... I think the reaction is based mostly in reality...an honest answer: If you give people the program, then you also give them the ability to reverse engineer it. It's as simple as that. No matter how dongled, obfuscated, compiled, encrypted, etc. At some point the code actually has to be executed/interpreted, and at that point, it can be intercepted. Thus, "by telling them that they don't really want to do it", the list is conveying the futility of attempting to strive for the goal. Obfuscation may be a shallow speedbump, and for some folks, better than nothing. However, it's better to have a good relationship with your customers and know that they will adhere to licensing conditions, rather than to try and strong-arm them into behaving a particular way. My "%s%0.2f" % (currency_marker, 0.02) on the matter. :) -tkc From python.list at tim.thechases.com Wed Aug 9 14:56:59 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 09 Aug 2006 13:56:59 -0500 Subject: Python share CPU time? In-Reply-To: <1155146500.063665.282430@p79g2000cwp.googlegroups.com> References: <1155146500.063665.282430@p79g2000cwp.googlegroups.com> Message-ID: <44DA2FFB.7070003@tim.thechases.com> > Problem is that I would have to share the CPU between all the robots, > and thus allocate a time period to each robot. However I couldn't find > any way to start a thread (robot), and interrupt it after a given time > period. > Any suggestions on how to proceed? >>> import thread, time >>> def robot(name): ... for i in xrange(5): ... print "%s on pass %i" % (name, i) ... time.sleep(0.01) ... >>> ids = [thread.start_new(robot, ("Robot%i" % i,)) for i in xrange(4)] Robot1 on pass 0 Robot2 on pass 0 Robot0 on pass 0 Robot3 on pass 0 Robot1 on pass 1 Robot0 on pass 1 Robot2 on pass 1 Robot3 on pass 1 Robot1 on pass 2 Robot0 on pass 2 Robot2 on pass 2 Robot3 on pass 2 Robot1 on pass 3 Robot0 on pass 3 Robot2 on pass 3 Robot3 on pass 3 Robot1 on pass 4 Robot0 on pass 4 Robot2 on pass 4 Robot3 on pass 4 Maintaining a Queue of things to do for each robot allows the robot to process a single thing before sleeping a bit. The thread scheduler does seem to provide interruptions, as I've run the above code with no sleep() call and larger iterations, and you'll find it bouncing from robot to robot. Or, you can take advantage of python's yield statement: >>> class Robot(object): ... def __init__(self, name): ... self.name = name ... self.thought = 0 ... self.done = False ... def think(self): ... while not self.done: ... yield self.thought ... self.thought += 1 ... def finish(self): ... self.done = True ... >>> robots = [Robot(str(i)) for i in xrange(5)] >>> generators = [robot.think() for robot in robots] >>> [g.next() for g in generators] [0, 0, 0, 0, 0] >>> [g.next() for g in generators] [1, 1, 1, 1, 1] >>> [g.next() for g in generators] [2, 2, 2, 2, 2] >>> [g.next() for g in generators] [3, 3, 3, 3, 3] >>> [g.next() for g in generators] [4, 4, 4, 4, 4] >>> generators[2].next() 5 >>> [g.next() for g in generators] [5, 5, 6, 5, 5] >>> robots[2].thought 6 >>> robots[3].thought 5 Just do more complex stuff in the think() method (to most folks, counting isn't very exciting thinking) and yield your current state. > Is Python just not adapted to this kind of things? Python is quite adaptable to these sorts of things...it requires an adaptable programmer to make the best use of it though... ;) -tkc From rogue_pedro at yahoo.com Tue Aug 15 18:45:33 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 15 Aug 2006 15:45:33 -0700 Subject: using python at the bash shell? In-Reply-To: References: <44d7e364$0$24980$c3e8da3@news.astraweb.com> <1155054162.683298.21760@m73g2000cwd.googlegroups.com> Message-ID: <1155681933.117671.54450@i3g2000cwc.googlegroups.com> cga2000 wrote: > On Tue, Aug 08, 2006 at 12:22:42PM EDT, Simon Forman wrote: > > John Salerno wrote: > > > skip at pobox.com wrote: > > > > John> Aside from the normal commands you can use, I was wondering if > > > > John> it's possible to use Python from the terminal instead of the > > > > John> normal bash commands (e.g. print instead of echo). > > > > > > > > Take a look at ipython . It's not precisely what > > > > you've asked for, but it provides some features that help integrate Python > > > > with the shell environment. > > > > > > > > Skip > > > > > > Can you use IPython to do normal bash things, like installing, etc.? > > > > "normal bash things"? :-) Yes, most commands can be run by putting an > > '!' before them. If you ever need to run something that for some > > reason doesn't work with this, you can always run !bash and do it in > > bash. :-) > > > Sorry, I'm late with my howmework .. but this is rather cool. > > Although .. prefixing all your "system commands" with the far-to-reach > "!" would probably become a royal pain after a while. I use my computer almost exclusively for programming, so I used xmodmap to remap the number & symbol keys the other way round, i.e. I get "!@#$%^&*()" from just pressing the keys and "1234567890" when I press shift+keys. It's soooo much nicer (except when I use another machine...) So hitting '!' for me at least ain't so bad. ;P YMMV I don't actually use Ipython as my shell, but I'd *like* to.. > > Why do you write "most commands" .. what type of command might not be > run by "putting '!' before them?" Well, I wrote that just to hedge my bets, but here's an example: I set up lesspipe and source-highlight to add syntax highlighting to various file types when viewed through less. But using "!less neat.py" in Ipython doesn't work because (I'm guessing here) Ipython doesn't handle the color escape codes. It winds up looking like this: ESC[31m#!/usr/local/bin/python2.5ESC[m ESC[01;34mfromESC[m random ESC[01;34mimportESC[m random as f ESC[01;34mdefESC[m ESC[01;30mgESC[mESC[31m(ESC[mESC[31m)ESC[mESC[31m:ESC[m n1 ESC[31m=ESC[m ESC[01;30mfESC[mESC[31m(ESC[mESC[31m)ESC[m ESC[01;34mwhileESC[m TrueESC[31m:ESC[m n2 ESC[31m=ESC[m ESC[01;30mfESC[mESC[31m(ESC[mESC[31m)ESC[m yield n1 ESC[31m-ESC[m n2 n1 ESC[31m=ESC[m n2 Ew. So in this case I'd have to "!bash" then "less neat.py"... > In the linux world it would be rather interesting if a distro was > available that uses nothing but python. > > The installer .. the startup scripts .. utilities .. etc. > > Maybe there is such a thing and I'm just not aware of it? IMHO it would be neat, but it'd be kind of a "stunt". There's a ton of excellent code in most any linux distro *not* written in python. > Since it would be byt-code being executed it would be faster than > regular shell stuff and a lot easier to customize/maintain. Mmmm... I bet it'd be hard to beat, say, grep... Or any of the small, custom-purpose C-coded tools. (then there's make... gcc... not easy to rewrite those.. just off the top of my head...) > > Don't know enough to figure out if such a thing is possible, though .. > > Thanks > > cga Peace, ~Simon From metaperl at gmail.com Thu Aug 31 04:36:43 2006 From: metaperl at gmail.com (metaperl) Date: 31 Aug 2006 01:36:43 -0700 Subject: Any relational database design tool written in Python Message-ID: <1157013403.490468.59760@m73g2000cwd.googlegroups.com> Hello, I am wondering if I overlooked such a tool at freshmeat, sf.net, and cheeseshop and google. I prefer Python, so that I can patch and upgrade it. Which also means I prefer opensource over commercial. I am hoping for something that can create database deltas. I am sort of divided over the logical versus physical modeling issue. While I am looking for something fairly graphical like dbSketch or dbWrench, I am pretty impressed with Django's built-in ORM's ability to create and update databases. From tim at tdw.net Sat Aug 26 12:57:50 2006 From: tim at tdw.net (Tim Williams) Date: Sat, 26 Aug 2006 17:57:50 +0100 Subject: Python web service ... In-Reply-To: References: <1156590455.555359.247410@h48g2000cwc.googlegroups.com> Message-ID: <9afea2ac0608260957y6513da2cke317465ddeaa2ecb@mail.gmail.com> > At this time right now I prefer to do something that works the quickest > possible... > I never had any experience with CGI, do I need to set up a web server > for that ? > can you point me some usefull reading material so I can get a start ? > I will post for a comment at Zope , I had installed once and it was > very easy. Don't know if it will be easy too to get my job done... If you need a quick-start and short learning curve, Karrigell is the one to go for. You can have the beginnings of your own site/web-app running within minutes of downloading it. It now has better CGI handling too - if you must go that route :) www.karrigell.com I recommend the Karrigell tour also, click on the icon next to each example to see how each one is coded, and it has a file upload example that should get you started. http://karrigell.no-ip.info/demo/frame_tour_en.htm :) From shekhar.kaushik at gmail.com Fri Aug 4 00:29:23 2006 From: shekhar.kaushik at gmail.com (Chandrashekhar kaushik) Date: Fri, 4 Aug 2006 09:59:23 +0530 Subject: SWIG Python Extension winth C++ Problematic Message-ID: someone ?? On 8/4/06, Chandrashekhar kaushik wrote: > > Hi > I have been working getting my C++ code to be used in Python ( Basically > Extending ) > This is the problem i am facing rite now. > > I have a function that returns a Pointer to a class in my C++ Code > > It looks like this > > SLSocket* SLSocket::accept( SLHostInfo& client ){ > socklen_t addrlen = sizeof( struct sockaddr_in ); > int new_fd = ::accept( sock_fd , ( struct sockaddr* )client.address() > , &addrlen ); > if( new_fd == -1 ){ > sl_set_error(string("SLSocket::accept() : ") + string( > sys_errlist[ errno ] )); > return NULL; > }else{ > return new SLSocket( new_fd ); > } > } > > I have used SWIG to get the Glue code. > > When i call this function ( in python ) and it eventually returns ( when > it gets a connection in this case ) > it crashes ! I get a SEG FAULT ! > > Is it some thing that cannot be done ? > Are C++ functions those return pointers a pain in Python > > Help :D > > > -- > shekhar > -- -- shekhar -------------- next part -------------- An HTML attachment was scrubbed... URL: From futurelogix at gmail.com Thu Aug 10 05:23:01 2006 From: futurelogix at gmail.com (flogic) Date: 10 Aug 2006 02:23:01 -0700 Subject: def __init__(self, link, *arg, **key): In-Reply-To: References: <1155196761.085198.140530@i3g2000cwc.googlegroups.com> Message-ID: <1155201781.710569.294440@m79g2000cwm.googlegroups.com> Thanks a lot... CIAO Duncan Booth wrote: > flogic wrote: > > > Hi > > i m a newbie to python .. > > jus started to learn ...am quite confused about variable arguments used > > in python functions and in init. > > > > i dont where to use **keys , **kwds,*args ...etc... > > > > if anyone culd give some explanation with examples or clear detailed > > web link, it wuld be helpful to me > > > Have you read sections 4.7.2-4.7.4 of the Tutorial? > > http://docs.python.org/tut/node6.html#SECTION006720000000000000000 From justask at acme.com Mon Aug 14 18:34:01 2006 From: justask at acme.com (Vincent Delporte) Date: Tue, 15 Aug 2006 00:34:01 +0200 Subject: Compiling wxPython app for Windows; Single EXE References: <1155573542.310208.43190@i3g2000cwc.googlegroups.com> Message-ID: On 14 Aug 2006 09:39:02 -0700, "ajaksu" wrote: >I'm using PyInstaller (http://pyinstaller.hpcf.upr.edu/) precisely to >"compile" a wxPython-based program. So I'm curious about what makes >py2exe "the best tool...", because I'm about to miss that due to my >ignorance. I didn't know about PyInstaller. I'll check it out. Thanks. From rdiaz02 at gmail.com Wed Aug 23 10:08:13 2006 From: rdiaz02 at gmail.com (Ramon Diaz-Uriarte) Date: Wed, 23 Aug 2006 16:08:13 +0200 Subject: idutils and Python In-Reply-To: References: <1156226173.596437.266680@75g2000cwc.googlegroups.com> <624934630608220305k31b91a2ao9263c19cb342b662@mail.gmail.com> Message-ID: <624934630608230708v5df41b02ie0f6b862a4bd6a1c@mail.gmail.com> Thanks for the answer. I had read about PyDev and its extenssions but, if at all possible, I'd like to keep working with Emacs (or Vim) instead of Eclipse, and I'd rather use free/open source software. Best, R. On 8/23/06, Fabio Zadrozny wrote: > > > > > > > What exactly are you trying to accomplish? If you want to index > > > function/class names, variables, etc then you should take a look at > > > "exuberant ctags" http://ctags.sourceforge.net53 --although it started > > > off as a C indexer, it has excellent Python support, it's free, and as > > > a bonus its indices are well supported from inside major editors (vim, > > > emacs, etc) so you can easily follow code flow, find function/class > > > definitions, etc. > > > > > > Sorry for not being clear enough. I want the following: > > > > a) have my editor go to the point where a function/whatever is defined > > > Pydev Extensions (http://www.fabioz.com/pydev) should do that without any > problems with F3 (it first tries a 'context-sensitive' match, trying to find > it in locals, globals, current class, etc and if not found like that, it > goes and looks for the signature in a context-insensitive way, as if it was > a simple text-search) > > > > b) see all places where a function/whatever is used. > > > This can be handed pretty well with the search that is builtin into Eclipse > (ctrl+h). > > Cheers, > > Fabio > -- Ramon Diaz-Uriarte Bioinformatics Unit Spanish National Cancer Centre (CNIO) http://ligarto.org/rdiaz From meyer at acm.org Tue Aug 8 05:35:24 2006 From: meyer at acm.org (Andre Meyer) Date: Tue, 8 Aug 2006 11:35:24 +0200 Subject: class variables In-Reply-To: <44cdd6cd$0$5868$636a55ce@news.free.fr> References: <7008329d0607271421m40d34558u8654de80a89d94b0@mail.gmail.com> <44cdd6cd$0$5868$636a55ce@news.free.fr> Message-ID: <7008329d0608080235p2c9db418q67fc455ab67ec70a@mail.gmail.com> On 7/31/06, Bruno Desthuilliers wrote: > Colin J. Williams wrote: > > Andre Meyer wrote: > >> Hi all > >> > >> I am trying to understand the magic of Python's class variables and > >> tried the following code (see below). > >> > >> Just out of curiosity, I tried to define a property that provides > >> access to a seemingly instance variable which is in fact a class > >> variable. > > [...] > > I'm afraid there are too much problems with indentation in the posted > code to give any serious answer. So, here we go again (plain formatting). The following code shows two versions of using class variables. The first one uses the __class__ attribute directly and works. The second one tries to hide the __class__ attibute with the help of a property, which does not work, because an assignment in the instance replaces the property with the assigned value. Any idea how the second version could be fixed with either a property and/or a decorator? thanks for your help Andr? class Value(object): def __init__(self, i): self.i = i def work(self): return 'done', self.i print; print "*** Case A ***"; print class ClassA(object): v = None def __init__(self, value): print '-', self.v self.__class__.v = Value(value) print '+', self.__class__.v @classmethod def value1(self): print self.v.work() return self.v def value2(self): print self.__class__.v.work() return self.__class__.v va1 = ClassA(1) va2 = ClassA(2) print va1.value1() print va1.value2() print va1.v print va1.__class__.v print va1.v.work() print "*** Case B ***"; print class ClassB(object): def __set_v(self, v): self.__class__.__v = v def __get_v(self): return self.__class__.__v def __del_v(self): del self.__class__.__v # v = property(__get_v, __set_v, __del_v, 'make class variable') v = None def __init__(self, value): self.v = property(self.__get_v, self.__set_v, self.__del_v, 'make class variable') print '-', self.v self.v = Value(value) print '+', self.v @classmethod def value1(self): print self.v.work() return self.v def value2(self): print self.v.work() return self.v vb1 = ClassB(1) vb2 = ClassB(2) print vb1.value2() print vb1.v print vb1.__class__.v print vb1.v.work() From gelists at gmail.com Wed Aug 2 15:19:02 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Wed, 2 Aug 2006 16:19:02 -0300 Subject: Windows vs. Linux References: <1154301694.445639.99580@m79g2000cwm.googlegroups.com> <44cddfb3$0$7761$7a628cd7@news.club-internet.fr> Message-ID: <1ag7fy1et1lhg$.dlg@gelists.gmail.com> On 2006-08-02 11:29:18, Sybren Stuvel wrote: > John Salerno enlightened us with: >> But of course I still agree with you that in either case it's not a >> judgment you can fairly make 30 years after the fact. > > I don't see Microsoft changing it the next 30 years either... Apple > moved from \r to \n as EOL character. AFAIK there are few programs from Apple's \r era that still work in the \n era systems, or am I mistaken with this? :) I also doubt that the line terminator had any influence in Apple's decision to change their OS. It was a mere (unintended) side effect, not an objective. If they had chosen a line terminator, they better had chosen \r\n (the internet email standard). Unix-type systems still don't use natively the line terminator that is used in internet email. Windows-type systems do. So when you want to send a text file stored on a Unix-type system as email, you have to translate the line terminations (or vice versa). Just as for MS there are good reasons not to "fix" the backslash now (what would be a good reason to change it?), there are good reasons for Unix-type system writers to stick with their traditional \n. (From a different message) > I'm talking about the fact that they have chosen a common escape > character as path separator. What's so specifically bad about a "common escape character"? Any character that has a special meaning in something can be inconvenient when it has to be used normally. A backslash in a C string, a dot in a regex, you probably can find examples for any non-alphanumeric ASCII character. The only "problem" with the backslash is that you need to escape it in C strings; I never had any trouble with that. BTW, are you really sure that the backslash was a "common escape character" in the 70ies? How common was it back then? Even today, it seems to be mostly a C idiom. (In that respect, Python is leaning on C, even ever so slightly.) Get over it... there are any number of definitions out there, some better chosen than others, and most had a good set of reasons at the time they were chosen. Mostly by chance, some fit better into the picture some decades later, and some fit less nicely. Without really getting down to it, there's no way to tell whether any of the standards was well-chosen. Even the ones that look now as if they were... could be mere luck. You're of course entitled to your opinion. I never wanted to doubt that. But an unfounded opinion usually tells more about the subject than the object... :) Gerhard From caolan at ldmf.net Thu Aug 31 12:39:25 2006 From: caolan at ldmf.net (Caolan) Date: Thu, 31 Aug 2006 09:39:25 -0700 Subject: How to include and use a .NET DLL and namespace. Message-ID: Hello, I am in need of importing in a .NET namespace from a built DLL. How do I get Python to pickup and recognise the namespace and classes in the DLL? Thanks, Caolan O'Domhnaill -------------- next part -------------- An HTML attachment was scrubbed... URL: From rwNOSPAM at NOSPAMsmsnet.pl Fri Aug 25 14:47:15 2006 From: rwNOSPAM at NOSPAMsmsnet.pl (Rob Wolfe) Date: Fri, 25 Aug 2006 20:47:15 +0200 Subject: django's view.py as class not just methods References: Message-ID: <873bbk64b0.fsf@smsnet.pl> Skink writes: > Hi, > > I'm relatively new to django and maybe my question is stupid, but... > > Is it possible to map in urls.py some url not to function in views.py > (which has first argument with HttpRequest) but to some class method? > In that case each instance of such class would be created when session > starts and for subsequent calls would be served as self ? > > I know, I know that HttpRequest has session member and I can use it. > But maybe it would be good idea to have such url ==> class.method > mapping. I didn't try it with django but maybe closure is the solution. Try this: #!/usr/bin/env python class MyView(object): def __init__(self): self.visited = [] def index(self, *args): self.visited.append("index") print "%s.index: %r" % (self.__class__.__name__, args) return "response from index" def detail(self, *args): self.visited.append("detail") print "%s.detail: %r" % (self.__class__.__name__, args) return "response from detail" def error(self, *args): self.visited.append("error") print "%s.error: %r" % (self.__class__.__name__, args) return "response from error" def make_view(obj, methodname): def view(*args): try: return getattr(obj, methodname)(*args) except AttributeError: return obj.error(*args) return view view_obj = MyView() index = make_view(view_obj, "index") detail = make_view(view_obj, "detail") download = make_view(view_obj, "download") print index("request to index") print detail("request to detail", 25) print download("request to download", "abc", 99) print print "\n".join(view_obj.visited) index, detail and download functions can be mapped in urls.py now. -- HTH, Rob From michele.petrazzo at TOGLIunipex.it Mon Aug 21 04:43:29 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Mon, 21 Aug 2006 08:43:29 GMT Subject: Python for EXIF-info-additions ? In-Reply-To: <4kmp5jFctg9cU1@individual.net> References: <4kmp5jFctg9cU1@individual.net> Message-ID: Bror Johansson wrote: > Is there somewhere some Python-module that can be used for adding > EXIF-info to JPEG files? > > (Modules for extraction of EXIF-data are easily found, but lacks - as > I see it - capacity to add new tags.) > Hi, this is a feature that I want to add to FreeImagePy. It's not so difficult, but now I haven't time to do it. If you want to spend some hours for make enjoying yourself and all the python community, email me! :) > /BJ > > Bye, Michele From cemerick at snowtide.com Wed Aug 23 11:12:22 2006 From: cemerick at snowtide.com (Chas Emerick) Date: Wed, 23 Aug 2006 11:12:22 -0400 Subject: Python + Java Integration Message-ID: This may seem like it's coming out of left field for a minute, but bear with me. There is no doubt that Ruby's success is a concern for anyone who sees it as diminishing Python's status. One of the reasons for Ruby's success is certainly the notion (originally advocated by Bruce Tate, if I'm not mistaken) that it is the "next Java" -- the language and environment that mainstream Java developers are, or will, look to as a natural next step. One thing that would help Python in this "debate" (or, perhaps simply put it in the running, at least as a "next Java" candidate) would be if Python had an easier migration path for Java developers that currently rely upon various third-party libraries. The wealth of third-party libraries available for Java has always been one of its great strengths. Ergo, if Python had an easy-to-use, recommended way to use those libraries within the Python environment, that would be a significant advantage to present to Java developers and those who would choose Ruby over Java. Platform compatibility is always a huge motivator for those looking to migrate or upgrade. In that vein, I would point to JPype (http://jpype.sourceforge.net). JPype is a module that gives "python programs full access to java class libraries". My suggestion would be to either: (a) include JPype in the standard library, or barring that, (b) make a very strong push to support JPype (a) might be difficult or cumbersome technically, as JPype does need to build against Java headers, which may or may not be possible given the way that Python is distributed, etc. However, (b) is very feasible. I can't really say what "supporting JPype" means exactly -- maybe GvR and/or other heavyweights in the Python community make public statements regarding its existence and functionality, maybe JPype gets a strong mention or placement on python.org....all those details are obviously not up to me, and I don't know the workings of the "official" Python organizations enough to make serious suggestions. Regardless of the form of support, I think raising people's awareness of JPype and what it adds to the Python environment would be a Good Thing (tm). For our part, we've used JPype to make PDFTextStream (our previously Java-only PDF text extraction library) available and supported for Python. You can read some about it here: http://snowtide.com/PDFTextStream.Python And I've blogged about how PDFTextStream.Python came about, and how we worked with Steve M?nard, the maintainer of JPype, to make it all happen (watch out for this URL wrapping): http://blog.snowtide.com/2006/08/21/working-together-pythonjava-open- sourcecommercial Cheers, Chas Emerick Founder, Snowtide Informatics Systems Enterprise-class PDF content extraction cemerick at snowtide.com http://snowtide.com | +1 413.519.6365 From bill.pursell at gmail.com Mon Aug 21 15:25:49 2006 From: bill.pursell at gmail.com (Bill Pursell) Date: 21 Aug 2006 12:25:49 -0700 Subject: List Splitting In-Reply-To: <1156187837.378252.36420@m73g2000cwd.googlegroups.com> References: <1156187837.378252.36420@m73g2000cwd.googlegroups.com> Message-ID: <1156188349.773844.118170@b28g2000cwb.googlegroups.com> Steven wrote: > Hello everyone, > > I'm trying to work through a bit of a logic issue I'm having with a > script I'm writing. Essentially, I have a list that's returned to > me from another command that I need to regroup based on some aribitrary > length. > > For the purposes of this question, the list will be: > > t = [ "a", "b", "c", "n", "a", "a", "t", "t", "t" ] > > Now, I know that every 3rd element of the list belongs together: > > Group 1 = 0, 3, 6 > Group 2 = 1, 4, 7 > Group 3 = 2, 5, 8 > > I'm trying to sort this list out so that I get a list of lists that > contain the correct elements: > > Goal = [ [ "a", "n", "t"], [ "b", "a", "t"], > ["c", "a", "t" ] ] > > The actual data isn't as simple as this, but if I can get the logic > sorted out, I can handle the other part. > > Anyone have any good ideas on how to do this? how about: >>> t = [ "a", "b", "c", "n", "a", "a", "t", "t", "t" ] >>> [t[i::3] for i in range(0,len(t)/3)] [['a', 'n', 't'], ['b', 'a', 't'], ['c', 'a', 't']] -- Bill Pursell From sjmachin at lexicon.net Sun Aug 13 20:09:26 2006 From: sjmachin at lexicon.net (John Machin) Date: 13 Aug 2006 17:09:26 -0700 Subject: open() and Arabic language References: <1155492625.573013.78440@74g2000cwt.googlegroups.com> Message-ID: <1155514166.796313.206900@75g2000cwc.googlegroups.com> MaaSTaaR wrote: > Hello ... > > firstly , sorry for my bad English . > > i have problem with open() function when i use it with file which name > in Arabic , the open() will not find the file , and i am sure the file > is exist . > > > so how i can solve this problem ? Provide more information -- a major factor is which operating system [my crystal ball says that you are using Linux but it could be wrong]. Also an actual test case with a short file name. Here's an example with a part-Chinese filename on a Windows machine, which just uses the information in the Unicode HOWTO that you were pointed at by another poster: C:\junk\unicode_name>dir [snip] 30/05/2006 09:25 AM 17 ??.txt [snip] # only 1 file in the directory; dir command mangles the displayed name C:\junk\unicode_name>python Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. |>>> import os |>>> os.listdir('.') ['??.txt'] |>>> os.listdir(u'.') [u'\u5f20\u654f.txt'] # filename is kept in Unicode, so we can open it that way |>>> f = open(u'\u5f20\u654f.txt') |>>> f.read() 'yadda yadda yadda' # success |>>> import sys |>>> sys.getfilesystemencoding() 'mbcs' ... I'm guessing that you will find that you have to encode the filename in utf-8 then feed it to the open() function. If you still have a problem, come back with exact (copy/paste) results of both os.listdir() [the '.' and the u'.'], the sys.getfilesystemencoding(), and your failed open() attempt. Hope this helps, John From gregpinero at gmail.com Thu Aug 31 11:49:27 2006 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Thu, 31 Aug 2006 11:49:27 -0400 Subject: Basic import Questions (with bonus profiling question) Message-ID: <312cfe2b0608310849m6967e2cx259046143728b29e@mail.gmail.com> Hey Folks, Some import questions that a search didn't turn up for me. 1. Will "from somemodule import onething" take as long to start up as import somemodule? 2. Is there anyway I can get at onething more quickly? 3. If I put an import statement hidden away in some function, will Python only do the import when that function is called? If I say, never use that function would that import statement affect performance at all? Ultimately I have IIS running python as a CGI script and it seems to just be taking many seconds to load a small page. I'm guessing the issue is starting up the interpreter and loading all the modules. BTW I know it would be better to profile the code but how do you profile a CGI script? I can't just pass it CGI parameters can I? And does profiling take into account the time of loading modules? Thanks, -Greg Pinero From jzgoda at o2.usun.pl Thu Aug 17 16:40:16 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Thu, 17 Aug 2006 22:40:16 +0200 Subject: sqlite3 or mysqldb? In-Reply-To: References: Message-ID: John Salerno napisa?(a): > I did a little experimentation with MySQL, and yesterday I was reading > up on SQLite. Since they both use the SQL language, does this mean that > the queries you write will be the same for both modules? I'm sure there > are slight differences for how you connect to DBs, but since they both > use the same DB API 2.0, and both use SQL, I was wondering how easily > you could 'switch' them out if you needed to go from one to the other. > > (I know there are slight differences between the two in terms of SQL > commands understood, but I'm mainly referring to the most important > things, like simply accessing and changing DB information.) > > I was using mysqldb just because MySQL seems to be a pretty big > standard, but now that sqlite3 is coming with Python 2.5, I might > switch, since it seems to be easier to use. > > (And again, I'm such an amateur programmer that really I'm using these > things just to learn them. It's not like I control my company's entire > employee records or anything.) :) To learn SQL SQLite should be enough - it has all the basics, just as MySQL, while it doesn't require any server/client configuration (encoding configuration in MySQL is real PITA). But if you want any "serious SQL", go with any freely available *real SQL server*, like Firebird or PostgreSQL. I'd consider Firebird, as it's pretty lightweight. In theory, switching from one db backend to another should go without problem (at least at ANSI SQL level), but usually requires much work, so it's rather rare practice. While basics, like DML or DDL syntax, remain similar, often particular backends require specific tweaks and optimizations to get desired level of efficiency. You know, this part of application is a bottleneck. -- Jarek Zgoda http://jpa.berlios.de/ From robert.kern at gmail.com Tue Aug 29 21:19:11 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 29 Aug 2006 20:19:11 -0500 Subject: M$ windows python libs installed in arbitrary directories forcustomized python distributions In-Reply-To: References: <44f31d35$0$17268$9b622d9e@news.freenet.de> Message-ID: alf wrote: > Fredrik Lundh wrote: >> http://www.catb.org/~esr/faqs/smart-questions.html#writewell >> >> > > and means? It's his signature. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From *firstname*nlsnews at georgea*lastname*.com Sat Aug 5 14:28:13 2006 From: *firstname*nlsnews at georgea*lastname*.com (Tony Nelson) Date: Sat, 05 Aug 2006 18:28:13 GMT Subject: E' possibile integrare ironpython con visual studio 2005? References: <44d25f48$0$47956$4fafbaef@reader3.news.tin.it> <1hjikzd.1ym4sp75xbujvN%aleax@mac.com> Message-ID: <*firstname*nlsnews-A87A0A.14281405082006@news.verizon.net> In article <1hjikzd.1ym4sp75xbujvN%aleax at mac.com>, aleax at mac.com (Alex Martelli) wrote: > LaGuna wrote: > > > Se si come? > > > > Ciao by Enzo > > Questo newsgroup preferisce l'inglese -- per favore, chiedi su > it.comp.lang.python invece che qui. > > This newsgroup prefers English -- please ask on it.comp.lang.python > rather than here. Still, the question is obvious enough. Microsoft's "Visual Studio 2005 SDK" now contains IronPython integration. I haven't used it, as I have only the free Visual C# 2005 Express Edition. ________________________________________________________________________ TonyN.:' *firstname*nlsnews at georgea*lastname*.com ' From bdesth.quelquechose at free.quelquepart.fr Wed Aug 2 18:44:50 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 03 Aug 2006 00:44:50 +0200 Subject: Is there an obvious way to do this in python? In-Reply-To: References: Message-ID: <44d128e5$0$13484$636a55ce@news.free.fr> H J van Rooyen a ?crit : > Hi, > > I want to write a small system that is transaction based. > > I want to split the GUI front end data entry away from the file handling and > record keeping. > > Now it seems almost trivially easy using the sockets module to communicate > between machines on the same LAN, so that I want to do the record keeping on one > machine. > > I want to keep the "server" machine as simple as possible - just doing record > keeping on a stimulus response basis - I would prefer it to do one thing at a > time to completion because this style of operation, though limited in > performance, keeps a lot of hassles out of life - a transaction has either > completed, or it has not - recovery scenarios are relatively easy... IOW, you want a SQL DBMS. May I recommand PostgreSQL ? > Up to this point, I don't have a problem - my toy system can create a dummy > transaction, and I can echo it from the "server" machine, with more than one > "user" machine running - so I think it is feasible to have several tens of "data > entry terminal" systems running, served by one not very strong machine. > > Now what I would really like to do is to differentiate between the 'User" > machines, so that some can do a full range of transactions, and others a limited > range. Any decent SQL DBMS is able to handle this. It's kind of builtin... > And I would like to make this flexible, so that it becomes easy to introduce new > transactions, without having to run around updating the code in all the user > machines, with the concomitant version number hassles. Then you want a web front end. > And I would like to do the whole thing in python You'll at least need bits of SQL (but SQLAlchemy may hide away most of it) and HTML (but there are some python packages that knows how to build HTML from declarative Python code). > - so my question is this - is > it possible to do the equivalent of dynamic linking? - i.e. if I keep a list of > what a user is allowed to do In SQL : GRANT/REVOKE > - can I somehow send him just the bits he needs to > do the job, without having to change the static code on his machine? HTTP/HTML. > - it seems > to me that the eval() thingy could possibly do this for me, Err... I thought you wanted a reasonnably secure system, but I may have misunderstood. > by sending it data > that makes it do import statements followed by calls to whatever... - will this > work, or is there a better way? > > Or has all this been done already? Yes, it's called a web frontend for a SQL DBMS. There's no shortage of Python frameworks to do this kind of things. > - and no I don't want a web server If you don't want Apache, there are Python-based application servers. CherryPy comes to mind. > and php Why PHP ? > and browsers and Java Why Java ? > and html or xml... - I want to write something that works > simply and reliably We do write SQL-based web apps all day long, and I can tell you they are certainly more simple and reliable than whatever eval()-based home-made solution we could imagine !-) From slawomir.nowaczyk.847 at student.lu.se Fri Aug 11 06:48:31 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Fri, 11 Aug 2006 12:48:31 +0200 Subject: converting a nested try/except statement into try/except/else In-Reply-To: <1155253367.600486.176300@75g2000cwc.googlegroups.com> References: <1155253367.600486.176300@75g2000cwc.googlegroups.com> Message-ID: <20060811102117.EFC0.SLAWOMIR.NOWACZYK.847@student.lu.se> On Thu, 10 Aug 2006 16:42:47 -0700 Simon Forman wrote: #> 6.) There's a single return statement. #> #> I forget now where I picked this up, but it's served me well for #> many years: Procedures, functions, methods, etc... should have one #> exit point. Something about having fewer "code paths" to test or #> something. Number of return statements has absolutely *nothing* to do with number of code paths to test. -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) Only drug dealers and software companies call their customers 'users.' From g.brandl-nospam at gmx.net Mon Aug 21 05:57:19 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Mon, 21 Aug 2006 11:57:19 +0200 Subject: sum and strings In-Reply-To: References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <1155922208.930580.135080@m79g2000cwm.googlegroups.com> <1155952305.848495.7060@i3g2000cwc.googlegroups.com> <7x4pw9h3yy.fsf@ruckus.brouhaha.com> Message-ID: Steven D'Aprano wrote: > On Fri, 18 Aug 2006 19:08:37 -0700, Paul Rubin wrote: > >> If the args are strings, the above is a quadratic time algorithm and >> it's better to throw an error than create such a trap for an unwary user. > > That's a nonsense argument. There is no shortage of slow algorithms, and > some of them are built into Python. When did O(n**2) become an error > condition? And overhead matters: if I'm only doing a few concatenations, > it is significantly faster to add the strings using + than to use join() > (at least in Python 2.3 -- YMMV): > >>>> s = timeit.Timer("''.join(L)", "L=['a'*50, 'b'*50, 'c'*50]") >>>> s.timeit() > 1.3470098972320557 >>>> t = timeit.Timer("a+b+c", "a,b,c = 'a'*50, 'b'*50, 'c'*50") >>>> t.timeit() > 1.0698421001434326 > > There's a word for optimizations that actually result in code running 25% > slower. > > I applaud that Python's language developers care about efficiency. I > applaud that the documentation warns people about traps and potential > areas of inefficiency. But I think it is a shame that sum() does a > special type-check to avoid something which is only sometimes slow. It > doesn't protect against O(n**2) performance; it merely protects against > just one of an infinite number of possible "traps for the unwary". > > I would have thought it would be better for sum() to raise a warning, not > an exception. If we take seriously the argument that sum implies > addition, and that string concatenation isn't really addition, then sum() > should also refuse to operate on lists and tuples and any other > non-numeric class. Either would be better than sum() "protecting" the user > from himself, except when it doesn't. Well, present that on python-dev. Georg From g.brandl-nospam at gmx.net Sat Aug 19 01:39:57 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Sat, 19 Aug 2006 07:39:57 +0200 Subject: sum and strings In-Reply-To: <7xd5axh4gn.fsf@ruckus.brouhaha.com> References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <7xr6zel2r2.fsf@ruckus.brouhaha.com> <7xd5axh4gn.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Georg Brandl writes: >> Why would you try to sum up strings? Besides, the ''.join idiom is quite >> common in Python. > > Just because it's common doesn't mean it's obvious. In my opinion > it's as ugly as sin, and the fact that it's an idiom shows a > shortcoming in Python. The obvious reason for summing strings is that > it's a long-established feature of Python that a+b concatenates two > strings, so summing a,b,c,d,e should result in a+b+c+d+e. Which is exactly how I would concatenate five strings. For concatenating longer sequences of strings, however, if it needs to be done fast, performance-wise, this approach is not sensible. Georg From fuzzyman at gmail.com Mon Aug 7 17:41:15 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 7 Aug 2006 14:41:15 -0700 Subject: Python Projects Continuous Integration In-Reply-To: <1154087739.722910.110310@b28g2000cwb.googlegroups.com> References: <1154087739.722910.110310@b28g2000cwb.googlegroups.com> Message-ID: <1154986875.566020.247080@b28g2000cwb.googlegroups.com> Dave Potts wrote: > Hi, > > I'm just starting a development project in Python having spent time in > the Java world. I was wondering what tool advice you could give me > about setting up a continuous integration environment for the python > code: get the latest source, run all the tests, package up, produce the > docs, tag the code repository. I'm used to things like Maven and > CruiseControl in the Java world. > Hello Dave, At Resolver Systems we use Cruise Control .NET along with IronPython and Subversion to provide Source Code Control and continuous integration. The combination is *great*. I've never had to configure it (I just poke it occassionally), but it *looks* like it should be usable with non .NET projects: we have it running all sorts of batch files and Python scripts as part of the built and test process. All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml > Cheers, > > Dave. From python at hope.cz Thu Aug 10 07:38:26 2006 From: python at hope.cz (Lad) Date: 10 Aug 2006 04:38:26 -0700 Subject: IP address In-Reply-To: References: <1155194251.196501.277470@m79g2000cwm.googlegroups.com> <1155206207.759038.38720@m79g2000cwm.googlegroups.com> Message-ID: <1155209906.742016.123250@p79g2000cwp.googlegroups.com> Sybren Stuvel wrote: > Lad enlightened us with: > > I have a website written in Python and I would like to login every > > visitor's IP address. > > Ehm... that's probably "log" not "login". > > > In other words, if a visitor come to my Python application, this > > application will record his IP. Is it possible? > > Sure it is. At least, using most Python web-interfaces. I can't give > you more info, since you don't describe anything about the website. Is > it mod_python? Django? CGI? Something else? Try giving us some > information we can work with! It is Django with mod_python Regards, L From python.list at tim.thechases.com Sun Aug 6 09:36:33 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 06 Aug 2006 08:36:33 -0500 Subject: Suppressing banner on interactive startup? [SOLVED] In-Reply-To: <2shbq3-i09.ln1@arch.brainshell.org> References: <2shbq3-i09.ln1@arch.brainshell.org> Message-ID: <44D5F061.9060905@tim.thechases.com> >> 1) is there a way to suppress the banner when starting Python >> interactively? [...] >> >> 2) is there a way to change the two prompts from ">>>" and "..." >> to other options? [...] > > I noticed that the first part of your query was never answered. > To combine both of these, try the following (modified to taste): > > python -ic 'import sys; sys.ps1="$ "; sys.ps2="> "' Yes, you are correct...while I got an answer to the second half, I never heard anything about the first half, so I just assumed there was no way as simple as this. Your answer worked like a charm, and makes my Text-To-Speech tool all the better. Thanks! -tkc From jeremy+complangpython at jeremysanders.net Tue Aug 29 09:02:27 2006 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Tue, 29 Aug 2006 14:02:27 +0100 Subject: ntp in python References: <1156846722.129525.254120@i42g2000cwa.googlegroups.com> Message-ID: Janto Dreijer wrote: > I want to measure the packet delivery delays over various network > links. For this I need to synchronise the times of the sender and > receiver, either against NTP or eachother. Couldn't you just use NTP itself to get the delivery delay? You can read the delay out from the ntpdc console using dmpeers, or lopeers in ntpq. You could have two peers either side of the link and measure the delay from NTP. You may also be able to query remote ntp servers to get their delays to their peers. Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From abhishek at ocf.berkeley.edu Thu Aug 31 07:15:20 2006 From: abhishek at ocf.berkeley.edu (abhishek at ocf.berkeley.edu) Date: 31 Aug 2006 04:15:20 -0700 Subject: Using eval with substitutions Message-ID: <1157022920.299174.22860@m73g2000cwd.googlegroups.com> >>> a,b=3,4 >>> x="a+b" >>> eval(x) 7 >>> y="x+a" Now I want to evaluate y by substituting for the evaluated value of x. eval(y) will try to add "a+b" to 3 and return an error. I could do this, >>> eval(y.replace("x",str(eval(x)))) 10 but this becomes unwieldy if I have >>> w="y*b" and so on, because the replacements have to be done in exactly the right order. Is there a better way? Thanks, Abhishek From chris.felton at gmail.com Thu Aug 31 19:42:04 2006 From: chris.felton at gmail.com (chris.felton at gmail.com) Date: 31 Aug 2006 16:42:04 -0700 Subject: Boost Python Issue In-Reply-To: <1157063033.800940.181130@e3g2000cwe.googlegroups.com> References: <1157063033.800940.181130@e3g2000cwe.googlegroups.com> Message-ID: <1157067724.506021.264070@i3g2000cwc.googlegroups.com> I believe this is more of a tools/compiler issue than a coding issue. If you are using the pre-built BOOST.Python library you get compile mismatches. I am not a Windows Visual Studio programmer (barely a programmer), I am probably not using the correct terminology. There are some settings for the threading type, debugging modes, etc. If these don't match between you VC compilation and the BOOST library complitation you can get those errors. I had similar problems and it took me forever to figure it out. Let me know if this helps, look at the command line from visual studio and compare it to your command line from the Bjam build. JDJMSon wrote: > I was wondering if someone here could help me with a problem I'm having > building Python extensions with the Boost.Python library. > Basically, if I have a wrapper class with something like this: > > string TestFunc() > { > return "Hello World"; > } > > BOOST_PYTHON_MODULE(TestClass) > { > def("TestFunc",TestFunc); > } > > > It compiles and I can use it without a problem. However, when I try to > wrap a class with code like this: > > class TestClass > { > public: > TestClass() {}; > ~TestClass() {}; > string TestFunction(){return "Hello World";}; > }; > > BOOST_PYTHON_MODULE(TestClass) > { > class_("TestClass") > .def("TestFunction",&TestClass.TestFunction) > ; > } > > > I get the following error: > vc-C++ > bin\PythonTest\TestClass.pyd\vc-8_0\debug\threading-multi\TestClass.obj > TestClass.cpp > TestClass.cpp(27) : error C2976: 'boost::python::class_' : too few > template arguments > > c:\Development\Boost\boost_1_33_1\boost/python/def_visitor.hpp(14) : > see declaration of 'boost::python::class_' > TestClass.cpp(27) : error C2440: '' : cannot > convert from 'const char [10]' to 'boost::python::class_' > Source or target has incomplete type > > I'm using Visual Studio 2005 Express Edition (I get the same error with > 2003 Professional), and am using bJam to build the extension. > > Does anyone have any idea what's causing this? From thomas at localhost.localdomain Sat Aug 26 07:54:39 2006 From: thomas at localhost.localdomain (Thomas Dybdahl Ahle) Date: Sat, 26 Aug 2006 13:54:39 +0200 Subject: Python daemon process Message-ID: Hi, I'm writing a program, using popen4(gnuchess), The problem is, that gnuchess keeps running after program exit. I know about the atexit module, but in java, you could make a process a daemon process, and it would only run as long as the real processes ran. I think this is a better way to stop gnuchess, as you are 100% sure, that it'll stop. Can you do this with popen? -- Thomas From johnjsal at NOSPAMgmail.com Sat Aug 19 17:57:42 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 19 Aug 2006 17:57:42 -0400 Subject: text editor suggestion? In-Reply-To: <1155995807.052337.272990@i42g2000cwa.googlegroups.com> References: <44e66724$0$2363$c3e8da3@news.astraweb.com> <1155995807.052337.272990@i42g2000cwa.googlegroups.com> Message-ID: <44e78a2b$0$12550$c3e8da3@news.astraweb.com> milosz wrote: > Did you try gedit? > It has an options, which you need, I think. > Regards. > Yes, I tried it and it's alright, but it doesn't support smart indentation or much customizing of syntax highlighting (i.e. you can change the color of functions, but you can't define what a 'function' is, or at least I have no idea where this can be done). It seems like what most editors do is highlight user-defined functions as they are defined, so: def func() 'func' would be highlighted here, but not when you call it elsewhere in your script. Furthermore, there isn't support for built-in Python functions and methods. The thing I liked about UltraEdit is that you can define your own groups of words and put whatever words you want in there, so my file had a group called '__builtins__' and it listed all the Python built-in methods, and those would be highlighted. Most editors I see don't seem to allow this...they just figure out what a function or method is on their own somehow. From quncao at gmail.com Tue Aug 8 19:23:23 2006 From: quncao at gmail.com (Qun Cao) Date: 8 Aug 2006 16:23:23 -0700 Subject: (Boost.Python) How to load header files? Message-ID: <1155079403.304584.315530@h48g2000cwc.googlegroups.com> Hi Everyone, I just started to use boost.python and having problem trying to get my first program working. I have a C++ class foo.cpp, defined in foo.h, I wrote a wrapper class for it to generate a python module. #include "Foo.h" #include #include #include using namespace boost::python; BOOST_PYTHON_MODULE(mymodule) { class_("Foo") .def ("init", &Foo:init) } The problem is that when I bjam it, the compiler cannot find the header file , although I had the location of Foo.h added into $PATH. I can make it work by copying Foo.h into the working directory, but Foo.h is also depended on other libraries, so I need a generic way to recognize the header files. Thanks for any hit, Qun From sjmachin at lexicon.net Tue Aug 1 18:49:19 2006 From: sjmachin at lexicon.net (John Machin) Date: 1 Aug 2006 15:49:19 -0700 Subject: BCD List to HEX List References: <5S8zg.1553$W93.658@dukeread05> <1154296114.094452.158000@p79g2000cwp.googlegroups.com> <1154298390.280625.206560@75g2000cwc.googlegroups.com> <1154299830.987261.9800@b28g2000cwb.googlegroups.com> <1154301233.360818.93450@s13g2000cwa.googlegroups.com> <0abzg.1576$W93.173@dukeread05> <1154361998.861851.157210@h48g2000cwc.googlegroups.com> <1154375956.397032.166310@p79g2000cwp.googlegroups.com> <1154411021.642620.255750@s13g2000cwa.googlegroups.com> <1154412245.996874.199260@h48g2000cwc.googlegroups.com> <1154446262.681764.73100@75g2000cwc.googlegroups.com> Message-ID: <1154472559.132312.12550@75g2000cwc.googlegroups.com> bryanjugglercryptographer at yahoo.com wrote: >My version assumes three subroutines: extracting > nibbles, shifting, and adding, Those are pretty simple, so I asked > if he needed them rather than presenting them. > Assuming we have > them, the algorithm is three lines long. Perhaps you could enlighten us by publishing (a) the spec for each of the get_nibble(s), shift, and add subroutines (b) the three-line algorithm (c) what the algorithm is intended to achieve ... > > He took a while to state the problem, but was clear from the start > that he had lists of digits rather than an integer datatype. Yes, input was a list [prototyping a byte array] of decimal digits. The OUTPUT was also a list of something. A few messages later, it became clear that the output desired was a list of hexadecimal digits. Until he revealed that the input was up to 24 decimal digits, I was pursuing the notion that a solution involving converting decimal to binary (in a 32-bit long) then to hexadecimal was the way to go. What is apparently needed is an algorithm for converting a "large" number from a representation of one base-10 digit per storage unit to one of a base-16 digit per storage unit, when the size of the number exceeds the size (8, 16, 32, etc bits) of the "registers" available. Is that what you have? Cheers, John From python.list at tim.thechases.com Fri Aug 18 15:00:16 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 18 Aug 2006 14:00:16 -0500 Subject: a bug in list.remove? In-Reply-To: <44E5FA22.7050304@al.com.au> References: <44E5FA22.7050304@al.com.au> Message-ID: <44E60E40.3030400@tim.thechases.com> > I have 2 lists. What Im doing is check the first list and remove all > occurances of the elements in the second list from the first list, like so: > >>> ps = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] > >>> qs = [6,7,8,9,10,11,12,1,2] > >>> for p in ps: > if p in qs: > ps.remove(p) > > The problem Im having is that when I do > >>> print ps > it gives me > [2, 3, 4, 5, 7, 9, 11, 13, 14, 15] > which is incorrect since 2,7,9,11 shouldnt be in that list. Is this a > bug in .remove? or is my algorithm somewhat flawed? I'd go with the "somewhat flawed" answer. I'd just use ps = [x for x in ps if x not in qs] which will remove *all* instances of x from ps if it exists in qs. There's a subtle difference from the remove() method, which will only remove the first instance: >>> help([].remove) Help on built-in function remove: remove(...) L.remove(value) -- remove first occurrence of value If qs is large, you'll get improved performance by converting it to a set first: >>> s = set(qs) >>> ps = [x for x in ps if x not in s] As for your algorithm, you're modifying the list over which you're iterating--at best, often considered bad form...at worst, I've had Python throw exceptions at me for attempting it. -tkc From onurb at xiludom.gro Tue Aug 29 11:27:58 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 29 Aug 2006 17:27:58 +0200 Subject: refering to base classes In-Reply-To: <1156862012.068397.284040@m73g2000cwd.googlegroups.com> References: <1156862012.068397.284040@m73g2000cwd.googlegroups.com> Message-ID: <44f45cff$0$22981$626a54ce@news.free.fr> glenn wrote: > hi - Im quite new to python, wondering if anyone can help me understand > something about inheritance here. In this trivial example, how could I > modify the voice method of 'dog' to call the base class 'creatures' > voice method from with in it? > > class creature: > def __init__(self): > self.noise="" > def voice(self): > return "voice:" + self.noise > > class dog(creature): > def __init__(self): > self.noise="bark" > > def voice(self): > print "brace your self:" It might be better to use newstyle classes if you can. Also, the convention is to use CamelCase for classes names (unless you have a strong reason to do otherwise). Here you could use a class attribute to provide a default: class Creature(object): noise = "" def voice(self): return "voice:" + self.noise class Dog(Creature): noise="bark" def voice(self): print "brace your self:" return Creature.voice(self) # can also use this instead, cf the Fine Manual return super(Dog, self).voice() My 2 cents -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From skip at pobox.com Thu Aug 24 16:12:49 2006 From: skip at pobox.com (skip at pobox.com) Date: Thu, 24 Aug 2006 15:12:49 -0500 Subject: Is this a good idea or a waste of time? In-Reply-To: <1156449402.022781.292840@p79g2000cwp.googlegroups.com> References: <1156449402.022781.292840@p79g2000cwp.googlegroups.com> Message-ID: <17646.2113.835619.191734@montanaro.dyndns.org> Arcadio> Would it be considered good form to begin every method or Arcadio> function with a bunch of asserts checking to see if the Arcadio> parameters are of the correct type (in addition to seeing if Arcadio> they meet other kinds of precondition constraints)? If it works for you. It's not generally considered Pythonic though. You should probably read up on "duck typing". Some food for thought: Do you normally care that the object passed to foo() is a real honest-to-goodness file object, or do you just care that it has a write() method? You will learn soon enough if it doesn't, and not that much later than if you have an assert at the beginning of your function. Of course, sometimes you do truly care about the type of an object. Then you test. When you care. Arcadio> This is something I miss from working with more stricter Arcadio> languages like C++, where the compiler will tell you if a Arcadio> parameter is the wrong type. It's a mistake to think that Python's typing is somehow less strict than C++'s. It's not like Perl where 1 + "2" is valid. It's simply that its type checks are performed at run-time, not at compile-time. If you're desparate to have some assistance with your code before you run it, check out pylint and pychecker. Skip From grahn+nntp at snipabacken.dyndns.org Fri Aug 4 12:42:30 2006 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 4 Aug 2006 16:42:30 GMT Subject: web searching scripts References: <1154706005.079353.172810@i42g2000cwa.googlegroups.com> Message-ID: On Fri, 04 Aug 2006 18:11:18 +0200, Avell Diroll wrote: > julien.lord at gmail.com wrote: >> Does anyone know of a freely available script that can take a given URL >> and follow every link within it? >> >> Ideally, I would like to start with this to build a quick application >> to grab all the content off a website to publish it to a CD. ... > If you just want to download websites (i.e. not necessarily writing a > program yourself to do that), you may try Httrack, it might suite your > needs. The well-known Gnu wget is what I always use. (IMHO, this is a situation where it's a /good/ idea to glue together existing software, rather than joining many bits of code to a mirror-from-http-to-cdr application.) /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From zxo102 at gmail.com Mon Aug 14 11:10:13 2006 From: zxo102 at gmail.com (zxo102) Date: 14 Aug 2006 08:10:13 -0700 Subject: why the method get() of python Queue is hang on there? Message-ID: <1155568212.888733.79920@b28g2000cwb.googlegroups.com> Hi, I am using Queue from python2.4. Here is what happen to me: import Queue b = Queue.Queue(0) b.put(9999) b.get() # this is ok, it pops out 9999 b.get() # this one does not return anything and is hang on there Anybody knows what is going on with the second b.get()? ouyang From effigies at gmail.com Mon Aug 7 09:52:01 2006 From: effigies at gmail.com (Chris Johnson) Date: 7 Aug 2006 06:52:01 -0700 Subject: PyGTK TreeView segmentation fault on expand_all() Message-ID: <1154958721.846406.281590@h48g2000cwc.googlegroups.com> Good morning. I have recently begun a project using PyGTK, and part of my planned interface has a gtk.TreeView showing a portion of the filesystem. Now, rather than load the entire FS structure into the tree right from the beginning, I made a lazy tree by adding blank children to rows representing directories, and connected a call to fill in the data when a row with blank children was expanded. Now, this works all fine and well, in general. I can browse my entire filesystem this way. But I noticed that hitting '*' (which I believe is a call to expand_all(), though the documentation does not say this explicitly) on a row representing any empty directory causes a segmentation fault. This problem can be alleviated by not removing the blank child after attempting to add directory contents, but I would like to avoid this approach. My suspicion is that expand_all() assumes that there are children present, and when I remove the blank row (after attempting to add any subdirectories and files), it does not check to make sure there are still children. So I suppose I have a couple questions. First, can anybody confirm my suspicions? Secondly, is this a PyGTK bug, or am I doing something that simply should never be done? Finally, do you see any way to fix this problem? Code follows ---------- def onExpand(self, view, iter, path): """Add directory contents on first expansion of its entry""" sorted = view.get_model() # TreeModelSort iter = sorted.convert_iter_to_child_iter(None,iter) store = sorted.get_model() # TreeStore child = store.iter_children(iter) cpath = store.get(iter,1)[0][1:] # Hidden column with fs path info if store.get_value(child, 0) is None: sorted.addDir(cpath,iter) store.remove(child) --------- If any other code is necessary, I can provide my entire program. However, I think I've isolated the problem to that last line (execution continues beyond it, so it's not exactly the line itself), and want to hear any recommendations for how to still remove that blank child without causing expand_all() to fall on its face. From kylotan at gmail.com Wed Aug 2 05:47:42 2006 From: kylotan at gmail.com (Ben Sizer) Date: 2 Aug 2006 02:47:42 -0700 Subject: Need a compelling argument to use Django instead of Rails In-Reply-To: <3scsc252be3d7a814ogj1ibnud3aothc1l@4ax.com> References: <1154077105.746752.153440@h48g2000cwc.googlegroups.com> <1154080209.603694.161170@i42g2000cwa.googlegroups.com> <1154092298.714808.158250@75g2000cwc.googlegroups.com> <44ca3420$0$30140$636a55ce@news.free.fr> <5hnlc25hfj56btkhdamfdi5gb5a3b8ts45@4ax.com> <1154354727.457387.142840@h48g2000cwc.googlegroups.com> <3scsc252be3d7a814ogj1ibnud3aothc1l@4ax.com> Message-ID: <1154512062.251725.177140@m73g2000cwd.googlegroups.com> Vincent Delporte wrote: > On 31 Jul 2006 07:05:27 -0700, "Ben Sizer" wrote: > >Typically you run PHP as a module in your webserver, so there should be > >no process startup overhead. mod_python provides the same sort of > >functionality for Python, but is not as popular or widely installed as > >the PHP Apache module. > > So, if mod_python provides the same functionality, it's not the main > reason why Python developers use application servers while PHP users > still program with page codes in /htdocs. > > Why do PHP users stick to that old way of things? Because they mostly > use shared hosts, with no way to install their application server? Yes, one reason is because they can't install anything other than web pages. Not only can they not install a Python application server, they can't install mod_python either, and few places will have it pre-installed. Shared hosting accounts for a massive number of sites so this is a significant issue. Another perfectly good reason is that PHP pages are much simpler to deploy than any given Python application server. Just add the code into your HTML pages as required and you're done. Python could come close to this if something like the Python Server Pages implementation in mod_python was to become widely available and well known, but that still requires overcoming the first problem. -- Ben Sizer From __peter__ at web.de Fri Aug 11 07:17:51 2006 From: __peter__ at web.de (Peter Otten) Date: Fri, 11 Aug 2006 13:17:51 +0200 Subject: Python checking for None/Null values References: <1155291204.446003.93760@m73g2000cwd.googlegroups.com> Message-ID: Fuzzydave wrote: > Okay, I have been handed a python project and working through it I have > had to add a report. I am returning 10 variables the results of an SQL > Query and as usual the number of results vary from 1 result to 10 results > so I implemented a check to see if the array item was empty or not. The > code is below based upon the code already in the python project i was > handed. In Python list items do not magically spring into existence if you ask for them. Therefore items[index] raises an IndexError if index is >= len(items). A possible resolution is to check the length of historyRep first: if len(historyRep) > 8 and historyRep[8] is not None: history8 = cmi.format_history(historyRep[8]) else: history8 = "" Note that names like history8 are a strong indication that you should use a list rather than individual variables, e. g: history = [] for item in historyRep: if item is None: s = "" else: s = cmi.format_history(item) history.append(s) or maybe even history = [cmi.format_history(item) for item in historyRep] if historyRep doesn't contain any None values. Peter From harry.g.george at boeing.com Thu Aug 17 01:06:09 2006 From: harry.g.george at boeing.com (Harry George) Date: Thu, 17 Aug 2006 05:06:09 GMT Subject: Python form Unix to Windows References: <1155712427.551814.247010@74g2000cwt.googlegroups.com> <1155714350.414644.29500@m79g2000cwm.googlegroups.com> Message-ID: "Simon Forman" writes: [snip] > Simplest way: Run the app in windows, see what breaks (probably less > than you might think), fix it. > > I have written large apps that required less than a dozen, or no, > changes to move between windows and *nix. YMMV > > Peace, > ~Simon > I agree with this-- just try it. When I've helped others move code, I found the biggest problem was when they had hardcoded file paths instead of using os.path mechanisms. -- Harry George PLM Engineering Architecture From jantod at gmail.com Tue Aug 29 06:18:42 2006 From: jantod at gmail.com (Janto Dreijer) Date: 29 Aug 2006 03:18:42 -0700 Subject: ntp in python Message-ID: <1156846722.129525.254120@i42g2000cwa.googlegroups.com> I want to measure the packet delivery delays over various network links. For this I need to synchronise the times of the sender and receiver, either against NTP or eachother. Unfortunately I won't necessarily have root priviledges to change the PCs' clocks. So I'm looking for a way I can determine the offset and simply correct my measurements from my Python code. I doubt something like http://www.nightsong.com/phr/python/setclock.py would give me a resolution of less than 10ms - which is what I want. Any Python module out there that uses a more sophisticated method? btw I can do round-trip delivery and avoid the whole clock-mismatch issue, but this would lose information on the network's asymmetry - which would be really nice to have. From horpner at yahoo.com Wed Aug 30 08:09:51 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 30 Aug 2006 14:09:51 +0200 Subject: Naming conventions (was: Re: refering to base classes) References: Message-ID: On 2006-08-30, Jean-Paul Calderone wrote: > On Wed, 30 Aug 2006 14:22:16 +1000, Ben Finney wrote: >>"glenn" writes: >> >>> Bruno Desthuilliers wrote: >>> > It might be better to use newstyle classes if you can. Also, the >>> > convention is to use CamelCase for classes names (unless you have >>> > a strong reason to do otherwise). >> >>Note that this style is more correctly called TitleCase, since the > > Or StudlyCaps :) The first time I saw StudlyCaps I thought it was the ugliest thing I'd ever seen. Now I use it a lot. I still have trouble with GVR's preference for HTTPServer over HttpServer. The latter is, to me, easier to read and write. -- Neil Cerutti These people haven't seen the last of my face. If I go down, I'm going down standing up. --Chuck Person From aleax at mac.com Wed Aug 2 11:41:44 2006 From: aleax at mac.com (Alex Martelli) Date: Wed, 2 Aug 2006 08:41:44 -0700 Subject: Windows vs. Linux References: <1154301694.445639.99580@m79g2000cwm.googlegroups.com> <44cddfb3$0$7761$7a628cd7@news.club-internet.fr> Message-ID: <1hjfow0.xza1lcpaytg8N%aleax@mac.com> Gerhard Fiedler wrote: ... a few fine points of computing history...: > >> (URLs probably use the slash because the internet protocols have been > >> developed largely on Unix-type systems for use with Unix-type systems?) > > > > It wasn't designed specifically for Unix-type systems, but for universal > > access. > > Right... the URI/URL syntax was formalized in the early 90ies, when The internet *protocols* were typically developed on non-Unix systems -- that's why each line in text-based protocols must be terminated by \r+\n, not just \n. The WWW, as you mention, came later (and I believe it was born on a NEXT cube, i.e., a unix-variant). > > My point also was that a lot of programming languages use the backslash > > as escape character. This has been true at least since the sixties. I > > think it's a bad design choice from the Microsoft team to pick this > > escape character as a path separator. > > Maybe... have you been involved in the decision? Or do you know what the > reasons were? Do you know whether it was even Microsoft's choice? > (Remember, they wrote DOS for IBM. And there was nobody who had foreseen > the PC explosion.) Microsoft did *NOT* write DOS -- they purchased it from a small Seattle company, which called it QDOS (Quick and Dirty OS) and had hacked it up "in desperation" because CP/M did not run on intel 8086 CPUs, so the small company's main business, selling 8086 boards, languished. QDOS was as compatible with CP/M as said small company could make it (rumor has it that big parts were disassembled from CP/M and reassembled to run on 8086 rather than 8080). Part of the CP/M compatibility did include the use of / as flag-indicator (the use of \r+\n as line ending also comes from CP/M -- in turn, CP/M had aped these traits from some DEC minicomputer operating systems). When MS did write an OS -- DOS 2.0, which introduced a directory tree -- they did put in the OS an undocumented switch to make - the flag-indicator and / the path separator, rather than / and \ respectively. However it was never documented and it got removed in later versions, perhaps because applications coded to the /-and-\ convention could break if the switch was thrown. > Did you know that most DOS versions accept the / as path separator? That > DOS was written on Xenix (Posix) systems (using the slash as path > separator)? That Microsoft was for a long time pretty much a pure Xenix > shop? Internally yes (indeed, they developed Xenix, before later selling it to SCO), but that does not mean that "DOS was written on Xenix" because DOS was *not* written in Microsoft, as above mentioned. Alex From skip at pobox.com Fri Aug 25 11:33:47 2006 From: skip at pobox.com (skip at pobox.com) Date: Fri, 25 Aug 2006 10:33:47 -0500 Subject: Don't use __slots__ (was Re: performance of dictionary lookup vs. object attributes) In-Reply-To: <7.0.1.0.0.20060825122244.03790010@yahoo.com.ar> References: <1156508104.583914.323700@b28g2000cwb.googlegroups.com> <7.0.1.0.0.20060825122244.03790010@yahoo.com.ar> Message-ID: <17647.6235.549608.427708@montanaro.dyndns.org> Aahz> Taking a look at __slots__ is fine as long as you don't actually Aahz> use them. Gabriel> Why? http://groups.google.com/group/comp.lang.python/browse_thread/thread/451ad25f9c648404/f4ac2dfde32b16fd?lnk=st&q=Python+__slots__+aahz&rnum=2#f4ac2dfde32b16fd Skip From martin at v.loewis.de Mon Aug 14 18:37:51 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 15 Aug 2006 00:37:51 +0200 Subject: Memory problem In-Reply-To: <1155590938.397801.302110@h48g2000cwc.googlegroups.com> References: <1155590938.397801.302110@h48g2000cwc.googlegroups.com> Message-ID: <44E0FB3F.6090801@v.loewis.de> John Machin wrote: > Incredible. That's only 34 MB. What is the size of your paging file? > What memory guzzlers were you running at the same time? What was the > Task Manager "Performance" pane showing while your test was running? > What version of Python? He didn't say Windows (so far). AFAICT, his system might be Linux, and he might have an ulimit of 1GB (or some such). Regards, Martin From sjmachin at lexicon.net Tue Aug 1 22:45:28 2006 From: sjmachin at lexicon.net (John Machin) Date: 1 Aug 2006 19:45:28 -0700 Subject: Convert string to mathematical function References: <1154483108.034363.112320@i42g2000cwa.googlegroups.com> Message-ID: <1154486728.834069.269710@p79g2000cwp.googlegroups.com> jeremito wrote: > I am extending python with C++ and need some help. I would like to > convert a string to a mathematical function and then make this a C++ > function. My C++ code would then refer to this function to calculate > what it needs. For example I want to tell my function to calculate > "x^2 + 3x +2", but later on I may want: "x + 3". Does anybody know how > I can get an arbitrary string in Python (but proper mathematical > function) turned into a C++ function? My one idea (although I don't > know how to implement it, I'm still new at this) is to pass to C++ a > pointer to a (Python) function. Will this work? It won't "work" in the sense "you can treat that pointer exactly like a pointer to a C++ function". You would need to embed Python in your C++ code -- read the "embedding" section of the "extending and embedding" manual. So far all we know is that you want Python to call C++ to call Python back again -- the run-time overhead and the sheer pain of getting all that working correctly are IMHO not worth it. What is the *total* functionality of your C++ extension? Why C++ and not C? Why C++ and not Pyrex? Consider doing the "extension" as a pure Python module -- Python's built-in eval() function will certainly do the parse-and-execute-a-formula trick for you. Even if you have extensive compute-bound requirements, I'd suggest prototyping in Python first. If the formula is to be executed many times and speed is a concern, then consider using the compile() built-in to get a code object, and see whether psyco wiil speed up its execution. I've never tried that but it should take you much less than an hour of fiddling about to test the idea yourself. Hope some of this helps, John From tobias at stud.cs.uit.no Wed Aug 9 04:47:00 2006 From: tobias at stud.cs.uit.no (Tobias Brox) Date: Wed, 9 Aug 2006 08:47:00 +0000 (UTC) Subject: #!/usr/bin/python or #!/usr/bin/env python? References: Message-ID: [Erik Max Francis > How does that make sense? `file` cannot possibly understand the > semantics of files at that level, at least not without executing them. > And that's exactly what you _don't_ want to do when you're using `file` ... This is very off-topic, but if it's fairly common to begin tcl-scripts as a /bin/sh-file with "exec tcl" at one of the first lines, I think "file" ought to be able to recognize it. """exec" python is clearly an obscure hack not used by many, so I don't see why "file" should ever recognize that :-) -- Tobias Brox, 69?42'N, 18?57'E From fredrik at pythonware.com Tue Aug 22 02:05:13 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Aug 2006 08:05:13 +0200 Subject: sum and strings In-Reply-To: References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <1155922208.930580.135080@m79g2000cwm.googlegroups.com> <1155952305.848495.7060@i3g2000cwc.googlegroups.com> <7x4pw9h3yy.fsf@ruckus.brouhaha.com> Message-ID: Steven D'Aprano wrote: >> and what exactly does the fact that Python can do operator-based >> dispatch much faster than it can do method-based dispatch have to >> do with sum's inability to add strings ? > > Sorry, I don't get you here. Are you saying that string addition doesn't > call the operands' __add__ methods? the "+" instruction (BINARY_ADD) special-cases integers and 8-bit strings, and uses a single C call via a type slot for other types. in contrast, "join" and "sum" needs to do a full name lookup and a full Python-level function call. compared to the effort needed to copy 100 bytes, that's a rather expensive set of operations. From bj_666 at gmx.net Fri Aug 11 13:51:01 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 11 Aug 2006 19:51:01 +0200 Subject: What's the cleanest way to compare 2 dictionary? References: <1155147450.628625.20270@m79g2000cwm.googlegroups.com> <1155165349.766502.314760@n13g2000cwa.googlegroups.com> <1155240726.922672.279230@i3g2000cwc.googlegroups.com> <1155247703.127047.57670@m79g2000cwm.googlegroups.com> <1155318148.342951.12590@h48g2000cwc.googlegroups.com> Message-ID: In <1155318148.342951.12590 at h48g2000cwc.googlegroups.com>, John Henry wrote: > When I do it under 2.3, I get: > > common_eq = set(k for k in _common if a[k] == b[k]) > ^ > SyntaxError: invalid syntax > > Don't know why that is. There are no generator expressions in 2.3. Turn it into a list comprehension:: common_eq = set([k for k in _common if a[k] == b[k]]) Ciao, Marc 'BlackJack' Rintsch From mcidras at yahoo.es Sat Aug 26 17:14:52 2006 From: mcidras at yahoo.es (=?iso-8859-1?q?Manuel=20Cidr=E1s=20Pidre?=) Date: Sat, 26 Aug 2006 23:14:52 +0200 (CEST) Subject: Problem installing Kinterbasdb on mac Message-ID: <20060826211452.92820.qmail@web25106.mail.ukl.yahoo.com> My question is to Mac users: Did you problems installing Kinterbasdb?. I have a lot of problems: .../... FINISHED PROBING DATABASE API FOR FEATURES. ------------------------------------------------------------------------------- building 'kinterbasdb._kinterbasdb' extension gcc -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -g -bundle -undefined dynamic_lookup build/temp.macosx-10.4-fat-2.4/_kinterbasdb.o -o build/lib.macosx-10.4-fat-2.4/kinterbasdb/_kinterbasdb.so -framework Firebird /usr/bin/ld: for architecture /usr/bin/ld: for architecture i386 /usr/bin/ld: can't locate framework for: -framework Firebird collect2: ld returned 1 exit status ppc /usr/bin/ld: can't locate framework for: -framework Firebird collect2: ld returned 1 exit status lipo: can't open input file: /var/tmp//ccMqcSm6.out (No such file or directory) error: command 'gcc' failed with exit status 1 I am using two machines: one 10.4.7 (Tiger), other 10.3.9 (Panther) --------------------------------- LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From emrahayanoglu at gmail.com Sun Aug 20 14:58:50 2006 From: emrahayanoglu at gmail.com (emrahayanoglu at gmail.com) Date: 20 Aug 2006 11:58:50 -0700 Subject: What do you want in a new web framework? Message-ID: <1156100330.768482.326760@h48g2000cwc.googlegroups.com> Hello Everyone, Now, I'm working on a new web framework. I tried many test on the other programming languages. Then i decided to use python on my web framework project. Now i want to listen all of you. What do you want in that web framework(Easy use of Database, Easy use of XML, GUI Designer, etc...)? I'm wating your answers. Thank you for all answers...! King Regards, Emrah Ayanoglu From fredrik at pythonware.com Tue Aug 22 14:38:03 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Aug 2006 20:38:03 +0200 Subject: Job Jar In-Reply-To: <1156271103.398243.45870@b28g2000cwb.googlegroups.com> References: <1156271103.398243.45870@b28g2000cwb.googlegroups.com> Message-ID: D wrote: > Hello, I apologize in advance for the vague description, but as of now > I only have an idea of what I'd like to do, and need some guidance as > to if it is feasible, and where to begin. Basically, I'd like to > create a web-based "job jar", that users in my office can access in > order to view, and "take ownership" of, misc. office tasks. One idea I > had was that when users select a task (i.e. by selecting a check box > and clicking an UPDATE button), tasks are automatically put in an In > Progress list (which identifies the task and the user who took > ownership of it) - then, when the action is complete, the user updates > it again which puts it in a Completed list (again, with the task > description and the user who completed it). However, only certain > users should be able to add and modify task descriptions. why not use an issue tracker? http://roundup.sourceforge.net/ http://trac.edgewall.org/ https://launchpad.net/ (etc) From gagsl-py at yahoo.com.ar Mon Aug 7 17:41:41 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 07 Aug 2006 18:41:41 -0300 Subject: Design Patterns in Python In-Reply-To: <1hjlz48.1o1bhxg1yabltmN%aleax@mac.com> References: <1hjlz48.1o1bhxg1yabltmN%aleax@mac.com> Message-ID: <7.0.1.0.0.20060807184032.03cfd440@yahoo.com.ar> At Saturday 5/8/2006 22:22, Alex Martelli wrote: > > But does anyone know of a complete discussion/analysis of patterns in > > Python? Books, articles, web pages... Thanks to all of you for your pointers on this subject! Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From jarrod.roberson at gmail.com Sun Aug 27 20:47:51 2006 From: jarrod.roberson at gmail.com (fuzzylollipop) Date: 27 Aug 2006 17:47:51 -0700 Subject: Pros/Cons of Turbogears/Rails? In-Reply-To: References: Message-ID: <1156726071.579429.44650@b28g2000cwb.googlegroups.com> kenneth.m.mcdonald at sbcglobal.net wrote: Looks like you mixing comparisons. > Ruby: > + More mature system. More stable? More features? uh, no, Python predates Ruby by a good bit Rails might be "older" than Turbogears but it still JUST went 1.0 officially. It can't be called "mature' by any defintition. > + Much better documented. This is a biggie. Rails has no documentation, period. The authors acknowledge this openly. > + Built-in Rubydoc system would make documenting the > system easier. (IMHO, developers almost always > underestimate the need for good documentation that > is written along withe the system.) Is there a > Python doc system that has received Guido's blessing > yet? D'oxygen would seem an obvious choice. Pydoc IS standard. This has been around for a long time. > + Better coordination with Javascript helper code? Again, is this a Python vs Ruby or Turbogears vs Rails post, you seem highly confused on the distinctions between language vs framework. > I was initially leaning towards Rails due to maturity, > but the most recent version of TurboGears seem to have > fixed a lot of the "ad hoc" feeling I got from previous > versions. But I'm still very much up in the air. > again, Ruby can't be considered 'mature' by any definition. > Thanks, > Ken > > P.S. If I wanted to provide an image by streaming the > file data directly over the connection, rather than by > referring to an image file, how would I do that? I'd > like to build code that would allow images to be assembled > into a single-file photo album (zip or bsddb file), and > so can't refer to them as individual image files. ?????? From saint.infidel at gmail.com Fri Aug 18 16:24:18 2006 From: saint.infidel at gmail.com (infidel) Date: 18 Aug 2006 13:24:18 -0700 Subject: The decentralized nature of the Python community is driving me crazy In-Reply-To: <1155157572.915538.280350@i3g2000cwc.googlegroups.com> References: <1155157572.915538.280350@i3g2000cwc.googlegroups.com> Message-ID: <1155932658.829113.89030@i42g2000cwa.googlegroups.com> > And then you have discussion and yet again, there is no perlmonks.org > for Python. We have this, IRC, and what else? There's also http://planet.python.org, which is an aggregator of python blogs that I check many times a day for new posts. From gelists at gmail.com Wed Aug 9 14:11:16 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Wed, 9 Aug 2006 15:11:16 -0300 Subject: Nested function scope problem References: <20060804155855.EE80.SLAWOMIR.NOWACZYK.847@student.lu.se> <20060809093215.EEDA.SLAWOMIR.NOWACZYK.847@student.lu.se> Message-ID: <816zp2meldzw$.dlg@gelists.gmail.com> On 2006-08-09 07:54:21, Slawomir Nowaczyk wrote: > Nope. Equivalence table can look like this: > > Python C > variable: a variable: a > textual representation: "a" address operator: &a > id of object: id(a) dereference operator: *a > > Also, notice, that "id(a)" does not really "identify" a variable. It > only identifies *object* which is bound to this variable. Both in > Python and in C. Rests one question: what is the value of the variable? In Python, it would be the result of "a". In C, it would be the result of ...? Gerhard From gabrielg_laburando at yahoo.com.ar Mon Aug 28 12:47:35 2006 From: gabrielg_laburando at yahoo.com.ar (Gabriel G) Date: Mon, 28 Aug 2006 13:47:35 -0300 Subject: question about class, functions and scope In-Reply-To: <1156583602.302530.206630@74g2000cwt.googlegroups.com> References: <1156583602.302530.206630@74g2000cwt.googlegroups.com> Message-ID: <7.0.1.0.0.20060828134446.03f2ad88@yahoo.com.ar> At Saturday 26/8/2006 06:13, nephish wrote: >i have an app that runs three classes as threads in the same program. >some of them need to be able to share some functions. Can i set a >function before i define a class and have the class use it ? Kinda like >this. > >def some_function(var1, var2): > do something with var1, var2 > return result It's ok - but beware of concurrency problems. By example, two threads trying to update the same thing. (Doesn't happen in your small example). Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From gelists at gmail.com Wed Aug 2 15:27:28 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Wed, 2 Aug 2006 16:27:28 -0300 Subject: Windows vs. Linux References: <1154531160.066733.71210@s13g2000cwa.googlegroups.com> <7ui1d250gp191lk059hihkb4jc5oroo06q@4ax.com> Message-ID: <1scx1mnz6rf6y$.dlg@gelists.gmail.com> On 2006-08-02 13:24:10, Dennis Lee Bieber wrote: > Change Directory may work... but > > C:\Documents and Settings\Dennis Lee Bieber>cd c:\ > > C:\>cd /windows/system32 > > C:\WINDOWS\SYSTEM32>cd c:\ > > C:\>dir /windows/system32 > Parameter format not correct - "windows". Since '/' is used as standard command line parameter separator, any command that uses standard Windows command line parameters can't accept a path with '/' as argument; it wouldn't know how to differentiate between a path element and an argument. Try C:\>dir "/windows/system32" That was one of the original reasons for using backslashes as path separator: the existing code base that used the slash as command line argument separator. Gerhard From olsongt at verizon.net Tue Aug 8 11:07:02 2006 From: olsongt at verizon.net (olsongt at verizon.net) Date: 8 Aug 2006 08:07:02 -0700 Subject: Info on continuations? In-Reply-To: <1155048104.107797.220630@b28g2000cwb.googlegroups.com> References: <1155048104.107797.220630@b28g2000cwb.googlegroups.com> Message-ID: <1155049622.601867.90340@75g2000cwc.googlegroups.com> vasudevram wrote: > Hi, > > I am Googling and will do more, found some stuff, but interested to get > viewpoints of list members on: > > Continuations in Python. > > Saw a few URLs which had some info, some of which I understood. But > like I said, personal viewpoints are good to have. > > Thanks > Vasudev Could you be a little more specific on what you're looking for? Continuations are a big can of worms. In general, some of the historical uses of continuations are better represented as classes in python. Generators provide some limited functionality as well, and will be able to send info both ways in python 2.5 to enable limited co-routines. Stackless python allows you to *really* suspend the stack at a given time and do a bunch of crazy stuff, but doesn't currently support 'full continuations'. From stargaming at gmail.com Thu Aug 17 11:44:45 2006 From: stargaming at gmail.com (Stargaming) Date: Thu, 17 Aug 2006 17:44:45 +0200 Subject: List match In-Reply-To: References: <1155823451.766317.7640@74g2000cwt.googlegroups.com> Message-ID: Richie Hindle schrieb: > [Stephen] > >>[...] compare 2 lists and generate a new list that does not copy similar >>entries. An example below >> >>list= ["apple", "banana", "grape"] >>list2=["orange","banana", "pear"] >> >>now I want to compare these lits and generate a third list after >>comparison >> >>list3 would be ["apple", "banana","grape","orange", "pear"] > > > Use sets: > > >>>>from sets import Set as set # For compatibility with Python 2.3 >>>>one = ["apple", "banana", "grape"] >>>>two = ["orange","banana", "pear"] >>>>print list(set(one) | set(two)) > > ['grape', 'apple', 'orange', 'pear', 'banana'] > Why using Set two times, when you can do it with one call? >>> list(set(one + two)) According to my benchmarks, this was five times faster than calling it twice and use |. There are also a few more good approaches uniquifying lists at http://www.peterbe.com/plog/uniqifiers-benchmark Regards, Stargaming From fredrik at pythonware.com Mon Aug 21 11:18:30 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Aug 2006 17:18:30 +0200 Subject: Need advice on how to improve this function In-Reply-To: References: Message-ID: Matthew Wilson wrote: > I'd like to know ways to make it better (more efficient, able to deal > with enormous-size arguments, etc). How would I write this as a > generator? what makes you think that a generator would be the right tool for this task? what's the use case? (btw, generating "enormous-size" html pages strikes me as a rather pointless exercise...) From grante at visi.com Wed Aug 30 10:43:52 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 30 Aug 2006 14:43:52 -0000 Subject: time.clock() going backwards?? References: <12f6455mjvuqv72@corp.supernews.com> <12f64pkr124f358@corp.supernews.com> Message-ID: <12fb9189ra05t0a@corp.supernews.com> On 2006-08-29, Ralf Muschall wrote: > Grant Edwards wrote: > >> This is a _Microsoft_Product_. There doesn't have to be a >> reason for something to be done in a half-assed manner. > > No, it is a quantum effect. If the energy of a clock has a > lower bound, there must be a nonzero probability for it to > run backwards. > > See <93ld7n$gv0$1 at news.state.mn.us> Brain... hurts... -- Grant Edwards grante Yow! JAPAN is a WONDERFUL at planet -- I wonder if we'll visi.com ever reach their level of COMPARATIVE SHOPPING... From ask at me Tue Aug 29 20:23:29 2006 From: ask at me (alf) Date: Tue, 29 Aug 2006 20:23:29 -0400 Subject: M$ windows python libs installed in arbitrary directories forcustomized python distributions In-Reply-To: References: <44f31d35$0$17268$9b622d9e@news.freenet.de> Message-ID: Fredrik Lundh wrote: > > http://www.catb.org/~esr/faqs/smart-questions.html#writewell > > and means? From jiangnutao at gmail.com Wed Aug 23 17:40:55 2006 From: jiangnutao at gmail.com (Jason Jiang) Date: Wed, 23 Aug 2006 14:40:55 -0700 Subject: setting a breakpoint in the module References: <1156366612.827337.256610@74g2000cwt.googlegroups.com> <1156368470.107201.78400@m73g2000cwd.googlegroups.com> Message-ID: Great! It's working now. Thank you so much. Jason "Simon Forman" wrote in message news:1156368470.107201.78400 at m73g2000cwd.googlegroups.com... > Jason Jiang wrote: >> "Simon Forman" wrote in message >> news:1156366612.827337.256610 at 74g2000cwt.googlegroups.com... >> > Jason Jiang wrote: >> >> Hi, >> >> >> >> I have two modules: a.py and b.py. In a.py, I have a function called >> >> aFunc(). I'm calling aFunc() from b.py (of course I import module a >> >> first). >> >> The question is how to directly set a breakpoint in aFunc(). >> >> >> >> The way I'm doing now is to set a breakpoint in b.py at the line to >> >> call >> >> aFunc(), 'c' to it, then 's' to step in, then set the breakpoint >> >> inside >> >> aFunc() by 'b lineNumber'. It's too cumbersome. >> >> >> >> Thanks. >> >> Jason >> > >> > What debugger are you using? >> >> I'm using Python pdb module pdb.py. >> > > So, can't you just issue the command: > > (Pdb) b a.py:aFunc > > or > > (Pdb) b a.py:lineNumber > > where "lineNumber" is a line number in a.py within aFunc()? > > > http://docs.python.org/lib/debugger-commands.html > > Peace, > ~Simon > > -- > http://mail.python.org/mailman/listinfo/python-list > From mail at microcorp.co.za Thu Aug 3 01:21:05 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Thu, 3 Aug 2006 07:21:05 +0200 Subject: Is there an obvious way to do this in python? References: <1154541495.486057.316740@i3g2000cwc.googlegroups.com> Message-ID: <016c01c6b6cd$2d854f20$03000080@hendrik> "Simon Forman" wrote: | H J van Rooyen wrote: | > Hi, | > | > I want to write a small system that is transaction based. | > | > I want to split the GUI front end data entry away from the file handling and | > record keeping. | > | > Now it seems almost trivially easy using the sockets module to communicate | > between machines on the same LAN, so that I want to do the record keeping on one | > machine. | > | > I want to keep the "server" machine as simple as possible - just doing record | > keeping on a stimulus response basis - I would prefer it to do one thing at a | > time to completion because this style of operation, though limited in | > performance, keeps a lot of hassles out of life - a transaction has either | > completed, or it has not - recovery scenarios are relatively easy... | > | > Up to this point, I don't have a problem - my toy system can create a dummy | > transaction, and I can echo it from the "server" machine, with more than one | > "user" machine running - so I think it is feasible to have several tens of "data | > entry terminal" systems running, served by one not very strong machine. | > | > Now what I would really like to do is to differentiate between the 'User" | > machines, so that some can do a full range of transactions, and others a limited | > range. | > | > And I would like to make this flexible, so that it becomes easy to introduce new | > transactions, without having to run around updating the code in all the user | > machines, with the concomitant version number hassles. | > | > And I would like to do the whole thing in python - so my question is this - is | > it possible to do the equivalent of dynamic linking? - i.e. if I keep a list of | > what a user is allowed to do - can I somehow send him just the bits he needs to | > do the job, without having to change the static code on his machine? - it seems | > to me that the eval() thingy could possibly do this for me, by sending it data | > that makes it do import statements followed by calls to whatever... - will this | > work, or is there a better way? | > | > Or has all this been done already? - and no I don't want a web server and php | > and browsers and Java and html or xml... - I want to write something that works | > simply and reliably - its just short message accounting type data... | > | > - Hendrik | | Don't reinvent the wheel. Use a database... This believe it or not, is why I asked the question... | | You probably don't want to hear this, but what you just described is a | GUI client front-end with a database backend. The time it takes to | download, install, and learn to use, say, postgres will be similar to | the time you'd spend implementing what you've described above, but with | at least 10 to 100 times the payoff. | In a way you are right - having just read postgres vs mySQL wars in another thread on this group - but on the other hand I am lazy and dont really want to spend time writing ISAM or hashed random access file methods either - I did my share of that in the late sixties and early seventies - and I have not yet done any "research" into the capabilities of the various contenders in this arena... *ducks* | As for updating the client on the fly, one strategy would be to keep | the "dynamic" code in it's own module and have the clients reload() | that module when you upload a new version of it to the client machines. | | Peace, | ~Simon This will work - but it is unsatisfying to me - I would have kind of liked to have the client machine not even have all the code available - having the "bits that can change" in one module implies some kind of build for every client if they are to be to different - what I would rather write is the kind of thing that is implemented in banking transaction terminals - the terminal has only the code for the transactions that it is authorised to have, and these different modules along with their parameters can be downloaded into it and activated on the fly, one at a time... And how to do that efficiently in python is really the question that I would like to have answered, if possible... Thanks for the response, Simon. - Hendrik From python.list at tim.thechases.com Sat Aug 12 17:53:48 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 12 Aug 2006 16:53:48 -0500 Subject: trouble with replace In-Reply-To: <44DE44E5.5040300@adapt.com> References: <1155401390.926925.252000@m79g2000cwm.googlegroups.com> <44DE44E5.5040300@adapt.com> Message-ID: <44DE4DEC.6040009@tim.thechases.com> >>>> pats = ['abcdef', 'defgef', 'effwer'] >>>> reps = ['highway', 'news', 'monitor'] >>>> s = 'defgefabcdefyuuuu\n\n\n effwerbyuuuterrfr' >>>> reduce(lambda x,y: x.replace(*y), zip(pats,reps), s) The reduce() method fairly works well if you have it as a dictionary as well: >>> m = {'effwer': 'monitor', 'abcdef': 'highway', 'defgef': 'news'} >>> s = 'defgefabcdefyuuuu\n\n\n effwerbyuuuterrfr' >>> reduce(lambda x,y: x.replace(y, m[y]), m.keys(), s) 'newshighwayyuuuu\n\n\n monitorbyuuuterrfr' One does get somewhat unpredictable results if one of the replacements contains a target search pattern (or creates it in the resulting string): >>> s = 'onetwothree' >>> m = {'one':'two', 'two':'three', 'three':'one'} >>> reduce(lambda x,y: x.replace(y, m[y]), m.keys(),s) 'twothreetwo' >>> m['three'] = 'four' >>> m['four'] = 'two' >>> reduce(lambda x,y: x.replace(y, m[y]), m.keys(),s) 'twothreefour' Just a few more ideas... -tkc From rogue_pedro at yahoo.com Fri Aug 25 15:27:11 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 25 Aug 2006 12:27:11 -0700 Subject: List comparison help please In-Reply-To: <1156118143.795096.249350@74g2000cwt.googlegroups.com> References: <1156110434.360601.102800@i3g2000cwc.googlegroups.com> <1156117633.053959.97460@b28g2000cwb.googlegroups.com> <1156118143.795096.249350@74g2000cwt.googlegroups.com> Message-ID: <1156534031.704561.214340@p79g2000cwp.googlegroups.com> Bucco wrote: > Simon Forman wrote: > > > 1) Don't use "dir", "file", and "list" as variable names, those are > > already python built in objects (the dir() function, list type, and > > file type, respectively.) > > Thanks. My own stupidity on this one. > > > > 2) 'r' is the default for open(), omit it. "self.flist = > > open(file).readlines()" > > > > Could you clarify? Show an example. Sorry if I sound newbyish, but I > am. Sure, no problem. "open(filename, 'r')" is exactly the same as "open(filename)". The flag argument is optional and when you leave it off it defaults to 'r'. > > > > 5) Since you have a list of things you're matching (excluding actually) > > this part: > > > > > for item in self.flist: > > > if item == fname[:-4]: > > > pass > > > else: > > > self.matches.append(fname) > > > > could become: > > > > if fname[:-4] not in self.flist: self.matches.append(fname) > > Thanks. This was what I was looking for. Cool! You're welcome. :-) > > > 6) Why are you using #~ for comments? > > This is just the automatic commenting on scite. I put my cursor on the > line I want to comment and press ctrl-q ans scite comments out the > whole line or selection. As for why the lines are commented; I > commented these lines so I could test out some of the code prior to > running the next bit. Ah, right on. I was just wondering. > > > Also, check out os.path.splitext() > > http://docs.python.org/lib/module-os.path.html#l2h-1761 > > > I will check this out also. > > Thank You for your help. You have answered some questions for me. > > Thanks:) > > SA You're very welcome. It's a pleasure. Peace, ~Simon From yuxi at ece.gatech.edu Mon Aug 7 15:12:25 2006 From: yuxi at ece.gatech.edu (Yu-Xi Lim) Date: Mon, 07 Aug 2006 15:12:25 -0400 Subject: format a number for output In-Reply-To: References: Message-ID: Yu-Xi Lim wrote: > >>> b = 189028499 > >>> ','.join([str(b)[::-1][x:x+3] for x in range(len(str(b)))[::3]])[::-1] > > '-,189,028,499' Oops, mis-paste >>> b = -189028499 >>> ','.join([str(b)[::-1][x:x+3] for x in range(len(str(b)))[::3]])[::-1] From jaywgraves at gmail.com Thu Aug 3 15:11:55 2006 From: jaywgraves at gmail.com (jay graves) Date: 3 Aug 2006 12:11:55 -0700 Subject: Running queries on large data structure References: <200608022224.00925.email@christoph-haas.de> <1154619645.356336.189640@p79g2000cwp.googlegroups.com> Message-ID: <1154632314.918069.29280@h48g2000cwc.googlegroups.com> Christoph Haas wrote: > On Thursday 03 August 2006 17:40, jay graves wrote: > > How hard would it be to create this nested structure? > Not hard. Instead of doing "INSERT INTO" I would add values to a dictionary > or list. That's even simpler. > > I've found > > pickling really large data structures doesn't really save a huge amount > > of time when reloading them from disk but YMMV and you would have to > > profile it to know for sure. > Okay, that takes a bit of pickle's magic away. :) But since it is so easy to create your nested structure, it may be worth trying. I've rarely used pickled files and maybe my specific data structure caused alot of churn in the pickle/unpickle code. Doesn't hurt to try. You also need to try walking your data structure to see how easy/efficient it is to get the results you want. If you have to do a text search for every node, it might actually be slower. In the app I described, everytime i do a reload (equvalent to your parse step) I interrogate each row and update multiple dictionaries with differents sets of key tuples with the dictionary value being the row itself. (just like indexes in a SQL db) The row is the same object so the only extra memory I need is for the key tuples. It sure beats iterating over a list with 50K entries top to bottom and testing for the right condition, but I don't know your app so I can't tell if this is a valid strategy. > > > So the question is: would you rather force the data into a relational > > > database and write object-relational wrappers around it? Or would you > > > pickle it and load it later and work on the data? The latter > > > application is currently a CGI. I'm open to whatever. :) > > Convert your CGI to a persistant python webserver (I use CherryPy but > > you can pick whatever works for you.) and store the nested data > > structure globally. Reload/Reparse as necessary. It saves the > > pickle/unpickle step. > Up to now I have just used CGI. But that doesn't stop me from looking at > other web frameworks. However the reparsing as necessary makes a quick > query take 10-30 seconds. And my users usually query the database just > once every now and then and expect to have little delay. That time is not > very user-friendly. I'm not sure I made the advantages of a python web/app server clear. The main point of CherryPy or similar web frameworks is that since they are serving the HTTP requests (which are admittedly light), it can keep any data you want persistent because it is always running, not respawned on each request. (Caveat: These are very broad strokes and there are possible race conditions but no worse than your Postgres solution) Imagine if you will: fwdata = {} expiretime = 0 def loaddata(): global fwdata,expiretime temp = {} parse data into temp dictionary expiretime = now + 5 minutes fwdata = temp loaddata() while 1: handle http request if query: if now > expiretime: loaddata() query fwdata and build output html Does the underlying change every 5 minutes? If not, you could even be trickier and provide a 'reload' url that foces the app to reload the data. If you can track when the source data changes (maybe there are sanctioned interfaces to use when editing the data), just hit the appropriate reload URL and your app is always up to date without lots of needless reparsing. e.g. fwdata = {} def loaddata(): global fwdata temp = {} parse data into temp dictionary fwdata = temp loaddata() while 1: handle http request if queryrequest: query fwdata and build output html elif reloadrequest: loaddata() Hope this helps or clarifies my point. ... jay graves From glar at inbox.ru Tue Aug 8 13:22:31 2006 From: glar at inbox.ru (=?koi8-r?Q?=E7=CC=CF=D4=CF=D7_=E1=D2=D4=C5=CD?=) Date: Tue, 08 Aug 2006 21:22:31 +0400 Subject: =?koi8-r?Q?ImportError=3A_math.so=3A_undefined_symbol_PyFPE=5Fjbuf?= Message-ID: Hello! I'm trying to install the web application written with Python, and have the trouble with module math.so: # lwp-request http://localhost/site/code/edit.py Mod_python error: "PythonHandler edit::handler" Traceback (most recent call last): File "/usr/local/lib/python2.3/site-packages/mod_python/apache.py", line 181, in Dispatch module = import_module(module_name, _req) File "/usr/local/lib/python2.3/site-packages/mod_python/apache.py", line 335, in import_module module = imp.load_module(mname, f, p, d) File "/usr/local/apache/htdocs/site/code/edit.py", line 6, in ? from PPA.HTTP.CGI import Adapter File "/usr/local/lib/python2.3/site-packages/PPA/HTTP/CGI.py", line 3, in ? import Base File "/usr/local/lib/python2.3/site-packages/PPA/HTTP/Base.py", line 102, in ? class Response: File "/usr/local/lib/python2.3/site-packages/PPA/HTTP/Base.py", line 104, in Response from Errors import statusCodes File "/usr/local/lib/python2.3/site-packages/PPA/HTTP/Errors.py", line 3, in ? import cgi File "/usr/lib/python2.3/cgi.py", line 40, in ? import mimetools File "/usr/lib/python2.3/mimetools.py", line 6, in ? import tempfile File "/usr/lib/python2.3/tempfile.py", line 33, in ? from random import Random as _Random File "/usr/lib/python2.3/random.py", line 42, in ? from math import log as _log, exp as _exp, pi as _pi, e as _e ImportError: /usr/lib/python2.3/lib-dynload/math.so: undefined symbol: PyFPE_jbuf I read similar topic at http://mail.python.org/pipermail/python-list/2006-July/349940.html but did not find the solution :( Of cource I'm using apache 1.3.33, mod_python 2.7.11, ppa, qps, mx modules, but I thing that the problem is in the Python 2.3.5. Any ideas? From yuxi at ece.gatech.edu Mon Aug 14 13:01:50 2006 From: yuxi at ece.gatech.edu (Yu-Xi Lim) Date: Mon, 14 Aug 2006 13:01:50 -0400 Subject: outputting a command to the terminal? In-Reply-To: References: <44df99f7$0$25025$c3e8da3@news.astraweb.com> Message-ID: Steven Bethard wrote: > import argparse # http://argparse.python-hosting.com/ > import subprocess > import sys Why not the standard lib's optparse? From earle.ady at gmail.com Tue Aug 1 20:23:41 2006 From: earle.ady at gmail.com (url81-1) Date: 1 Aug 2006 17:23:41 -0700 Subject: Get age of a file/dir In-Reply-To: <1154473622.749202.100300@75g2000cwc.googlegroups.com> References: <1154473622.749202.100300@75g2000cwc.googlegroups.com> Message-ID: <1154478221.479090.25960@i42g2000cwa.googlegroups.com> Actually this has nothing to do with datetime.datetime -- he's asking how to find the created time of the directory. Python has a builtin module called "stat" (afer sys/stat.h) which includes ST_ATIME, ST_MTIME, ST_CTIME members which are times accessed, modified, and created, respectively. Best, Earle Ady Jim wrote: > Carl J. Van Arsdall wrote: > > I've been looking around the OS module and I haven't found anything > > useful yet. Does anyone know how to get the age of a file or directory > > in days? I'm using unix and don't seem to find anything that will help > > me. The only function that comes close so far is > > > > os.path.getctime(path) > > > > > > However this only gets creation time on Windows, on Unix it gets the the > > time of the last change. Any ideas? > > > > Thanks! > > > > -carl > > > > -- > > > > Carl J. Van Arsdall > > cvanarsdall at mvista.com > > Build and Release > > MontaVista Software > > Hi, > You should check out the datetime module. And convert dates to an > ordinal number. > today = datetime.date.today().toordinal() > age = today - datetime.date(year, month, day).toordinal() > Jim From khemkaamit at gmail.com Wed Aug 30 05:51:27 2006 From: khemkaamit at gmail.com (Amit Khemka) Date: Wed, 30 Aug 2006 15:21:27 +0530 Subject: how can i change the text delimiter In-Reply-To: <1360b7230608300228w2f9e00f8ta066ab1a43fd9038@mail.gmail.com> References: <1156929540.715287.123060@h48g2000cwc.googlegroups.com> <1360b7230608300228w2f9e00f8ta066ab1a43fd9038@mail.gmail.com> Message-ID: <1360b7230608300251i6aee20d3oe3301aec07e646dc@mail.gmail.com> On 8/30/06, Amit Khemka wrote: > sonald wrote: > > Hi, > > Can anybody tell me how to change the text delimiter in FastCSV Parser > > ? > > By default the text delimiter is double quotes(") > > I want to change it to anything else... say a pipe (|).. Btw, I forgot to mention that AFAIK, in CSV '"' (double quotes) are *not* field seperator delimiters character ! ',' (comma) is the default field seperator, and my earlier suggestion was considering that you want to change the default value for the field seperator. http://en.wikipedia.org/wiki/Comma-separated_values cheers, amit. -- ---- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. From python.list at tim.thechases.com Mon Aug 14 11:29:09 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 14 Aug 2006 10:29:09 -0500 Subject: why the method get() of python Queue is hang on there? In-Reply-To: <1155568212.888733.79920@b28g2000cwb.googlegroups.com> References: <1155568212.888733.79920@b28g2000cwb.googlegroups.com> Message-ID: <44E096C5.6080605@tim.thechases.com> > import Queue > b = Queue.Queue(0) > b.put(9999) > b.get() # this is ok, it pops out 9999 > b.get() # this one does not return anything and is hang on > there > > Anybody knows what is going on with the second b.get()? >>> help(Queue.Queue) : : | get(self, block=True, timeout=None) | Remove and return an item from the queue. | | If optional args 'block' is true and | 'timeout' is None (the default), block if | necessary until an item is available. If | 'timeout' is a positive number, it blocks | at most 'timeout' seconds and raises the | Empty exception if no item was available | within that time. Otherwise ('block' is | false), return an item if one is | immediately available, else raise the | Empty exception ('timeout' is ignored in | that case). | | 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. : : Notice that by default, get() will block until there's something to read. You can use either b.get(block=False) or b.get_nowait() In either case, an exception will be raised when the Queue is empty, to let you know as much. Just trap for the exception and do as you please. -tkc From tkirke at gmail.com Fri Aug 11 18:31:51 2006 From: tkirke at gmail.com (tkirke at gmail.com) Date: 11 Aug 2006 15:31:51 -0700 Subject: help with c <-> python buffer transfer Message-ID: <1155335511.379184.200570@75g2000cwc.googlegroups.com> How does one transfer a buffer object from python -> c and back again (assuming the data gets modified)? I can't seem to get this or anything else to work, but am clueless as to what I'm doing wrong using namespace boost::python; static PyObject * proc_buf(PyObject *self, PyObject *args) { PyObject *resultobj; char* output_samples; int len; if (!PyArg_ParseTuple(args,"s#|l",&output_samples, &len)) { return NULL; /* wrong arguments provided */ } for (int i=0;i References: <9afea2ac0608211516h1bdaa365ua13a5207f1b85026@mail.gmail.com> Message-ID: <9afea2ac0608211526n59ddda97l6b6fe635df335afb@mail.gmail.com> On 21/08/06, Tim Williams wrote: > On 21/08/06, John Draper wrote: Sorry, there's an indentation error here except smtplib.SMTPRecipientsRefused, x : #all recips failed for recip in x.recipients: print recip server.quit() break it should be except smtplib.SMTPRecipientsRefused, x : #all recips failed for recip in x.recipients: print recip # will give the recip and the SMTP error too server.quit() break From emrahayanoglu at gmail.com Sun Aug 20 14:58:51 2006 From: emrahayanoglu at gmail.com (emrahayanoglu at gmail.com) Date: 20 Aug 2006 11:58:51 -0700 Subject: What do you want in a new web framework? Message-ID: <1156100331.329889.216340@p79g2000cwp.googlegroups.com> Hello Everyone, Now, I'm working on a new web framework. I tried many test on the other programming languages. Then i decided to use python on my web framework project. Now i want to listen all of you. What do you want in that web framework(Easy use of Database, Easy use of XML, GUI Designer, etc...)? I'm wating your answers. Thank you for all answers...! King Regards, Emrah Ayanoglu From taleinat at gmail.com Thu Aug 3 17:17:19 2006 From: taleinat at gmail.com (taleinat) Date: Thu, 3 Aug 2006 21:17:19 +0000 (UTC) Subject: help - iter & dict References: <1154632243.44d24a33a52ab@www3.helsinki.fi> <44D25A45.1080503@tim.thechases.com> Message-ID: Ali writes: >> Im trying to iterate through values in a dictionary so i can find the >> closest value and then extract the key for that value....what ive done so far: >> >> def pcloop(dictionary, exvalue): >> z = dictionary.itervalues() >> y = z - exvalue >> v = (y*y)**1/2 >> if v < 0.001: >> u = dictionary.get[z] >> return u First of all, your code was broken everywhere... Unlike many other languages, Python is fun! Just fire up an interpreter ("python" at the command line should work) and start playing around and trying stuff out. You would have quickly found that dictionary.itervalueS() return an iterator object (which must be iterated over), that dictionaries can be accessed either with brackets "[]" -or- with the .get() method, and more. If you're learning from a book, try everything you learn out at least once in the interpreter - that way you'll make sure you understand everything, and understand the syntax much faster (since the interpreter will -explain- what your syntax errors are). Second, Python has a built-in abs() method which returns the absolute value of a number - using it is simpler and more readable. Tim Chase tim.thechases.com> writes: > if closest_value: > if distance < closest_distance: > closest_key = k > closest_value = v > closest_distance = distance > else: > closest_key = k > closest_value = v > closest_distance = distance > return closest_key, closest_value This has a bug - if closest_value happens to be zero at some point, it would be overriden by the next value no matter what, since "if closest_value" would be false. You must explicitly check "if closest_value is not None:". Also the code could be simplified: if closest_value is None or distance < closest_distance: closest_key = k closest_value = v closest_distance = distance > > def findClosest2(dataset, target): if not dataset: # a dict is considered false if empty, true otherwise return (None,None) > return reduce( > lambda x,y: > ((target - y[1]) ** 2 < > (target - x[1]) ** 2) > and y or x, dataset.items()) I would advise everyone still learning the basics to completely ignore the second function. Yes, it works, but this code is VERY confusing for a beginner, both because of the reduce (tough to grasp) and because of the confusing and bug-prone "and-or trick". (even though this is a classic use for reduce) - Tal Einat a='maciogaiea at l.ntmtl'[::-1]; print reduce(lambda m,x:[m[i]+s[-1] for i,s in enumerate(sorted(m))],[list(a)]*len(a))[3] From rogue_pedro at yahoo.com Wed Aug 9 17:12:01 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 9 Aug 2006 14:12:01 -0700 Subject: Eval (was Re: Question about using python as a scripting language) In-Reply-To: References: <73BFFFC6-760D-4794-9B5C-AA749287B78A@carnegielearning.com> <20060809150432.GA15121@kateandchris.net> Message-ID: <1155157921.662196.11210@75g2000cwc.googlegroups.com> Chris Lambacher wrote: > On Wed, Aug 09, 2006 at 11:51:19AM -0400, Brendon Towle wrote: > > On 9 Aug 2006, at 11:04 AM, Chris Lambacher wrote: > > > > How is your data stored? (site was not loading for me). > > > > In the original source HTML, it's like this (I've deleted all but the > > beginning and the end of the list for clarity): > > var table_body = [ > > ["ATVI", "Activision, Inc.",12.75,0.150000,1.19,2013762,0.04,"N","N"] > > ,["YHOO", "Yahoo! Inc.",27.7,0.260000,0.95,6348884,0.21,"N","N"] > > ]; > I didn't realize it was javascript syntax, a json implimentation would > probably work for you: http://cheeseshop.python.org/pypi/simplejson > > > > > More sophisiticated situations (like nested lists) may require something > > like pyparsing. > > > > I could do that, or I could do something like the re.* trick mentioned by > > another poster. But, doesn't it offend anyone else that the only clean way > > to access functionality that's already in Python is to write long > > complicated Python code? Python already knows how to extract a list object > > from a string; why should I have to rewrite that? > I don't disagree with you. The problem is that the obvious way to do it > (eval) is a big security hole. In this case you are trusting that no one > inserts themselves between you and the website providing you with code to > EXECUTE. I have heard of people attempting to use the parser provided with > python and examining the AST to do this, but I think that approach is even > more complicated. > > B. > > > > On Wed, Aug 09, 2006 at 10:23:49AM -0400, Brendon Towle wrote: > > > > Slawomir Nowaczyk noted: > > #> Heck, whenever *is* it OK to use eval() then? > > eval is like optimisation. There are two rules: > > Rule 1: Do not use it. > > Rule 2 (for experts only): Do not use it (yet). > > So, that brings up a question I have. I have some code that goes > > out to a > > website, grabs stock data, and sends out some reports based on the > > data. > > Turns out that the website in question stores its data in the > > format of a > > Python list > > ([1][1]http://quotes.nasdaq.com/quote.dll?page=nasdaq100, search > > the source for "var table_body"). So, the part of my code that > > extracts > > the data looks something like this: > > START_MARKER = 'var table_body = ' > > END_MARKER = '];' > > def extractStockData(data): > > pos1 = data.find(START_MARKER) > > pos2 = data.find(END_MARKER, pos1) > > return eval(data[pos1+len(START_MARKER):END_MARKER]) > > (I may have an off-by-one error in there somewhere -- this is from > > memory, > > and the code actually works.) > > My question is: what's the safe way to do this? > > B. > > -- > > Brendon Towle, PhD > > Cognitive Scientist > > +1-412-690-2442x127 > > Carnegie Learning, Inc. > > The Cognitive Tutor Company ? > > Helping over 375,000 students in 1000 school districts succeed in > > math. > > References > > Visible links > > 1. [2]http://quotes.nasdaq.com/quote.dll?page=nasdaq100 > > > > -- > > [3]http://mail.python.org/mailman/listinfo/python-list > > > > -- > > Brendon Towle, PhD > > Cognitive Scientist > > +1-412-690-2442x127 > > Carnegie Learning, Inc. > > The Cognitive Tutor Company ? > > Helping over 375,000 students in 1000 school districts succeed in math. > > > > References > > > > Visible links > > 1. http://quotes.nasdaq.com/quote.dll?page=nasdaq100 > > 2. http://quotes.nasdaq.com/quote.dll?page=nasdaq100 > > 3. http://mail.python.org/mailman/listinfo/python-list Fredrik Lundh posted a great piece of code to parse a subset of python safely: http://groups.google.ca/group/comp.lang.python/browse_frm/thread/8e427c5e6da35c/a34397ba74892b4e Peace, ~Simon From paolopantaleo at gmail.com Mon Aug 14 12:15:17 2006 From: paolopantaleo at gmail.com (Paolo Pantaleo) Date: Mon, 14 Aug 2006 18:15:17 +0200 Subject: [Announce] p-gal: photo gallery generator with templating support In-Reply-To: <7xk65buyf9.fsf@ruckus.brouhaha.com> References: <7xk65buyf9.fsf@ruckus.brouhaha.com> Message-ID: <83e8215e0608140915v72d56b52p5bfacbf197dc95fe@mail.gmail.com> 14 Aug 2006 08:31:06 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid>: > "Paolo Pantaleo" writes: > > I would anyone to take a look at my piece of code, and give me his > > feedback about what is good and what should be improved. > > url? > -- > http://mail.python.org/mailman/listinfo/python-list > Sorry... www.sf.net/projects/ppgal From fredrik at pythonware.com Wed Aug 30 08:07:00 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 30 Aug 2006 14:07:00 +0200 Subject: how can i change the text delimiter References: <1156929540.715287.123060@h48g2000cwc.googlegroups.com><1156932106.948885.63980@i3g2000cwc.googlegroups.com> <1156938927.933389.101170@m73g2000cwd.googlegroups.com> Message-ID: "sonald" wrote: > fast csv is the the csv module for Python... no, it's not. the csv module for Python is called "csv". > and actually the string cannot be modified because > it is received from a third party and we are not supposed to modify the > data in any way.. that doesn't prevent you from using Python to modify it before you pass it to the csv parser, though. > for details on the fast CSV module please visit > > www.object-craft.com.au/projects/csv/ or that module is called "csv", not "fastcsv". and as it says on that page, a much improved version of that module was added to Python in version 2.3. what Python version are you using? From cvanarsdall at mvista.com Tue Aug 1 18:38:34 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Tue, 01 Aug 2006 15:38:34 -0700 Subject: Get age of a file/dir Message-ID: <44CFD7EA.6040107@mvista.com> I've been looking around the OS module and I haven't found anything useful yet. Does anyone know how to get the age of a file or directory in days? I'm using unix and don't seem to find anything that will help me. The only function that comes close so far is os.path.getctime(path) However this only gets creation time on Windows, on Unix it gets the the time of the last change. Any ideas? Thanks! -carl -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From steve at holdenweb.com Sat Aug 12 16:39:12 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 12 Aug 2006 21:39:12 +0100 Subject: Python share CPU time? In-Reply-To: <1155253594.681570.145910@b28g2000cwb.googlegroups.com> References: <1155146500.063665.282430@p79g2000cwp.googlegroups.com> <1155253594.681570.145910@b28g2000cwb.googlegroups.com> Message-ID: Yannick wrote: > Thank you all for the detailled answers. > > What I would like to achieve is something like: > > # main loop > while True: > for robot in robots: > robot.start() > robot.join(0.2) # wait 200ms > if robot.is_active(): > robot.stop() > # run all the game physics, pause, frame/rate, etc... > > Unfortunately the stop() call doesn't exist in Python. > > By using a generator I would make the assumption that every robot is > playing fair, and would yield often. But I cannot control this as > eventually robots would be coded by third parties. > > Using Python scheduler would allow me to share time equally between > each robot, but then I would loose the ability to have a main thread > organizing everything. > I think the best way is to give each robot its own thread. That way the interpreter will share time between each of the robots (whether or not they sleep or yield) on a reasonably fair basis. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From bj_666 at gmx.net Fri Aug 11 06:25:42 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 11 Aug 2006 12:25:42 +0200 Subject: Python checking for None/Null values References: <1155291204.446003.93760@m73g2000cwd.googlegroups.com> Message-ID: In <1155291204.446003.93760 at m73g2000cwd.googlegroups.com>, Fuzzydave wrote: > but regardless i am getting the error below and i can't seen to resolve > this, what am i > doing wrong? > > Traceback (most recent call last): File > "/home/phillipsd/work/medusa-new/htdocs/pricingrep.cgi", line 326, in ? > if historyRep[8]==None: IndexError: list index out of range `historyRep` seems to be shorter than you think it is. Try printing it too see what it actually contains. Ciao, Marc 'BlackJack' Rintsch From gandalf at designaproduct.biz Thu Aug 24 13:43:04 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Thu, 24 Aug 2006 19:43:04 +0200 Subject: lambda In-Reply-To: <1156440070.549332.18830@i3g2000cwc.googlegroups.com> References: <1156440070.549332.18830@i3g2000cwc.googlegroups.com> Message-ID: <44EDE528.4060407@designaproduct.biz> > what is a lambda expression? labmda is a reserved word and AFAIK it is an operatior. By using lamba, you can create an anonymous function. That is, a function without name. For example, doing def create_adder(amount): def adder(x): return x + amount return adder is equvalent to: def create_adder(amount): return lambda x : x + amount In the former case: >>> f1 = create_adder(4) >>>f1 >>> f1(2) 6 In the later case: >>> f2 = create_adder(4) >>> f2 at 0x00BE66F0> >>> f2(2) 6 For example, if you want create a new list by adding 4 to the elements of another list: >>> another = [1,2,3,4,5] >>> newlist = map( lambda x: x+4 , another) >>> newlist [5, 6, 7, 8, 9] Best, Laszlo From anthra.norell at tiscalinet.ch Wed Aug 2 17:25:48 2006 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Wed, 2 Aug 2006 23:25:48 +0200 Subject: need help of regular expression genius References: <1154532421.096157.289570@i42g2000cwa.googlegroups.com> Message-ID: <053601c6b67a$392306e0$0201a8c0@mcuf7> Harald, This works. 's' is your SQL sample. >>> import SE # From the Cheese Shop with a good manual >>> Split_Marker = SE.SE (' ";=\" "~\$_?\$(.|\n)*?\$_?\$~==" ') >>> s_with_split_marks = Split_Marker (s) >>> s_split = s_with_split_marks.split ('') That's it! And it isn't as complicated as it looks. The first expressions says translate the semicolon to your split mark. The second expression finds the $-blocks and says translate them to themselves. So they don't change. You can add as many expressions as you want. You'd probably want to choose a more convenient split mark. Frederic ----- Original Message ----- From: "GHUM" Newsgroups: comp.lang.python To: Sent: Wednesday, August 02, 2006 5:27 PM Subject: need help of regular expression genius > I need to split a text at every ; (Semikolon), but not at semikolons > which are "escaped" within a pair of $$ or $_$ signs. > > My guess was that something along this should happen withing csv.py; > but ... it is done within _csv.c :( > > Example: the SQL text should be splitted at "" (of course, > those "split heres" are not there yet :) > > set interval 2; > > CREATE FUNCTION uoibcachebetrkd(bigint, text, text, text, text, text, > timestamp without time zone, text, text) RETURNS integer > AS $_$ > DECLARE > result int4; > BEGIN > update bcachebetrkd set > name=$2, wieoftjds=$3, letztejds=$4, njds=$5, > konzern=$6, letztespeicherung=$7, betreuera=$8, jdsueberkonzern=$9 > where id_p=$1; > IF FOUND THEN > result:=-1; > else > insert into bcachebetrkd ( > id_p, name, wieoftjds, letztejds, njds, konzern, > letztespeicherung, betreuera, jdsueberkonzern > ) > values ($1, $2, $3, $4, $5, $6, $7, $8, $9); > result:=$1; > END IF; > RETURN result; > END; > $_$ > LANGUAGE plpgsql; > > CREATE FUNCTION set_quarant(mylvlquarant integer) RETURNS integer > AS $$ > BEGIN > perform relname from pg_class > where relname = 'quara_tmp' > and case when has_schema_privilege(relnamespace, 'USAGE') > then pg_table_is_visible(oid) else false end; > if not found then > create temporary table quara_tmp ( > lvlquara integer > ); > else > delete from quara_tmp; > end if; > > insert into quara_tmp values (mylvlquarant); > return 0; > END; > $$ > LANGUAGE plpgsql; > > > Can anybody hint me in the right direction, how a RE looks for "all ; > but not those ; within $$" ? > > Harald > > -- > http://mail.python.org/mailman/listinfo/python-list From deets at nospam.web.de Mon Aug 21 12:30:24 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 21 Aug 2006 18:30:24 +0200 Subject: Create a Multilanguage PDF in Python References: <1156073383.983914.149180@i3g2000cwc.googlegroups.com> <87mz9z4f8h.fsf@smsnet.pl> <1156108451.762961.70140@h48g2000cwc.googlegroups.com> <1156143575.547217.237270@p79g2000cwp.googlegroups.com> <1156172609.125230.218190@i42g2000cwa.googlegroups.com> Message-ID: <4ku5d0Fdsn8fU1@uni-berlin.de> Perseo wrote: > I can't upload in the PYTHONPATH but in a normal folder of our site. > Exist another way to do it? PYTHONPATH is an environment variable. You can set it to arbitrary paths, and python will look for module there, too. Or you modify sys.path before you try the import. Diez From gandalf at designaproduct.biz Thu Aug 24 17:17:26 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Thu, 24 Aug 2006 23:17:26 +0200 Subject: wxPython default radiobox choice In-Reply-To: <1156451235.958752.101510@i42g2000cwa.googlegroups.com> References: <1156451235.958752.101510@i42g2000cwa.googlegroups.com> Message-ID: <44EE1766.90406@designaproduct.biz> crystalattice ?rta: > In my GUI app, I have a radio box allowing the user to pick his/her > gender. When I click a button, I'd like the radio box to tell the > program which choice is marked. I can get it to work when I manually > pick a choice but I get an error when the choice is left at the default > value, which is "Male". > > I have the radio box tied to an event to "see" when a choice is made, > but how does it work if the person just leaves the default value? I've > looked at the wxPython demo but the radio box actions only work for > changing values. > > I'm not sure if I understood your problem. You can call the wxRadioBox.GetSelection method anytime to get the current value. If you need that value very often (e.g. thousand times per sec) then you can "shadow" the default value in an instance variable. Example (untested): class MyClass(wx.Frame): """In this frame, you can use the curchoice variable after construction.""" def __init__(self): # ... create your frame here... r =self.radio = wx.RadioBox(self,-1,choiches=['One','Two','Three']) # Set default value r.SetSelection(0) # This does not cause a wxEVT_COMMAND_RADIOBOX_SELECTED event to get emitted. self.curchoice = 0 # Bind the event r.Bind( wx.EVT_COMMAND_RADIOBOX_SELECTED, self.OnRadioChanged, r ) def OnRadioChanged(self,event): self.curchoice = self.radio.GetSelection() # Do whatever you want here... event.Skip() From ray_usenet at yahoo.com Mon Aug 28 22:44:33 2006 From: ray_usenet at yahoo.com (Ray) Date: 28 Aug 2006 19:44:33 -0700 Subject: Pros/Cons of Turbogears/Rails? In-Reply-To: <1156768355.275370.129680@h48g2000cwc.googlegroups.com> References: <1156726071.579429.44650@b28g2000cwb.googlegroups.com> <1156740469.645955.52080@i3g2000cwc.googlegroups.com> <1156768355.275370.129680@h48g2000cwc.googlegroups.com> Message-ID: <1156819473.592153.141940@i42g2000cwa.googlegroups.com> Paul Boddie wrote: > > But at least in most developers' perception, it is (not necessarily in > > the absolute sense, but perhaps relative to Django or Turbogears). > > Mind, it doesn't even need to be true, we're talking of perception > > here. > > So actual maturity isn't important when using a technology: it's > "perceived maturity" that counts, right? Well depends on "counts" in what sense. Counts as in the managers up there perceive something as mature, despite proofs of the contrary, certainly "counts", because then we'll end up having to work with a probably immature technology (nothing about RoR here, I'm talking in general). Yet with more people using it, its actual maturity will inevitably rise as well, maybe eventually to a level near that of its perceived maturity. "Counts" as in to us developers who are actually spending our lives doing this? Perhaps yes too. If you're well-versed in something that is widely perceived to be mature, you may find it easier to win bread for your family, even if you have a painful time using it. > Any continuation down that > particular path of reasoning surely leads you to the point where you > claim, in concert with the developers, that increasing levels of > inconvenience caused by gratuitous changes or broken documentation is > not caused by bugs or general immaturity but by "features". I guess > this is the definition of "opinionated software" that some people are > so excited about. > > [...] > > > Sadly, there are more Java guys who know about Ruby than Python, > > despite the fact that Python predates Ruby by quite a few years... > > (this must be that Bruce Tate dude's fault! ) > > If you only listen to Bruce Tate et al, I imagine you could have the > above impression, but I'd be interested to see hard facts to back up > those assertions. Yeah, see, the thing is that Python is not lacking luminaries endorsing it either, e.g.: Eric Raymond and Bruce Eckel. But for some reason this "Python is good" meme is not that viral. I wonder why... And, since when do hard facts matter anyway? I've met a number of people who've told me they'd program in Eiffel if they could. And hey, perhaps in its day Eiffel *was* the best OO language out there. Certainly it looked cleaner than C++! :) > Paul From nyamatongwe+thunder at gmail.com Tue Aug 8 19:56:41 2006 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Tue, 08 Aug 2006 23:56:41 GMT Subject: (Boost.Python) How to load header files? In-Reply-To: <1155079403.304584.315530@h48g2000cwc.googlegroups.com> References: <1155079403.304584.315530@h48g2000cwc.googlegroups.com> Message-ID: Qun Cao wrote: > I have a C++ class foo.cpp, defined in foo.h, I wrote a wrapper class > for it to generate a python module. > > #include "Foo.h" If you are on Windows it shouldn't matter but try to keep capitalisation consistent: #include "foo.h". > The problem is that when I bjam it, the compiler cannot find the header > file , although I had the location of Foo.h added into $PATH. Headers don't go into $PATH. The bjam way is to use an include dependency in the Jamfile. One of my Jamfile's looks something like this with extra stuff removed: extension SinkWorld : # sources SinkWorld.cpp : ../../base ../../lexers ; I'm not a Jam or Boost expert and the best place for Boost.Python questions is http://mail.python.org/mailman/listinfo/c++-sig Neil From moverx at gmail.com Mon Aug 21 14:23:33 2006 From: moverx at gmail.com (V@mpire Hunter Rojas) Date: Mon, 21 Aug 2006 14:23:33 -0400 Subject: urllib question Message-ID: <28b127080608211123n69e73800o461ed851dc924f51@mail.gmail.com> how can I retrieve a web page using an authenticated proxy? -------------- next part -------------- An HTML attachment was scrubbed... URL: From gslindstrom at gmail.com Thu Aug 10 07:43:05 2006 From: gslindstrom at gmail.com (gslindstrom at gmail.com) Date: 10 Aug 2006 04:43:05 -0700 Subject: do people really complain about significant whitespace? In-Reply-To: <1155134902.103617.71810@i3g2000cwc.googlegroups.com> References: <1154986984.740638.241130@m79g2000cwm.googlegroups.com> <87bqqwyumq.fsf@benfinney.id.au> <1155077965.100108.232790@m79g2000cwm.googlegroups.com> <44d9d949$0$14310$626a54ce@news.free.fr> <1155134902.103617.71810@i3g2000cwc.googlegroups.com> Message-ID: <1155210185.163476.149610@p79g2000cwp.googlegroups.com> Carl Banks wrote: > Although Python doesn't do this, it is possible to mandate a specific > indent (4 spaces, say), or at least a reasonable consistent indent I like running reindent.py (found in your Python source directory under Tools/Scripts) which cleans up indentations, trailing whitespace, and other things. We run our entire source directory through reindent before we check it into our library. A very nice routine courtesy of Tim Peters, I believe. --greg From steve at holdenweb.com Mon Aug 14 18:24:27 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 14 Aug 2006 23:24:27 +0100 Subject: help parsing this In-Reply-To: <1155557530.383959.241150@75g2000cwc.googlegroups.com> References: <1155557530.383959.241150@75g2000cwc.googlegroups.com> Message-ID: a wrote: > mx.DateTime.RangeError at /podcasts > Failed to parse "31 Apr 2006 20:19:00 -0400": day out of range: 31 > Python /usr/lib/python2.4/site-packages/mx/DateTime/Parser.py in > DateTimeFromString, line 608 > > how to parse this date > thanks > """ 30 days hath September APRIL, June and November All the rest have 31 Excepting February alone That has 29 days clear And 29 in each leap year """ regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From gagsl-py at yahoo.com.ar Tue Aug 29 03:26:57 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 29 Aug 2006 04:26:57 -0300 Subject: a question about my script In-Reply-To: <20060829065559.81733.qmail@web56505.mail.re3.yahoo.com> References: <20060829065559.81733.qmail@web56505.mail.re3.yahoo.com> Message-ID: <7.0.1.0.0.20060829041316.03da8e20@yahoo.com.ar> At Tuesday 29/8/2006 03:55, alper soyler wrote: >I am trying to get some files from an ftp site by ftplib module and >I wrote the below script. However I have a problem. With my script, >I login to ftp.genome.jp site. then, I am changing the directory to >pub/kegg/genomes/afm and I am downloading "a.fumigatus.pep" file. >However, what I want is to connect pub/kegg/genomes directory and in >this directory there are 3 letters name files 3 letters *files*? or 3 letters *directories*? >e.g. 'afm' and in each of these 3 letters files there is a file with >the extension of '.pep' like a.fumigatus.pep. I want to get these >'.pep' files from the 3 letter named files. If you help me I will be >very glad. Thanks you in advance. Do a cwd() starting one level above (that is, pub/kegg/genomes); using ftp.dir() you can get the subdirectories, then iterate over all of them, using another dir() to find the .pep files needed. >directory = 'pub/kegg/genomes/ afm' Is that whitespace intentional? (If you just want to download the files and don't need really a Python script, try wget...) Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From igowhari at gmail.com Thu Aug 17 16:00:14 2006 From: igowhari at gmail.com (iman gowhari) Date: 17 Aug 2006 13:00:14 -0700 Subject: FrontPage COM Object Model Message-ID: <1155844814.500920.213880@m79g2000cwm.googlegroups.com> I want to get frontpage web and page object models with this code. OnPageNew works properly but when I click on the page nothing happen. from win32com.client import DispatchWithEvents import time, pythoncom, msvcrt class FrontPageEvents: def __init__(self): print 'FrontPageEvents' def OnPageNew(self, page): DispatchWithEvents(f.ActiveDocument, PageEvents) class PageEvents: def __init__(self): print 'PageEvents' def onclick(self): print 'onclick' f=DispatchWithEvents("FrontPage.Application", FrontPageEvents) while not msvcrt.kbhit(): pythoncom.PumpWaitingMessages() time.sleep(.2) msvcrt.getch() From tim.peters at gmail.com Fri Aug 25 10:15:39 2006 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 25 Aug 2006 10:15:39 -0400 Subject: random writing access to a file in Python In-Reply-To: References: Message-ID: <1f7befae0608250715r4c6ee439nf39a5c86729283ca@mail.gmail.com> [Claudio Grondi] > I have a 250 Gbyte file (occupies the whole hard drive space) Then where is Python stored ;-)? > and want to change only eight bytes in this file at a given offset of appr. 200 > Gbyte (all other data in that file should remain unchanged). > > How can I do that in Python? Same way you'd do it in C, really: f = open(PATH_TO_FILE, "r+b") f.seek(appr. 200 Gbyte) f.write(A_STRING_CONTAINING_YOUR_NEW_8_BYTES) f.close() This depends on your operating system and file system and platform C library supporting seeks to very large offsets. For example, Windows using NTFS does. Try it. Python should complain (raise an exception during the seek() attempt) if your box refuses to cooperate. Use as recent a released version of Python as you can. From aisaac0 at verizon.net Sun Aug 27 23:49:35 2006 From: aisaac0 at verizon.net (David Isaac) Date: Mon, 28 Aug 2006 03:49:35 GMT Subject: Don't use __slots__ (was Re: performance of dictionary lookup vs. object attributes) References: <1156621904.481215.243080@m73g2000cwd.googlegroups.com> <1156625365.346825.18630@74g2000cwt.googlegroups.com> Message-ID: "Jacob Hallen" wrote in message news:ectbls$ofa$1 at gide.ita.chalmers.se... > Unfortunately there is a side effect to slots. They change the behaviour of > the objects that have slots in a way that can be abused by control freaks > and static typing weenies. This is bad, because the contol freaks should > be abusing the metaclasses and the static typing weenies should be abusing > decorators, since in Python,there should be only one obvious way of doing something. Can you please elaborate? (How to abuse metaclasses and decorators to achieve these effects? And why is it abuse?) Thank you, Alan Isaac From johnjsal at NOSPAMgmail.com Mon Aug 14 15:03:47 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 14 Aug 2006 19:03:47 GMT Subject: outputting a command to the terminal? In-Reply-To: <1155581272.460369.37810@b28g2000cwb.googlegroups.com> References: <44df99f7$0$25025$c3e8da3@news.astraweb.com> <44dfc1cb$0$2397$c3e8da3@news.astraweb.com> <1155580175.313400.136900@m79g2000cwm.googlegroups.com> <1155581272.460369.37810@b28g2000cwb.googlegroups.com> Message-ID: Simon Forman wrote: > Neat trick: man -k Ah, so much command line magic to learn! Maybe I should just go back to Windows....or maybe not. ;) From originalbrownster at gmail.com Sun Aug 20 16:49:22 2006 From: originalbrownster at gmail.com (OriginalBrownster) Date: 20 Aug 2006 13:49:22 -0700 Subject: uploading files to file system/zipping/downloading problems Message-ID: <1156106962.684908.311950@m73g2000cwd.googlegroups.com> I am currently uploading a file from a users computer to the file system on my server using python, just reading the file and writing the binaries. total_data=' ' while True: data = upload_file.file.read(8192) if not data: break total_data += data f = open(target_file_name, 'wb') f.write(total_data) f.close However when i download the file from the server it is not intact and it cannot be opened. It is happening with every type of file. It seemed to be working before and now it is..maybe I goofed up and deleted something. However I can't seem to find it. any ideas?? From aleax at mac.com Thu Aug 3 22:13:56 2006 From: aleax at mac.com (Alex Martelli) Date: Thu, 3 Aug 2006 19:13:56 -0700 Subject: Python open a named pipe == hanging? References: Message-ID: <1hjic95.ojxkeuodeqbtN%aleax@mac.com> Rochester wrote: > Hi, > > I just found out that the general open file mechanism doesn't work > for named pipes (fifo). Say I wrote something like this and it > simply hangs python: ...just as it would "hang" any other language...!-). Looks like you may not be fully cognizant of the semantics of fifos -- understandably, because the man pages on most systems are not too limpid on the subject. But there's a good one, e.g., at , and I selectively quote...: """ O_RDWR Open for reading and writing. The result is undefined if this flag is applied to a FIFO. """ (which means that your open with r+ _might_ cause the system to make demons fly out of your nose, according to e.g. ...:-); so, _don't_ use 'r+' to open your fifo. But, moreover...: """ O_NONBLOCK When opening a FIFO with O_RDONLY or O_WRONLY set: If O_NONBLOCK is set: An open() for reading only will return without delay. An open() for writing only will return an error if no process currently has the file open for reading. If O_NONBLOCK is clear: An open() for reading only will block the calling thread until a thread opens the file for writing. An open() for writing only will block the calling thread until a thread opens the file for reading. """ This last paragraph is the crucial one: the fundamental semantics of FIFOs in Unix is for the writing and reading processes (or more modernly "threads":-) to "rendezvous" around their respective calls to open (2), blocking until both of them reach the open point. The semantics in the nonblocking case(s) are somewhat weird (to my way of thinking, but then, my Unix background _is_ somewhat dated!-), but they wouldn't help you anyway, it seems to me -- looks like you'd like drastically different semantics (with neither open blocking, or just the reading one), but Unix just doesn't really offer them... Alex From paul at boddie.org.uk Tue Aug 29 08:12:13 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 29 Aug 2006 05:12:13 -0700 Subject: Pros/Cons of Turbogears/Rails? References: <1156726071.579429.44650@b28g2000cwb.googlegroups.com> <1156740469.645955.52080@i3g2000cwc.googlegroups.com> <1156768355.275370.129680@h48g2000cwc.googlegroups.com> <1156819473.592153.141940@i42g2000cwa.googlegroups.com> <1156842974.103231.86930@m73g2000cwd.googlegroups.com> <1156848642.090479.159740@p79g2000cwp.googlegroups.com> Message-ID: <1156853533.101407.232680@b28g2000cwb.googlegroups.com> Ray wrote: > > It can certainly make money--true. "Don't seek any meaning in what they > do"?! You're just accusing a lot of honest hardworking people to be > mindless drones there. We have feelings too, you know :( Well, I'm sorry for the unintentional insult. However, I've come to believe that some people have the personality traits that let them tolerate redoing the same work over and over again for no reason other than management "furniture rearranging", whereas others start to resent having their (working) life repeatedly flashed before their eyes, but in slightly different colours, over a longer period of time. If there's some kind of art that somehow increases tolerance of such things in a humane way, I'd be interested to know what it is. [...] > Well, I posted in this group a few weeks ago because I was trying to > convince the managers to give Python a try and was looking for > additional ammo. In the end Django is out because of its lack of > support for Oracle. But it's a catch 22 isn't it? In the end, provided you have the time and energy (or money) for it, you just have to make your own plan for bridging whatever gap there is in the functionality of whatever open source project you intend to employ professionally. I was once in a similar situation myself, with Oracle products as well, where I had to put in the work myself to get the necessary support needed for having my Python plus Oracle code working in an environment that was Python-sceptical at best. I guess the code was ultimately taken out of production, and everyone went over to a pure Java strategy, but you can't always infuence people by lobbying. > We're a Java shop so > our developers are trained in Java, Struts, Tomcat, etc. Any switch to > a dynamic language will be a huge change. However it baffles me that > they are open to at least a PoC in Rails. but when I suggested Python, > they went: "nah we're not interested in Python. Rails it is." > > *shrugs* whatever it is, those guys are doing something right. Making the Java people feel like they're doing something wrong, I guess. And perhaps the Rails people realised that by giving those people who lack direction, motivation, conviction or a sense of purpose or control something to gravitate towards, some of them might feel empowered enough to evangelise their discovery to the rest of the group. Paul From rpdooling at gmail.com Thu Aug 3 12:33:05 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 3 Aug 2006 09:33:05 -0700 Subject: What is the best way to print the usage string ? References: Message-ID: <1154622784.844584.180670@p79g2000cwp.googlegroups.com> Leonel Gayard wrote: > > Notice that the string messes the indentation in my script. The > indentation is correct, and if the script is invoked without > arguments, the usage string is printed correctly. > > Now, how can I achieve the same result while keeping a clean > indentation ? How is this done in python world ? In C, I would do > this: > The whitespace at the beginning of the string helps me keep the > indentation clean, and the construct "a" "b" is syntactic sugar that > allows me to create a large string without concatenating them at > runtime. > > How can I get this in Python ? Not sure exactly what you are after, but it sounds like you need the textwrap module: http://docs.python.org/lib/module-textwrap.html Or look at string formatting opeartions http://docs.python.org/lib/typesseq-strings.html rd : From neokosmos at gmail.com Thu Aug 10 23:06:32 2006 From: neokosmos at gmail.com (neokosmos at gmail.com) Date: 10 Aug 2006 20:06:32 -0700 Subject: Python share CPU time? In-Reply-To: <1155146500.063665.282430@p79g2000cwp.googlegroups.com> References: <1155146500.063665.282430@p79g2000cwp.googlegroups.com> Message-ID: <1155265592.225934.251190@75g2000cwc.googlegroups.com> Yannick wrote: > I would like to program a small game in Python, kind of like robocode > (http://robocode.sourceforge.net/). > Problem is that I would have to share the CPU between all the robots, > and thus allocate a time period to each robot. However I couldn't find > any way to start a thread (robot), and interrupt it after a given time > period. > Any suggestions on how to proceed? You've gotten a number of other suggestions from other posters. Let me suggest, though, as someone else has already beat me to, that programming the robots in Python might not be ideal. Without some significant work, you won't be able to prevent one of your "robots" from tying up your Python interpreter for arbitrary lengths of time. Consider, for example, a robot that executes the following line: x = 10 ** 10 ** 10 Now, if you're careful, you *can* prevent this sort of thing. My guess is, however, for a "small game," this effort is not going to be worth it. > Is Python just not adapted to this kind of things? That depends. I think Python would be a good choice of language to implement a custom VM for such a game, where you could have the level of control you need. Now, implementing a simple and limited-purpose VM really isn't as hard as it sounds. The hard part comes if you want to program your VM in anything other than its equivalent of Assembler. Then, you basically need to write a Language X -> VM compiler for whatever Language X you'd really like to program in, and that's generally not a trivial task. From jaywgraves at gmail.com Thu Aug 17 10:28:49 2006 From: jaywgraves at gmail.com (jay graves) Date: 17 Aug 2006 07:28:49 -0700 Subject: Read Picasa metadata using Python? In-Reply-To: <1155820764.151065.280770@i3g2000cwc.googlegroups.com> References: <1155820764.151065.280770@i3g2000cwc.googlegroups.com> Message-ID: <1155824929.576388.138510@i42g2000cwa.googlegroups.com> Thomas W wrote: > Anyway, if there are any other app allready reading Picasa metadata > with Flickr-support that you know of that would save me alot of > work/hassle. Still, Picasa is great, but I would really like access to > my own metadata outside Picasa and I want to use python to do it. I've looked at this in the past but I never got further than the exploration stage. I'm not at my home machine so this is from memory. I found all of the data in XML format in the Application Data folder in your personal directory. (i.e. C:\Documents and Settings\jgraves\Application Data\Google\Picasa (probably not exactly right)) Also there is a Google Groups for Picasa and it might have some pointers in the archives. http://groups.google.com/group/Picasa?lnk=gschg&hl=en Have fun! ... Jay Graves From paul at boddie.org.uk Mon Aug 14 11:42:06 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 14 Aug 2006 08:42:06 -0700 Subject: hide python code ! References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155300852.497741.73230@74g2000cwt.googlegroups.com> <1155301468.870340.82920@b28g2000cwb.googlegroups.com> <1155307415.855555.124760@i3g2000cwc.googlegroups.com> <1155309563.898182.195950@p79g2000cwp.googlegroups.com> <1155313092.743230.33950@m73g2000cwd.googlegroups.com> <1155320948.142524.124990@p79g2000cwp.googlegroups.com> <1155564295.361980.279350@m73g2000cwd.googlegroups.com> Message-ID: <1155570126.905733.137850@m79g2000cwm.googlegroups.com> Ben Sizer wrote: > Paul Boddie wrote: > > Ben Sizer wrote: > > > > > > Imagine if you were the single-person developer of a small application > > > that did something quite innovative, and charged a small fee for your > > > product. Now imagine you were practically forced to make your algorithm > > > obvious - a couple of months later, Microsoft bring out a freeware > > > version and destroy your business in an instant. Sure, they and others > > > can (and have) done that with closed-source products, but you increase > > > your chances of survival 10-fold if the key algorithms are not obvious. > > > > This point is fairly comprehensively answered in the following article: > > > > http://radar.oreilly.com/archives/2006/08/apple_eats_whiners.html > > I don't believe so. Well, it talks about competing against some large business who will eventually emulate your work. The advantage of small businesses competing against anyone with a fairly rigid schedule and an arguably non-agile internal organisation is that there will be a certain amount of time before that large business firstly gets round to dismantling your product (as opposed to that of the other small competitors), secondly manages to produce something which does more or less the same thing, and thirdly is able to bring it to market with the same level of quality/branding that its customers expect. Successful software businesses are not merely founded on the process of having ideas and implementing them - they might also need to be effective at delivering those ideas and going through the whole process again and again. Writing a neat utility for Windows is not by itself the foundation of a successful business - other factors are critical, whether they be continuous improvements, service, support, or a number of other things. > That talks about copying of ideas, which is quite > distinct from copying of implementations. The distinction may be > meaningless in your typical desktop app where implementation is usually > obvious from the interface. However in more high-tech systems such as > multimedia or AI, the same is far from true. Well, let's say that algorithms are a step up from mere ideas, and let's also say that actual code is a step up from mere descriptions of algorithms (since actual code serves to verify the behaviour of those algorithms). The article I mention states that people shouldn't expect to be rewarded forever for dreaming up some idea, and I extend that point by stating that people shouldn't expect to be rewarded forever for describing an algorithm - both of these things being patentable in various permissive patent regimes, which (in conjunction with a few other factors) really is quite harmful for anyone actually doing work in any of the affected lines of work. So, if we decide to ignore people waving pieces of paper around which make some claim to an idea or some way of solving some problem, instead investigating the actual code, others have pointed out already that if you provide just a binary and there exist people who want to know what you've done, those people will find it out whether you make it easy for them or not. Now, if we sidestep the issue of decompiling binaries and cast the affected work as some kind of service, the question can now be expressed as whether you should expect to be rewarded forever for providing such a service. This brings in a number of issues that are suddenly more apparent than in the case where the end-user has some binary - notably the issue of control over the activity that the service performs - and such issues could possibly increase competitive pressure rather than enhance any supposed competitive advantage if people felt that the market wasn't providing enough in the way of choice in that area. > > I read an article where various aging popular musicians were > > lobbying the British government to extend the period of copyright > > beyond 50 years because their first works would soon fall into the > > public domain and that they'd no longer earn royalties on those works. > > But in what percentage of the many other jobs that exist do you still > > get paid for a day at work that happened over 50 years ago? > > However, in most of those jobs you get paid properly at the time. Aside > from the 1% of musicians who are pop stars, musicians generally do not. The article I read was in the paper edition of the newspaper in question, but here's a fairly similar electronic version: http://www.telegraph.co.uk/news/main.jhtml?xml=/news/2006/03/29/nroyal29.xml&sSheet=/news/2006/03/29/ixhome.html I don't doubt that sessions musicians are paid badly, but multiplying every musician's income by a certain factor doesn't necessarily represent a just solution to that issue. > I'm not saying I agree with extending the copyright period, however I > do think you can't just compare it to 'a day at work'. It's a totally > different set of circumstances which requires a different set of rules > to both encourage artists to continue creating while benefitting > society in the long run too. For some of those musicians (ie. probably not Sir Cliff Richard), it probably was a day at work for which they were badly paid, whilst others (eg. Sir Cliff Richard) went on to make quite a bit of money. Of course, one can always argue that the result of this particular kind of day at work is something that can be enjoyed again and again, but then you should consider the issue of why the person working at the car factory doesn't get paid royalties every time you turn the key in the ignition (even if it's just $0.0001 each time). Paul From dwai.lahiri at gmail.com Fri Aug 18 10:25:12 2006 From: dwai.lahiri at gmail.com (implicate_order) Date: 18 Aug 2006 07:25:12 -0700 Subject: Creating Charts in Excel with pyExcelerator.ExcelMagic In-Reply-To: <1155665828.595235.214360@75g2000cwc.googlegroups.com> References: <1155665828.595235.214360@75g2000cwc.googlegroups.com> Message-ID: <1155911112.777767.123500@75g2000cwc.googlegroups.com> Gentlemen, Thanks for your responses. I also found some additional threads on this newsgroup that gave me insight into how to use the MS Excel com objects (or whatever they are called)... So I used this: xl = win32com.client.Dispatch("Excel.Application") wb = xl.Workbooks.Open(outfile01) prodws = wb.Worksheets(1) wc_prod = wb.Charts.Add() wc_prod.ChartWizard(Source=prodws.Range("b1", "g30"), Gallery=11, Format=5, CategoryLabels=3, SeriesLabels=3, PlotBy=None, Title="Prod" ) Does a pretty decent job of creating charts (we can change the chart type by changing the Gallery and Format values) So I use pyExcelerator to generate the workbook with various worksheets and then use win32com.client to generate the charts. From rogue_pedro at yahoo.com Mon Aug 28 02:03:29 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 27 Aug 2006 23:03:29 -0700 Subject: newbe question about removing items from one file to another file In-Reply-To: <1156714534.318183.326220@i3g2000cwc.googlegroups.com> References: <1156714534.318183.326220@i3g2000cwc.googlegroups.com> Message-ID: <1156745009.227818.317620@74g2000cwt.googlegroups.com> Eric_Dexter at msn.com wrote: > def simplecsdtoorc(filename): > file = open(filename,"r") > alllines = file.read_until("") > pattern1 = re.compile(" orcfilename = filename[-3:] + "orc" > for line in alllines: > if not pattern1 > print >>orcfilename, line > > I am pretty sure my code isn't close to what I want. I need to be able > to skip html like commands from to and to key on > another word in adition to to end the routine > > I was also looking at se 2.2 beta but didn't see any easy way to use it > for this or for that matter search and replace where I could just add > it as a menu item and not worry about it. > > thanks for any help in advance If you're dealing with html or html-like files, do check out beautifulsoup. I had reason to use it the other day and man is it ever useful! Meantime, there are a few minor points about the code you posted: 1) open() defaults to 'r', you can leave it out when you call open() to read a file. 2) 'file' is a builtin type (it's the type of file objects returned by open()) so you shouldn't use it as a variable name. 3) file objects don't have a read_until() method. You could say something like: f = open(filename) lines = [] for line in f: lines.append(line) if '' in line: break 4) filename[-3:] will give you the last 3 chars in filename. I'm guessing that you want all but the last 3 chars, that's filename[:-3], but see the os.path.splitext() function, and indeed the other functions in os.path too: http://docs.python.org/lib/module-os.path.html 5) the regular expression objects returned by re.compile() will always evaluate True, so you want to call their search() method on the data to search: if not pattern1.search(line): But, 6) using re for a pattern as simple as ">orcfilename, line else: print >>orcfilename, line[:pos] 7) the "print >> file" usage requires a file (or file-like object, anything with a write() method I think) not a string. You need to use it like this: orcfile = open(orcfilename, 'w') #... print >> orcfile, line 8) If you have a list of lines anyway, you can use the writelines() method of files to write them in one go: open(orcfilename, 'w').writelines(lines) of course stripping out your unwanted data from that last line using find() as shown above. I hope this helps. Check out the docs on file objects: http://docs.python.org/lib/bltin-file-objects.html, but like I said, if you're dealing with html or html-like files, be sure to check out beautifulsoup. Also, there's the elementtree package for parsing XML that could help here too. ~Simon From vito.detullio at gmail.com Wed Aug 9 05:25:30 2006 From: vito.detullio at gmail.com (ZeD) Date: Wed, 09 Aug 2006 09:25:30 GMT Subject: #!/usr/bin/python or #!/usr/bin/env python? References: Message-ID: Erik Max Francis wrote: > The file _is_ a /bin/sh executable. You're just having that /bin/sh > executable run something else -- how could `file` figure that out > without a ridiculously complicated set of rules that rise to the level > of a sh interpreter -- thereby, defeating the purpose? but... $ cat test.py #!/usr/bin/env python print "Hello, world" $ file test.py file.py: a python script text executable following what you said, test.py is a /usr/bin/env script, not a python one. -- Under construction From fredrik at pythonware.com Wed Aug 23 15:06:11 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Aug 2006 21:06:11 +0200 Subject: Python + Java Integration In-Reply-To: <1156347822.349659.147270@75g2000cwc.googlegroups.com> References: <1156347822.349659.147270@75g2000cwc.googlegroups.com> Message-ID: Ben Sizer wrote: > Java itself never deserved to be the 'next' anything anyway. I've had a lot of developers come up to me and say, "I haven't had this much fun in a long time. It sure beats writing Cobol" -- James Gosling From antroy at gmail.com Wed Aug 16 10:38:54 2006 From: antroy at gmail.com (Ant) Date: 16 Aug 2006 07:38:54 -0700 Subject: Memory usage of an 'empty' python interpreter In-Reply-To: <1155716926.343428.263870@h48g2000cwc.googlegroups.com> References: <1155710349.127768.17280@h48g2000cwc.googlegroups.com> <1155715912.930984.207150@i42g2000cwa.googlegroups.com> <1155716926.343428.263870@h48g2000cwc.googlegroups.com> Message-ID: <1155739133.958790.319420@b28g2000cwb.googlegroups.com> > > Are you sure ps is reporting in bytes not KB? The bare interpreter in > > Windows is 3368KB. > > Where did you get that from? With Python 2.4.3, on my machine (Win XP > SP2): > > C:\junk>dir \python24\python* > [snip] > 29/03/2006 05:35 PM 4,608 python.exe > 29/03/2006 05:35 PM 1,871,872 python24.dll > 29/03/2006 05:35 PM 5,120 pythonw.exe He's asking for the memory required, not the disk space used by the exe. The 3368KB is reported by the Task Manager. From alistair.king at helsinki.fi Fri Aug 4 06:16:42 2006 From: alistair.king at helsinki.fi (Alistair King) Date: Fri, 04 Aug 2006 13:16:42 +0300 Subject: help - iter & dict In-Reply-To: <1154640029.488670.283430@b28g2000cwb.googlegroups.com> References: <1154640029.488670.283430@b28g2000cwb.googlegroups.com> Message-ID: <44D31E8A.4000003@helsinki.fi> Simon Forman wrote: > aking at mappi.helsinki.fi wrote: > >> Dear Python people, >> >> im a newbie to python and here...so hello! >> > > Hi Ali, and welcome. > > >> Im trying to iterate through values in a dictionary so i can find the >> closest value and then extract the key for that value....what ive done so far: >> >> def pcloop(dictionary, exvalue): >> z = dictionary.itervalues() >> y = z - exvalue >> v = (y*y)**1/2 >> if v < 0.001: >> u = dictionary.get[z] >> return u >> >> >> ive been working off a couple of books and this is the best i can get it in >> short time. I was trying to define a function (its my first!) so that i >> could apply to several 'dictionary's and 'exvalue's. The best ive been able >> to come up with is iterating over the dictionary values, subtracting the >> exvalue, squaring then root squaring to render positive and applying an >> error (0.001) which is not the ideal solution i want. Is there any easy way >> to iterate through dictionary values and return the key for the minimum. Or >> can someone tell me where im going wrong with this def & loop. >> >> regards all >> >> Ali >> > > You're doing many interesting things wrong here. :-) I'm going to > take them slightly out of order. > > First, very ingenious way to get the absolute value of a number, but > there are a few issues with this that you should know about. > > For instance, just as multiplication and division take precedence over > addition and subtraction, the "power" operator ** take precedence over > division, so what you're really doing above is > > ((y*y)**1)/2 > > rather than > > (y*y)**(1/2) > > However, the above still wouldn't work correctly because of the way > python handles integer division. 1/2 == 0 in python, try it at the > interactive prompt and you'll see. > > So, you'd have to change at least one of the division's operands to > float to get the proper result you desire. > > (y*y)**(1./2) > > Except that you should actually use the (built in) abs() function, > > v = abs(y) > > :-) > > Next, the itervalues() method of dicts does not return a number, but > rather a "dictionary-valueiterator" object, as you can see from this: > > |>> d = {} > |>> z = d.itervalues() > |>> z > > > In order to get values out of it you need to iterate over it like so: > > for z in d.itervalues(): > # Do something with z's here... > > You could also get both the keys and values at the same time by > iterating like so: > > for k, z in d.iteritems(): > # Do something with k's and z's here... > > (I'll come back to that.) > > Now, a little further down in your function, you seem to want to use > the z value with the get() method of the dict to retrieve the key. > This won't work. > > First, you're not *calling* the get method (that uses ()'s) you're > *subscripting* it (that uses []'s.) If your code got this far, it > would break here. > > | > > In fact, there is no easy way to get the key from a dict given a value. > Dicts work the other way around. (You basically have to iterate > through the values *and* keys, one pair at a time, testing each value > as you go. This is very slow, compared to getting the value given a > key.) > > value = d[key] > > This is extremely fast. It's pretty much the whole point of a > dictionary that this is very fast. > > So, when you build the dict that you pass in to your function, you > might want to build it the other way round, i.e. make the keys the > values and the values keys. However, you might not and here's why: > > Dicts can only have one key of any given value of key. Look: > > |>> d = {1: 'a', 1: 'b'} > |>> d > {1: 'b'} > |>> d = {'a': 1, 'b': 1} > |>> d > {'a': 1, 'b': 1} > > So, if you're running a mathematical function on a range of input (x's) > and storing the results (y's) as values in a dict, then you *do* want > the x's to be the keys and the y's to be the values. > > I'm guessing that's what you're doing, and if so, you're doing it > correctly. > > [this is what i want but am not sure its correct] > So, given a dict and an exvalue, how to return the key corresponding > to the value that's closest to exvalue? > > here goes... > > thanks simon for this, it seems a little easier to understand for me but i still get the error when i run the script: #here is a sample dictionary from the 1000 key:values normally in it. they are all non zero and values to 15 decimal places CDSitdict = {32.030822391220937: "'1.3679999999999874'", 29.150765445901769: "'2.2079999999999727'", 27.930109636681877: "'2.744999999999993'", 28.590095427450688: "'2.4359999999999813'", 27.595161357952588: "'2.9219999999999997'", 29.961761413410386: "'1.9229999999999674'", 36.311798000222424: "'0.66300000000000048'", 34.358611987430052: "'0.93300000000000072'", 41.199188199569292: "'0.20400000000000013'", 29.560651138651014: "'2.057999999999967'"} #i have tried to format the numerical key into the dictionary to give a string using %s but it didnt work so eventually i used # #itera = "\'" + `DSit` + "\'" #CDSitdict[Cpcmax] = itera # #i am now wondering if i have been trying to iterate through the key value pairs, does the numerical part im trying to iterate over have to be the value #side or can it be any side? #here is a sample exvalue Cpcb = 33.94 ************************************************** def pcloop(dictionary, exvalue): ''' Return the key in dictionary whose value is closest to exvalue. If dictionary is empty, return None. ''' # Get a iterator over *both* keys and values. diter = dictionary.iteritems() # Get the first (key, value) pair. try: u, z = diter.next() except StopIteration: # The dictionary was empty! # You might want to do something else here return # Compute the closeness of the first value. closest = abs(z - exvalue) # Create a var to store the closest key result = u # Iterate through the rest of the dict. for u, z in diter: # Compute the closeness. v = abs(z - exvalue) # Check if it's closer than the closest. if v < closest: # If so, store the new closest. closest = v # And store the new closest key. result = u return result Cpcb = input("\n\nPlease enter the carbon percentage value obtained from the microanalysis. If none, enter 0: ") print"\n\nCellulose Carbon Percentage is " + `Cpca` + "\n\nMaximum potential monomer carbon weight is " + `Cwmax` + "\n\nMaximum potential carbon percentage is " + `Cpcmax` + "\n\nPercentage difference between Cellulose and Maximum is " + `Cdiff` + "\n\n" exvalue = Cpcb dictionary = CDSitdict CDS = pcloop(dictionary, exvalue) **************************************** error is: Traceback (most recent call last): File "elementalDS.py", line 184, in ? CDS = pcloop(dictionary, exvalue) File "elementalDS.py", line 158, in pcloop closest = abs(z - exvalue) TypeError: unsupported operand type(s) for -: 'str' and 'float' :( ali -- Dr. Alistair King Research Chemist, Laboratory of Organic Chemistry, Department of Chemistry, Faculty of Science P.O. Box 55 (A.I. Virtasen aukio 1) FIN-00014 University of Helsinki Tel. +358 9 191 50429, Mobile +358 (0)50 5279446 Fax +358 9 191 50366 From nevillednz at gmail.com Tue Aug 15 21:38:49 2006 From: nevillednz at gmail.com (NevilleDNZ) Date: 15 Aug 2006 18:38:49 -0700 Subject: proc A def/calls proc B: variable scoping rules. In-Reply-To: References: <1155685233.002415.184150@74g2000cwt.googlegroups.com> Message-ID: <1155692329.075173.49060@p79g2000cwp.googlegroups.com> Steve Holden wrote: > Hardly surprising. This statement is an assignment to x2, which > therefore becomes local to the function. Since no previous value has > been assigned to this local, the exception occurs. But: In this case the assignment is never reached.... eg.. #!/usr/bin/env python def A(): print "begin A:" x1=123 x2=456 def B(): print "begin B:",x1,x2 if False: x2 = x2 + 210 # Magically disappears when this line is commented out. print "end B:",x1,x2 print "pre B:",x1,x2 B() print "end A:",x1,x2 A() # same error message... $ ./x1x2.py begin A: Pre B: 123 456 begin B: 123 Traceback (most recent call last): File "./x1x2.py", line 13, in A() File "./x1x2.py", line 11, in A B() File "./x1x2.py", line 7, in B print "begin B:",x1,x2 UnboundLocalError: local variable 'x2' referenced before assignment I guess it is something to do with the scoping of duck typing. I WAS expecting that the A.x2 was visable until x2 is somehow (by assignment) made local. I guess I am learning that what you do to a variable in the middle of scope (even in an unreachable statement) effects the entire scope. Is there anyway to force x2 to be A.x2 (without declaring it to be a global.x2)? Maybe I can put it into a A.local class... The result sh/could be: begin A: pre B: 123 456 begin B: 123 456 end B: 123 666 end A: 123 666 ThanX NevilleD From aleax at mac.com Mon Aug 21 00:10:32 2006 From: aleax at mac.com (Alex Martelli) Date: Sun, 20 Aug 2006 21:10:32 -0700 Subject: write eof without closing References: <12eeala1klcrtcf@corp.supernews.com> <12ei9r2c134tr32@corp.supernews.com> Message-ID: <1hkdzxu.120yyqo10acpqlN%aleax@mac.com> Grant Edwards wrote: ... > IIRC, ctrl-Z is not used _in_files_ to represent EOF. Only > when text is being entered at the console. Easy to test, if you have Windows: >>> n='foo.txt' >>> s='ba\r\n'+chr(26)+'bo\r\r' >>> open(n,'wb').write(s) >>> ss=open(n).read() >>> ss 'ba\n' As you see, in _text_ files on Windows a control-Z (char(26), AKA '\x1a') does indeed represent "end of file" -- a convention going back to CP/M (which lacked metadata to represent file length except in multiples of 256 characters, if I recall correctly) and is still followed by Windows (and by Python running on Windows). Nevertheless I doubt it would help the original poster -- I think, like /F and you, that a line-end and flush may be what he needs. Alex From timothy.grant at gmail.com Fri Aug 25 13:28:29 2006 From: timothy.grant at gmail.com (Timothy Grant) Date: Fri, 25 Aug 2006 10:28:29 -0700 Subject: ANN: DMetaph.py An implementation of the Double Metaphone algorithm Message-ID: Hello everyone, I recently had a need to do some work with fuzzy matches, so I ported Lawrence Philips DMetaph class from C++ to Python. This is currently pretty much a line for line port of his his C++ code. It is not very pythonic at all. Because it is SO ugly, I'm not yet making it available for download, but am making it available on request. I hope to clean it up significantly and make it far more pythonic in the near future. -- Stand Fast, tjg. From dpeschel at eskimo.com Wed Aug 23 05:52:31 2006 From: dpeschel at eskimo.com (Derek Peschel) Date: 23 Aug 2006 09:52:31 GMT Subject: Finding the type of indexing supported by an object? Message-ID: Here are two functions. def invert_dict_to_lists(dict): lists = {} for key in dict: value = dict[key] if not value in lists: lists[value] = [key] else: lists[value].append(key) return lists def invert_list_to_lists(list): lists = {} for key in range(len(list)): value = list[key] if not value in lists: lists[value] = [key] else: lists[value].append(key) return lists They are the same except for the expression in "for key in ...". Can they be combined into one function? How can I determine if the argument is like a list (with numeric indices that are not stored in the list) or a dict (with arbitrary keys that are stored)? I said "object" in the subject, but I want to support Python primitive types, class instances, extension module types (array, dictproxy, dbm, gdbm, etc.), and any future types. I've thought about looking for keys(), looking for the special method names that allow you to override indexing behavior, and looking at the class or type of the object. I could be wrong, but I don't think any of those strategies will work with all arguments. Thanks, -- Derek From thomasasta at gmx.net Tue Aug 22 10:39:22 2006 From: thomasasta at gmx.net (thomasasta at gmx.net) Date: Tue, 22 Aug 2006 16:39:22 +0200 Subject: bit-torrent client code open source in Python written Message-ID: <20060822143922.18940@gmx.net> Hey there is a new python written open source bit-torrent client out. Don?t mit it up with brams c++ bittorrent, in python it is bit-torrent.sf.net Don?t forget the minus - http://bit-torrent.sourceforge.net/ It?s out till 10 days and the code is open source, so you can add it to any other application in python like CyberSpace or any other app ! ;-)) Btw: does anyone know a pyhton written kedamlia client for the emule network or any other kademlia function ? Kind regards... -- "Feel free" ? 10 GB Mailbox, 100 FreeSMS/Monat ... Jetzt GMX TopMail testen: http://www.gmx.net/de/go/topmail From fredrik at pythonware.com Mon Aug 28 18:16:24 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 29 Aug 2006 00:16:24 +0200 Subject: Max OSX and Excel In-Reply-To: References: <32822fe60608281500l762b61ddqc6f3300ec1e296a6@mail.gmail.com> Message-ID: Johanna Pfalz wrote: > To be more specific, I'm interested in reading in certain rows and columns > from an excel spreadsheet directly without converting the information to a > text file. I'd also like to be able to write directly to an excel > spreadsheet from python. tried http://sourceforge.net/projects/pyexcelerator ? From meyer at acm.org Mon Aug 28 03:56:58 2006 From: meyer at acm.org (Andre Meyer) Date: Mon, 28 Aug 2006 09:56:58 +0200 Subject: Pros/Cons of Turbogears/Rails? In-Reply-To: References: <1156726071.579429.44650@b28g2000cwb.googlegroups.com> <1156740469.645955.52080__9194.07857950336$1156740696$gmane$org@i3g2000cwc.googlegroups.com> <1156748398.870837.13690@p79g2000cwp.googlegroups.com> Message-ID: <7008329d0608280056p6513ce15r8fc1d93a9287fb6d@mail.gmail.com> Hi all It might be interesting to watch the videos about Django and Rails ( http://www.djangoproject.com/snakesandrubies/). Django makes a good impression, although I would not agree with all of their arguments (eg. templating language, ajax). Most striking, though, is the difference in attitude! While Django grew out of a production environment and solves real problems very elegantly, Rails comes "out of beauty", whatever that means. Is Ruby code more beautiful than Python - don't think so. Nevertheless, I agree with original statement that we Python guys need to look very closely at Ruby and why they are able to catch so much attention. There are good things in the language and Python marketing could certainly be improved. The new web site and logo are good steps in the right direction. Now for free t-shirts to create pervasive awareness? ;-) regards Andre -------------- next part -------------- An HTML attachment was scrubbed... URL: From mahs at telcopartners.com Thu Aug 17 19:40:54 2006 From: mahs at telcopartners.com (Michael Spencer) Date: Thu, 17 Aug 2006 16:40:54 -0700 Subject: Optimizing Inner Loop Copy In-Reply-To: References: Message-ID: Mark E. Fenner wrote: > > and the copy is taking the majority (42%) of my execution time. > So, I'd like to speed up my copy. I had an explicit copy method that did > what was needed and returned a new object, but this was quite a bit slower > than using the standard lib copy.copy(). > How are you measuring? It seems to me that your Rule.copy method is a lot faster than copy.copy: >>> r= Rule(range(100)) >>> shell.timefunc(r.copy) 'copy(...) 36458 iterations, 13.71usec per call' >>> from copy import copy >>> shell.timefunc(copy, r) 'copy(...) 4498 iterations, 111.17usec per call' >>> where shell.timefunc is: def _get_timer(): if sys.platform == "win32": return time.clock else: return time.time return def timefunc(func, *args, **kwds): timer = _get_timer() count, totaltime = 0, 0 while totaltime < 0.5: t1 = timer() res = func(*args, **kwds) t2 = timer() totaltime += (t2-t1) count += 1 if count > 1000: unit = "usec" timeper = totaltime * 1000000 / count else: unit = "msec" timeper = totaltime * 1000 / count return "%s(...) %s iterations, %.2f%s per call" % \ (func.__name__, count, timeper, unit) Michael From rgelfand2 at hotmail.com Tue Aug 29 11:58:34 2006 From: rgelfand2 at hotmail.com (Roman) Date: 29 Aug 2006 08:58:34 -0700 Subject: RE Module In-Reply-To: <44f3262e$0$8896$88260bb3@free.teranews.com> References: <1156478366.165463.277480@h48g2000cwc.googlegroups.com> <44ef3f95$0$8926$88260bb3@free.teranews.com> <1156539112.253232.321820@i3g2000cwc.googlegroups.com> <44ef5ba7$0$8907$88260bb3@free.teranews.com> <44ef6207$0$8914$88260bb3@free.teranews.com> <1156645334.603909.167010@i3g2000cwc.googlegroups.com> <44f3262e$0$8896$88260bb3@free.teranews.com> Message-ID: <1156867114.409645.139220@74g2000cwt.googlegroups.com> It turns out false alarm. It work. I had other logic in the expression involving punctuation marks and got all confused with the escape characters. It becomes a mess trying to keep track of all the reserved character as you are going from module to module. tobiah wrote: > Roman wrote: > > I looked at a book called beginning python and it claims that <.*?> is > > a non-greedy match. > > Yeah, I get that now, but why didn't it work for you in > the first place? > > -- > Posted via a free Usenet account from http://www.teranews.com From nephish at gmail.com Sun Aug 6 22:13:19 2006 From: nephish at gmail.com (nephish) Date: 6 Aug 2006 19:13:19 -0700 Subject: easy question about join method In-Reply-To: <87r6zt4848.fsf@gmail.com> References: <1154914663.090280.55700@b28g2000cwb.googlegroups.com> <87r6zt4848.fsf@gmail.com> Message-ID: <1154916799.486267.271920@h48g2000cwc.googlegroups.com> yep, easy enough thanks -shawn Jorge Godoy wrote: > "nephish" writes: > > > i have seen the join method before, mostly in this group and i want to > > get it a little better. > > > > if i have a list > > > > x = ['this','is','a','sentence','held','in','a','list'] > > > > how can i make it print as a single string? or make a single string out > > of it ? > > print ' '.join(x) > > -- > Jorge Godoy From you at cogeco.ca Thu Aug 31 14:56:23 2006 From: you at cogeco.ca (AlbaClause) Date: Thu, 31 Aug 2006 14:56:23 -0400 Subject: python loops References: <1157050085.120921.31840@h48g2000cwc.googlegroups.com> Message-ID: Putty wrote: > In C and C++ and Java, the 'for' statement is a shortcut to make very > concise loops. In python, 'for' iterates over elements in a sequence. > Is there a way to do this in python that's more concise than 'while'? > > C: > for(i=0; i > > python: > while i < length: > i += 1 for i in range(length): print i -- -- There are several things that I will never be: * I will never be attracted to females. * I will never enjoy the company of others. Exactly how these realities bode for my enemy, is not of my concern. From riko at despammed.com Wed Aug 23 02:52:53 2006 From: riko at despammed.com (Mc Osten) Date: Wed, 23 Aug 2006 08:52:53 +0200 Subject: Python and STL efficiency References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <1hkh28d.xscw4v1y4v9a6N%riko@despammed.com> <1hkh6lb.6dsnh51lj8z96N%riko@despammed.com> <1156252193.524186.107520@b28g2000cwb.googlegroups.com> <1156299389.336939.211670@i42g2000cwa.googlegroups.com> <1156300663.405909.39350@74g2000cwt.googlegroups.com> Message-ID: <1hkil7z.dex1g6h2p4ltN%riko@despammed.com> Ray wrote: > Not really, see my test, in my other post in the same thread. I'm using > VC++ Express 2005. If we're comparing with Python 2.5 I think it's just > fair that for C++ we're using the latest as well. In your test, you are looping 10000 times, we looped 1000000. In Python tests with 10000 elements, it was about 10 ms. Moreover, we tried various Python and C++ configurations. Most of the tests are done with Python 2.4, not 2.5. And I used gcc4, that is to say the latest on my platform. > Same here, although that said Python's implementation of those data > structure must already be as optimal as mortals can do it. I think this is the rationale behind it. -- blog: http://www.akropolix.net/rik0/blogs | Uccidete i filosofi, site: http://www.akropolix.net/rik0/ | tenetevi riso e forum: http://www.akropolix.net/forum/ | bacchette per voi. From riteshsarraf at gmail.com Fri Aug 4 03:26:27 2006 From: riteshsarraf at gmail.com (Ritesh Raj Sarraf) Date: 4 Aug 2006 00:26:27 -0700 Subject: Thread Question In-Reply-To: <1154613366.350191.81880@m73g2000cwd.googlegroups.com> References: <1153998422.670828.148360@m79g2000cwm.googlegroups.com> <1154019801.999805.150000@m73g2000cwd.googlegroups.com> <1154544553.990241.280030@i3g2000cwc.googlegroups.com> <1154590917.731457.106230@s13g2000cwa.googlegroups.com> <1154613366.350191.81880@m73g2000cwd.googlegroups.com> Message-ID: <1154676387.063576.100570@i42g2000cwa.googlegroups.com> Carl Banks wrote: > If you have multiple threads trying to access the same ZIP file at the > same time, whether or not they use the same ZipFile object, you'll have > trouble. You'd have to change download_from_web to protect against > simultaneous use. A simple lock should suffice. Create the lock in > the main thread, like so: > > ziplock = threading.Lock() > Thanks. This looks to be the correct way to go. I do have access to all the source code as it is under GPL. > Then change the zipping part of download_from_web to acquire and > release this lock; do zipfile operations only between them. > > ziplock.acquire() > try: > do_all_zipfile_stuff_here() > finally: > ziplock.release() > I hope while one thread has acquired the lock, the other threads (which have done the downloading work and are ready to zip) would wait. > If you can't change download_from_web, you might have no choice but to > download sequentially. > > OTOH, if each thread uses a different ZIP file (and a different ZipFile > object), you wouldn't have to use a lock. It doesn't sound like you're > doing that, though. > > It shouldn't be a problem if one thread is zipping at the same time > another is downloading, unless there's some common data between them > for some reason. > > Thanks, Ritesh From fredrik at pythonware.com Sun Aug 27 11:13:43 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 27 Aug 2006 17:13:43 +0200 Subject: How to let a loop run for a while before checking for break condition? In-Reply-To: <4ldovvF1dgtrU1@uni-berlin.de> References: <4ldfp0F1csmpU1@uni-berlin.de> <4ldiacF1ckeeU1@uni-berlin.de> <4ldovvF1dgtrU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > No doubt that changing the flag asynchronously is a gain by delegating > the timing code to the OS. Yet the while loop still has a condition - > you could as well set a flag in the signal handler an do it like this: if the OP is obsessed with performance, why are you arguing that he "could as well" use a slower solution ? > This is on my machine about 1.5 times slower than func1, but much more > readable polling a global state flag being "much more readable" than handling an exception in the usual way? surely you're joking. are you sure you're posted the code you're writing about, btw. that "or True" looks a bit suspicious. From harald_karner at a1.net Mon Aug 21 06:52:59 2006 From: harald_karner at a1.net (Harald Karner) Date: Mon, 21 Aug 2006 12:52:59 +0200 Subject: Detect current virtual desktop In-Reply-To: References: Message-ID: Maciej Blizi?ski wrote: > How to detect current virtual desktop in GNOME? How to detect a virtual > desktop change? > Take a look at http://wallpapoz.sourceforge.net/ Harald From fredrik at pythonware.com Mon Aug 28 06:18:30 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 28 Aug 2006 12:18:30 +0200 Subject: Starting up the server References: <1156757061.162827.301260@h48g2000cwc.googlegroups.com> <1156759099.329337.238190@m73g2000cwd.googlegroups.com> Message-ID: "john Perry" wrote: >> what server? what software are you using? > > TurboGears 0.8.9,python 2.53 and using sql server have you checked the TurboGears mailing list archives ? From pDOTpagel at gsf.de Wed Aug 30 09:06:34 2006 From: pDOTpagel at gsf.de (Philipp Pagel) Date: Wed, 30 Aug 2006 13:06:34 +0000 (UTC) Subject: where or filter on list References: <1156939493.558819.8410@i42g2000cwa.googlegroups.com> Message-ID: charles.hebert at gmail.com wrote: > Can anybody tell me how to to find the nearest value to zero in a > list? > >>> foo = [-5,-1,2,3] # nearest value to zero ? > >>> [value for value in foo if math.fabs(value) == min([int(math.fabs(x)) for x in foo])] > [-1] > Something simpler ? Maybe something like this: mindist = min(map(abs, foo)) filter(lambda x: abs(x) == mindist, a)[0] Only annoyance: we compute abs twice for each value. We could probably avoid that by using reduce() and a suitable function... > How to extend this function to any given value ? By subtracting the desired value from foo. cu Philipp -- Dr. Philipp Pagel Tel. +49-8161-71 2131 Dept. of Genome Oriented Bioinformatics Fax. +49-8161-71 2186 Technical University of Munich http://mips.gsf.de/staff/pagel From limodou at gmail.com Wed Aug 23 04:07:06 2006 From: limodou at gmail.com (limodou) Date: Wed, 23 Aug 2006 16:07:06 +0800 Subject: [ANN]UliPad 3.3 is released Message-ID: What's it? ======== It's an Editor based on wxPython. NewEdit is the old name, and UliPad is the new name. UliPad uses Mixin and Plugin technique as its architecture. Most of its classes can be extended via mixin and plugin components, and finally become an integrity class at creating the instance. So UliPad is very dynamic. You can write the new features in new files, and hardly need to modify the existing code. And if you want to extend the existing classes, you could write mixins and plugins, and this will be bound to the target class that I call "Slot Class". This technique will make the changes centralized and easily managed. What are its features? ================ * Cross platform o based on wxPython, so it can run anywhere that wxPython works, such as: Windows, Linux. o Unicode support. * Most features of wxStyledTextCtrl(Scintilla) o Syntax highlighting, support Python, c/c++, html, plain text, perl, ruby, css, javascript o Folding o Brace Matching o ... * Extended selection o Extended word selection -- You can press Ctrl+MouseDoubleClick to select a word including '.' o Matched selection -- Select text in quoted chars like: (), [], {}, '', "". * Other editing extension o Duplicating text -- Just like Vim Ctrl+V, Ctrl+P, and more. You can duplicate above or below char, word, line o Quoting text -- Add some quoted chars before and after selected text, just as: "", '', (), [], {}, and o Text convertion and view -- python -> html, reStructured Text -> html, textile -> html, and you can output or view o Utf-8 encoding auto detect o Changing document encoding o Auto backup o Last session support -- It'll save all the filenames as closed, and reopen the files as next started. o Smart judge the indent char -- It'll auto guess the indent char, and sets it. o Finding in files o Bookmark support * Python support o built-in python interactive window based on ?PyShell, support Unicode o Auto completion o Function syntax calltips o Run, run with argument, stop python source o Auto change current path o Python class browser o Indent pasting support(New) * Code snippets o You can manage your code snippets with categories, and each category can have many items. Every item will represent a code snippet. You can insert an item just by double-clicking on it. It even supports importing and exporting. * Simple project support o Can create a special file _project, so every file and folder under the folder which has the _project can be considered as a whole project. * Extension mechanism o Script -- You can write easy script to manipulate the all resource of UliPad, just like: text conversion, etc. o Plugin -- Customized function. More complex but more powerful. Can easily merge with UliPad, and can be managed via menu. o Shell command -- Add often used shell commands, and execute them. * Ftp support o You can edit remote files through ftp. You can add, rename, delete, upload, download file/directory. * Multilanguage support o Currently supports two languages: English and Chinese, which can be auto-detected. * Shipped plugins(must be configed as used them before) o Document links -- Python documentation and wxPython documentation. o Many plugins can be found at UliPad wiki page. * Shipped scripts o Many scripts can be found at UliPad wiki page. * Wizard (New) o You can make your own wizard template. The wizard can input user data, combine with template, and output the result. And wizard also support code framework created. This feature will help you improving coding efficiency. * Direcotry Browser(New) o Browse multiple directories, and you can really add, delete, rename directories and files. Double click will open the file in Editor window. o Support Copy, Cut, and Paste. o Search in Directory * AutoComPlete(acp)(New) o Suport user autocomplete file, it can help to input code very helpful and functional. Just like EditPlus, but may be more powerful. o Manually apply some acp files to current document * Column Edit Mode(New) Where to download it? ================ download lastest version 3.3: http://wiki.woodpecker.org.cn/moin/UliPad?action=AttachFile&do=get&target=UliPad_3.3.zip also have windows installer: http://wiki.woodpecker.org.cn/moin/UliPad?action=AttachFile&do=get&target=UliPad3.3.exe wiki: http://wiki.woodpecker.org.cn/moin/UliPad svn: http://cvs.woodpecker.org.cn/svn/woodpecker/ulipad/trunk maillist: http://groups.google.com/group/ulipad If you have any problem as using UliPad, welcome to join the UliPad maillist to discuss. Hope fun! -- I like python! My Blog: http://www.donews.net/limodou My Django Site: http://www.djangocn.org NewEdit Maillist: http://groups.google.com/group/NewEdit From mail at microcorp.co.za Tue Aug 29 12:11:36 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 29 Aug 2006 18:11:36 +0200 Subject: How to let a loop run for a while before checking for break condition? Message-ID: <002801c6cb87$38ce3760$03000080@hendrik> "Hendrik van Rooyen" wrote: 8<------------------------------------- Here are some more results, three runs without, and three with a comment in the body of the interesting loop: (a summary follows the detail) > python junk.py 0x5000001 Loop 1 Elapsed time is: 31.2168951035 Loop 1 used : 16.39 Time out used was : 28 comment removed from Loop 1 0x5000001 Loop 2 Elapsed time is: 75.8846828938 Loop 2 used : 37.93 > python junk.py 0x5000001 Loop 1 Elapsed time is: 31.3769760132 Loop 1 used : 16.1 Time out used was : 28 comment removed from Loop 1 0x5000001 Loop 2 Elapsed time is: 76.4928090572 Loop 2 used : 38.23 > python junk.py 0x5000001 Loop 1 Elapsed time is: 34.8213500977 Loop 1 used : 18.24 Time out used was : 28 comment removed from Loop 1 0x5000001 Loop 2 Elapsed time is: 82.6038169861 Loop 2 used : 39.13 > python junk.py 0x5000001 Loop 1 Elapsed time is: 36.7637741566 Loop 1 used : 18.81 Time out used was : 28 comment inserted into Loop 1 0x5000001 Loop 2 Elapsed time is: 77.6277718544 Loop 2 used : 38.82 > python junk.py 0x5000001 Loop 1 Elapsed time is: 37.6858890057 Loop 1 used : 19.71 Time out used was : 28 comment inserted into Loop 1 0x5000001 Loop 2 Elapsed time is: 76.0855400562 Loop 2 used : 38.04 > python junk.py 0x5000001 Loop 1 Elapsed time is: 35.0458369255 Loop 1 used : 18.32 Time out used was : 28 comment inserted into Loop 1 0x5000001 Loop 2 Elapsed time is: 75.850135088 Loop 2 used : 37.9 Summary of results: Without comment: Average elapsed time calculated by hand: 32.47 Average clock.clock() time : 16.91 With comment: Average elapsed time calculated by hand: 36.39 Average clock.clock() time : 18.95 Normal loop performance over 6 runs: Average elapsed time calculated by hand: 77.42 Average clock.clock() time : 38.34 Conclusion 1: The lower level test for the signal is far more efficient than the Python comparison. - these kind of shenanigans are well worth while if the loop is known to be a long running one. Conclusion 2: The setting of the appropriate time out is a PITA... (any ideas?) Conclusion 3: Don't put comments in the body of long running loops... Conclusion 4: (from earlier in the thread) - using calls are expensive... Conclusion 5: I learnt something - Thank you all... Off topic Question - I see that giving the signal.alarm a float instead of an integer gives a deprecation warning - does anybody know why this was decided? (I was trying to do a binary search...) Here is Claudio's code as I have hacked it: import signal, time def func1(timeout): def callback(signum, frame): raise EOFError # could use a custom exception instead signal.signal(signal.SIGALRM, callback) signal.alarm(timeout) count = 0 try: while 1: # this is a comment in the body of the loop count += 1 except EOFError: while True: count += 1 if count > 0x5000000: break print hex(count) def func2(): count = 0 while True: count += 1 if count > 0x5000000: break print hex(count) def func3(): return 0 timeout = 28 print startTime = time.time() start_use = time.clock() func1(timeout) eltime = time.time() - startTime utime = time.clock() - start_use print "Loop 1 Elapsed time is:", eltime print "Loop 1 used :", utime print "Time out used was :", timeout print "comment inserted into Loop 1" print startTime = time.time() start_use = time.clock() func2() eltime = time.time() - startTime utime = time.clock() - start_use print "Loop 2 Elapsed time is:", eltime print "Loop 2 used :", utime print - Hendrik From deets at nospam.web.de Thu Aug 17 11:06:36 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 17 Aug 2006 17:06:36 +0200 Subject: iTunes Search Algorithm/Data Structure? In-Reply-To: <1155823844.679026.276610@i3g2000cwc.googlegroups.com> References: <1155823844.679026.276610@i3g2000cwc.googlegroups.com> Message-ID: <4kjevuFcg38tU1@uni-berlin.de> Bill Mill schrieb: > Hello all, > > What data structure would you use to implement something analogous to > the iTunes search? I imagine that it must be a tree of some sort, but I > can't figure out an easy structure for it. > > Requirements (in case you haven't used it): > > You are given 4 rows in a list view: > [["alpha, "beta"], ["delta", "gamma"], ["foo", "bar"], ["etc", "etc"]] > > and a search text box. > > Typing "a" in the list box leaves rows 0, 1 and 2 in the list box, > because some element in each of those rows has an "a" in it. Typing > "am" leaves only row 1, since "gamma" has the substring "am" in it. > > The key here is that this works instantaneously as you type, even with > very large lists with many elements per row. I'd like the employee list > in my current application to be similarly filtered, but I don't quite > see how. > > Thoughts? Use an index. You can create one for each character, tuples of characters and so on that are contained in a word. That makes finding the entries a dict lookup + throwing the results together, filtering doubles. I guess you can stop using indices at 3 or 4 characters, and then linearily search through the rest of the possibilities linearily. Diez From maric at aristote.info Mon Aug 28 19:53:46 2006 From: maric at aristote.info (Maric Michaud) Date: Tue, 29 Aug 2006 01:53:46 +0200 Subject: Anonymous dynamic import In-Reply-To: <6addebae0608281315q798cfd8dof0b51fa16969304f@mail.gmail.com> References: <6addebae0608281315q798cfd8dof0b51fa16969304f@mail.gmail.com> Message-ID: <200608290153.47343.maric@aristote.info> Le lundi 28 ao?t 2006 22:15, Christian Convey a ?crit?: > I've looked at using imp.load_source() or imp.load_module(), but it looks > to me like all of these polute the global namespace with the names of the > modules I'm importing. Really ? They don't. (there are some quirks in my little function) In [1]: def importer(*mods): ...: import imp ...: from os import path as _p ...: for i in mods : ...: n, p = _p.splitext(_p.split(i)[1])[0], _p.dirname(i) ...: print imp.load_module(n,*imp.find_module(n, [p])) ...: ...: In [2]: importer('temp', 'temp.py', 'test', 'test/', './test', 'test/__init__.py', 'test/mod', 'test/mod.py') <--- here <--- and here In [3]: temp ... NameError: name 'temp' is not defined Neither do a simple import in a function scope : In [14]: def f() : import temp ....: In [15]: f() In [16]: temp ... NameError: name 'temp' is not defined But maybe you are worried by the sys.modules repository ? I don't see why it could be a problem, but if this is the case you can't use import machinery, You could go that way : #temp.py A=0 def test_execfile() : print A In [1]: d={} In [2]: execfile('temp.py',d, d) In [3]: d['test_execfile'] Out[3]: In [4]: d['test_execfile']() 0 In [5]: d['A'] = 1 In [6]: d['test_execfile']() 1 -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From rogue_pedro at yahoo.com Fri Aug 25 00:58:16 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 24 Aug 2006 21:58:16 -0700 Subject: lazy arithmetic References: <1156476992.102203.304450@p79g2000cwp.googlegroups.com> Message-ID: <1156481896.043165.84770@i3g2000cwc.googlegroups.com> pianomaestro at gmail.com wrote: > # This is what I have in mind: > > class Item(object): > def __add__(self, other): > return Add(self, other) > > class Add(Item): > def __init__(self, a, b): > self.a = a > self.b = b > > a = Item() > b = Item() > > c = a+b > > # Now, I am going absolutely crazy with this idea > # and using it in a big way. So I'm looking at > # automating the process. As a first step, > # I thought maybe this would work: > > class Item(object): > pass > > class Add(Item): > def __init__(self, a, b=None): > print self, a, b > self.a = a > self.b = b > > Item.__add__ = Add > > x = Item() > y = Item() > > print x, y > > c = x+y > > # This time, the Add constructor gets only the first two arguments: > "self" and "y". > # So, what happened to "x" ? Is this some kind of property voodoo going > on ? > > # Simon. Look at the signature for __add__: __add__(self, other) Now look at the signature for __init__: __init__(self, a, b=None) Now look at the output of your script: |>> <__main__.Item object at 0xb6faa4ac> <__main__.Item object at 0xb6faa3ec> <__main__.Add object at 0xb6faa5ec> <__main__.Item object at 0xb6faa3ec> None When python calls x.__add__ as a result of "x+y" it only passes it y as 'other', or, in this case, as 'a'. The 'self' arg gets filled in with a brand new Add instance, because __add__ (rather than being a method of Item) is really the class Add. (b will never be filled in using the Add.__init__ method this way.) Consider: |>> x <__main__.Item object at 0xb6f10f0c> |>> x.__add__ |>> Badd = x.__add__ |>> Badd |>> b = Badd(23, 18) <__main__.Add object at 0xb6f10e8c> 23 18 |>> b <__main__.Add object at 0xb6f10e8c> Make more sense? :-) "Item.__add__ = Add" is a very strange thing to do, I'm not surprised it didn't work. HTH, ~Simon From sjmachin at lexicon.net Fri Aug 11 17:51:59 2006 From: sjmachin at lexicon.net (John Machin) Date: 11 Aug 2006 14:51:59 -0700 Subject: datetime to timestamp In-Reply-To: References: <44dc87b7$1@news.eftel.com> <44dc8891$1@news.eftel.com> Message-ID: <1155333119.633626.272450@b28g2000cwb.googlegroups.com> Tim Peters wrote: > [Simen Haugen] > >>> How can I convert a python datetime to a timestamp? It's easy to convert > >>> a timestamp to datetime (datetime.datetime.fromtimestamp(), but the > >>> other way around...?) > > [John Machin] > >> Is the timetuple() method what you want? > >> > >> #>>> import datetime > >> #>>> n = datetime.datetime.now() > >> #>>> n > >> datetime.datetime(2006, 8, 11, 23, 32, 43, 109000) > >> #>>> n.timetuple() > >> (2006, 8, 11, 23, 32, 43, 4, 223, -1) > > [also John] > > Aaaarrrggghhh no it's not what you want > > Yes, it is ;-) > > > -- looks like you have to do the arithmetic yourself, starting with toordinal() > > It's just one step from the time tuple: > > import time > time.mktime(some_datetime_object.timetuple()) > Thanks, Tim. In mitigation, yer honour, I'd like to draw your attention to the local time (23:32); the defendant was rushing to do the OP's RTFantasticM for him before retiring for the night, and not doing it well enough :-) Cheers, John From bayazee at gmail.com Thu Aug 10 19:34:00 2006 From: bayazee at gmail.com (Bayazee) Date: 10 Aug 2006 16:34:00 -0700 Subject: hide python code ! Message-ID: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> hi can we hide a python code ? if i want to write a commercial software can i hide my source code from users access ? we can conver it to pyc but this file can decompiled ... so ...!! do you have any idea about this ...? --------------------------------------- First Iranian Open Source Community : www.python.ir From deets at nospam.web.de Wed Aug 9 09:16:07 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 09 Aug 2006 15:16:07 +0200 Subject: need hint for refactoring References: <1155128930.807498.179700@75g2000cwc.googlegroups.com> Message-ID: <4ju5gnF9p72jU1@uni-berlin.de> GHUM wrote: > I have a bunch of function like: > > def p2neufrage(_): > """ create new element""" > anfrage,ergebnis=getanfrage() > if ergebnis.get("status","ok") == "ok": > wert=anfrage["feld"] > # do something > # unique here > > > ergebnis["innerHTML"]=..... something .... > > # > return simplejson.dumps(ergebnis, skipkeys=False, > ensure_ascii=False, check_circular=True, allow_nan=True) > > > so, everywhere there is the same beginning: > > anfrage,ergebnis=getanfrage() > > I analyze some transmitted jason-document; check for errors > > then I take the values out of the request, process it and fill the > slots of a result ("ergebnis") dictionary, which is returned. > > > So the beginning and the end of the function is allways repeated. It > would be great to factor it out ... i startet with that ...getanfrage() > call. > > Is there anything more possible? Use a decorator, out of my head: def foo(f): def _w(*args, **kwargs): anfrage,ergebnis=getanfrage() new_args = (args[0],) + (anfrage, ergebnis) + args[1:] f(*new_args, **kwargs) return simplejson.dumps(ergebnis, skipkeys=False, ensure_ascii=False, check_circular=True, allow_nan=True) return _w Then do @foo def p2neufrage(_, anfrage, ergebnis): """ create new element""" if ergebnis.get("status","ok") == "ok": wert=anfrage["feld"] # do something # unique here ergebnis["innerHTML"]=..... something .... Diez From davecook at nowhere.net Fri Aug 4 06:58:42 2006 From: davecook at nowhere.net (Dave Cook) Date: Fri, 04 Aug 2006 10:58:42 GMT Subject: [Linux] What toolkit for a good grid/spreadsheet widget? References: <6fo4d2h0lnq2qcgi8jknh0ddmphhdgaulj@4ax.com> Message-ID: On 2006-08-04, Vincent Delporte wrote: > Thx for the two pointers. Are those widgets more than just tables, ie. > can I edit the contents, including displaying a combo box, can items > be grouped or hierarchized, or are they just basic, read-only tables > to display results? You can display combo boxes in cells in pygtk, as well as edit cells. But both pyqt and wxpython also offer that. Try running the demos for each. Dave Cook From andrew.arobert at gmail.com Mon Aug 28 08:11:09 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Mon, 28 Aug 2006 08:11:09 -0400 Subject: Middle matching - any Python library functions (besides re)? In-Reply-To: <1156743141.536257.157410@74g2000cwt.googlegroups.com> References: <1156722194.089832.282510@74g2000cwt.googlegroups.com> <7xirkd4s5w.fsf@ruckus.brouhaha.com> <1156743141.536257.157410@74g2000cwt.googlegroups.com> Message-ID: <12f5nbck5bn3o7d@corp.supernews.com> Simon Forman wrote: > Paul Rubin wrote: >> "EP" writes: >>> Given that I am looking for matches of all files against all other >>> files (of similar length) is there a better bet than using re.search? >>> The initial application concerns files in the 1,000's, and I could use >>> a good solution for a number of files in the 100,000's. >> If these are text files, typically you'd use the Unix 'diff' utility >> to locate the differences. > > If you can, you definitely want to use diff. Otherwise, the difflib > standard library module may be of use to you. Also, since you're > talking about comparing many files to each other, you could pull out a > substring of one file and use the 'in' "operator" to check if that > substring is in another file. Something like this: > > f = open(filename) # or if binary open(filename, 'rb') > f.seek(somewhere_in_the_file) > substr = f.read(some_amount_of_data) > f.close() > > try_diffing_us = [] > for fn in list_of_filenames: > data = open(fn).read() # or again open(fn, 'rb')... > if substr in data: > try_diffing_us.append(fn) > > # then diff just those filenames... > > That's a naive implementation but it should illustrate how to cut down > on the number of actual diffs you'll need to perform. Of course, if > your files are large it may not be feasible to do this with all of > them. But they'd have to be really large, or there'd have to be lots > and lots of them... :-) > > More information on your actual use case would be helpful in narrowing > down the best options. > > Peace, > ~Simon > Would it be more efficient to checksum the files and then only diff the ones that fail a checksum compare? Utilizing the functions below may be of some help. #!/usr/bin/python # # # Function: generate and compare checksums on a file import md5, sys def getsum(filename): """ Generate the check sum based on received chunks of the file """ md5sum = md5.new() f = open(filename, 'r') for line in getblocks(f) : md5sum.update(line) f.close() return md5sum.hexdigest() def getblocks(f, blocksize=1024): """ Read file in small chunks to avoid having large files loaded into memory """ while True: s = f.read(blocksize) if not s: break yield s def checksum_compare(caller, cs='',check='', filename=''): """ Compare the generated and received checksum valued """ if cs != check: return 1 # compare failed else: return 0 # compare successful -- Adversity: That which does not kill me only postpones the inevitable. From rogue_pedro at yahoo.com Tue Aug 8 17:27:29 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 8 Aug 2006 14:27:29 -0700 Subject: newb question: file searching References: <1155067111.892386.130610@n13g2000cwa.googlegroups.com> <1155067720.211789.208560@i42g2000cwa.googlegroups.com> <1155068675.101390.299110@i3g2000cwc.googlegroups.com> <1155070517.448510.149380@b28g2000cwb.googlegroups.com> Message-ID: <1155072449.876547.53420@75g2000cwc.googlegroups.com> jaysherby at gmail.com wrote: > hiaips wrote: > > > jaysherby at gmail.com wrote: > > > > I'm new at Python and I need a little advice. Part of the script I'm > > > > trying to write needs to be aware of all the files of a certain > > > > extension in the script's path and all sub-directories. Can someone > > > > set me on the right path to what modules and calls to use to do that? > > > > You'd think that it would be a fairly simple proposition, but I can't > > > > find examples anywhere. Thanks. > > > > dir_name = 'mydirectory' > > extension = 'my extension' > > import os > > files = os.listdir(dir_name) > > files_with_ext = [file for file in files if file.endswith(extension)] > > > > That will only do the top level (not subdirectories), but you can use > > the os.walk procedure (or some of the other procedures in the os and > > os.path modules) to do that. > > > > --Dave > > Thanks, Dave. That's exactly what I was looking for, well, except for > a few small alterations I'll make to achieve the desired effect. I > must ask, in the interest of learning, what is > > [file for file in files if file.endswith(extension)] > > actually doing? I know that 'file' is a type, but what's with the set > up and the brackets and all? Can someone run down the syntax for me on > that? And also, I'm still not sure I know exactly how os.walk() works. > And, finally, the python docs all note that symbols like . and .. > don't work with these commands. How can I grab the directory that my > script is residing in? > > Thanks. > > 'file' *is* the name of the file type, so one shouldn't reuse it as the name of a variable as Dave did in his example. the brackets are a "list comprehension" and they work like so: files_with_ext = [] for filename in files: if filename.endswith(extension): files_with_ext.append(filename) The above is exactly equivalent to the [filename for filename in files... ] form. AFAIK, os.listdir('.') works fine, but you can also use os.listdir(os.getcwd()). However, both of those return the current directory, which can be different than the directory your script's residing in if you've called os.chdir() or if you start your script from a different directory. HTH. (Also, if you're not already, be aware of os.path.isfile() and os.path.isdir(). They should probably be helpful to you.) Peace, ~Simon From eternalsquire at comcast.net Mon Aug 7 16:21:46 2006 From: eternalsquire at comcast.net (The Eternal Squire) Date: 7 Aug 2006 13:21:46 -0700 Subject: where can I find Python acceptance test suite? In-Reply-To: References: <1154897422.081562.80780@n13g2000cwa.googlegroups.com> Message-ID: <1154982106.533335.187190@75g2000cwc.googlegroups.com> Thanks. Terry Reedy wrote: > "The Eternal Squire" wrote in message > news:1154897422.081562.80780 at n13g2000cwa.googlegroups.com... > > I've been doing some hacking of the Python engine, and I've been > > looking for > > where the comprehensive regression tests are kept so that I can > > determine > > where I've broken part of the engine. > > ...python2x/Lib/test From accurrent at gmail.com Fri Aug 11 14:35:01 2006 From: accurrent at gmail.com (accurrent at gmail.com) Date: 11 Aug 2006 11:35:01 -0700 Subject: having issues Installing Python 2.5b3 on Windows XP In-Reply-To: <1155318944.456810.128010@p79g2000cwp.googlegroups.com> References: <1155315119.400903.49090@h48g2000cwc.googlegroups.com> <1155318944.456810.128010@p79g2000cwp.googlegroups.com> Message-ID: <1155321301.736778.80130@i42g2000cwa.googlegroups.com> Bucco wrote: > The python 2.4 version msi did no better. Please help. I do not > really want to go back to Active State Python. > > > Thanks:) > > SA > > > Bucco wrote: > > I > > am going to try to install python 2.4 with the msi installer and see if > > I have the same issue with that version. If anyone else has any ideas > > please help. It is a beta after all. You should expect some bugs. From claudio.grondi at freenet.de Fri Aug 25 17:05:03 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Fri, 25 Aug 2006 23:05:03 +0200 Subject: time.clock() going backwards?? In-Reply-To: References: Message-ID: Terry Reedy wrote: > "Giovanni Bajo" wrote in message > news:vkFHg.82529$_J1.759243 at twister2.libero.it... > >>Hello, >> >>I experimented something very strange, a few days ago. I was debugging an >>application at a customer's site, and the problem turned out to be that >>time.clock() was going "backwards", that is it was sometimes >>(randomically) >>returning a floating point value which was "less than" the value returned >>by >>the previous invokation. The computer was a pretty fast one (P4 3Ghz I >>think, >>running Windows XP), and this happened only between very close >>invokations of >>time.clock(). > > > I seem to remember this being mentioned before on the list, perhaps by Tim > Peters. Perhaps he will chime in. > > tjr If I remember it right, the cause of such a problem is updating the clock by accessing a time server over a network. Just any such access results in adjusting the time a bit and leads eventually to such problems. Claudio Grondi From Avizoa at gmail.com Sat Aug 5 10:46:42 2006 From: Avizoa at gmail.com (Avizoa at gmail.com) Date: 5 Aug 2006 07:46:42 -0700 Subject: More int and float attributes In-Reply-To: <1154780600.348169.158150@i42g2000cwa.googlegroups.com> References: <1154780600.348169.158150@i42g2000cwa.googlegroups.com> Message-ID: <1154789202.032115.244090@i42g2000cwa.googlegroups.com> It seems as though just about all of those would be rarely, if ever, used by the vast majority of programmers. Plus, python already handles the two most important (NaN and complex) well. From webraviteja at gmail.com Mon Aug 14 00:16:33 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 13 Aug 2006 21:16:33 -0700 Subject: recommended general-purpose string template packages? In-Reply-To: <1155523735.614470.199840@h48g2000cwc.googlegroups.com> References: <1155523735.614470.199840@h48g2000cwc.googlegroups.com> Message-ID: <1155528993.321226.103240@m79g2000cwm.googlegroups.com> > In general, I'm mainly interested in a template engine for dynamic web > pages but would like a general purpose one to avoid learning yet > another package for generating e-mail messages, form letters, source > code, whatever. > > In particular, does anyone have much experience with the Python > interface to Terence Parr's StringTemplate > (http://www.stringtemplate.org/)? Reading the website, I'm attracted by > the approach, but a Google search (both generally and in this > newsgroup) gives me the impression that it's little used in the Python > world. Most Python templating engines are general purpose. Choice between them however is sometimes a matter of preference, like editors. I settled down on Cheetah for most part. Here is a list of some popular ones. http://wiki.python.org/moin/Templating From thomas.samson at gmail.com Mon Aug 28 08:43:50 2006 From: thomas.samson at gmail.com (thomas.samson at gmail.com) Date: Mon, 28 Aug 2006 14:43:50 +0200 Subject: Segmentation Fault References: <1156737764.729811.297280@m79g2000cwm.googlegroups.com> <1156741148.580820.309840@74g2000cwt.googlegroups.com> Message-ID: <6hssljhrpx5.fsf@koollbox.kooll.org> "Simon Forman" writes: > pycraze wrote: >> I would like to ask a question. How do one handle the exception due to >> Segmentation fault due to Python ? Our bit operations and arithmetic >> manipulations are written in C and to some of our testcases we >> experiance Segmentation fault from the python libraries. >> >> If i know how to handle the exception for Segmentation fault , it will >> help me complete the run on any testcase , even if i experiance Seg >> Fault due to any one or many functions in my testcase. > > AFAIK, seg fault kills your program dead. There's no exception to > handle. If you're getting seg faults from the python standard library, > that's a pretty serious thing, way more serious than just not-passed > testcases. Segfault handling is platform-dependant... So, at least on unix-like platform, you can use the signal module to detect segfault: import signal def handler(signum, frame): print 'Segfault detected' # you may use the stack frame here to help debugging signal.signal(signal.SIGSEGV, handler) -- Thomas SAMSON "You're very sure of your facts, " he said at last, "I couldn't trust the thinking of a man who takes the Universe - if there is one - for granted. " From f.braennstroem at gmx.de Thu Aug 24 05:56:31 2006 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Thu, 24 Aug 2006 11:56:31 +0200 Subject: radio buttons in curses References: Message-ID: Hi Steve, * Steve Holden wrote: > Fabian Braennstroem wrote: >> Sorry, me again... >> Does nobody have an idea or is it to stupid? >> >> * Fabian Braennstroem wrote: >> >>>Hi, >>> >>>I want to add some radio and check buttons to my curses >>>script. As I understand it, there are no buttons in the >>>'basic' curses module. Now, I found the curses-extra module, >>>but I not able to download and install it. >>> >>>Does anybody have an idea, where I can download the module >>>or, even better, how I can create radio and check buttons >>>with the 'ordinary' curses module? Would be nice... >>> >>>Greetings! >>> Fabian >>> >>>-- >>>http://mail.python.org/mailman/listinfo/python-list >>> >> >> >> Greetings! >> Fabian >> > Sounding a bit like a "no", looks like. Did you Google much? Yes, it looks like this ... actually, I did google and found out that it does not work, so that I am looking for curses-extra. Maybe, somebody has a copy and could send me one? Would be nice! Greetings! Fabian From mensanator at aol.com Tue Aug 15 19:11:28 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 15 Aug 2006 16:11:28 -0700 Subject: Creating Charts in Excel with pyExcelerator.ExcelMagic In-Reply-To: <1155665828.595235.214360@75g2000cwc.googlegroups.com> References: <1155665828.595235.214360@75g2000cwc.googlegroups.com> Message-ID: <1155683488.481776.185060@i3g2000cwc.googlegroups.com> implicate_order wrote: > Greetings, > > I'm new to python and am in the process of writing a script to parse > some CSV data, spread it across multiple Excel worksheets and then > generate charts. I searched the internet to find some place where I > could look up a HOWTO doc/recipe to do that using either pyExcelerator > or win32com.client. > > Could someone point me in the right direction? > I'm at the stage where the spreadsheet and associated data worksheets > are ready. The chart is created (with win32com.client). I need to know > how I can use win32com.client to actually generate some data based on > the contents of a particular work sheet. > > >>> from win32com.client import * > >>> xl = win32com.client.Dispatch("Excel.Application") > >>> wb = xl.Workbooks.open("C:\scripts\dummytest.xls") > >>> xl.Visible = 1 > >>> ws = wb.Worksheets(1) > >>> ws.Range('$A1:$D1').Value = ['NAME', 'PLACE', 'RANK', 'PRICE'] > >>> ws.Range('$A2:$D2').Value = ['Foo', 'Fooland', 1, 100] > >>> ws.Range('$A3:$D3').Value = ['Bar', 'Barland', 2, 75] > >>> ws.Range('$A4:$D4').Value = ['Stuff', 'Stuffland', 3, 50] > >>> wb.Save() > >>> wb.Charts.Add() > >>> wc1 = wb.Charts(1) > > At this point, I'm lost -- I couldn't find any lucid docs to indicate > what can be done to populate the chart from the worksheet "ws". Try this one: > > Any help would be greatly appreciated. > > TIA From dasn at bluebottle.com Mon Aug 28 03:37:50 2006 From: dasn at bluebottle.com (Dasn) Date: Mon, 28 Aug 2006 02:37:50 -0500 Subject: Problem of function calls from map() In-Reply-To: References: <2Gf*MkSor@news.chiark.greenend.org.uk> Message-ID: <200608280738.k7S7borB007213@fe10.bluebottle.com> On Tue, Aug 22, 2006 at 04:50:39PM +0200, Fredrik Lundh wrote: > (you cannot really use "profile" to *benchmark* things written in > Python either; the profiler tells you where a given program spends the > time, not how fast it is in com- parision with other programs) Thanks for your indication. From skip at pobox.com Mon Aug 28 10:31:51 2006 From: skip at pobox.com (skip at pobox.com) Date: Mon, 28 Aug 2006 09:31:51 -0500 Subject: Truly platform-independent DB access in Python? In-Reply-To: <1156748466.739709.117850@h48g2000cwc.googlegroups.com> References: <1156748466.739709.117850@h48g2000cwc.googlegroups.com> Message-ID: <17650.65111.603281.306741@montanaro.dyndns.org> boris> I am using the Python DB API for access to MySQL. But it is not boris> platform-independent - I need a module not included in Python by boris> default - python-mysql, and it uses a compiled binary boris> _mysql.so. So it is not platform-independent because for each boris> web-server on different platform, I would have to download it and boris> extra compile it specifically for that platform. Do you know of boris> any Python solution for MySQL access that is 100% boris> platform-independent? I don't think you mean "platform-independent". I suspect you mean "batteries included". Prior to the release of Python 2.5, no modules to access SQL databases were distributed with core Python. Starting with 2.5, sqlite access will be available: >>> import sqlite3 >>> sqlite3.__file__ '/Users/skip/local/lib/python2.5/sqlite3/__init__.pyc' So, if what you were really asking was "what SQL databases can I access without installing any software other than Python?", then the answer is "No SQL databases were distributed with Python prior to 2.5. Starting with Python 2.5, access to sqlite databases is available by default." Python 2.5 is due out soon (according to PEP 356, on 12 September). The still-officially-in-development-but-almost-certainly-frozen documentation for the sqlite3 module is here: http://docs.python.org/dev/lib/module-sqlite3.html Skip From a at tempinbox.com Sun Aug 13 04:10:02 2006 From: a at tempinbox.com (a) Date: 13 Aug 2006 01:10:02 -0700 Subject: keep a list of read and unread items Message-ID: <1155456602.502808.105990@m79g2000cwm.googlegroups.com> keep a list of read and unread items hi guys i m building an rss reader and i want you suggestions for datastructure for keeping read and unread list for each use i m assuming it will be very sparse thanks From guyon.moree at gmail.com Tue Aug 1 11:02:01 2006 From: guyon.moree at gmail.com (=?iso-8859-1?B?R3V5b24gTW9y6WU=?=) Date: 1 Aug 2006 08:02:01 -0700 Subject: fast pythonic algorithm question References: <1154443185.562918.140090@s13g2000cwa.googlegroups.com> <7x64hcjyge.fsf@ruckus.brouhaha.com> Message-ID: <1154444521.644351.226760@75g2000cwc.googlegroups.com> Memory is no problem. It just needs to be as fast as possible, if that's what this is, fine. If not, I'd like to find out what is :) thanx, Guyon Moree http://gumuz.looze.net Paul Rubin schreef: > "Guyon Mor?e" writes: > > if (((src_host,src_port, protocol) in dict or (dest_host, dest_port, > > protocol) in dict) and starttime < time < endtime): > > print "we have a winner" > > If you have enough memory to do it that way, what's the problem? From bill.pursell at gmail.com Sun Aug 20 14:12:38 2006 From: bill.pursell at gmail.com (Bill Pursell) Date: 20 Aug 2006 11:12:38 -0700 Subject: import In-Reply-To: References: <1156093283.529579.80600@i42g2000cwa.googlegroups.com> <1156093799.775420.51970@m73g2000cwd.googlegroups.com> <1156094307.576025.3430@i3g2000cwc.googlegroups.com> <1156096550.873958.289300@m79g2000cwm.googlegroups.com> Message-ID: <1156097558.414635.298510@p79g2000cwp.googlegroups.com> Georg Brandl wrote: > 01 wrote: > > Georg Brandl wrote: > >> figo_wei01 at 126.com wrote: > >> > bugnthecode ??? > >> > > >> >> How are you trying to import it? Is it in the same directory as your > >> >> other script? If not is your python path set correctly? > >> >> > >> >> When importing a module that you have written you exlude the .py > >> >> extension. You should be using: > >> >> import hello > >> >> > >> >> Hope that helps, > >> >> Will > >> > > >> > i am on a windows platform. i have written scrip named 123.py. it can > >> > be run. ok i save it to C:\Python24 ,exactly the same dir where python > >> > works. but " import 123" doesnt work. > >> > >> You can't import modules whose names have non-identifier names with > >> plain "import". Or would you like "123" to refer to a module? > >> > >> If you have to do this (and I have a strong feeling that you haven't) > >> use the built-in function __import__(). > >> > > you have to name your program with the name mymodule,or something like > > that when you use "import". does python have a clear declaration on > > how to name a module? > > A module name can be everything also usable as a Python identifier. This > means that it contains only letters, digits and underscores and doesn't > start with a digit. > > Running a file as the main file, using "python 123.py" works because > Python then won't need to provide the file name as a name in the script. On an almost totally unrelated note...(except that it definitely belongs in a thread entitled "import")... I've occasionally run into difficulty when I fail to include a she-bang in my script. If the first word of the script is import, which it often is for quickly written scripts that contain an import line before any doc string and that doesn't have "#!/usr/bin/env python", bash doesn't report a syntax error. Instead, it annoyingly runs the ImageMagick command import, which dutifully sits there waiting for a mouse click. The first time this happened, it took me a good 15 minutes to figure out what was happening. (The first instance was more subtle than forgetting the she-bang, as I'd merely forgotten the "bang" and the "#/usr/bin/env python" looked pretty good when I looked at the file.) I'm just curious if anyone else has ever bumped into that mistake. From fredrik at pythonware.com Tue Aug 29 04:45:20 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 29 Aug 2006 10:45:20 +0200 Subject: XML parsing and writing References: <1154111594.276996.161800@b28g2000cwb.googlegroups.com><44cdc907$0$18516$9b4e6d93@newsread2.arcor-online.net><1154374561.173011.45590@i3g2000cwc.googlegroups.com> <44f3e6c7$0$10144$9b4e6d93@newsspool2.arcor-online.net> Message-ID: someone wrote: >> Nice package ElementTree is but sadly it doesn't have a pretty print, >> well, guess I'll have to do it myself, if you have one already can you >> please give it to me? thanks :) http://effbot.python-hosting.com/file/stuff/sandbox/elementlib/indent.py From grante at visi.com Sun Aug 27 10:41:05 2006 From: grante at visi.com (Grant Edwards) Date: Sun, 27 Aug 2006 14:41:05 -0000 Subject: avoiding file corruption References: <1156664673.325201.271140@i42g2000cwa.googlegroups.com> Message-ID: <12f3bo1t1ccr858@corp.supernews.com> On 2006-08-27, Amir Michail wrote: > Trying to open a file for writing that is already open for writing > should result in an exception. MS Windows seems to do something similar, and it pisses me off no end. Trying to open a file and read it while somebody else has it open for writing causes an exception. If I want to open a file and read it while it's being writtent to, that's my business. Likewise, if I want to have a file open for writing twice, that's my business as well. I certainly don't want to be hobbled to prevent me from wandering off in the wrong direction. > It's all too easy to accidentally open a shelve for writing > twice and this can lead to hard to track down database > corruption errors. It's all to easy to delete the wrong element from a list. It's all to easy to re-bind the wrong object to a name. Should lists be immutable and names be permanently bound? -- Grant Edwards grante Yow! I'm in a twist at contest!! I'm in a visi.com bathtub! It's on Mars!! I'm in tip-top condition! From mail at microcorp.co.za Fri Aug 4 04:10:44 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Fri, 4 Aug 2006 10:10:44 +0200 Subject: Is there an obvious way to do this in python? References: <44d128e5$0$13484$636a55ce@news.free.fr> <7s94d2tcermjbifq2r9hr0meu0lj49rbmg@4ax.com> Message-ID: <00d801c6b79d$fdd6d060$03000080@hendrik> "Dennis Lee Bieber" wrote: | On Thu, 3 Aug 2006 14:05:19 +0200, "H J van Rooyen" | declaimed the following in comp.lang.python: | | > What I mean by this is that the server does stuff that I think belongs on the | > client - | > like getting involved in the nitty gritty of what the client should display - | > I want the client to be smart enough to do the assembly of the elements of a | > transaction | > by itself, going back to the server for data only when its needed - remember | | One thing to consider: Where is the separation between the database | and the client. I believe most textbooks these days tend recommend: | | [db-server] <-> [app-server] <-> [client] | | (db-server and app-server can be the same hardware; the idea is that | clients do not have direct access to the database system, and hence the | back-end can be changed out without affecting any client... also, | clients don't need to handle database errors, etc.) Agreed - I would also need this application server to do the server end of my "terminal management system" | | > so I see the client interacting with the server quite a lot, eventually to be | > able do things like auto completion of things like stock codes and descriptions, | > customer details, etc. - but I don't want every keystroke flying over the LAN | > and | > being handled by the server... | > | And where did you see the client obtaining the "completion data" -- | direct access to some other database tables or did you intend to | download /all/ possible data. no just a framework of more or less static stuff like document types, name and address data, and account names and codes that is not subject to continous change... *grin* I would have to apply *some* skull sweat to the problem... | | Typical web-based applications may have a minimal bit of data | validation running on the client (JavaScript ... things like making sure | /something/ has been entered into required fields, but not verifying | that it makes sense), and only when the user clicks on a submit is | everything sent to the application server, which then generates the | needed SQL from the data fields for submittal to the database server. | | > transaction is completed - like in a banking system, I envisage ways for the | > client to 'poll' the server to get the state of the last transaction, to make | > this possible. | > | Bad choice... Upon submittal to the server, there should be a | mandatory "good/bad" return code... Here I take umbrage - not bad, good choice - let me elucidate - the return code you are talking about is the normal thing, and it is the dead wrong way to operate if that is all you do - what I am talking about is the failure scenario - the way to make any transactionally based system robust is to have a "GetTranResult" transaction that is routinely used before starting a new transaction, to see if the previous one has completed properly - that way, the client can either - continue with the new transaction, or - resubmit the old one to try to get it to work or fail, or thirdly - advise the user that the previous transaction has failed - it is, when you have thought about the flows and all the possible ways in which they can fail - truly the only way to operate reliably. The above is the simple minded way to use such a facility - You could also argue that the time to use this "polling" transaction is after submitting the transaction, but if your return code is to be trusted, its not needed - if the flows complete normally, its not needed - it is just needed for built in recovery, and it works like a charm if both the server and the client try to keep state over power failures and other disastrous events like losing comms halfway through - especially for multi flow transactions that must update different things on the server... And it does no harm to ask the server the result of your last transaction when you come up after power failure - you can then set the screens and stuff up to the point where the server knows about them and have the user just curse a bit, instead of a lot... And most importantly, the data is safe (unless the database is corrupted, in which case the likelyhood is high that yer screwed in any case) - and on this note - if you have the reversed transaction too - i.e. a kind of "GetPreviousLoggedTransactionResult" from the server to the client, you can make recovery less painful, even in the case of database corruption... Bad choice indeed! *snorts* ;-) - Hendrik From mail at microcorp.co.za Thu Aug 3 10:50:15 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Thu, 3 Aug 2006 16:50:15 +0200 Subject: Is there an obvious way to do this in python? References: <44d128e5$0$13484$636a55ce@news.free.fr> <1154602887.279222.37980@75g2000cwc.googlegroups.com> Message-ID: <002701c6b723$7d1e1660$03000080@hendrik> "Nick Vatamaniuc" wrote: |HJ, | |As far as GUI language/library goes: | |Some people suggested HTML, but I think HTML is a very awkward way to |create a good looking dynamic GUI that is _both_ easy to use and fast |and easy to design (which is what you would want probably). Just to |have a nice user editable table for example, you would have to jump |through hoops (using Javascript, DOM, CSS etc), while you could do it |much easier with PyGTK and wxPython, especially if you use a gui |designer like Glade or wxGlade. Even Tkinter beats HTML as far as |building GUIs in Python goes. I believe this might change in the future |with the adaption of SVG but that will take a while... That said, if |your interface can "get by" with just buttons, text boxes, and text |areas HTML will be the best choice. | At the moment my toy system just uses Tkinter- Buttons, Labels, Entry boxes and Listboxes (which I populate from a dict) - and it has logic in it to do only one dummy transaction, which I just ship to the server machine where nothing happens - it is just echoed back to the client which prints it on stdout - If I stay with this it will be a most uninteresting GUI - but that is not the point at issue now... | |As far as "updating-on-the-fly" goes: | |For the client to get the code on the fly you will have to implement |some sort of a downloader in the first place that when the user logs |in, it downloads the GUI code from the server and runs it. So if you |update the code the day before the next day they will get a different |interface, or if a new user/machine type is created you just have the |new code ready on the server and it will automatically be downloaded |and run, is that right? | This is broadly what I had in mind, yes - but sort of down to a transaction level - this user does invoicing, this one enters cheques, this one does credit notes, and their supervisor can do all three, and in a different department its different because the jobs are different, but the invoicing GUI module is the same for wherever its used... |Here is then how I see your use case: |1) You would define your business rules in your database, you will have |usernames, user types, access rights, data tables, columns types, |relations, views, etc... Yes no matter how you do it, you need to keep a per user or per machine set of what can be done. - in banking terms - a sort of Terminal Management System... My thinking is simpler than this, because you are already thinking in "data base speak" - now dont get me wrong - I realise that I will have to use a database - but for me to start thinking in terms of views and stuff is kind of premature when I dont even have a clear picture in my head of the kind of data the said management system should keep, as I am not sure of what can, and cannot be done. |2) Then each user type will have a specific interface GUI code kept on |the server (perhaps as a zipped binary GUI.zip in a database column |called ClientSpecificGUI). I would like to split this down further - see above - so for each user there is a sort of *pointer* to each of the kinds of transactions she can do, and these are shipped separately and *linked* at the client side... |3) The client starts your Application.py which is the same across all |clients. They will enter their username/password. The Application.py |then sends those to the server to log into the DB. *nods* |4) After successful login, the Application.py performs a SELECT query |to download the zipped GUI.py file. |5) GUI.py is unzipped and executed to start the GUI. The Application.py |code will pass the DB connection object to the GUI.py, so the GUI can |continue to talk with the database. GUI.py runs and does its magic, in |the meantime Application.py waits for GUI.py to finished and then both |exit. |Is that what you had in mind? Very close - I have not even thought this far - I did not think of building a GUI for each user, I thought of building it for each transaction - kind of a series of things like my toy - and then I got stuck on the "linking the separate transaction guis into an app on the fly" bit, which is why I started the thread - I really want to know if it is possible to do this sort of thing in Python, and so far Bruno has come up with Pyro, while everybody else (including Bruno) is beating me over the head with HTML Now part of the reason I would like to go the transaction type route instead of the "per user" route is robustness and maintainability, and the ability it would give me to introduce new transaction types easily - as I see it if say an invoice's GUI code is stable I would never have to touch it again even if I combine it with anything else, as it would have been designed from the start to combine with others of it's own ilk, under a kind of communications controller that is standard... |NOTE: This means that the client will need to have all the required |libraries at just the right versions. Imagine that your user decides to |upgrade to Python 3000 because it sounds cooler than plain old Python |2.4 ;) , but then they won't realize that it will break your code and |they might not be able to run your application anymore. So you would |have to know at least roughly how much control over the whole client |machine you will have. Will they all be regular desktops that users |will use day to day and then once in a while launch your application |then close it, or will these all be dedicated terminals like an ATM? |The two are very different. You can assume complete control of all the |OS environment in a dedicated terminal but not in the case of a user |desktop. True - have not even considered this - this would, I imagine, vary from site to site, and depend more on local IT policy - this is probably the strongest argument to date against going this route, as these machines would not be as tightly controlled as an ATM... but then - If I want to use Python in the client at all, I would have to somehow come to terms with this - its more the normal sort of version control that would have to be done - after all if a user's machine is an XT running DOS - then its going to have to be upgraded before it can be used as a terminal... So this is more an argument against the use of Python on the client and I don't like that... |Hope this helps, |Nick Vatamaniuc 8<---------------------------------------------------- Yes it does, Thanks. I feel we are getting closer to the point where I can decide if what I am thinking of is practical or a pipe dream - it sounded so simple - make a series of guis for a series of transactions, ship them to the client, where there is a simple top level thingy that swallows them and ties them all together and handles the comms to the server... I mean the language is called Python... :-) - Hendrik From tjreedy at udel.edu Tue Aug 15 10:01:36 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 15 Aug 2006 10:01:36 -0400 Subject: what is the keyword "is" for? References: <1155625097.784052.31330@p79g2000cwp.googlegroups.com> Message-ID: "Sybren Stuvel" wrote in message news:slrnee2sqi.qt8.sybrenUSE at schuimige.stuvel.eu... > 'is' compares the object's addresses. It actually compares the objects' integer identifiers. That happens to be the linear memory address for CPython, but not necesarily so for other interpreters. tjr From rdrink at gmail.com Tue Aug 29 00:13:46 2006 From: rdrink at gmail.com (rdrink) Date: 28 Aug 2006 21:13:46 -0700 Subject: eval() woes References: <1156735954.796051.290600@i3g2000cwc.googlegroups.com> <1156740704.380857.76670@i42g2000cwa.googlegroups.com> <1156817948.765024.13770@p79g2000cwp.googlegroups.com> Message-ID: <1156824826.778486.251380@74g2000cwt.googlegroups.com> Ok, maybe now I can make some more sense of this, with an example of real code (sorry if it's a bit dense): This is the basic function... def equate(parts,new_eq): oL = int(parts[0]) iL = int(parts[1]) iR = int(parts[2]) oR = int(parts[3]) oLoL = int(str(oL)+str(oL)) oLiL = int(str(oL)+str(iL)) oLiR = int(str(oL)+str(iR)) oLoR = int(str(oL)+str(oR)) iLoL = int(str(iL)+str(oL)) iLiL = int(str(iL)+str(iL)) iLiR = int(str(iL)+str(iR)) iLoR = int(str(iL)+str(oR)) iRoL = int(str(iR)+str(oL)) iRiL = int(str(iR)+str(iL)) iRiR = int(str(iR)+str(iR)) iRoR = int(str(iR)+str(oR)) oRoL = int(str(oR)+str(oL)) oRiL = int(str(oR)+str(iL)) oRiR = int(str(oR)+str(iR)) oRoR = int(str(oR)+str(oR)) new_seed = eval(new_eq) return new_seed ... into which is passed two items: - 'parts' , which is a list e.g ['12','34','56','78'] (of strings) - and 'new_eq',which is also a string read from a text file, e.g. "pow(oLiL,2)" And so...for the first 9 entries (of 480) in the text file where... pow(oLiL,2) pow(oLiL,2) - oL pow(oLiL,2) - iL pow(oLiL,2) - iR pow(oLiL,2) - oR pow(oLiL,2) + oL pow(oLiL,2) + iL pow(oLiL,2) + iR pow(oLiL,2) + oR pow(oLiL,2) pow(oL - iL,2) ... eval() works fine. But on the 10th... pow(oL - iL,2) - oL ... it bombs with the error: pow(oL - iL,2) - oL Traceback (most recent call last): File "the_farmer2.py", line 264, in ? seed = equate(parts,equation) File "the_farmer2.py", line 112, in equate iL = int(parts[1]) ValueError: invalid literal for int(): - And what is interseting/odd is: - For the third, '- iL' evaluates fine... - as well as the 9th, [where it is nested, oL - iL, inside pow()] ... - but in the 10th, where a subtraction is called twice, it doesn't. Which leads me to believe that the problem is either inside eval() it's self, or in the way these variables are being cast... but I can't tell which. (BTW, as a footnote: For each of the above 'equations' the function equate() was called 500 times... in some cases with the list 'parts' equaling things like ['0',2','3','0'], so I have no reason to believe that the problem is with the way the list is being passed in... but I could be wrong) Can anyone see something I can't? Robb From chosechu at gmail.com Tue Aug 29 16:35:17 2006 From: chosechu at gmail.com (chosechu) Date: 29 Aug 2006 13:35:17 -0700 Subject: Extending the dict class In-Reply-To: <44f458e9$0$12791$626a54ce@news.free.fr> References: <1156852916.254032.172390@b28g2000cwb.googlegroups.com> <44f4313e$0$26985$626a54ce@news.free.fr> <1156854958.228815.107090@m73g2000cwd.googlegroups.com> <1156856325.095181.303140@p79g2000cwp.googlegroups.com> <1156858083.338457.66590@b28g2000cwb.googlegroups.com> <44f458e9$0$12791$626a54ce@news.free.fr> Message-ID: <1156883717.316350.24530@i42g2000cwa.googlegroups.com> Bruno Desthuilliers wrote: > It's usually possible to modify third-parts classes behaviour on the fly > (googling for 'monkey-patching' should get you started). But true, this > doesn't work with builtins. I guess this stems from the fact that Python dictionaries are C creatures and they are themselves used for internal housekeeping, so no high-level modifications can be allowed to disturb language internals. This all makes sense. It is sad not to have the possibility to extend built-ins but on the other hand it guarantees a constant (predictable) behaviour, which I agree is something we should protect. Thanks to all contributors for your nearly instantaneous reaction times and help on the topic. From mail at microcorp.co.za Wed Aug 23 02:14:50 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 23 Aug 2006 08:14:50 +0200 Subject: What do you want in a new web framework? References: <1156100331.329889.216340@p79g2000cwp.googlegroups.com><1156156636.515678.118210@75g2000cwc.googlegroups.com><4jele2pe011di99c5dnq4olclglrkieggc@4ax.com> <1hkgnbt.ebn4o1111ftp0N%aleax@mac.com> Message-ID: <00b301c6c684$2961dd20$03000080@hendrik> "Alex Martelli" | Tim Roberts wrote: | ... | > themselves. However, in the case of web frameworks, I believe Marc is | > fundamentally correct: the web framework proliferation in Python is | > actually doing the language a huge disservice. | | Indeed, it has been truthfully observed that Python's the only language | with more web frameworks than keywords. | | I have already suggested to the BDFL that he can remedy this situation | in Py3k: all he has to do, of course, is to add a LOT more keywords. | | | Alex *groan* From cliff at develix.com Thu Aug 31 17:58:45 2006 From: cliff at develix.com (Cliff Wells) Date: Thu, 31 Aug 2006 14:58:45 -0700 Subject: Pros/Cons of Turbogears/Rails? In-Reply-To: <740c3aec0608311431q1fdd21a6x496957508135504d@mail.gmail.com> References: <1157034321.926854.123520@m79g2000cwm.googlegroups.com> <1157037862.804249.81290@b28g2000cwb.googlegroups.com> <32822fe60608311112u7ad04f1bhb998351fb15d682@mail.gmail.com> <740c3aec0608311431q1fdd21a6x496957508135504d@mail.gmail.com> Message-ID: <1157061525.31869.54.camel@devilbox> On Thu, 2006-08-31 at 23:31 +0200, BJ?rn Lindqvist wrote: > On 8/31/06, Jorge Vargas wrote: > > On 31 Aug 2006 08:24:29 -0700, Adam Jones wrote: > > > > Someone ones said on the mailing list TG is the Ubuntu of web > > frameworks, and I think I'll add and you can strip down the kernel and > > it wont break :) > > But that is not really true. If you use Cheetah instead of Kid, you > lose out: No widgets, Untrue. Even though I don't use widgets much myself, I wanted to make sure they *could* be used with TurboStan, so I did a quick test with Kevin's autocomplete widget. Worked fine. I can't see why Cheetah would be any different. > no auto-generated code What auto-generated code? The example templates that you get with quickstart? Hardly a loss. > and the (incomplete) > documentation won't apply anymore (it assumes Kid templates ofcourse). True. However I've had little trouble translating from Kid to Stan (and that's probably a longer jump than from Kid to Cheetah). > If you use SQLAlchemy instead of SQLObject, no identity framework, Completely false. > no administrative tools (tg-admin sql, True. > CatWalk etc True. > ) and no documentation. Partially true. The documentation exists but some of it is out-of-date and it was never very complete to begin with. Of course, like many OSS projects, the mailing list is your best resource and SQLAlchemy itself has quite good documentation. > If you use prototype instead of MochiKit... I have no idea what > happens You get Prototype instead of MochiKit. > and using another webserver than CherryPy isn't possible right > now, I guess? Not that I'm aware of. Nor do I think it would make much sense since CherryPy is the heart of TurboGears. I typically use CherryPy to serve the dynamic content and a real webserver (Nginx) to serve static files. I've never felt this was a handicap. > In fact, if you decide to replace so many modules that TurboGears > depend on, what do you gain in using TurboGears at all? If you got to the point where you were replacing more parts than you were using, then you'd certainly want to find a different framework as TurboGears is clearly not for you. I fail to see your point. Personally I've chosen to go a different route on a couple things and leave the rest intact. I expect most people are the same. With most frameworks, there's typically one or two things most people don't like and it's nice to be able to replace those things without a lot of fuss. I don't see how that's a liability. > It seems like > the TurboGears developers have a lot of work to do, (and a lot of > documentation to write) if they want to make their framework as easy > to use as others (ie: Django) that takes a more holistic approach. That's odd, because I've actually used both and found TurboGears far easier to get started with (no mucking about with Apache and mod_python for one thing, no need to setup explicit url regexes just to get "hello, world" on a page). Judging from your above comments it sounds to me like you're mostly speculating about TurboGears. > TurboGears more seem to be like emacs than Ubuntu - infinitely > customizable... Not quite enough IMO, but close enough. > In the future both Rails and TurboGears will probably be great. But > since someone mentioned Rails moving to YARV, and TurboGears moving to > SQLAlchemy and Markup, it seems to me that they are both in a state of > flux and not quite ready yet. TurboGears is certainly in a state of flux although from an outside (i.e. API) standpoint it's not nearly as bad as you might think from the changes that have gone on under the hood. There's been only a few breaking changes up til now (I converted a site I'd built on 0.8 to the latest SVN last night and most of the issues I encountered were with my own changes to TurboStan). Regards, Cliff -- From rogue_pedro at yahoo.com Sat Aug 12 13:03:30 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 12 Aug 2006 10:03:30 -0700 Subject: iterator wrapper References: <8cednRaDbu_RkkDZnZ2dnUVZ_sKdnZ2d@comcast.com> <1155339879.395139.182050@m73g2000cwd.googlegroups.com> <1155340917.733325.74780@i3g2000cwc.googlegroups.com> <1155351613.395862.211900@74g2000cwt.googlegroups.com> Message-ID: <1155402210.257607.266410@h48g2000cwc.googlegroups.com> alf wrote: > Simon Forman wrote: > >> > >>>|>> I = ([n] for n in i) > >> > >>This is nice but I am iterating thru hude objects (like MBs) so you know ... > >> > > > > No, I don't know... :-) > > potentially my source lists are huge - so wanted to avoid unnecessary > memory allocation > > > > My friend, I think you've misunderstood. Observe: > > > > |>> L = [n for n in range(3)] > > |>> G = (n for n in range(3)) > > |>> L > > [0, 1, 2] > > |>> G > > > > well, I am in the python 2.3 word where generator comprehensions seem > not to work. So I just took it a preallocated list comprehention. still > wonder if there would be a difference between: > > G = (n for n in range(300000000)) - this creates the huge list there > G = (n for n in xrange(300000000)) - this (at least to my understanding) > does not > Yes, you've got it, the xrange() version will not allocate a huge list. It's not part of your main question, and I understand that there may be reasons why you can't, but consider upgrading to 2.4 (or very soon now 2.5...) Meanwhile, in 2.3 both John Machin's and Paul Rubin's solutions will do the trick (as you already know ;-) ) > > > > List comprehensions [] create lists, generator comprehensions () create > > generators. > > > > > > Generator comprehensions work "just-in-time", pulling items from > > whatever they're iterating over as they themselves are iterated over, > > as I hope this example makes clear: > > > >[...] > > got it now ... thx or the lesson.... > > > A. No problem. These are things I learned over time, it's fun to share the knowledge. :) Peace, ~Simon From paddy3118 at netscape.net Sat Aug 5 16:22:14 2006 From: paddy3118 at netscape.net (Paddy) Date: 5 Aug 2006 13:22:14 -0700 Subject: Something for PyPy developers? Message-ID: <1154809334.734417.314660@i42g2000cwa.googlegroups.com> I just found this: http://www.cs.princeton.edu/~dpw/popl/06/Tim-POPL.ppt And thought of you... :-) called "The Next Mainstream Programming Languages", Tim Sweeney of Epic Games presents on problems that game writers see and muses on possible solutions. - Pad. From slawomir.nowaczyk.847 at student.lu.se Thu Aug 10 06:43:53 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Thu, 10 Aug 2006 12:43:53 +0200 Subject: do people really complain about significant whitespace? In-Reply-To: <1155134021.169710.24540@75g2000cwc.googlegroups.com> References: <1155134021.169710.24540@75g2000cwc.googlegroups.com> Message-ID: <20060810115400.EF31.SLAWOMIR.NOWACZYK.847@student.lu.se> On Wed, 09 Aug 2006 07:33:41 -0700 Rob Wolfe wrote: #> Slawomir Nowaczyk wrote: #> #> > Really, typing brace after function/if/etc should add newlines and #> > indent code as required -- automatically. Actually, for me, it is even #> > *less* typing in C and similar languages... I probably should teach my #> > Emacs to automatically add newline after colon in Python, just as it #> > does after a brace in C... As soon as I figure out how to deal with #> > dictionary literals. Hmmm. #> #> Are you sure? My Emacs already know how to do it with the help #> of python-mode and magic function py-newline-and-indent. #> #> emacs-version "21.3.1" #> py-version "$Revision: 4.63 $" OK, my python-mode.el was older, so I upgraded to 4.75, but it still doesn't work. Did you mean that after you write if x==1: the newline is inserted automatically when you type ":"? That's a functionality I would like to see, but it doesn't seem to work this way. Anyway, I am using python.el most of the time and it doesn't have that functionality yet. -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) Live in the past and future only. From duncan.booth at invalid.invalid Sun Aug 27 15:11:51 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 27 Aug 2006 19:11:51 GMT Subject: avoiding file corruption References: <1156664673.325201.271140@i42g2000cwa.googlegroups.com> <12f3bo1t1ccr858@corp.supernews.com> Message-ID: Dennis Lee Bieber wrote: > On Sun, 27 Aug 2006 14:41:05 -0000, Grant Edwards > declaimed the following in comp.lang.python: > >> >> MS Windows seems to do something similar, and it pisses me off >> no end. Trying to open a file and read it while somebody else >> has it open for writing causes an exception. If I want to open >> a file and read it while it's being writtent to, that's my >> business. >> > Though strangely, Windows seems to permit one to make a COPY of that > open file, and then open that with another application... Yes, so long as the file hasn't been opened so as to deny reading you can open it for reading, but you do have to specify the sharing mode. Microsoft too follow the rule that "Explicit is better than implicit." From sjmachin at lexicon.net Wed Aug 9 19:15:49 2006 From: sjmachin at lexicon.net (John Machin) Date: 9 Aug 2006 16:15:49 -0700 Subject: What's the cleanest way to compare 2 dictionary? In-Reply-To: <1155147450.628625.20270@m79g2000cwm.googlegroups.com> References: <1155147450.628625.20270@m79g2000cwm.googlegroups.com> Message-ID: <1155165349.766502.314760@n13g2000cwa.googlegroups.com> John Henry wrote: > Hi list, > > I am sure there are many ways of doing comparision but I like to see > what you would do if you have 2 dictionary sets (containing lots of > data - like 20000 keys and each key contains a dozen or so of records) > and you want to build a list of differences about these two sets. > > I like to end up with 3 lists: what's in A and not in B, what's in B > and not in A, and of course, what's in both A and B. > > What do you think is the cleanest way to do it? (I am sure you will > come up with ways that astonishes me :=) ) > Paddy has already pointed out a necessary addition to your requirement definition: common keys with different values. Here's another possible addition: you say that "each key contains a dozen or so of records". I presume that you mean like this: a = {1: ['rec1a', 'rec1b'], 42: ['rec42a', 'rec42b']} # "dozen" -> 2 to save typing :-) Now that happens if the other dictionary contains: b = {1: ['rec1a', 'rec1b'], 42: ['rec42b', 'rec42a']} Key 42 would be marked as different by Paddy's classification, but the values are the same, just not in the same order. How do you want to treat that? avalue == bvalue? sorted(avalue) == sorted(bvalue)? Oh, and are you sure the buckets don't contain duplicates? Maybe you need set(avalue) == set(bvalue). What about 'rec1a' vs 'Rec1a' vs 'REC1A'? All comparisons are equal, but some comparisons are more equal than others :-) Cheers, John From crystalattice at gmail.com Fri Aug 25 13:35:15 2006 From: crystalattice at gmail.com (crystalattice) Date: 25 Aug 2006 10:35:15 -0700 Subject: Best Editor In-Reply-To: <44ed8db6$0$75034$14726298@news.sunsite.dk> References: <44ed8db6$0$75034$14726298@news.sunsite.dk> Message-ID: <1156527313.995637.49930@i42g2000cwa.googlegroups.com> JAG CHAN wrote: > Friends, I am trying to learn Python. > It will be of great help to me if you let me know which one would be best > editor for learning Python. > Plese note that I would like to have multiplatform editor which will be > useful for both LInux and Windows XP. > Thanks. My choice is SPE. It has wxGlade built-in for easy creation of wxPython GUIs, syntax error highlighting, etc. It's cross-platform too. It does require installing wxPython, though that's not difficult. From djoefish at gmail.com Sat Aug 19 16:34:34 2006 From: djoefish at gmail.com (djoefish) Date: 19 Aug 2006 13:34:34 -0700 Subject: install patch on windows In-Reply-To: <87y7tka3ev.fsf@gmail.com> References: <1156014103.715131.143360@i3g2000cwc.googlegroups.com> <1156017314.249545.296940@h48g2000cwc.googlegroups.com> <1156017655.849634.95240@p79g2000cwp.googlegroups.com> <87y7tka3ev.fsf@gmail.com> Message-ID: <1156019674.571704.196780@i42g2000cwa.googlegroups.com> Jorge Godoy wrote: > "djoefish" writes: > > > Tim Golden wrote: > >> djoefish wrote: > >> > Does anyone know how to install a patch on Winodws? For example, I want > >> > to install the patch 'ocmalloc-free-arenas.diff' in Python 2.3. > >> > >> You can get patch (and quite a lot besides) for win32 from > >> the UnxUtils project: > >> > >> http://sourceforge.net/projects/unxutils > >> > >> TJG > > > > Thanks, but that project seems to be dead.... > > The files there didn't work? > > -- > Jorge Godoy not exactly...there are NO files there. Butfrom the forums I found out about GNUWin32, which has a 'patch' program for windows. I amd trying it now to see if it works. From fredrik at pythonware.com Tue Aug 22 17:20:29 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Aug 2006 23:20:29 +0200 Subject: how do you get the name of a dictionary? In-Reply-To: <1156281268.865624.302070@b28g2000cwb.googlegroups.com> References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> <1156264475.968894.221710@p79g2000cwp.googlegroups.com> <1156266720.205126.284050@i3g2000cwc.googlegroups.com> <1156268752.574983.123520@75g2000cwc.googlegroups.com> <1156281268.865624.302070@b28g2000cwb.googlegroups.com> Message-ID: jojoba wrote: > I know i must be driving python purists to their limits... no, you're just wasting a lot of bandwidth making it clear that you just cannot be bothered to learn how things actually work. do you behave this way in real life too, or is it just something you're doing on the internet ? From drodrig at magicbrain.com Sat Aug 12 15:17:38 2006 From: drodrig at magicbrain.com (drodrig) Date: 12 Aug 2006 12:17:38 -0700 Subject: Kill process based on window name (win32) References: <1155356918.399290.266470@p79g2000cwp.googlegroups.com> <1155362407_8127@sp6iad.superfeed.net> Message-ID: <1155410258.877085.86840@75g2000cwc.googlegroups.com> Thank you Roger. Your advice did the trick. For anyone interested, the basic code to terminate a process (politely) would be something like this (hwnd is retrieved using win32gui.EnumerateWindows): # Get the window's process id's t, p = win32process.GetWindowThreadProcessId(hwnd) # Ask window nicely to close win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0) # Allow some time for app to close time.sleep(10) # If app didn't close, force close try: handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, p) if handle: win32api.TerminateProcess(handle,0) win32api.CloseHandle(handle) except: pass: Roger Upole wrote: > drodrig wrote: > > Hi. > > > > I am trying to close/kill all processes that show visible windows on > > Windows XP. So far I've created a script that uses win32gui.EnumWindows > > to iterate through all windows, check for which windows are visible, > > then send a WM_CLOSE message to the window to request that it closes. > > Of course, not all apps want to close nicely. At this point I need to > > use something like TerminateProcess to kill the app, but how do I find > > the process id (hopefully based on the window id). > > > > Thanks for any help. > > > > win32process.GetWindowThreadProcessId should do the trick. > > Roger From mccredie at gmail.com Wed Aug 16 23:22:15 2006 From: mccredie at gmail.com (Matimus) Date: 16 Aug 2006 20:22:15 -0700 Subject: Printing n elements per line in a list References: <1155685889.626881.37040@m73g2000cwd.googlegroups.com> <1155769304.916282.183340@i3g2000cwc.googlegroups.com> <1155770893.267734.81400@h48g2000cwc.googlegroups.com> Message-ID: <1155784935.362159.241630@m79g2000cwm.googlegroups.com> John Machin wrote: > Matimus wrote: > > unexpected wrote: > > > If have a list from 1 to 100, what's the easiest, most elegant way to > > > print them out, so that there are only n elements per line. > > > > > > So if n=5, the printed list would look like: > > > > > > 1 2 3 4 5 > > > 6 7 8 9 10 > > > 11 12 13 14 15 > > > etc. > > > > > > My search through the previous posts yields methods to print all the > > > values of the list on a single line, but that's not what I want. I feel > > > like there is an easy, pretty way to do this. I think it's possible to > > > hack it up using while loops and some ugly slicing, but hopefully I'm > > > missing something > > > > I suppose 'elegance' is in the eye of the beholder. I agree with the > > previous posts, a readable for loop is probably the best way to go. > > I've instead chosen to use the functional paradigm. I thought someone > > might appreciate this: > > > > p = sys.stdout.write > > map(p,[str(i)+("\n"+" "*(n-1))[i%n] for i in range(1,101)]) > > At least three strikes: > > 1. The functional paradigm AFAIK abjures side effects. > > |>>> n = 3 > |>>> map(p,[str(i)+("\n"+" "*(n-1))[i%n] for i in range(1,11)]) > 1 2 3 > 4 5 6 > 7 8 9 > 10 [None, None, None, None, None, None, None, None, None, None] > > If you want functional, instead of > map(sys.stdout.write, strings) > do this: > sys.stdout.write(''.join(strings)) > > 2. This little gem > ("\n"+" "*(n-1))[i%n] > is better written > " \n"[i%n==0] > > 3. Like some other attempts, it's missing the trailing \n when len(seq) > % n != 0 > > 4. It needs elaboration so that it works with any sequence, not just > range(1, size+1) > > Yer out! > > Cheers, > John Well, I have another at bat, so I will try to redeem myself... using recursion: def printTable(l,c): print(("%d "*len(l[:c]))%tuple(l[:c])) if( len(l[:c]) > 0 ): printTable(l[c:],c) printTable(range(1,101),5) From ray_usenet at yahoo.com Tue Aug 29 06:50:42 2006 From: ray_usenet at yahoo.com (Ray) Date: 29 Aug 2006 03:50:42 -0700 Subject: Pros/Cons of Turbogears/Rails? In-Reply-To: <1156842974.103231.86930@m73g2000cwd.googlegroups.com> References: <1156726071.579429.44650@b28g2000cwb.googlegroups.com> <1156740469.645955.52080@i3g2000cwc.googlegroups.com> <1156768355.275370.129680@h48g2000cwc.googlegroups.com> <1156819473.592153.141940@i42g2000cwa.googlegroups.com> <1156842974.103231.86930@m73g2000cwd.googlegroups.com> Message-ID: <1156848642.090479.159740@p79g2000cwp.googlegroups.com> Paul Boddie wrote: > Sure. Just get certified on whatever today's middle management are > advocating, spend a few years working with that stuff, then repeat the > process for the next generation of middle management - it can certainly > make money for people who don't seek any meaning in what they do. It can certainly make money--true. "Don't seek any meaning in what they do"?! You're just accusing a lot of honest hardworking people to be mindless drones there. We have feelings too, you know :( > > Yeah, see, the thing is that Python is not lacking luminaries endorsing > > it either, e.g.: Eric Raymond and Bruce Eckel. But for some reason this > > "Python is good" meme is not that viral. I wonder why... > > Python has had its share of the spotlight: Eric Raymond's advocacy > dates back to the late 1990s; Bruce Eckel still advocates Python but > started doing so a few years ago. Perhaps the latest arrivals to the > party (celebrating dynamic languages in this case) are usually the > loudest, in order to make up for their sluggish realisation that Java > isn't the panacea they insisted it was while it was still the cool new > thing. Or perhaps a lot of these people do quite nicely out of surfing > whatever trend currently is the cool new thing. Perhaps that is true. A pity though, personally I tried to learn Ruby but it just doesn't go well with my brain. > > And, since when do hard facts matter anyway? > > When certain individuals claim that more Java people know about Ruby > than they do about Python. First, that question was supposed to be rhetorical :) Second, my claim is not that general. Certainly proving such a general claim is an enormous undertaking. It just happens that most of Java developers I know, and I know quite a lot since I've been doing this for years, they know Ruby and Rails. Python, Django, Turbogears, make them go "huh?". I've heard of one entrepreneurial guy starting an exclusively RoR shop and doing quite well at it. I haven't heard a Django/Turbogears shop yet. > I know that there are people out there who > know (about) Java but not about Jython, for example, but even in > circles where buzz and hype seem like everything (eg. marketing) the > hard facts or statistics are still critical because they actually help > those people do their job properly. Moreover, just stating something > doesn't make it true - the hard facts serve to prove or disprove such > assertions, and to anyone serious about understanding the underlying > phenomena, it's vital to seek those facts out. True. But since when do hard facts matter? That is, it's not that I haven't tried to make people know how great Python is. but I can talk until I'm blue in the face and they just go, "nah". What I'm saying is that people (and management) unfortunately are sold to not with hard facts, but with whatever that X viral factor is. And for some reason the RoR crowd has managed to make it quite viral. > > I've met a number of > > people who've told me they'd program in Eiffel if they could. And hey, > > perhaps in its day Eiffel *was* the best OO language out there. > > Certainly it looked cleaner than C++! :) > > So why don't they? Management pressure? Why don't people write more > Python in their day job? Any suggestions? Well, I posted in this group a few weeks ago because I was trying to convince the managers to give Python a try and was looking for additional ammo. In the end Django is out because of its lack of support for Oracle. But it's a catch 22 isn't it? We're a Java shop so our developers are trained in Java, Struts, Tomcat, etc. Any switch to a dynamic language will be a huge change. However it baffles me that they are open to at least a PoC in Rails. but when I suggested Python, they went: "nah we're not interested in Python. Rails it is." *shrugs* whatever it is, those guys are doing something right. > Paul From saad82 at gmail.com Mon Aug 7 19:58:48 2006 From: saad82 at gmail.com (wipit) Date: 7 Aug 2006 16:58:48 -0700 Subject: python - HTML processing - need tips Message-ID: <1154995128.118127.227840@i3g2000cwc.googlegroups.com> I need to process a HTML form in python. I'm using urllib2 and HTMLParser to handle the html. There are several steps I need to take to get to the specific page on the relevant site the first of which is to log in with a username/password. The html code that processes the login consists of 2 edit boxes (for User ID and Password) and a Submit button which uses ASP.net client side validation as follows (formatted for clarity): User ID: Valid Email format is required Password:       I've looked at all the relevant posts on this topic and already looked at mechanize and ClientForm. It appears I can't use those for 2 reasons: 1) that they can't handle client side validation and 2) this button doesn't actually reside in a form and I haven't been able to find any python code that obtains a handle to a submit control and simulates clicking on it. I've tried sending the server a POST message as such: loginParams = urllib.urlencode({'txtUserName': theUsername, 'txtUserPass': thePassword}) txdata = None txheaders = {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'} req = Request(url1, txdata, txheaders) # url1 points to the secure page seen following login handle = urlopen(req, loginParams) But this doesn't work. I dont understand the use of Page_ClientValidate( ) and haven't really found any useful documentation on it for my purposes. I basically need to be able to submit this information to the site, by simulating the onclick event through python. As far as I understand I need a solution to the 2 points I mentioned above (getting past client-side validation and simulating a click of a non-form button). Any help on this (or other issues I might have missed but are important/relevant) would be great! Many thanks, Pythonner From apardon at forel.vub.ac.be Tue Aug 29 02:06:38 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 29 Aug 2006 06:06:38 GMT Subject: Is this a good idea or a waste of time? References: <1156449402.022781.292840@p79g2000cwp.googlegroups.com> <1156485945.967160.238790@m73g2000cwd.googlegroups.com> <44f322cd$1@nntp0.pdx.net> <1156802762.331853.80000@75g2000cwc.googlegroups.com> <1156830387.226840.39070@b28g2000cwb.googlegroups.com> Message-ID: On 2006-08-29, Simon Forman wrote: > Antoon Pardon wrote: >> On 2006-08-28, sjdevnull at yahoo.com wrote: >> > Antoon Pardon wrote: >> >> There seem to be enough problems that work with ints but not with >> >> floats. In such a case enforcing that the number you work with >> >> is indeed an int seems fully appropiate. >> > >> > I've _never_ seen a case where enforcing types in the manner of the OP >> > is appropriate. >> > >> > It fails with trivial wrappers like >> > >> > class myInt(int): >> > def printFormatted(self): >> > .......... >> > >> > Even looser checking with isinstance is rarely right. You may want to >> > exclude floats, but that doesn't mean you want to exclude int-like >> > objects that don't inherit from int. >> >> That may be true. But one may wonder if this is a failing of the >> programmer or a failing of the language that doesn't support >> such things. > > What the hell are you talking about? Yes, I should have been more clearer. > I'm curious: what is the meaning, to you, of the word "this" in your > sentence above? That something like "type(x) == int" or "isinstance(x, int)" doesn't allow to check for all int like objects, nor that there is some python idiom that should allow you to test for such a thing (although it might be circumvented). With that second sentence I mean that there could exist a python convention that prescribed that all int like objects had to be subtypes of int. In that case code that followed the convention could use "isinstance(x, int)" to check for int like objects. -- Antoon Pardon From rdrink at gmail.com Mon Aug 28 22:19:08 2006 From: rdrink at gmail.com (rdrink) Date: 28 Aug 2006 19:19:08 -0700 Subject: eval() woes References: <1156735954.796051.290600@i3g2000cwc.googlegroups.com> <1156740704.380857.76670@i42g2000cwa.googlegroups.com> Message-ID: <1156817948.765024.13770@p79g2000cwp.googlegroups.com> Hey Simon, Thanks for the reply. Simon Forman wrote: > You must be doing something weird, that equation works for me: > Try posting the minimal code example that causes the error and the > full, exact traceback that you get. I appreciate the offer... but at this point my code is too recursive and deeply nested to send a "simple" example > (Also, assuming your equations are already strings, there's no reason > to call str() on them again. This is an interesting point: I AM putting them into the file as strings, and then pulling them back out as such and you are right, they do not need to be re-cast as strings. I think as some point I was getting errors there, but for now I can omit that.... > And you mention a "dictionary level" but > don't mention using a dict.) Sorry, that was a spurious thought... No I'm not using a dict (although I am still not sure if I should be)... > FWIW, the error "ValueError: invalid literal for int()" occurs when > you, uh, pass an invalid literal to the int() function (actually int > type.. but not important here), and includes the invalid input so you > don't have to guess at it: > > |>> int('wombat') > HTH Yes that is helpful. I am still getting errors... which leads me to belive that it all has to do with how I am casting, and re-casting, things as strings and ints. I need a little more time to try to suss this all out; after which, if I still can't get it to work, I'll post some more code. Thanks again for your thoughts and comments. Robb From bj_666 at gmx.net Wed Aug 16 03:57:49 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 16 Aug 2006 09:57:49 +0200 Subject: Very weird behavior that's driving me crazy References: <44e2c4c3$0$20039$9b4e6d93@newsspool4.arcor-online.net> Message-ID: In <44e2c4c3$0$20039$9b4e6d93 at newsspool4.arcor-online.net>, Pupeno wrote: > - Shouldn't the manager be the same in the first print and the second, that > is, the id is different, shouldn't it be the same ? > - What happened with all the output of SensorSingleton.getStatus() ? there's > no trace of it (but there's output of the method it calls). > - Why doesn't the SensorSingleton.getStatus() return the return value of > manager.getStatus(), it's a very straight forward call to it and return it. How have you tested this? Is there any chance it was an interactive session and you forgot to reload the module after making changes to it? Ciao, Marc 'BlackJack' Rintsch From yuxi at ece.gatech.edu Mon Aug 14 23:56:02 2006 From: yuxi at ece.gatech.edu (Yu-Xi Lim) Date: Mon, 14 Aug 2006 23:56:02 -0400 Subject: How to fill a form In-Reply-To: <20060815054343.1c31f3f7.sulsa@gazeta.pl> References: <20060815034051.89ef7e18.sulsa@gazeta.pl> <20060815050733.10e14112.sulsa@gazeta.pl> <12e2gau4jouhmcf@corp.supernews.com> <20060815054343.1c31f3f7.sulsa@gazeta.pl> Message-ID: Sulsa wrote: > but i don't know how to post these data if i knew there there would > be no topic. http://docs.python.org/lib/module-urllib.html You want to look at urlopen and urlencode. But if you mean you don't know what fields and data to use, then you need a HTML reference, not a Python one. From rosedb0 at gmail.com Mon Aug 14 09:48:24 2006 From: rosedb0 at gmail.com (hiaips) Date: 14 Aug 2006 06:48:24 -0700 Subject: Best IDE for Python In-Reply-To: <1155555537.877334.61030@75g2000cwc.googlegroups.com> References: <1155541849.350392.31190@h48g2000cwc.googlegroups.com> <1155555537.877334.61030@75g2000cwc.googlegroups.com> Message-ID: <1155563304.915322.249360@b28g2000cwb.googlegroups.com> I'm assuming that FOS = "free open source"... In any case, what operating system do you run? If you're on OS X, I highly recommend TextMate. It's not free, but it has good support (either via built-in or third-party plugins) for Python as well as HTML, SQL, XML, Django templates, and the like. A lot of Rails folks use it (as well as Django and TurboGears developers, I might add). The best general-purpose IDE for Python, IMO, is WingIDE. Again, it's not free (personal license will cost you $30). It runs on each of the major platforms - Windows, Linux, OS X - and has some nice features, including code completion, syntax highlighting, a built-in Python shell, etc. I don't think it has any features built-in specifically for web dev, however; if you have to do lots of HTML, XML, and SQL as part of your project, you might want something a bit more general-purpose. If you're determined to go the FOSS route, you can always use VIM, Emacs, Eric, or SPE. Just my two cents... --dave From mturillo at gmail.com Tue Aug 22 13:34:42 2006 From: mturillo at gmail.com (Perseo) Date: 22 Aug 2006 10:34:42 -0700 Subject: Create a Multilanguage PDF in Python In-Reply-To: <4ku5d0Fdsn8fU1@uni-berlin.de> References: <1156073383.983914.149180@i3g2000cwc.googlegroups.com> <87mz9z4f8h.fsf@smsnet.pl> <1156108451.762961.70140@h48g2000cwc.googlegroups.com> <1156143575.547217.237270@p79g2000cwp.googlegroups.com> <1156172609.125230.218190@i42g2000cwa.googlegroups.com> <4ku5d0Fdsn8fU1@uni-berlin.de> Message-ID: <1156268082.297699.210830@m79g2000cwm.googlegroups.com> Thanks I will try it. Diez B. Roggisch wrote: > Perseo wrote: > > > I can't upload in the PYTHONPATH but in a normal folder of our site. > > Exist another way to do it? > > PYTHONPATH is an environment variable. You can set it to arbitrary paths, > and python will look for module there, too. Or you modify sys.path before > you try the import. > > Diez From fluxent at gmail.com Wed Aug 9 11:22:03 2006 From: fluxent at gmail.com (fluxent at gmail.com) Date: 9 Aug 2006 08:22:03 -0700 Subject: timeout calling local sendmail In-Reply-To: <1154963394.878933.80540@h48g2000cwc.googlegroups.com> References: <1154963394.878933.80540@h48g2000cwc.googlegroups.com> Message-ID: <1155136923.344196.67010@m73g2000cwd.googlegroups.com> that's "timeout calling local sendmail" not "timeout calling local se" fluxent at gmail.com wrote: > (Environment: RedHat Linux recent, Python 2.3.5) > > We have a batch processing script that on occasion needs to send out an > email. We have a sendmail running locally. > > Sometimes we get a socket timeout on sending that email. Increasing the > timeout to 30sec reduced but did not eliminate it. > > It seems to happen more often when sending to some addresses in the UK, > but it's definitely not limited to that. > > And, while we sometimes send a number of messages in a short period of > time, (a) it's all single-threaded, and (b) the failure is often but > not always the 1st message in the batch. > > Any ideas on what's going on? I don't know much about the > thread/process model of sendmail to have any clue why this is > happening. From duncan.booth at invalid.invalid Tue Aug 1 09:06:01 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Aug 2006 13:06:01 GMT Subject: Html character entity conversion References: <1154266972.154519.175040@m73g2000cwd.googlegroups.com> <1154274049.338215.116340@75g2000cwc.googlegroups.com> <1154285566.501511.117190@b28g2000cwb.googlegroups.com> Message-ID: pak.andrei at gmail.com wrote: > How can I convert encoded string > > sEncodedHtmlText = 'привет > питон' > > into human readable: > > sDecodedHtmlText == '???????????? ??????????' How about: >>> sEncodedHtmlText = 'text: приветпитоl 5;' >>> def unescape(m): return unichr(int(m.group(0)[2:-1])) >>> print re.sub('&#[0-9]+;', unescape, sEncodedHtmlText) text: ??????????? I'm afraid my newsreader couldn't cope with either your original text or my output, but I think this gives the string you wanted. You probably also ought to decode sEncodedHtmlText to unicode first otherwise anything which isn't an entity escape will be converted to unicode using the default ascii encoding. From sjmachin at lexicon.net Fri Aug 11 09:35:54 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 11 Aug 2006 23:35:54 +1000 Subject: datetime to timestamp In-Reply-To: References: Message-ID: <44dc87b7$1@news.eftel.com> On 11/08/2006 11:10 PM, Simen Haugen wrote: > Hi. > > How can I convert a python datetime to a timestamp? It's easy to convert > a timestamp to datetime (datetime.datetime.fromtimestamp(), but the > other way around...?) > > -Simen > Is the timetuple() method what you want? #>>> import datetime #>>> n = datetime.datetime.now() #>>> n datetime.datetime(2006, 8, 11, 23, 32, 43, 109000) #>>> n.timetuple() (2006, 8, 11, 23, 32, 43, 4, 223, -1) Cheers, John From i3x9mdw at j9n35c.invalid Sat Aug 12 23:40:12 2006 From: i3x9mdw at j9n35c.invalid (Alan Connor) Date: Sun, 13 Aug 2006 03:40:12 GMT Subject: [OT] John Salerno References: <44dd3a65$0$2381$c3e8da3@news.astraweb.com> <44de73c3$0$12587$c3e8da3@news.astraweb.com> Message-ID: On alt.os.linux, in <44de73c3$0$12587$c3e8da3 at news.astraweb.com>, "John Salerno" wrote: Correction: Someone who _sometimes_ calls himself "John Salerno" wrote:

So. You post using three different newsservers, which no one who posts under the same alias all the time does. And are attacking Linux in your original subject: > Subject: and i thought windows made a mess of files... With the typical display of non-literacy of a troll: No caps where caps belong. Your User-Agent string in your headers reads Windows, until this thread, where it is modified only to say Linux instead of Windows, but otherwise the same newsreader. And there are virtually no Linux groups in your posting history for the last year. You are a stinking troll and you will wear a gag when you are in my newsreader. Nor will anyone be allowed to send replies to yourarticles to my newsreader. Regardless of which alias you are hiding behind at the moment, with your tail between your legs where your balls should be. No way I am going to help a stinking troll learn Linux. If you are even trying to, that is... Note: I won't be downloading any articles on this thread. Alan -- Challenge-Response Systems are the best garbage-mail blockers in the world. Spammers and trolls can't beat them and you don't need to be a geek to use them. A brief introduction: http://home.earthlink.net/~alanconnor/cr.html From http Fri Aug 11 20:53:25 2006 From: http (Paul Rubin) Date: 11 Aug 2006 17:53:25 -0700 Subject: iterator wrapper References: <8cednRaDbu_RkkDZnZ2dnUVZ_sKdnZ2d@comcast.com> <1155339879.395139.182050@m73g2000cwd.googlegroups.com> <1155340917.733325.74780@i3g2000cwc.googlegroups.com> Message-ID: <7x1wrmwz96.fsf@ruckus.brouhaha.com> alf writes: > > |>> I = ([n] for n in i) > > This is nice but I am iterating thru hude objects (like MBs) so you know ... I don't understand the objection-- the above is entirely correct and produces the same iterator you'd get from def wrap(i): for x in i: yield [x] I = wrap(i) You could also use import itertools I = itertools.imap(lambda x: [x], i) which again does the same thing. From http Thu Aug 10 19:32:05 2006 From: http (Paul Rubin) Date: 10 Aug 2006 16:32:05 -0700 Subject: Password authentication systems References: <1155218165.193546.136090@h48g2000cwc.googlegroups.com> <7xk65g3cis.fsf@ruckus.brouhaha.com> <1155221184.665002.95160@i42g2000cwa.googlegroups.com> Message-ID: <7xr6zo5fre.fsf@ruckus.brouhaha.com> neokosmos at gmail.com writes: > This is a password authentication system > intended for a game server (a MUD/MMOG, in fact). The real limiting > factor here is that I want to keep the server accessible via pure > telnet protocol. Otherwise, using SSH would make sense. If you're going to broadcast passwords in the clear over the network, that's a pretty big leak as well, that obscuring the stored server-side checksums won't help with. Will the game players use a special client program? If yes, use SRP (http://srp.stanford.edu). This has already been implemented in Python several times. > I had considered the hmac module. The thing that bugs me about it is > that I'd have to keep this secret key around someplace accessible to > the server. Most likely, this means storing it in a file. Yeah, this issue is traditionally a nuisance, especially if the server has to restart itself after a crash. If you start the server manually, you can type in a passphrase. From justin.azoff at gmail.com Thu Aug 3 16:56:32 2006 From: justin.azoff at gmail.com (Justin Azoff) Date: 3 Aug 2006 13:56:32 -0700 Subject: help - iter & dict References: Message-ID: <1154638592.335626.305020@s13g2000cwa.googlegroups.com> aking at mappi.helsinki.fi wrote: > Im trying to iterate through values in a dictionary so i can find the > closest value and then extract the key for that value....what ive done so far: [snip] > short time. I was trying to define a function (its my first!) so that i > could apply to several 'dictionary's and 'exvalue's. [snip] If you plan on searching a single dictionary for many values, it may be much faster to convert the dictionary into a sorted list, and use the bisect module to find the closest value... something like: import bisect class closer_finder: def __init__(self, dataset): self.dataset = dataset flat = [(k,v) for v,k in dataset.iteritems()] flat.sort() self.flat = flat def __getitem__(self, target): flat = self.flat index = bisect.bisect_right(flat, (target, )) #simple cases, smaller than the smaller, #or larger than the largest if index == 0: v,k = flat[0] return k,v elif index == len(flat): v,k = flat[-1] return k,v #otherwise see which of the neighbors is closest. leftval, leftkey = flat[index-1] rightval, rightkey = flat[index] leftdiff = abs(leftval - target) rightdiff = abs(rightval - target) if leftdiff <= rightdiff: return leftkey, leftval else: return rightkey, rightval In [158]:sample_data Out[158]:{'a': 1, 'c': 6, 'b': 3} In [159]:d=closer_finder(sample_data) In [160]:d.flat Out[160]:[(1, 'a'), (3, 'b'), (6, 'c')] In [161]:d[4] Out[161]:('b', 3) -- - Justin From paddy3118 at netscape.net Fri Aug 18 21:51:45 2006 From: paddy3118 at netscape.net (Paddy) Date: 18 Aug 2006 18:51:45 -0700 Subject: sum and strings In-Reply-To: References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <1155922208.930580.135080@m79g2000cwm.googlegroups.com> Message-ID: <1155952305.848495.7060@i3g2000cwc.googlegroups.com> Fredrik Lundh wrote: > Paddy wrote: > > > Here is where I see the break in the 'flow': > > > >>>> 1+2+3 > > 6 > >>>> sum([1,2,3], 0) > > 6 > >>>> [1] + [2] +[3] > > [1, 2, 3] > >>>> sum([[1],[2],[3]], []) > > [1, 2, 3] > >>>> '1' + '2' + '3' > > '123' > >>>> sum(['1','2','3'], '') > > Traceback (most recent call last): > > File "", line 1, in ? > > TypeError: sum() can't sum strings [use ''.join(seq) instead] > Hi Frederik, > do you often write programs that "sums" various kinds of data types, > and for which performance issues are irrelevant? I was asking if sum was indeed an optimization that did not work for strings. I was pointing out its affects on duck-typing. I was hoping that someone might know the history and implementation of sum and could point out the design decisions taken at the time and/or discuss the merits of making sum accept strings. or indeed any type that works with operator.add and that has an additive identity value. Pythons designers seem to know and apply the advantages of having fewer 'themes' that can be applied with less constraints I am curious about such a constraint on sum. - Paddy. From roelmathys at gmail.com Tue Aug 8 16:45:34 2006 From: roelmathys at gmail.com (roelmathys at gmail.com) Date: 8 Aug 2006 13:45:34 -0700 Subject: is it possible to dividing up a class in multiple files? In-Reply-To: References: Message-ID: <1155069934.310677.137920@m79g2000cwm.googlegroups.com> Martin H?fling wrote: > Hi there, > > is it possible to put the methods of a class in different files? I just > want to order them and try to keep the files small. > > Regards > Martin you could do this: file_1.py: class A: def __init__(self): self.a = 1 file_2.py: from file_1 import A def seta(self,value): self.a = value setattr(A,"seta",seta) but to use the "complete" class you should then import file_2 in other source files. bye rm From kylotan at gmail.com Fri Aug 4 10:08:16 2006 From: kylotan at gmail.com (Ben Sizer) Date: 4 Aug 2006 07:08:16 -0700 Subject: Using Python for my web site In-Reply-To: References: <1154361480.915174.262720@b28g2000cwb.googlegroups.com> <1154409902.320511.114320@75g2000cwc.googlegroups.com> Message-ID: <1154700484.212503.264700@i3g2000cwc.googlegroups.com> Cliff Wells wrote: > On Mon, 2006-07-31 at 22:25 -0700, Luis M. Gonz?lez wrote: > > IMHO the best way of using mod_python is with its publisher handler. > > It let's you code your applications in a MVC (model view controller) > > style. > > While I agree (or at least consider the point moot) that this is > possibly the best way to use plain mod_python, I'd disagree that it's a > good way to develop modern web applications in Python. By the time > you've decided on every bit of framework to use, and made all the little > decisions that go into turning a fresh, clean spot on your hard drive > into an application, what you've done is reinvent TurboGears rather than > develop your application. However, at least whatever you come up with would be better documented than TurboGears. ;) (I reserve the right to amend this jocular opinion after TurboGears hits version 1.0.) -- Ben Sizer From rpdooling at gmail.com Wed Aug 9 15:09:38 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 9 Aug 2006 12:09:38 -0700 Subject: os.path.normpath In-Reply-To: <1155149144.453575.181870@m79g2000cwm.googlegroups.com> References: <1155149144.453575.181870@m79g2000cwm.googlegroups.com> Message-ID: <1155150577.991657.225780@h48g2000cwc.googlegroups.com> nathanbullock at gmail.com wrote: > But if this string is going into a webpage link http://docs.python.org/lib/module-urlparse.html rd From xhoster at gmail.com Tue Aug 29 10:38:05 2006 From: xhoster at gmail.com (xhoster at gmail.com) Date: 29 Aug 2006 14:38:05 GMT Subject: A Sort Optimization Technique: decorate-sort-dedecorate References: <1156719092.603277.57390@b28g2000cwb.googlegroups.com> <1156723602.192984.49610@m79g2000cwm.googlegroups.com> <280820061150081729%jgibson@mail.arc.nasa.gov> Message-ID: <20060829103844.416$HQ@newsreader.com> Joachim Durchholz wrote: > Jim Gibson schrieb: > > > > The problem addressed by what is know in Perl as the 'Schwartzian > > Transform' is that the compare operation can be an expensive one, > > regardless of the whether the comparison uses multiple keys. Since in > > comparison sorts, the compare operation will be executed N(logN) times, > > it is more efficient to pre-compute a set of keys, one for each object > > to be sorted. That need be done only N times. > > Wikipedia says it's going from 2NlogN to N. If a sort is massively > dominated by the comparison, that could give a speedup of up to 100% > (approximately - dropping the logN factor is almost irrelevant, what > counts is losing that factor of 2). It seems to me that ln 1,000,000 is 13.8, and that 13.8 is quite a bit greater than 2. Cheers, Xho -- -------------------- http://NewsReader.Com/ -------------------- Usenet Newsgroup Service $9.95/Month 30GB From deets at nospam.web.de Sun Aug 27 10:36:46 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 27 Aug 2006 16:36:46 +0200 Subject: How to let a loop run for a while before checking for break condition? In-Reply-To: References: <4ldfp0F1csmpU1@uni-berlin.de> <4ldiacF1ckeeU1@uni-berlin.de> Message-ID: <4ldovvF1dgtrU1@uni-berlin.de> Fredrik Lundh schrieb: > Diez B. Roggisch wrote: > >> A while loop has a condition. period. The only thing to change that is >> to introduce a uncoditioned loop, and use self-modifying code to make >> it a while-loop after that timer interrupt of yours. > > or use a timer interrupt to interrupt the loop: > > import signal, time > > def func1(timeout): > > def callback(signum, frame): > raise EOFError # could use a custom exception instead > signal.signal(signal.SIGALRM, callback) > signal.alarm(timeout) > > count = 0 > try: > while 1: > count += 1 > except EOFError: > for i in range(10): > count += 1 > print count > > for an utterly trivial task like the one in that example, the alarm > version runs about five times faster than a polling version, on my test > machine (ymmv): No doubt that changing the flag asynchronously is a gain by delegating the timing code to the OS. Yet the while loop still has a condition - so you could as well set a flag in the signal handler an do it like this: def func3(timeout): global flag flag = True def callback(signum, frame): global flag flag = False signal.signal(signal.SIGALRM, callback) signal.alarm(timeout) count = 0 while flag or True: count += 1 for i in range(10): count += 1 print count This is on my machine about 1.5 times slower than func1, but much more readable especially wrt the OPs request of a condition being evaluated after a certain timeout, as you don't repeat any code. And apart from that, the overall gain of performance diminishes the very moment anything non-trivial occurs in the loops body anyway. Diez From will at willmcgugan.com Wed Aug 23 10:19:42 2006 From: will at willmcgugan.com (Will McGugan) Date: 23 Aug 2006 07:19:42 -0700 Subject: Python-like C++ library Message-ID: <1156342782.435869.250350@75g2000cwc.googlegroups.com> Hi folks, I'm forced to use C++ and STL at work, and consequently miss the ease of use of Python. I was wondering if there was a C++ library that implemented the fundamental objects of Python as close as possible, perhaps using STL underneath the hood. Too clarify, Im not looking to interface C++ with Python in any way, just to emulate the strings / containers / slicing etc. I did google for it but my search terms were too vague... Thanks in advance, Will McGugan -- http://www.willmcgugan.com From mfenner at gmail.com Thu Aug 17 23:00:20 2006 From: mfenner at gmail.com (Mark E. Fenner) Date: Fri, 18 Aug 2006 03:00:20 GMT Subject: Optimizing Inner Loop Copy References: <1155863280.800878.127310@p79g2000cwp.googlegroups.com> <1155868377.930442.157210@74g2000cwt.googlegroups.com> Message-ID: <83aFg.11563$5M.6900@trnddc02> danielx wrote: > > Mark E. Fenner wrote: >> Mark E. Fenner wrote: >> >> > John Machin wrote: >> > >> >> >> >> Mark E. Fenner wrote: >> >> >> >>> Here's my class of the objects being copied: >> >> >> >> Here's a couple of things that might help speed up your __init__ >> >> method, and hence your copy method: >> >> >> >>> >> >>> class Rule(list): >> >>> def __init__(self, lhs=None, rhs=None, nClasses=0, nCases=0): >> >> >> >> def __init__(self, lhs=None, rhs=(), nClasses=0, nCases=0): >> >> >> >>> self.nClasses = nClasses >> >>> self.nCases = nCases >> >>> >> >>> if lhs is not None: >> >>> self.extend(lhs) >> >> what does the extend method do? If it is small, perhaps inline a copy >> >> of its code here. >> >>> >> >>> if rhs is None: >> >>> self.rhs=tuple() >> >>> else: >> >>> self.rhs=rhs >> >> >> >> Replace the above 4 lines by: >> >> self.rhs = rhs >> >> >> >> HTH, >> >> John >> > >> > John, >> > >> > Thanks. I thought of those at the same you did! I also incorporated >> > one other use of the default=() + no conditional: >> > >> > class Rule(list): >> > def __init__(self, lhs=(), rhs=(), nClasses=0, nCases=0): >> > self.nClasses = nClasses >> > self.nCases = nCases >> > self.extend(lhs) # note, self is a list so this is list.extend >> > self.rhs=rhs >> > >> > def copy(self): >> > return Rule(self, >> > self.rhs, >> > self.nClasses, >> > self.nCases) >> >> >> Actually, I also removed the "passthrough" that copy was doing and just >> called the constructor directly. So, at the top level code, we have: >> >> allNew = [] >> for params in cases: >> # newobj = initialObject.copy() >> newObj = Rule(initialObject, initialObject.rhs, >> initialObject.nClasses, >> initialObject.nCases) >> newObj.modify(params) >> allNew.append(newObj) >> return allNew >> >> Regards, >> Mark > > I'm not sure how much this will help, but another thing you can do is > put this line before the "for": > > append = allNew.append > > Then, replace the last line in the loop with > > append(newObj) > > Check out this doc for more info on optimizing Python, and the section > which talks about eliminating dots: > > http://wiki.python.org/moin/PythonSpeed/PerformanceTips > http://wiki.python.org/moin/PythonSpeed/PerformanceTips#head-aa6c07c46a630a2fa10bd6502510e532806f1f62 I've read these, but they do yield additional nuggets upon rereading (does that make them generators?). In reality, my loop has several lines of code instead of a newObj.modify(args) method. I localised the obvious functions and attributes that I was using. In reality, the Rule.copy/Rule.__init__ is swamping everything else ... humm, unless ... I'll get back to you. Regards, Mark From R.Brodie at rl.ac.uk Wed Aug 30 11:19:56 2006 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Wed, 30 Aug 2006 16:19:56 +0100 Subject: windows pagfile utilization References: <1156950270.045140.44950@p79g2000cwp.googlegroups.com> Message-ID: "djoefish" wrote in message news:1156950270.045140.44950 at p79g2000cwp.googlegroups.com... > My program still crashes at 2g (according to the task manager). Do I > need to inform python that the pagefile has a new size? How do I check > that python is utilizing the full pagefile? It won't. You'll hit the 2Gb user virtual address space limit first. From grahamd at dscpl.com.au Wed Aug 9 23:17:03 2006 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 9 Aug 2006 20:17:03 -0700 Subject: os.path.normpath References: <1155149144.453575.181870@m79g2000cwm.googlegroups.com> Message-ID: <1155179823.172826.71600@p79g2000cwp.googlegroups.com> nathanbullock at gmail.com wrote: > I am using a windows box and passing a string like "../foo/../foo2" to > normpath which then returns "..\\foo2". But if this string is going > into a webpage link it should really be "../foo". > > Is there any way to tell os.path.normpath to act like we are an a unix > style box? Use posixpath.normpath() instead. From martin at v.loewis.de Tue Aug 8 17:35:30 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 08 Aug 2006 23:35:30 +0200 Subject: #!/usr/bin/python or #!/usr/bin/env python? In-Reply-To: References: <44d8e5a5$0$5567$9b622d9e@news.freenet.de> Message-ID: <44D903A2.6080203@v.loewis.de> Erik Max Francis schrieb: >> I use /usr/bin/env if I don't know what the operating system is; >> some systems don't have Python in /usr/bin. I use /usr/bin/pythonX.Y >> if I want a specific version on a specific operating system (typically >> Linux). > > Even there, /usr/bin/env pythonX.Y would be a better choice. (Maybe > that's what you meant.) I'm uncertain. When I refer to /usr/bin/python2.3, I know I get the system vendor's installation. When I use /usr/bin/env python2.3, I may get something that somebody has build and which may not work at all, or lack certain add-on packages that the script needs. It's bad when the script works for some users but fails for others. Regards, Martin From SPAMworFREEwor at bellsouth.net Mon Aug 14 17:09:16 2006 From: SPAMworFREEwor at bellsouth.net (Charles Russell) Date: Mon, 14 Aug 2006 21:09:16 GMT Subject: TypeError: 'module' object is not callable (newby question) In-Reply-To: <1155580968.024991.107040@i3g2000cwc.googlegroups.com> References: <1155580968.024991.107040@i3g2000cwc.googlegroups.com> Message-ID: <0E5Eg.19638$yE1.18048@trndny02> John Machin wrote: > > Contemplate the following: > > C:\junk>type glob.py > if __name__ == "__main__": > print "*** Being run as a script ..." > import glob > print "glob was imported from", glob.__file__ > print "glob.glob is", type(glob.glob) > print "glob.glob was imported from", glob.glob.__file__ > print "(glob.glob is glob) is", glob.glob is glob > print "--- end of script" > else: > print "*** Aarrgghh!! I'm being imported as", __name__ > import glob > print "glob was imported from", glob.__file__ > print "glob.glob is", type(glob.glob) > print "glob.glob was imported from", glob.glob.__file__ > print "(glob.glob is glob) is", glob.glob is glob > print "--- end of import" > Thanks. Another newby question: __name__ and __file__ appear to be predefined variables. To look up their meaning in the manual, is there some method less clumsy than grepping the whole collection of .html source files? I can't find any comprehensive index. From SergioADiez at gmail.com Sun Aug 27 21:32:13 2006 From: SergioADiez at gmail.com (ishtar2020) Date: 27 Aug 2006 18:32:13 -0700 Subject: Newbie Question Message-ID: <1156728733.654878.177100@p79g2000cwp.googlegroups.com> Hi everyone I'm sure this question is kinda stupid and has been answered a few times before... but I need your help! I'm writing a small application where the user can analyze some text based on a set of changing conditions , and right now I'm stuck on a point where I'd like to automatically generate new classes that operate based on those user-defined conditions. Is there a way in python to define a class in runtime? For instance, can I define a class which extends another(that I have previously defined in some module) , create some instance completely on the fly and then add/redefine methods to it? If affirmative, I've thought of a problem I would maybe have to face: as the class has been defined by direct input to the python interpreter, I could only create instances of it on the same session I entered the definition(because it's not on a module I can load on future uses) but not afterwards. Is there a way to keep that code? Even more newbie paranoia: what would happen if I make that 'on the fly" object persist via pickle? Where would Python find the code to handle it once unpickled on another session (once again, i take that no code with the definition of that instance would exist, as it was never stored on a module). Hope it wasn't too ridiculous an idea. Thank you for your time, guys. From andrea.gavana at gmail.com Fri Aug 11 08:13:08 2006 From: andrea.gavana at gmail.com (Andrea Gavana) Date: Fri, 11 Aug 2006 13:13:08 +0100 Subject: Reading unformatted big-endian files Message-ID: Hello John, > (1) Upgrade to 2.5 as soon as it goes final -- struct's performance has > been improved. I would love to, but I have some dependencies (like wxPython, Numeric, py2exe and so on) for which a 2.5 stable release either doesn't exist or is not fully tested or will break my app in some way. I believe Numeric doesn't exist anymore (!) and I am somewhat afraid to use numpy. It is a little bit more "hostile" :-D > How big are your files, anyway? Well, they ranges from 6-7 MB (the smallest) to 600-700 MB (the biggest)... I will try the new script and see how it performs. Thank you very much! Andrea. -- "Imagination Is The Only Weapon In The War Against Reality." http://xoomer.virgilio.it/infinity77/ From horpner at yahoo.com Thu Aug 24 15:42:31 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 24 Aug 2006 21:42:31 +0200 Subject: Python and STL efficiency References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <1156445446.280027.92160@b28g2000cwb.googlegroups.com> Message-ID: On 2006-08-24, JSprenkle at gmail.com wrote: > > Licheng Fang wrote: >> Hi, I'm learning STL and I wrote some simple code to compare the >> efficiency of python and STL. >> >> //C++ >> #include >> #include >> #include >> #include >> #include >> using namespace std; >> >> int main(){ >> vector a; >> for (long int i=0; i<10000 ; ++i){ >> a.push_back("What do you know?"); >> a.push_back("so long..."); >> a.push_back("chicken crosses road"); >> a.push_back("fool"); >> } >> set b(a.begin(), a.end()); >> unique_copy(b.begin(), b.end(), ostream_iterator(cout, "\n")); >> } > > I think you probably want this C++ code instead: > > //C++ > #include > #include > #include > #include > #include > using namespace std; > > int main(){ > vector a; > a.reserve( 40000 ); //<------------------ note this change > for (long int i=0; i<10000 ; ++i){ > a.push_back("What do you know?"); > a.push_back("so long..."); > a.push_back("chicken crosses road"); > a.push_back("fool"); > } > set b(a.begin(), a.end()); > unique_copy(b.begin(), b.end(), ostream_iterator(cout, > "\n")); > } > > It will run a lot faster if it doesn't have to keep resizing > the array. I don't see why it should run a lot faster that way. Appending elements to a vector with push_back takes amortized constant time. In the example above, preallocating 40000 strings saves (probably) math.log(40000, 2) reallocations of the vector's storage along with the consequent copy-construction and destruction of some fixed number of strings. Most of those reallocations take place while the vector is still proportionally quite small. -- Neil Cerutti From claird at lairds.us Sat Aug 5 19:01:57 2006 From: claird at lairds.us (Cameron Laird) Date: Sat, 5 Aug 2006 23:01:57 +0000 Subject: Something for PyPy developers? References: <1154809334.734417.314660@i42g2000cwa.googlegroups.com> Message-ID: <5kkfq3-qg5.ln1@lairds.us> In article <1154809334.734417.314660 at i42g2000cwa.googlegroups.com>, Paddy wrote: >I just found this: > http://www.cs.princeton.edu/~dpw/popl/06/Tim-POPL.ppt >And thought of you... :-) > >called "The Next Mainstream Programming Languages", Tim Sweeney of Epic >Games presents on problems that game writers see and muses on possible >solutions. . . . 1. I liked this presentation more than I expected. I suspect my mistake is not to recognize adequately that POPL *does* have high standards. 2. To me, the closest existing models are Erlang and, of course, Lisp-the-universal-solution. 3. I remember a couple of earlier waves of effort in parallelism-savvy languages. Maybe this time we'll get it right. Stranger things have happened than for a Parallel Python to emerge. From larry.bates at websafe.com Wed Aug 2 18:05:25 2006 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 02 Aug 2006 17:05:25 -0500 Subject: Hiding Console Output In-Reply-To: <1154549874.490652.106980@m73g2000cwd.googlegroups.com> References: <1154549874.490652.106980@m73g2000cwd.googlegroups.com> Message-ID: Kkaa wrote: > I'm using the os.system command in a python script on Windows to run a > batch file like this: > > os.system('x.exe') > > The third-party program x.exe outputs some text to the console that I > want to prevent from being displayed. Is there a way to prevent the > output of x.exe from python? > Check out the subprocess module. With it you can control more than with os.system(). -Larry From ghalib at sent.com Sat Aug 26 11:29:17 2006 From: ghalib at sent.com (Ghalib Suleiman) Date: Sat, 26 Aug 2006 11:29:17 -0400 Subject: Avoiding if..elsif statements In-Reply-To: <1156545375.962486.49540@h48g2000cwc.googlegroups.com> References: <1156545375.962486.49540@h48g2000cwc.googlegroups.com> Message-ID: <321AB457-CB55-4031-AA4B-C7AA78E866E4@sent.com> Try it and see. Functions are first-class citizens in Python. On Aug 25, 2006, at 6:36 PM, unexpected wrote: > I have a program where based on a specific value from a dictionary, I > call a different function. Currently, I've implemented a bunch of > if..elsif statements to do this, but it's gotten to be over 30 right > now and has gotten rather tedious. Is there a more efficient way to do > this? > > Code: > > value = self.dictionary.get(keyword)[0] > > if value == "something": > somethingClass.func() > elsif value == "somethingElse": > somethingElseClass.func() > elsif value == "anotherthing": > anotherthingClass.func() > elsif value == "yetanotherthing": > yetanotherthingClass.func() > > Is it possible to store these function calls in a dictionary so that I > could just call the dictionary value? > > -- > http://mail.python.org/mailman/listinfo/python-list From michiel at thingmajig.org Sun Aug 20 07:24:50 2006 From: michiel at thingmajig.org (Michiel Sikma) Date: Sun, 20 Aug 2006 13:24:50 +0200 Subject: Text parsing Message-ID: <33BB8117-CCDD-48F9-9299-FD6319FA0FC0@thingmajig.org> Hello everybody. Inspired by an example from the book Beginning Python: From Novice to Professional, I started working on a simple text parser which I can hopefully then extend into a more comprehensive system. I've got a little problem, though. My code: ---- test.py ---- import sys def preparse(file): block = [] for line in file: if line.strip(): block.append(line) elif block: yield ''.join(block).strip() block = [] yield '\n' def makeList(file): testOutput = list(preparse(file)) print testOutput testInput = open("test", "r") makeList(testInput) ---- ---- test ---- test1 test2 test3 test4 test5 test6 test7 test8 test9 test10 ---- When I run test.py, it prints this: michiel-sikmas-computer:~/Desktop msikma$ python test.py ['test1\ntest2', 'test3\ntest4\ntest5\ntest6', 'test7\ntest8', 'test9', '\n'] What happened to "test10"? It seems to be gone unless I add two linebreaks at the end of the file. Greets, Michiel Sikma michiel at thingmajig.org From python-url at phaseit.net Wed Aug 23 14:55:43 2006 From: python-url at phaseit.net (Jack Diederich) Date: Wed, 23 Aug 2006 18:55:43 +0000 (UTC) Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Aug 23) Message-ID: QOTW: "Because there's no chance that the original request is sane." - Georg Brandl (responding to a question involving a Banana) "this is one of your last chances to test the new code in 2.5 before the final release. *Please* try this release out and let us know about any problems you find" - Anthony Baxter, Python Release Manager sum() is for numbers. It doesn't work with strings for your protection. http://groups.google.com/group/comp.lang.python/browse_thread/thread/e782a88bf5b2f911/ Parsing valid email addresses is hard. http://groups.google.com/group/comp.lang.python/browse_thread/thread/dfb305247edd7c6c/ Q: How do I make my code python 3000 compatible? A: Wait for python 3000. http://groups.google.com/group/comp.lang.python/browse_thread/thread/8aee8423747c094d/ The C++ STL can't match python's speed in some applications. http://groups.google.com/group/comp.lang.python/browse_thread/thread/94fed9a76015a5e4/ David Wahler is no longer out of the office. http://groups.google.com/groups/search?q=David+Wahler+out+of+office Releases of Note Python 2.5 Release Candidate 1 See http://www.python.org/2.5/ byteplay - a python bytecode assembler/disassembler http://wiki.python.org/moin/ByteplayDoc ratfun-2.3 Polynomials and Ration Function library http://calcrpnpy.sourceforge.net/ratfun.html PyYAML-3.04 YAML parser and emitter for Python http://pyyaml.org/wiki/PyYAML Upcoming Community Events Plone Conference 2006, October 25-27 (Seattle, Washington) http://plone.org/events/conferences/seattle-2006 Open Source Developers Conference Dec 5-8 (Melbourne, Australia) http://www.osdc.com.au/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/python/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From grover.uk at gmail.com Sat Aug 26 17:07:15 2006 From: grover.uk at gmail.com (groves) Date: 26 Aug 2006 14:07:15 -0700 Subject: rollover effect In-Reply-To: References: <1156607403.741240.25000@74g2000cwt.googlegroups.com> <1156608042.466471.210270@m73g2000cwd.googlegroups.com> <1156608554.489516.243640@h48g2000cwc.googlegroups.com> <1156609000.477885.289150@h48g2000cwc.googlegroups.com> <1156609368.745082.324510@h48g2000cwc.googlegroups.com> <1156611065.857764.129500@b28g2000cwb.googlegroups.com> <1156611342.994894.288160@m79g2000cwm.googlegroups.com> Message-ID: <1156626434.997829.248420@i42g2000cwa.googlegroups.com> SuperHik wrote: > groves wrote: > > Simon Forman wrote: > >> groves wrote: > >>> Sorry, as I am new to python so couldn't understand what yu were > >>> asking. > >>> Now the problem is that i annot use pmw in my project..is thre anyother > >>> alternative by which I can have a rollover mouse effect on the canvas. > >>> thanks > >> Not a problem. Although "IDE" and "GUI" are terms that are not > >> specific to python. But you still haven't answered my question? Are > >> you using Tkinter? wxWidgets? Gtk bindings? > >> > >> Assuming that you're using Tkinter, what prevents you from using Pmw? > >> > >> Peace, > >> ~Simon > > > > Yes I am using Tkinter... > > the thing is I I m new to Tkhave not used PMW bfore..Nd inter... > > So just though If there is any alternative,,,as i don't have much time > > > PMW uses Tkinter too, so there is nothing "new", > it just has more "complicated" widgets already > written for you using Tkinter... Thanks a lot Ill have a look From cliff at develix.com Thu Aug 24 14:52:20 2006 From: cliff at develix.com (Cliff Wells) Date: Thu, 24 Aug 2006 11:52:20 -0700 Subject: Python Syntax Highlighting Module In-Reply-To: <1156173569.306945.320640@m79g2000cwm.googlegroups.com> References: <1156172592.903109.172520@p79g2000cwp.googlegroups.com> <1156173569.306945.320640@m79g2000cwm.googlegroups.com> Message-ID: <1156445540.13191.135.camel@devilbox> On Mon, 2006-08-21 at 08:19 -0700, gene tani wrote: > frikker at gmail.com wrote: > > Hello, > > I have an idea for a project which involves an editor that supports > > syntax highlighting. This would be for any language, particularly php, > > html, css, etc. I would like to write this program using python. It > > would only make sense to base this upon existing open source code. My > > question is there a python module or examples on how to write a code > > editor which supports modulated syntax highlighting? > > > > Thank you, > > Blaine > > just a *few* examples If I were to start a GUI editor project, I'd undoubtedly start by looking at Scintilla: http://www.scintilla.org/ Also see: http://scintilla.sourceforge.net/ScintillaRelated.html Regards, Cliff -- From pavlovevidence at gmail.com Wed Aug 30 15:29:53 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 30 Aug 2006 12:29:53 -0700 Subject: Coding style and else statements In-Reply-To: References: <44f355d6$0$8812$88260bb3@free.teranews.com> <1156898310.795476.187030@i3g2000cwc.googlegroups.com> Message-ID: <1156966193.189210.44660@74g2000cwt.googlegroups.com> Steve Holden wrote: > Carl Banks wrote: > [...] > > However, I have rare cases where I do choose to use the else (ususally > > in the midst of a complicated piece of logic, where it's be more > > distracting than concise). In that case, I'd do something like this: > > > > def foo(thing): > > if thing: > > return thing+1 > > else: > > return -1 > > assert False > > I think that's about the most extreme defensive programming I've seen in > a while! I can imaging it's saved your ass a couple of times when you've > edited the code a while after writing it. 1. The "assert False" is more for documenting than error checking. 2. The right way to be defensive here is not to have redundant logic. The above is really something I do rarely only when some other factor makes the redundant logic a lesser of evils. Carl Banks From felipe.lessa at gmail.com Sun Aug 20 19:33:04 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sun, 20 Aug 2006 20:33:04 -0300 Subject: List comparison help please In-Reply-To: <1156110434.360601.102800@i3g2000cwc.googlegroups.com> References: <1156110434.360601.102800@i3g2000cwc.googlegroups.com> Message-ID: 20 Aug 2006 14:47:14 -0700, Bucco : > I am trying to compare a list of items to the list of files generated > by os.listdir. I am having trouble getting this to work and think I > may be going down the wrong path. Please let me know if hter is a > better way to do this. THis is what I have for my class so far: > Have you tried using sets? >>> import os >>> os.listdir('/') ['lost+found', 'var', 'etc', 'media', 'cdrom', 'bin', 'boot', 'dev', 'home', 'initrd', 'lib', 'mnt', 'opt', 'proc', 'root', 'sbin', 'srv', 'sys', 'tmp', 'usr', 'initrd.img', 'vmlinuz', 'windows', 'initrd.img.old', 'vmlinuz.old'] >>> s = set(os.listdir('/')) >>> p = set(['opt', 'mnt', 'initrd', 'home', 'tmp', 'lib', 'media', 'boot', 'usr', 'var', 'proc', 'bin', 'sys', 'initrd.img.old', 'cdrom', 'lost+found', 'sbin', 'vmlinuz.old', 'windows']) >>> s - p set(['dev', 'etc', 'vmlinuz', 'srv', 'root', 'initrd.img']) -- Felipe. From webraviteja at gmail.com Tue Aug 22 00:02:53 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 21 Aug 2006 21:02:53 -0700 Subject: text editor suggestion? In-Reply-To: <44e66724$0$2363$c3e8da3@news.astraweb.com> References: <44e66724$0$2363$c3e8da3@news.astraweb.com> Message-ID: <1156219373.342609.71480@h48g2000cwc.googlegroups.com> > I also just started using Scite, and I really like it, except I find its > syntax highlighting to be very inflexible. You aren't able to define > your own groups of words -- you have to use what's given, basically. One > thing I like about UltraEdit is that you simply define as many groups of > keywords as you want and then assign a style to each one. Scite has a > very strange and rigid method of highlighting. Stick to SciTE. It takes almost no learning effort and meets everyone of those requirements. As far as customerization goes, SciTE can be customerized quite well. In fact, it can even be scripted with Lua. You seem to be using the single file executable which does not come with the configuration files. Otherwise, I cannot see how you could be missing this ability. Try this one instead if you are on Windows. http://gisdeveloper.tripod.com/scite.html You need to edit the file python.properties to add keywords. Windows - C:\Program Files\SciTe\python.properties Debian - /usr/share/scite/python.properties From spamspam at spam.eggs Sat Aug 12 04:59:02 2006 From: spamspam at spam.eggs (Ben C) Date: Sat, 12 Aug 2006 03:59:02 -0500 Subject: PIL Image transform References: <8O3Dg.6929$Mz3.4039@fed1read07> Message-ID: On 2006-08-11, Dean Card wrote: [snip] > thanks for the reply. I have been able to use the Image.PERSPECTIVE > transform via trial and error to get it to work properly for each transform. > What I am really looking for I guess is a way to calculate the 8 int tuple > to match the perspective change I am going for. For a given image there may > be 5 elements that need to be 'painted' on with perspective. A database > table will include the transform tuples based on the source image. So, by > passing a starting image and a pattern image, the starting image can be > covered with. Perhaps the best way to explain is visually.... > > http://seanberry.com/perspective.png > > What I need to know is how you take a surface like (P1, P5, P6, P2) and > describe it with the 8 int tuple? You could try asking this in comp.graphics.algorithms. The question is easily made non-Python-specific, just say you have a function in a library that does this: Transform each point {x,y} in an image into a new point {x1,y1} where {x1,y1} = {(ax + by + c)/(gx + hy + 1), (dx + ey + f)/(gx + hy + 1)} then ask how to choose the params a to h to achieve the effect illustrated on http://seanberry.com/perspective.png. From timr at probo.com Thu Aug 10 02:10:17 2006 From: timr at probo.com (Tim Roberts) Date: Thu, 10 Aug 2006 06:10:17 GMT Subject: using python at the bash shell? References: <44d7e364$0$24980$c3e8da3@news.astraweb.com> Message-ID: <5bjld21cj7k55v5tvb1ije9p4o41i2ie3m@4ax.com> John Salerno wrote: > >Can you use IPython to do normal bash things, like installing, etc.? Most scripts on Linux have a "hash-bang" line as their first line: #! /bin/sh When you execute that script, the system knows that it has to load sh or bash to process it, regardless of what program launched the script. The same thing works for Python scripts: #! /usr/bin/python -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From wegein at gmail.com Mon Aug 21 23:13:36 2006 From: wegein at gmail.com (damacy) Date: 21 Aug 2006 20:13:36 -0700 Subject: exception handling; python program that interacts with postgresql db In-Reply-To: References: <1154567757.143305.19910@75g2000cwc.googlegroups.com> Message-ID: <1156216416.390620.52240@75g2000cwc.googlegroups.com> thanks. i started to use psycopg. however, i have this error message and i don't quite get what it means. it says "DROP DATABASE cannot run inside a transaction block". does anyone have a clue? Tim Roberts wrote: > "damacy" wrote: > > >hi, there. i have this question which might sound quite stupid to some > >people, but here we go anyway. > > > >i have written a python program which interacts with a postgresql > >database. what it does is simply drops an existing database called > >'mytempdb'. > > > >the code looks like below; > > > >link = subprocess.Popen(command, stdin = subprocess.PIPE, stdout = > >subprocess.PIPE, shell = True) > >link.communicate(password) > >link.wait() > > > >where command looks like "psql -h 127.0.0.1 -U postgres -W -f filename" > >and > >filename is the name of the file which contains a single SQL command > >which is "drop database mytempdb". > > hiaips is right. The right way to do this is to use a Postgres module. > psycopg is my favorite, but there are several alternatives. > > import psycopg > db = psycopg.connect( > "dbname=template1 user=postgres password=%s" % password ) > c = db.cursor() > c.execute( "drop database mytempdb;" ) > -- > - Tim Roberts, timr at probo.com > Providenza & Boekelheide, Inc. From bobrien18 at yahoo.com Wed Aug 16 16:18:48 2006 From: bobrien18 at yahoo.com (KraftDiner) Date: 16 Aug 2006 13:18:48 -0700 Subject: trouble understanding inheritance... In-Reply-To: References: <1155753183.207393.116940@m79g2000cwm.googlegroups.com> <1155754767.694480.256200@h48g2000cwc.googlegroups.com> <1155756282.851876.46470@b28g2000cwb.googlegroups.com> <1155757992.706040.288890@74g2000cwt.googlegroups.com> Message-ID: <1155759528.110048.73420@m79g2000cwm.googlegroups.com> Simon Brunning wrote: > On 16 Aug 2006 12:53:12 -0700, KraftDiner wrote: > > I can see that this might work... > > c = [a, b] > > for c in [a,b]: > > c.getName() > > > > but when does baseClass ever get used? > > Why did i even have to define it? > > Well, quite. > I agree... welll... quite... :) > -- > Cheers, > Simon B, > simon at brunningonline.net, > http://www.brunningonline.net/simon/blog/ From caolan at ldmf.net Tue Aug 22 19:21:01 2006 From: caolan at ldmf.net (Caolan) Date: Tue, 22 Aug 2006 16:21:01 -0700 Subject: Newbie questions for Python usage Message-ID: Thanks Fred. > just assign to the attribute and be done with > it. if you want to use a placeholder value, use None: I thought I had tried that already but got an error. I'll try it again, and as for the 2nd one, I was hoping to avoid the usage of .cmd or .bat files altogether. Thanks! -Caolan O'Domhnaill ________________________________ From: python-list-bounces+caolan=ldmf.net at python.org on behalf of Fredrik Lundh Sent: Tue 8/22/2006 4:08 PM To: python-list at python.org Subject: Re: Newbie questions for Python usage Caolan wrote: > 1. I understand HOW to use the lambda operator, but WHY would you > want to use it? Can anyone please give an example of WHY you would > need it as opposed to just declaring a function either in the > local scope, or outside? you don't *need* it, because callback = lambda arg: expression is, for most practical purposes, the same thing as def callback(arg): return expression (the only difference is that the __name__ attribute for the function objects will differ; all lambdas are named "", while objects created by "def" have the original name.) however, in some cases, it's may be convenient to use the lambda form, for stylistic reasons. > 2. I would like to be able to declare as a member attribute a file > object, however because there is no declaration of variable types > like there is in C++, there doesn't seem to be a way to do this > without first making a fobj = open(...) call. Is this true? not sure what you mean, really -- attributes are not typed, and there's no way to "declare" them. just assign to the attribute and be done with it. if you want to use a placeholder value, use None: class foo: def __init__(self): self.file = None # not opened yet def open(self, name): self.file = open(name) or class foo: file = None # shared placeholder def __init__(self): pass def open(self, name): self.file = open(name) > Now for an os import question for Windows. I wish to automate the > builds of VS.NET 2005 and I can do so by executing the os.system(...) > command however I cannot see how to execute the vcvars32.cmd first to > set environment variables and then execute the actual command-line for > the build itself. there's no easy way to do that: environment variables set by a sub- process isn't available to the main process. the easiest way to do this might be to simply generate a short temporary BAT-file for each command, and do os.system() on that file: f = open("temp.bat", "w") f.write("@call vcvars32.bat\n") f.write("cl ...\n") f.close() os.system(f.name) os.remove(f.name) -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From ajaksu at gmail.com Mon Aug 14 12:39:02 2006 From: ajaksu at gmail.com (ajaksu) Date: 14 Aug 2006 09:39:02 -0700 Subject: Compiling wxPython app for Windows; Single EXE In-Reply-To: References: Message-ID: <1155573542.310208.43190@i3g2000cwc.googlegroups.com> Vincent Delporte wrote: > - py2exe is still the best tool in town to compile Python scripts to > run on a Windows host that doesn't have Python installed, including > wxWidgets/wxPython Hi Vincent and c.l.p-ers I'm using PyInstaller (http://pyinstaller.hpcf.upr.edu/) precisely to "compile" a wxPython-based program. So I'm curious about what makes py2exe "the best tool...", because I'm about to miss that due to my ignorance. I learned PyInstaller for something else and laziness kept me from trying py2exe. Now, the blurb on py2exe's site doesn't sound better than what I have with PyInstaller. FWIW, PyInstaller (NB: it's an exe-maker, not an installer) can compress your binaries using UPX, create single file executables and works cross-platforms too. It'll even include w9xpopen.exe and allow custom icons for the executable. It doesn't need setup.py. My "buildtest.bat" is: python Makespec.py -X -F -o ecoz ecotools.py grid.py similarity.py diversity.py python -O Build.py ecoz\ecotools.spec >> pyinstaller_log.txt ecoz\ecotools.exe test I've notice that application start time (or rather, 're-start', as it's more noticeable for the subsequent runs) is much better for the "single directory" method, because single file will always decompress to a temporary directory. All the best, Daniel From fredrik at pythonware.com Wed Aug 23 06:16:45 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Aug 2006 12:16:45 +0200 Subject: how do you get the name of a dictionary? References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com><1155926705.233273.231650@75g2000cwc.googlegroups.com><1156204770.339106.151110@m73g2000cwd.googlegroups.com><1156264475.968894.221710@p79g2000cwp.googlegroups.com><1156266720.205126.284050@i3g2000cwc.googlegroups.com> Message-ID: Steven D'Aprano wrote: > Here's a traceback. One of the arguments to spam() is too small. Can you > tell which one just by looking at the traceback? > >>>> a, b, c, d = range(4) >>>> spam(a, b, c, d) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 6, in spam > File "", line 5, in eggs > File "", line 4, in beans > ValueError: x is too small > > Of course you can't. x could be any one of a, b, c or d, and the traceback > doesn't give you enough information to tell which. for some reason, your example gives a different error on my machine: StrawManError: Attempt to construct Reductio ad absurdum argument failed From enigmadude at rock.com Wed Aug 9 13:02:42 2006 From: enigmadude at rock.com (enigmadude at rock.com) Date: 9 Aug 2006 10:02:42 -0700 Subject: using python with tar files and compressed files In-Reply-To: <1HmCg.2661$No6.51985@news.tufts.edu> References: <1HmCg.2661$No6.51985@news.tufts.edu> Message-ID: <1155142962.511995.265280@p79g2000cwp.googlegroups.com> This syntax works on other bzipped tar files. But it's not unheard of that large tarballs will get corrupted from a download mirror. Use a download manager and try redownloading the file. Usually a mirror will include an md5sum text file so that you can compare the checksum to your downloaded file to verify its integrity. For some reason, the wxPython site doesn't have them. John Salerno wrote: > Here's the name of a file I have: wxPython-newdocs-2.6.3.3.tar.bz2 > > Now, I tried this: > > import tarfile > tar = tarfile.open('wxPython-newdocs-2.6.3.3.tar.bz2', 'r:bz2') > > but got this: > > Traceback (most recent call last): > File "", line 1, in -toplevel- > tar = tarfile.open('wxPython-newdocs-2.6.3.3.tar.bz2', 'r:bz2') > File "C:\Python24\lib\tarfile.py", line 901, in open > return func(name, filemode, fileobj) > File "C:\Python24\lib\tarfile.py", line 1006, in bz2open > raise ReadError, "not a bzip2 file" > ReadError: not a bzip2 file > > So I'm a little confused. When dealing with a tar.gz or tar.bz2 file, do > you need to uncompress it first with the proper module (gzip or bz2)? Or > does tarfile take care of this? If so, why doesn't it recognize the > above file? Or am I just doing it the wrong way? (I'm following an > example in the docs) From kirk at strauser.com Tue Aug 1 12:09:57 2006 From: kirk at strauser.com (Kirk Strauser) Date: Tue, 01 Aug 2006 11:09:57 -0500 Subject: Finding the name of a class References: <44cf7538$0$29435$626a54ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Kirk Strauser wrote: >>>>> class foo(object): >>>>> pass >> >> how can I find its name, such as: >> >>>>> b = foo > I suppose you mean b = foo() ? Actually, I meant 'b = foo' in this case - I want to find the name of the class that b references, but the name of an instance (which may have zero or many references to it). > The name of a class is in the attribute '__name__' of the class. The > class of an object is in the attribute '__class__' of the object. I swear that didn't work earlier. Honest. :-) OK, now for the good stuff. In the code below, how can I find the name of the class that 'bar' belongs to: >>> class Foo(object): ... def bar(self): ... pass ... >>> b = Foo.bar >>> dir(b) ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'im_class', 'im_func', 'im_self'] >>> b.__class__ >>> b.__class__.__name__ 'instancemethod' I was sort of hoping that it would print 'Foo'. -- Kirk Strauser From roman.yakovenko at gmail.com Thu Aug 24 14:31:44 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Thu, 24 Aug 2006 21:31:44 +0300 Subject: [ANN]pygccxml 0.8.1 In-Reply-To: <7465b6170608241130k6cbce8e6w9dab5511e2b25020@mail.gmail.com> References: <7465b6170608241130k6cbce8e6w9dab5511e2b25020@mail.gmail.com> Message-ID: <7465b6170608241131n66941e1ck81315d7ba6ce949e@mail.gmail.com> I'm glad to announce the new version of pygccxml is available. Download page: http://www.language-binding.net/pygccxml/download.html What is it? "...The purpose of the GCC-XML extension is to generate an XML description of a C++ program from GCC's internal representation. Since XML is easy to parse, other development tools will be able to work with C++ programs without the burden of a complicated C++ parser..." The purpose of pygccxml is to read GCC-XML generated file and provide a simple framework to navigate C++ declarations using Python classes. Project home page: http://www.language-binding.net/pygccxml/pygccxml.html Changes: 1. The project has been ported to Mac OS. 2. New type traits that works with STD containers were added. 3. Logging and user messages related functionality were improved. 4. Support for Java native types was added. 5. Cache classes implementation and performance were improved. You can find the full list of changes here: http://language-binding.net/pygccxml/history/history.html#version-0-8-1 -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From jedi200581 at yahoo.co.uk Thu Aug 24 08:03:38 2006 From: jedi200581 at yahoo.co.uk (jedi200581 at yahoo.co.uk) Date: 24 Aug 2006 05:03:38 -0700 Subject: Pygame, mouse events and threads Message-ID: <1156421018.882740.166810@b28g2000cwb.googlegroups.com> Hi, I'm trying to retreive mouse event in a python thread using pygame. It's not working and I don't know why! Here is the code: import pygame, sys, os, threading from pygame.locals import * from threading import * class Display(Thread) : """Class managing display""" def __init__(self, xRes = 640, yRes = 480): Thread.__init__(self) #initializing display self._xRes = xRes self._yRes = yRes pygame.display.init() self._window = pygame.display.set_mode((xRes, yRes)) pygame.display.set_caption('Display') self._screen = pygame.display.get_surface() pygame.display.flip() self._log = [] def input(self, event): if event.type == KEYDOWN: sys.exit(0) else: print event def run(self): print "starting event handling thread" i = 0 while True: self.input(pygame.event.wait()) disp = Display() disp.start() When I put the content of the run and input functions in the main thread, it's working, why not in the thread? From rcs at bgoark.no Fri Aug 4 18:31:24 2006 From: rcs at bgoark.no (baalbek) Date: Sat, 05 Aug 2006 00:31:24 +0200 Subject: Which KDE IDE for Python? In-Reply-To: <1154682596.419636.70320@p79g2000cwp.googlegroups.com> References: <1154682596.419636.70320@p79g2000cwp.googlegroups.com> Message-ID: <44d3cab9$0$8006$c83e3ef6@nn1-read.tele2.net> If you have Eclipse, I strongly recommend the pydev package (see http://pydev.sourceforge.net/ for install). Code completion, etc works great! Baalbek From horpner at yahoo.com Fri Aug 25 16:21:41 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 25 Aug 2006 22:21:41 +0200 Subject: Newbie programmer question: How do parsers work?(Python examples?) References: <1156535724.221400.175230@m79g2000cwm.googlegroups.com> Message-ID: On 2006-08-25, bio_enthusiast wrote: > I was wondering exactly how you create a parser. I'm learning > Python and I recently have come across this material. I'm > interested in the method or art of writing a parser. > > If anyone has some python code to post for an abstract parser, > or links to some informative tutorials, that would be great. Start with the comp.compilers FAQ. http://compilers.iecc.com/faq.txt For a treatment aimed at non-computer scientists, check out Jack Crenshaw's Let's Build a Compiler series. The sample code is Pascal, but translating it to Python is an OK way to learn Python and get a taste of writing several different recursive-descent-parsers. http://compilers.iecc.com/crenshaw/ You don't really need to know Pascal to be able to read the simple, small, functions, as long as you have experience in other similar languages. -- Neil Cerutti I'm tired of hearing about money, money, money, money, money. I just want to play the game, drink Pepsi, wear Reebok. --Shaquille O'Neal From marco.wahl at gmail.com Tue Aug 29 15:02:12 2006 From: marco.wahl at gmail.com (Marco Wahl) Date: 29 Aug 2006 12:02:12 -0700 Subject: unit test for a printing method In-Reply-To: References: <1156780399.289589.58750@m73g2000cwd.googlegroups.com> <1156831448.829576.140240@h48g2000cwc.googlegroups.com> Message-ID: <1156878132.030243.74570@m79g2000cwm.googlegroups.com> "Fredrik Lundh" writes: >>> >>> why are you trying to reinvent doctest ? >> >> The OP asked for unit test. This could be read that >> the OP wants to use module unittest. > > http://docs.python.org/lib/doctest-unittest-api.html Ahh, that's good to know that doctests can be integrated into unittest suites. Thank you for the information From onurb at xiludom.gro Fri Aug 4 06:53:53 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 04 Aug 2006 12:53:53 +0200 Subject: Is there an obvious way to do this in python? In-Reply-To: References: <44d128e5$0$13484$636a55ce@news.free.fr> <44d1c6cb$0$13458$636a55ce@news.free.fr> <44d21087$0$19117$626a54ce@news.free.fr> Message-ID: <44d32741$0$31776$626a54ce@news.free.fr> H J van Rooyen wrote: > "Bruno Desthuilliers" wrote: > | H J van Rooyen wrote: (snip) > | > so if Pyro is for 'moving the scripts around' - Then that is what I must > look at > | > very hard... > | > | It's not for "moving the scripts around", it's for remote objects - kind > | of like Java's RMI, but, well, much more pythonic !-). Now the point is > | that Python being very powerful when it comes to dynamism and > | introspection, it should be possible to have a common client that > | basically just knows how to connect to the application server (using > | pyro). Once connected, the client asks the server for a set of objects > | (forms, menus etc) and the corresponding data. These objects then use > | the same mechanism to interact with the server. It's basically similar > | to the interaction between a browser and a web app - in that the client > | is potentially able to run any application sent by the server -, but > | with much more specialized client and app server and another protocol - > | and no other language than Python. > | > > This is getting more and more interesting - its not the simple minded mechanism > I had in mind, but it will achieve the same thing, and it exists already WARNING : Actually, the only thing that "exists already" is Pyro (and of course Python...) - all the rest is just me thinking out loud, and I by no mean garantee that what I describe above is viable or sensible or even reasonably implementable. > and I > can imagine it to be a very powerful mechanism, if I understand you correctly - > I am going to have to cry "time out!" to go and do some reading... Indeed. And please don't hold it against me if it ends up being some kind of Frankenstein's monster !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From atkedzierski at gmail.com Thu Aug 10 12:34:55 2006 From: atkedzierski at gmail.com (AndrewTK) Date: 10 Aug 2006 09:34:55 -0700 Subject: reading from sockets Message-ID: <1155227695.625250.17920@m73g2000cwd.googlegroups.com> Hello, I'm trying to read data from a socket and I'm not seeing what I'm expecting.... it seems to skip the first line of data. I am new to Python and just trying to test what I can do with it... and it's not looking pretty. I have some Python code: [------------------------------ #! /usr/bin/python import socket s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect( ("localhost",54321) ); s.send("hello") data = s.recv(1024) while len(data) > 0: print repr(data) # the first print of data always seems to "ignore" the first line of data... data = s.recv(1024) ------------------------------] On localhost 54321 I have a server (in Java) writing out [------------------------------ first second third ------------------------------] (on EOF, the stream is simply closed.) The result of the script is to print [------------------------------ second third ------------------------------] I have tried already [++++++++++++++ data = " " while len(data) > 0: data = s.recv(1024) print repr(data) ++++++++++++++] but that has not changed anything. The first line to come through is always skipped it would seem. Any ideas as to why that would be....? I was thinking scope when I made the last example, but apparently that is not the case. Andrew From deets at nospam.web.de Tue Aug 1 09:34:59 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 01 Aug 2006 15:34:59 +0200 Subject: how to get size of unicode string/string in bytes ? References: <1154420030.988013.89310@m79g2000cwm.googlegroups.com> <44cf167c$0$24894$9b4e6d93@newsread4.arcor-online.net> <4j8k58F6th46U1@uni-berlin.de> <44cf2906$0$24899$9b4e6d93@newsread4.arcor-online.net> Message-ID: <4j93emF6t2nqU1@uni-berlin.de> > So then the easiest thing to do is: take the maximum length of a unicode > string you could possibly want to store, multiply it by 4 and make that > the length of the DB field. > However, I'm pretty convinced it is a bad idea to store Python unicode > strings directly in a DB, especially as they are not portable. I assume > that some DB connectors honour the local platform encoding already, but > I'd still say that UTF-8 is your best friend here. It was your assumption that the OP wanted to store the "real" unicode-strings. A moot point anyway, at it is afaik not possible to get their contents in byte form (except from a C-extension). And assuming 4 bytes per character is a bit dissipative I'd say - especially when you have some > 80% ascii-subset in your text as european and american languages have. The solution was given before: chose an encoding (utf-8 is certainly the most favorable one), and compute the byte-string length. Diez From cliff at develix.com Wed Aug 23 00:29:51 2006 From: cliff at develix.com (Cliff Wells) Date: Tue, 22 Aug 2006 21:29:51 -0700 Subject: Can I do this with list comprehension? In-Reply-To: <1156306056.165984.37820@h48g2000cwc.googlegroups.com> References: <1156306056.165984.37820@h48g2000cwc.googlegroups.com> Message-ID: <1156307391.6319.112.camel@devilbox> On Tue, 2006-08-22 at 21:07 -0700, barberomarcelo at gmail.com wrote: > b = [2, 4, 6, 8, 10, 12] >>> a = [0, 1, 0, 1, 1, 0] >>> b = [2, 4, 6, 8, 10, 12] >>> [ j for i, j in zip ( a, b ) if i ] [4, 8, 10] -- From rochester1976 at gmail.com Sun Aug 6 23:09:21 2006 From: rochester1976 at gmail.com (Rochester) Date: Sun, 06 Aug 2006 23:09:21 -0400 Subject: Python open a named pipe == hanging? References: <1hjic95.ojxkeuodeqbtN%aleax@mac.com> <1hjk5ng.1e8swk9u9cxwzN%aleax@mac.com> Message-ID: Thanks Alex, now I think I understand much better the fifo/pipe mechanism and how Python treats them. For those who are interested, I would like to restate the problem I was tring to solve and a working solution (inspired by Alex Martelli's code), feel free to criticize it: The problem: I have an external program which takes two matrices (two text files) as input, and produces an output to stdout, you can take diff as an example. I want to call this program from within Python, without writing any temporary file (for the performance reason). In Bash, this task would be best written as: #!/bin/bash diff <(step1) <(step2) | step3 Where step1, step2 and step3 have to be independent external programs. Now in Python, since there is no exact equivalence of <() magic a.k.a. process substitution, I figured taht the best solution should be to create a pair of fifos and do something like this: #!/bin/bash mkfifo fifo1 fifo2 step1 > fifo1 & step2 > fifo2 & diff step1 step2 | step3 And a working Python equivalent code is: #!/usr/bin/python import os # do step1 and step2 in Python, say we end up with something like these: s1 = "some string\n second line." # results from step1 s2 = "some string\n a different line." # results from step2 os.mkfifo('fifo1') os.mkfifo('fifo2') op = os.popen(' '.join(['diff', 'fifo1', 'fifo2'])) # this step is crucial! print >> open('fifo1', 'w'), s1 print >> open('fifo2', 'w'), s2 os.unlink('fifo1') os.unlink('fifo2') x = op.read() # Now do something about x print x P.S.: process substitution is a Bash hack which uses /dev/fd/ to send (usually more than one) processes output to a program which takes (more than one) filename as input. Heuristically speaking, this is like a multiway pipe. You can find more about this mechanism here: http://www.tldp.org/LDP/abs/html/process-sub.html From jurgenex at hotmail.com Thu Aug 17 11:22:20 2006 From: jurgenex at hotmail.com (Jürgen Exner) Date: Thu, 17 Aug 2006 15:22:20 GMT Subject: The Semicolon Wars as a software industry and human condition References: <1155822175.534005.100490@75g2000cwc.googlegroups.com> <1155827943.041208.51220@i3g2000cwc.googlegroups.com> Message-ID: Iain King wrote: > Xah Lee wrote: >> Of interest: >> >> . The Semicolon Wars, by Brian Hayes. 2006. >> http://www.americanscientist.org/template/AssetDetail/assetid/51982 >> >> in conjunction to this article, i recommend: >> >> . Software Needs Philosophers, by Steve Yegge, 2006 >> http://xahlee.org/Periodic_dosage_dir/_p/software_phil.html >> >> . What Languages to Hate, Xah Lee, 2002 >> http://xahlee.org/UnixResource_dir/writ/language_to_hate.html >> >> Xah >> xah at xahlee.org >> ? http://xahlee.org/ > > I'm confused - I thought Xah Lee loved Perl? Now he's bashing it? He only loves himself. Aside of that: +-------------------+ .:\:\:/:/:. | PLEASE DO NOT | :.:\:\:/:/:.: | FEED THE TROLLS | :=.' - - '.=: | | '=(\ 9 9 /)=' | Thank you, | ( (_) ) | Management | /`-vvv-'\ +-------------------+ / \ | | @@@ / /|,,,,,|\ \ | | @@@ /_// /^\ \\_\ @x@@x@ | | |/ WW( ( ) )WW \||||/ | | \| __\,,\ /,,/__ \||/ | | | jgs (______Y______) /\/\/\/\/\/\/\/\//\/\\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ ============================================================== jue From no at spam.com Mon Aug 7 19:38:40 2006 From: no at spam.com (Farshid Lashkari) Date: Mon, 07 Aug 2006 16:38:40 -0700 Subject: singleton decorator In-Reply-To: References: Message-ID: <4aQBg.689$0F5.49@fed1read04> Andre Meyer wrote: > Am I missing something here? What is the preferred pythonic way of > implementing singleton elegantly? The "Open Issues" section of that PEP says the following: "It's exceedingly unlikely that class decorators will be in Python 2.4" So it might not be in the current version of python. -Farshid From stevebread at yahoo.com Mon Aug 21 07:09:34 2006 From: stevebread at yahoo.com (stevebread at yahoo.com) Date: 21 Aug 2006 04:09:34 -0700 Subject: Regular Expression question References: <1156153916.849933.178790@75g2000cwc.googlegroups.com> <1156154876.874272.283160@i3g2000cwc.googlegroups.com> <1156156724.165790.208880@b28g2000cwb.googlegroups.com> <1156157962.192238.116160@74g2000cwt.googlegroups.com> Message-ID: <1156158574.263980.319450@i3g2000cwc.googlegroups.com> got zero results on this one :) From g.brandl-nospam at gmx.net Tue Aug 8 06:46:37 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Tue, 08 Aug 2006 12:46:37 +0200 Subject: singleton decorator In-Reply-To: References: Message-ID: Andre Meyer wrote: > While looking for an elegant implementation of the singleton design > pattern I came across the decorator as described in PEP318 > . > Unfortunately, the following does not work, because decorators only work > on functions or methods, but not on classes. > > def singleton(cls): > instances = {} > def getinstance(): > if cls not in instances: > instances[cls] = cls() > > return instances[cls] > return getinstance > > @singleton > class MyClass: > ... > > > Am I missing something here? What is the preferred pythonic way of > implementing singleton elegantly? You can always use the syntax the decorator replaces: class MyClass: ... MyClass = singleton(MyClass) But there are better ways, and maybe you don't even need a singleton. See the Python Cookbook. Georg From claird at lairds.us Tue Aug 1 21:32:51 2006 From: claird at lairds.us (Cameron Laird) Date: Wed, 2 Aug 2006 01:32:51 +0000 Subject: Multiple Telnet sessions through one script References: <1154352823.619882.20870@i3g2000cwc.googlegroups.com> Message-ID: <3vb5q3-dfs.ln1@lairds.us> In article , Carl J. Van Arsdall wrote: >Well, although you spawn seperate telnet processes there is still only >one thread of control in your pythons script. If you need to do two >things simultaneously you'll need to setup a parallel control >mechanism. For example you could use python threads, each thread spawns >a separate telnet and controls it accordingly. Similarly, you could >fork off other python scripts that control each telnet session. > >Alright, so that's for controlling two telnets at once. I think you'll >have another problem, and that's controlling each telnet session >manually. To do this I think you'll need to setup an interface that >provides the two consoles you are after. I'm not exactly sure the best >way to do that. One thought I have is if you used one of the various >GUI toolkits you could have your app open a window that is seperated >into two consoles. Each thread could be bound to one of these consoles >and you could switch between the two by clicking on one side versus the >other. Although if you want to do it all in a shell, or have your >program open multiple shells I'm not sure how to do that, you might >check google. I suppose if you were doing things from a single shell >and wanted to do thing similar to the GUI toolkit I described earlier, >you could try something like ncurses. > >I guess I have one final idea, you could use a single shell, buffer >output from each telnet session and have your main control loop give you >the ability to switch back and forth between the two sessions. > >Anyhow, hope those ideas help you out a little. > >vmalhotra wrote: >> Hi >> >> I am new in python scripting. I want to open a Multiple telnet session >> through once script. In other way i can tell i want to open two linux >> consoles through one script. >> >> I wrote one script, but the issue is I am not able to open multiple >> consoles. The Scripts which i wrote is as follows: >> >> import pexpect >> session = pexpect.spawn("telnet localhost 2601\n") >> session.expect("Password: ") >> session.send("XYZ\n\n") >> session.expect("Router1> ") >> session1 = pexpect.spawn("telnet localhost 2604\n") >> session1.expect("Password: ") >> session1.send("ABCD\n\n") >> session1.expect("ospfd> ") >> #session1.interact() >> session1.interact() >> >> output : >> ospf> >> >> But in this case, i want in one console router one can open and on >> other console ospf should open. But this i want to do is through one >> script only. . . . While pexpect makes these matters feasible, the Tcl-based Expect has had years more practice dealing with concurrency and its consequences. If this problem were mine, I'd start with Expect. From ray_usenet at yahoo.com Tue Aug 22 04:37:10 2006 From: ray_usenet at yahoo.com (Ray) Date: 22 Aug 2006 01:37:10 -0700 Subject: Python and STL efficiency In-Reply-To: References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <1156162237.274636.17850@i3g2000cwc.googlegroups.com> Message-ID: <1156235830.290285.21990@74g2000cwt.googlegroups.com> Fredrik Lundh wrote: > Ray wrote: > > >> in the C++ example, you're creating 40000 string objects. > > > > In which case, Licheng, you should try using the /GF switch. This will > > tell Microsoft C++ compiler to pool identical string literals together. > > in what way does that change the implementation of C++'s string type ? Ah, yes what was I thinking? The fact that it stores std::string objects escaped my mind somehow. /GF just pools the string literals. Thanks for the correction. > > From kirklin.mcdonald at gmail.com Mon Aug 7 23:49:04 2006 From: kirklin.mcdonald at gmail.com (Kirk McDonald) Date: Mon, 07 Aug 2006 20:49:04 -0700 Subject: Question on try/except In-Reply-To: <5KTBg.4514$Jg1.2316@trndny05> References: <5KTBg.4514$Jg1.2316@trndny05> Message-ID: <44d80393$1@nntp0.pdx.net> Dan wrote: > While perusing sre.py in the standard library, I came upon this snippet > of code in the _compile() function definition: > > try: > p = sre_compile.compile(pattern, flags) > except error, v: > raise error, v # invalid expression > > Is there some particular use in catching an exception and immediately > re-raising it? Why catch it at all? > > /Dan > All I can think of is that it changes the traceback to point to the re-raise and not the original raise. -Kirk McDonald From onurb at xiludom.gro Fri Aug 4 13:18:53 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 04 Aug 2006 19:18:53 +0200 Subject: Need a compelling argument to use Django instead of Rails In-Reply-To: <7xejvz5mwj.fsf@ruckus.brouhaha.com> References: <1154077105.746752.153440@h48g2000cwc.googlegroups.com> <1154080209.603694.161170@i42g2000cwa.googlegroups.com> <1154092298.714808.158250@75g2000cwc.googlegroups.com> <44ca3420$0$30140$636a55ce@news.free.fr> <5hnlc25hfj56btkhdamfdi5gb5a3b8ts45@4ax.com> <1154354727.457387.142840@h48g2000cwc.googlegroups.com> <3scsc252be3d7a814ogj1ibnud3aothc1l@4ax.com> <1154512062.251725.177140@m73g2000cwd.googlegroups.com> <7xejvz5mwj.fsf@ruckus.brouhaha.com> Message-ID: <44d3817d$0$13470$636a55ce@news.free.fr> Paul Rubin wrote: > "Ben Sizer" writes: >> Another perfectly good reason is that PHP pages are much simpler to >> deploy than any given Python application server. Just add the code into >> your HTML pages as required and you're done. Python could come close to >> this if something like the Python Server Pages implementation in >> mod_python was to become widely available and well known, but that >> still requires overcoming the first problem. > > I didn't realize you could do shared hosting with mod_python, because > of the lack of security barriers between Python objects (i.e. someone > else's application could reach into yours). You really need a > separate interpreter per user. mod_python uses sub-interpreters - can be per virtual server, per directory etc, cf http://www.modpython.org/live/current/doc-html/dir-other-ipd.html http://www.modpython.org/live/current/doc-html/dir-other-ipdv.html -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From wegein at gmail.com Wed Aug 2 23:09:43 2006 From: wegein at gmail.com (damacy) Date: 2 Aug 2006 20:09:43 -0700 Subject: exception handling; python program that interacts with postgresql db In-Reply-To: <1154569009.315335.275350@i42g2000cwa.googlegroups.com> References: <1154567757.143305.19910@75g2000cwc.googlegroups.com> <1154568651.386892.198840@s13g2000cwa.googlegroups.com> <1154569009.315335.275350@i42g2000cwa.googlegroups.com> Message-ID: <1154574583.152885.3130@m79g2000cwm.googlegroups.com> yes, i'll have a read. thanks. =) hiaips wrote: > Another option would be to use the psycopg module to connect to > postgres from within your Python code. See > http://www.initd.org/projects/psycopg1 for more information. > > --hiaips From ilias at lazaridis.com Tue Aug 22 09:27:07 2006 From: ilias at lazaridis.com (lazaridis_com) Date: 22 Aug 2006 06:27:07 -0700 Subject: CONSTRUCT - Module Attributes and Execution Environment Message-ID: <1156253227.092971.36510@74g2000cwt.googlegroups.com> I would like to change the construct: if __name__ == '__main__': to something like: if exec.isMain(): My (OO thought) is to place a class in an separate code module and to instantiate an singleton instance which would keep th something like this: class ExecutionEnv: def isMain(self) if CALLING_MODULE.__name__ == '__main__': return true else return false exec = ExecutionEnv() How to I get access to the CALLING_MODULE ? - Are ther alternative constructs/mechanism available, which could be used to add this functionality possiby directly to a code-module? From jmrcook at earthlink.net Tue Aug 8 17:03:55 2006 From: jmrcook at earthlink.net (John & Mary Cook) Date: Tue, 8 Aug 2006 14:03:55 -0700 Subject: New to Python-- Help Message-ID: <3%6Cg.57$1W7.17@fe04.lga> I just installed Python on Windows XP Pro. When I enter 'python' at the >>> prompt in Pythonwin IDE I get the following: Traceback (most recent call last): File "", line 1, in ? Name Error: name 'python' is not defined Can anyone help? Thank you, J. T. Cook From fredrik at pythonware.com Wed Aug 30 09:50:07 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 30 Aug 2006 15:50:07 +0200 Subject: From xml data to python code to run References: <1156941309.897863.196830@h48g2000cwc.googlegroups.com> Message-ID: ralfbrand50 at gmail.com wrote: > Is it possible to run data that's from an xml file as python code, by > this I mean the following. > > In a xml file there's the following data > > > > Now I want to extract the self.wTree.signal_autoconnect(dic)* from the > xml file and make it possible that Python runs this, instead of having > a python file were with the hardcoded self.wTre.. in it. from elementtree import ElementTree as ET text = """""" doc = ET.fromstring(text) class Object: def method(self, value): print value # populate the namespace namespace = { "object": Object() } # execute all code fragments for code_elem in doc.findall(".//code"): exec code_elem.text in namespace From crystalattice at gmail.com Tue Aug 1 15:36:18 2006 From: crystalattice at gmail.com (crystalattice) Date: 1 Aug 2006 12:36:18 -0700 Subject: Programming newbie coming from Ruby: a few Python questions References: <1154458926.738922.156910@h48g2000cwc.googlegroups.com> Message-ID: <1154460978.604511.209260@75g2000cwc.googlegroups.com> simonharrison at fastmail.co.uk wrote: > Hi all. I've been try to learn ruby for a few months but I'm about > ready to give up. The available books either assume a programming > background, or are out of date. Anyway, I think python may suit me more > due to its 'theres one way to do it' philosophy (hope the quote is > right)! Another quote that I liked was: > > 'Clever is not considered a compliment in Python.' (don't know where I > read that...) > > In Ruby, there are many ways to do the same thing and cleverness seems > to be held in high regard. These attitudes are not too helpful for > beginners in my experience. Anyway, enough waffle. > > What books and tutorials are recommended to learn Python? The tutorial > that comes with Python is great and has given me a good overview but I > think I'd benefit from some programming projects, now I have a little > understanding of how Python works. > > Ideally, I'd like a whole series of projects where I'm walked through > how to go about writing real Python. The way I look at it, nobody > learnt to build a house just from reading about building materials! > > Any other tips for getting up to speed with Python fairly quickly will > be greatly appreciated. > > If anyone can help, thanks very much Of course there's the O'Reilly set: Learning Python, Programming Python, Python in a Nutshell, etc. I found them great for an overview and capabilities look at the language, but like you I prefer a more project-oriented approach. They are good to have on your reference shelf though. The best book I've found for "teaching" you the language is from Deitel and Deitel: Python, How to Program. It's outdated in that is uses Python 2.2 but the vast majority of concepts still apply; it does mention when certain features are deprecated so you shouldn't have a problem. It is a college textbook so it goes into detail in many areas plus it has the usual quizes, chapter summaries, and tests. The tests are usually easy enough to figure out but with enough difficulty to make them challenging. It covers a wide range of topics, from CGI and XML to multithreading and networking. It's normally $90-$100 but you should be able to find it used for <$40. From fuzzyman at gmail.com Fri Aug 11 08:54:12 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 11 Aug 2006 05:54:12 -0700 Subject: hide python code ! In-Reply-To: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> Message-ID: <1155300852.497741.73230@74g2000cwt.googlegroups.com> Bayazee wrote: > hi > can we hide a python code ? > if i want to write a commercial software can i hide my source code from > users access ? > we can conver it to pyc but this file can decompiled ... so ...!! > do you have any idea about this ...? > > --------------------------------------- > First Iranian Open Source Community : www.python.ir You can distribute the compiled byte-code files (*.pyc) which are harder to turn back into source code. There was a product called decompyle which could do it, but although there is a version floating around which works for Python 2.4 I've never heard of anyone getting it to work. Import hooks and encrypted source are a good option. Py2exe embeds the byte-code file for your main script into the executable which is also pretty good. All of these make it hard enough to deter most people who will ever want to abuse your source code. Until you have *lots* of users this is probably enough. I never understand the knee-jerk reaction on this mailing list to answer people who ask this question by telling them they don't really want to do it... Fuzzyman http://www.voidspace.org.uk/python/index.shtml From john at castleamber.com Thu Aug 24 00:59:05 2006 From: john at castleamber.com (John Bokma) Date: 24 Aug 2006 04:59:05 GMT Subject: all ip addresses of machines in the local network References: <1156387621.568779.191420@m73g2000cwd.googlegroups.com> Message-ID: "damacy" wrote: > hi, there. i have a problem writing a program which can obtain ip > addresses of machines running in the same local network. > > say, there are 4 machines present in the network; [a], [b], [c] and [d] > and if i run my program on [a], it should be able to find "host names" > and "ip addresses" of the other machines; [b], [c] and [d]? > > i have read some threads posted on this group, however, they only work > for localhost, not the entire network. > > any hints if possible? google for nmap, don't reinvent the wheel. -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From bayazee at gmail.com Tue Aug 15 08:51:13 2006 From: bayazee at gmail.com (Bayazee) Date: 15 Aug 2006 05:51:13 -0700 Subject: hide python code ! In-Reply-To: References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> Message-ID: <1155646273.926275.41610@74g2000cwt.googlegroups.com> Armin Steinhoff wrote: > Bayazee wrote: > > hi > > can we hide a python code ? > > if i want to write a commercial software can i hide my source code from > > users access ? > > we can conver it to pyc but this file can decompiled ... so ...!! > > do you have any idea about this ...? > > Use Pyrex in order to build C-Modules from the critical parts of your > software. > > > > > --------------------------------------- > > First Iranian Open Source Community : www.python.ir > > Interesting ... but you are not a member of this community. Right? > > --Armin Hi thanx for your answers . i read all of your replys carefully ... i am an open source Programmer ! i love to distribute my sources and use other ideas ! but asking a question is't reason of using it ! i want to find a way to hide python source codes ! can we do it ? how ? but i dont want to use it .... this is a question that i must be answer to a friend ! From maric at aristote.info Wed Aug 23 04:24:48 2006 From: maric at aristote.info (Maric Michaud) Date: Wed, 23 Aug 2006 10:24:48 +0200 Subject: Python and STL efficiency In-Reply-To: References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <200608222249.35315.maric@aristote.info> Message-ID: <200608231024.49656.maric@aristote.info> Le mardi 22 ao?t 2006 23:15, Fredrik Lundh a ?crit?: > Maric Michaud wrote: > > The problem here, is that the strings in the set are compared by value, > > which is not optimal, and I guess python compare them by adress ("s*n is > > s*n" has the same complexity than "s*n == s*n" in CPython, right ?). > > wrong. > Ah ! wrong, thanks, but not in our case : In [80]: for i in (10**e for e in range(5)) : ....: res1 = timeit.Timer('s == t', 's, t = "e"*%i, "e"*%i'%(i, i)).timeit() ....: res2 = timeit.Timer('s is t', 's, t = "e"*%i, "e"*%i'%(i, i)).timeit() ....: print res1/res2 ....: ....: 1.10532866525 1.27507328965 1.90244004672 8.33974283485 89.5215441627 Indeed, it's wrong for two instances of str, but not if we compare an instance to itself : In [79]: for i in (10**e for e in range(9)) : ....: r1=timeit.Timer('s is p', "s, p = ('s'*%s,)*2" % i).timeit() ....: r2=timeit.Timer('s == p', "s, p = ('s'*%s,)*2" % i).timeit() ....: print r1/r2 ....: ....: 0.854690643008 0.872682262181 0.851785060822 0.871193603744 0.890304121256 0.86925960859 0.846364097331 0.91614070798 0.825424114324 So my lastest c++ algorithm is the good one still, as the python code is like : In [29]: timeit.Timer('set(t)', 't=("e"*10,)*10').timeit() Out[29]: 1.883868932723999 In [30]: timeit.Timer('set(t)', 't=("e"*100,)*10').timeit() Out[30]: 1.8789899349212646 and not : In [27]: timeit.Timer('set(t)', 't=["e"*10 for i in range(10)]').timeit() Out[27]: 2.6000990867614746 In [28]: timeit.Timer('set(t)', 't=["e"*100 for i in range(10)]').timeit() Out[28]: 4.1173238754272461 > > timeit -s"s='x'; n=1000" "s*n is n*s" > > 1000000 loops, best of 3: 1.9 usec per loop > > > timeit -s"s='x'; n=1000" "s*n == n*s" > > 100000 loops, best of 3: 4.5 usec per loop > > -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From da.martian at gmail.com Tue Aug 1 15:39:51 2006 From: da.martian at gmail.com (ChaosKCW) Date: 1 Aug 2006 12:39:51 -0700 Subject: FTP (ftplib) output capture In-Reply-To: <1154364593.644336.65060@h48g2000cwc.googlegroups.com> References: <1154361189.292460.108940@p79g2000cwp.googlegroups.com> <1154364593.644336.65060@h48g2000cwc.googlegroups.com> Message-ID: <1154461190.981763.218140@m73g2000cwd.googlegroups.com> Hi Thanks for the reply. I will send it in when I am done :-) Simon Forman wrote: > ChaosKCW wrote: > > Hi > > > > Has anyone caputerd the output from the std ftp lib? It seems a bit > > annoying that everything is printed to stdout. It means incorporating > > this into any real program is a problem. It would have been much better > > if they used the std logging module and hooked up a console logger for > > the feault ftp application. Alas it isnt that way. > > > > Capturing stdout like this??? : > > > > import sys > > > > sys.stdout = open('bb', 'w) > > > > But I want to re-route it to the logging module not a file , so do I > > need to write a steam object? > > > > Thanks, > > ftplib pre-dates the standard logging system by a bit. > > I think ftplib only prints stuff if you set its (the FTP class > instances') debug level to greater than 0. > > If you really want to replace sys.stdout with something that passes the > data to a logger, then something like the following (untested) class > should do it: > > class FileLog: > def __init__(self, log): > self.log = log > def write(self, data): > self.log.debug(data) > > The best solution might be to subclass or rewrite FTP to really do what > you want. I believe one of the goals of Python-3000 is better > integration of the standard library with the new-ish standard logging > system, so if you do a good job send it in. ;-) > > Peace, > ~Simon From grahn+nntp at snipabacken.dyndns.org Fri Aug 4 13:04:53 2006 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 4 Aug 2006 17:04:53 GMT Subject: Windows vs. Linux References: <1154301694.445639.99580@m79g2000cwm.googlegroups.com> <44cddfb3$0$7761$7a628cd7@news.club-internet.fr> Message-ID: On Tue, 1 Aug 2006 14:47:59 -0300, Gerhard Fiedler wrote: > On 2006-08-01 12:31:01, Sybren Stuvel wrote: ... > Is that really true? From what I know, it's more like this: > > - Unix-type systems: '/' > - Windows-type systems: '\' > - Mac OS: ':' > - OpenVMS: '.' > - ... > > Maybe someone else can fill in some of the missing OSes. AmigaDOS: '/'. (On the other hand, it didn't understand '.' and '..' without third-party patches, and it didn't have the '/' directory.). > It doesn't seem to > look like Windows is the odd man out; it rather seems that every type of OS > uses its own separator. In the 1980s, MS-DOS /was/ an ugly bastard child; lots of other systems existed that I have never heard about. As for what path separator they used and why, I'm afraid you'd have to ask on alt.folklore.computers ... /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From JSprenkle at gmail.com Thu Aug 24 14:50:46 2006 From: JSprenkle at gmail.com (JSprenkle at gmail.com) Date: 24 Aug 2006 11:50:46 -0700 Subject: Python and STL efficiency In-Reply-To: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> Message-ID: <1156445446.280027.92160@b28g2000cwb.googlegroups.com> Licheng Fang wrote: > Hi, I'm learning STL and I wrote some simple code to compare the > efficiency of python and STL. > > //C++ > #include > #include > #include > #include > #include > using namespace std; > > int main(){ > vector a; > for (long int i=0; i<10000 ; ++i){ > a.push_back("What do you know?"); > a.push_back("so long..."); > a.push_back("chicken crosses road"); > a.push_back("fool"); > } > set b(a.begin(), a.end()); > unique_copy(b.begin(), b.end(), ostream_iterator(cout, "\n")); > } I think you probably want this C++ code instead: //C++ #include #include #include #include #include using namespace std; int main(){ vector a; a.reserve( 40000 ); //<------------------ note this change for (long int i=0; i<10000 ; ++i){ a.push_back("What do you know?"); a.push_back("so long..."); a.push_back("chicken crosses road"); a.push_back("fool"); } set b(a.begin(), a.end()); unique_copy(b.begin(), b.end(), ostream_iterator(cout, "\n")); } It will run a lot faster if it doesn't have to keep resizing the array. From skip at pobox.com Wed Aug 30 06:29:28 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 30 Aug 2006 05:29:28 -0500 Subject: how can i change the text delimiter In-Reply-To: <1156929540.715287.123060@h48g2000cwc.googlegroups.com> References: <1156929540.715287.123060@h48g2000cwc.googlegroups.com> Message-ID: <17653.26760.317688.98150@montanaro.dyndns.org> sonald> Can anybody tell me how to change the text delimiter in FastCSV sonald> Parser? By default the text delimiter is double quotes(") I sonald> want to change it to anything else... say a pipe (|).. can sonald> anyone please tell me how do i go about it? I'm not familiar with a FastCSV module in Python. Google suggests there is a FastCsv module in Ruby. Just in case what you are really referring to is the csv module in Python, here's how you do it. Suppose your CSV file looks like an Excel-generated CSV file save for the weird quote character: import csv class PipeQuote(csv.excel): quotechar='|' ... reader = csv.reader(open("somefile", "rb"), dialect=PipeQuote) for row in reader: print row Full documentation is here: http://docs.python.org/dev/lib/module-csv.html Skip From h112211 at gmail.com Sun Aug 6 02:32:00 2006 From: h112211 at gmail.com (h112211 at gmail.com) Date: 5 Aug 2006 23:32:00 -0700 Subject: Which Python API for PostgreSQL? References: <1154742196.522410.138770@i3g2000cwc.googlegroups.com> Message-ID: <1154845920.841236.222480@75g2000cwc.googlegroups.com> Hi, > I also recommend psycopg. Any specific reasons to go for psycopg instead of PyGreSQL? From mturillo at gmail.com Wed Aug 23 11:15:32 2006 From: mturillo at gmail.com (Perseo) Date: 23 Aug 2006 08:15:32 -0700 Subject: Create a Multilanguage PDF in Python In-Reply-To: <1156325189.795356.45770@b28g2000cwb.googlegroups.com> References: <1156073383.983914.149180@i3g2000cwc.googlegroups.com> <87mz9z4f8h.fsf@smsnet.pl> <1156108451.762961.70140@h48g2000cwc.googlegroups.com> <1156143575.547217.237270@p79g2000cwp.googlegroups.com> <1156172609.125230.218190@i42g2000cwa.googlegroups.com> <4ku5d0Fdsn8fU1@uni-berlin.de> <1156272524.800930.27710@p79g2000cwp.googlegroups.com> <1156325189.795356.45770@b28g2000cwb.googlegroups.com> Message-ID: <1156346130.927241.296190@75g2000cwc.googlegroups.com> PERFECT! Done! Thanks Now I create a little file in pdf format but the data are in the MySql database! :( How can I connect to it? Thanks for all suggestions Perseo Rob Wolfe wrote: > Perseo wrote: > > Nothing to do! > > I enable test2.py and the folder with 777 permission and I write at the > > top of the file the PYTHONPATH "#!/usr/bin/python" as you told me but > > it doesn't works as well. > > #!/usr/bin/python is not PYTHONPATH. I think you should > read this: > http://docs.python.org/tut/node4.html#SECTION004220000000000000000 > > > The verdana font doesn't exist in the reportlab fonts folder. I try to > > delete the rows where it is called like (registerFont, setFont) but > > nothing to do. > > Fonts are not part of reportlab package. You should find it > in your OS or in the net. You need to know what font do you want to > use. > > > any suggestion?! > > Install reportlab package in your home directory, for example > /home/perseo/python/lib > > and then in the shell write this: > > export PYTHONPATH=/home/perseo/python/lib > > and look here: > http://docs.python.org/tut/node8.html#SECTION008110000000000000000 > > HTH, > Rob From steve at holdenweb.com Tue Aug 29 00:20:31 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 29 Aug 2006 05:20:31 +0100 Subject: How to let a loop run for a while before checking for break condition? In-Reply-To: References: Message-ID: Claudio Grondi wrote: > Sorin Schwimmer wrote: [...] > It doesn't. > > Claudio Sometimes silence is preferable to a concrete response. It takes less time and occupies less bandwidth. regards Steve who should perhaps have followed his own advice -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From claudio.grondi at freenet.de Mon Aug 28 08:42:22 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Mon, 28 Aug 2006 14:42:22 +0200 Subject: Misleading error message when opening a file (on Windows XP SP 2) In-Reply-To: References: <1f7befae0608280239k67e2d484h2b2c916511ece42d@mail.gmail.com> Message-ID: Fredrik Lundh wrote: > Tim Peters wrote: > > >>>Traceback (most recent call last): >>> File "", line 1, in -toplevel- >>> f = file('veryBigFile.dat','r+') >>>IOError: [Errno 2] No such file or directory: 'veryBigFile.dat' >>> >>>Is it a BUG or a FEATURE? >> >>Assuming the file exists and isn't read-only, I bet it's a Windows >>bug, and that if you open in binary mode ("r+b") instead I bet it goes >>away (this wouldn't be the first large-file text-mode Windows bug). > > > however, if you use the C level API, you get EINVAL (which presumably means > that the CRT cannot open this file in text mode), not ENOENT. this is also true > for older versions of Python: > > Python 2.1.1 (#20, Aug 23 2001, 11:27:17) [MSC 32 bit (Intel)] on win32 > >>>>f = open("bigfile.dat") >>>>f = open("bigfile.dat", "r+") > > Traceback (most recent call last): > File "", line 1, in ? > IOError: [Errno 22] Invalid argument: 'bigfile.dat' > > which probably means that this fix > > http://www.python.org/sf/538827 > > is partially responsible for the misleading error message. > > (the cause of this seems to be that when you open a text file for updating, the > CRT check if there's a chr(26) at the end of the file, but the 32-bit lseek API > doesn't support seeking to positions larger than 2^31-2) > > Using MSVC++ .NET 2003 compiler (if I did it all the right way): fstm = fopen("bigfile.dat","r+"); if(fstm == 0) { printf( " ErrNo: %i \n", errno ); } // ^-- prints : // on "r+" with too large file: 22 (EINVAL-Invalid argument) // on non-existing file : 2 (ENOENT-no such file) // on bad mode string spec. : 0 (??? why not EINVAL ...) So there _is_ a way to distinguish the different problems occurred while opening the file. The error message comes from Python (errnomodule.c), not from Windows(errno.h). Concluding from this it becomes evident for me, that this misleading error message is Python fault (even if originated by misleading errno values set after fopen in the MSVC++ environment and Windows), right? Probably also in Python 2.5? Claudio Grondi From maport at googlemail.com Wed Aug 30 06:29:10 2006 From: maport at googlemail.com (maport at googlemail.com) Date: 30 Aug 2006 03:29:10 -0700 Subject: Odd unicode() behavior Message-ID: <1156933750.471407.161400@i42g2000cwa.googlegroups.com> The behavior of the unicode built-in function when given a unicode string seems a little odd to me: >>> unicode(u"abc") u'abc' >>> unicode(u"abc", "ascii") Traceback (most recent call last): File "", line 1, in ? TypeError: decoding Unicode is not supported I don't see why providing the encoding should make the function behave differently when given a Unicode string. Surely unicode(s) ought to bahave exactly the same as unicode(s,sys.getdefaultencoding())? Any opinions? Mike. From cginboston at hotmail.com Wed Aug 30 08:19:12 2006 From: cginboston at hotmail.com (Chaz Ginger) Date: Wed, 30 Aug 2006 12:19:12 GMT Subject: Naming conventions In-Reply-To: References: Message-ID: <44F58240.4040903@hotmail.com> Neil Cerutti wrote: > On 2006-08-30, Jean-Paul Calderone wrote: >> On Wed, 30 Aug 2006 14:22:16 +1000, Ben Finney wrote: >>> "glenn" writes: >>> >>>> Bruno Desthuilliers wrote: >>>>> It might be better to use newstyle classes if you can. Also, the >>>>> convention is to use CamelCase for classes names (unless you have >>>>> a strong reason to do otherwise). >>> Note that this style is more correctly called TitleCase, since the >> Or StudlyCaps :) > > The first time I saw StudlyCaps I thought it was the ugliest > thing I'd ever seen. Now I use it a lot. I still have trouble > with GVR's preference for HTTPServer over HttpServer. The latter > is, to me, easier to read and write. > Personally I think so long as you are consistent in your coding style, be it httpserver, HttpServer or HTTPServer or any other variation, the reader will soon figure out what it means. If you feel you are being held hostage to capitalized naming conventions you might want to consider having things end in ...Class or ...Instance. At least you would be doing what you say you want to do: making the code more maintainable. Otherwise I say just be consistent and don't let dogma get in the way. All those that remember "Hungarian notation" please stand up! From steve at REMOVEME.cybersource.com.au Fri Aug 25 00:19:26 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Fri, 25 Aug 2006 14:19:26 +1000 Subject: sum and strings References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <1155922208.930580.135080@m79g2000cwm.googlegroups.com> <1156365271.487489.62640@m73g2000cwd.googlegroups.com> <44ECC789.1010202@tim.thechases.com> <44EDCFDE.9060604@tim.thechases.com> Message-ID: On Thu, 24 Aug 2006 18:24:19 +0200, Fredrik Lundh wrote: > besides, in all dictionaries I've consulted, the word "sum" means > "adding numbers". are you sure it wouldn't be more predictable if "sum" > converted strings to numbers ? And then on Thu, 24 Aug 2006 19:12:17 +0200 Fredrik also wrote: > (and note that the python-dev consensus is that sum is for numbers and > join is for strings. anyone who cares about writing readable code knows > that names matter; different things should have different names.) And yet sum() sums lists, tuples, custom classes, and many other things which are not numbers. Did python-dev not notice this? I doubt it. I've read all the arguments in favour of type-checking the arguments to sum() (actually only the second argument). I'm not convinced that this case is special enough to break the rules by raising an exception for strings. (Insert usual arguments about consistency, duck typing, least surprise, etc.) There is an alternative: raise a warning instead of an exception. That permits the admirable strategy of educating users that join() is generally a better way to concatenate a large number of strings, while still allowing programmers who want to shoot themselves in the foot to do so. Python generally allows the programmer to shoot himself in the foot, if the programmer insists, e.g. private attributes are by convention, not enforced by the language. That's one of the nice things about the language: it *suggests* what to do, but doesn't *insist* it knows what you want better than you do. -- Steven D'Aprano From skip at pobox.com Mon Aug 7 21:54:55 2006 From: skip at pobox.com (skip at pobox.com) Date: Mon, 7 Aug 2006 20:54:55 -0500 Subject: using python at the bash shell? In-Reply-To: <44d7e364$0$24980$c3e8da3@news.astraweb.com> References: <44d7e364$0$24980$c3e8da3@news.astraweb.com> Message-ID: <17623.61167.504867.705687@montanaro.dyndns.org> John> Aside from the normal commands you can use, I was wondering if John> it's possible to use Python from the terminal instead of the John> normal bash commands (e.g. print instead of echo). Take a look at ipython . It's not precisely what you've asked for, but it provides some features that help integrate Python with the shell environment. Skip From johnjsal at NOSPAMgmail.com Fri Aug 11 10:18:56 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 11 Aug 2006 14:18:56 GMT Subject: some n00b question In-Reply-To: <1155305094.295652.218220@i3g2000cwc.googlegroups.com> References: <1155305094.295652.218220@i3g2000cwc.googlegroups.com> Message-ID: Omar wrote: > b) I'm also interested in created GUI's sooner rather than later. Can > anyone point me to a fast track to doing GUI's on python? I recommend reading wxPython in Action. It's a great starter and reference to the wxPython GUI toolkit. Tkinter is usually considered easier and simpler, but I find it lacking in functionality, and wxPython is actually fairly easy to learn. From matt at vazor.com Tue Aug 29 20:07:36 2006 From: matt at vazor.com (matt at vazor.com) Date: 29 Aug 2006 17:07:36 -0700 Subject: How to let a loop run for a while before checking for breakcondition? In-Reply-To: References: Message-ID: <1156896455.939224.13640@h48g2000cwc.googlegroups.com> IMHO you're better off avoiding all this... It makes the code unnecessarily complicated when you're not sure if this is a performance bottleneck or not... Common advice is to write the code as simple as possible first, then go back and optimize as needed using the profiler. This is where extending in C becomes useful, but don't go to that level if it isn't really needed. KISS -- Keep It Simple Stupid thx m Hendrik van Rooyen wrote: > "Claudio Grondi" wrote: > > > | Diez B. Roggisch wrote: > | > Claudio Grondi schrieb: > | > > | >> > | >> Sometimes it is known in advance, that the time spent in a loop will > | >> be in order of minutes or even hours, so it makes sense to optimize > | >> each element in the loop to make it run faster. > | >> One of instructions which can sure be optimized away is the check for > | >> the break condition, at least within the time where it is known that > | >> the loop will not reach it. > | >> > | >> Any idea how to write such a loop? > | >> > | >> e.g. > | >> > | >> counter = 2*64 > | >> > | >> while counter(BUT DON'T CHECK IT THE FIRST ONE HOUR LONG): > | > > | > > | > now = time.time() > | > while time.time() - now < 3600.0 or some_other_condition: > | > ... > | > > | > > | > The short circuiting of the or will prevent the execution of > | > some_other_condition. > | > > | >> ... do something ... # and decrease the counter > | >> > | >> Thanks for any hint, but in particular if related to timers on the > | >> Windows 2000/XP system I am mainly working with. > | >> > | >> What do you think about this idea? Does it make sense? > | > > | > What idea? > | This one you haven't probably got from what I have written. > | I thought, that the introductory text gives enough context to be able to > | see what I mean, but I was apparently wrong. > | > | The idea is to speed up a loop by using a timer interrupt interfering > | with the loop, so that only after the timer interrupt would occur, the > | loop will start to check its break condition in each iteration. > | No checking of any kind in the loop should happen up to that time to > | minimize the number of operations in each iteration within the loop > | itself (i.e. the loop more or less won't know, that there is a timer on > | its way to change the loops behavior at a later time). > | > | I hope this above helps to understand what I would like to achieve. > | > | Claudio Grondi > > I don't think this is usefully possible in python - the problem is that you will > simply replace one check - The expiry of the counter - with another - to see if > the interrupt has occurred already - > > That said - the way I would do it would be to do something like this (in > horrible pseudo code): > > loop_start: > do_something() > jump loop_start > if counter > end_value: > break > jump loop_start > loop_end: > > > Interrupt_routine: > replace the first jump to loop_start with a bunch of no - ops > return > > I don't think you can do this in python - it involves altering the running > loop - but hey maybe I can learn something here... > > This example sort of exposes the break for what it is - a jump statement in > disguise - "look you cant recognise me - I am wearing dark glasses" - and > "continue" is exactly like that too - the only difference is that the one jumps > to the end, and the other to the beginning of the loop... > > - Hendrik From inigoserna at gmail.com Thu Aug 17 19:11:37 2006 From: inigoserna at gmail.com (=?ISO-8859-1?Q?I=F1igo_Serna?=) Date: Fri, 18 Aug 2006 01:11:37 +0200 Subject: Looking For mp3 ID Tag Module In-Reply-To: <44E4EC79.3020005@tundraware.com> References: <44E4EC79.3020005@tundraware.com> Message-ID: <65a1d6f80608171611m3057eeefq60caaf2daff70395@mail.gmail.com> On 8/18/06, Tim Daneliuk wrote: > > try mutagen. http://www.sacredchao.net/quodlibet/wiki/Development/Mutagen > > This module is more-or-less exactly what I needed. However, I am running > into problems when the filenames or ID tags have unicode characters in them. > > Typically, I do something like: > > from mutagen.easyid3 import EasyID3 > > audio["title'] = Something based on the filename that has unicode chars in it > > I then get this: > > UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 56: ordinal not in range(128) >From the docs: """Mutagen has full Unicode support for all formats. When you assign text strings, we strongly recommend using Python unicode objects rather than str objects. If you use str objects, Mutagen will assume they are in UTF-8.""" So I suppose the value you try to assign as title is not unicode, check the encoding used in the file system. I?igo From johnjsal at NOSPAMgmail.com Tue Aug 8 12:07:15 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 08 Aug 2006 16:07:15 GMT Subject: using python at the bash shell? In-Reply-To: References: <44d7e364$0$24980$c3e8da3@news.astraweb.com> Message-ID: skip at pobox.com wrote: > >> I've just reconsiled to pick up my BASH by osmosis and concentrate on > >> (much!) cleaner scripting with Python. > > John> I don't have much of a need to learn the actual programming parts > John> of the bash language, ... > > As long as you promise never, ever, ever to try programming in csh... > > Skip Heh heh, Python all the way! From fccoelho at gmail.com Thu Aug 24 14:11:42 2006 From: fccoelho at gmail.com (Flavio) Date: 24 Aug 2006 11:11:42 -0700 Subject: can't destroy a wxMiniFrame Message-ID: <1156443102.524257.14500@i3g2000cwc.googlegroups.com> Hi, I have a miniframe composed mainly of combo boxes, that I need to destroy and recreate multiple time with different choice lists for the combo boxes. My problem is that even after destroying a miniframe with the Destroy() method, when it is recreated, the combo boxes show the same lists of its previous incarnation... how can I completely destroy a miniframe? Flavio From atkedzierski at gmail.com Sun Aug 13 10:33:07 2006 From: atkedzierski at gmail.com (AndrewTK) Date: 13 Aug 2006 07:33:07 -0700 Subject: reading from sockets In-Reply-To: <1155404471.418202.252850@75g2000cwc.googlegroups.com> References: <1155227695.625250.17920@m73g2000cwd.googlegroups.com> <1155387684.513673.130770@75g2000cwc.googlegroups.com> <1155404471.418202.252850@75g2000cwc.googlegroups.com> Message-ID: <1155479587.521795.307670@m73g2000cwd.googlegroups.com> Simon Forman wrote: > So I'm guessing it's something wrong in your java server. Thanks then. I'll keep testing then... Although I don't seem to have netcat on my unit... I'm using a uni computer so I can't install stuff... but I'm guessing what I wrote is something like a basic-basic thingy that does what netcat is designed to do.....? From skip at pobox.com Thu Aug 24 21:24:30 2006 From: skip at pobox.com (skip at pobox.com) Date: Thu, 24 Aug 2006 20:24:30 -0500 Subject: OS X and Python - what is your install strategy? In-Reply-To: <1156460483.616400.120160@i3g2000cwc.googlegroups.com> References: <1156460483.616400.120160@i3g2000cwc.googlegroups.com> Message-ID: <17646.20814.4654.382081@montanaro.dyndns.org> [ mp asks what version of Python to install on Mac OSX ] I just do a Unix build from the Subversion repository. I do have fink installed, so some of the external libraries match up there. Also, the Mac's readline module is really libedit, which doesn't provide enough functionality for Python's readline module. Having fink or Darwin Ports available is handy for that sort of thing. Skip From aleax at mac.com Wed Aug 2 11:46:41 2006 From: aleax at mac.com (Alex Martelli) Date: Wed, 2 Aug 2006 08:46:41 -0700 Subject: Windows vs. Linux References: <1154301694.445639.99580@m79g2000cwm.googlegroups.com> <1154345450.373339.74070@m79g2000cwm.googlegroups.com> <44cdf1f7$0$7762$7a628cd7@news.club-internet.fr> Message-ID: <1hjfpj0.h6wvcy18z0cqaN%aleax@mac.com> jean-michel bain-cornu wrote: > Andy Dingley a ?crit : > > I'd never recommend dual-boot for anything! > Don't agree man, it's good for testing... It's bothersome for testing: virtualization is much handier in most cases. Alex From onurb at xiludom.gro Thu Aug 10 09:15:41 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Thu, 10 Aug 2006 15:15:41 +0200 Subject: Absolute beginner - is this feasible? In-Reply-To: <1155213953.799292.207930@p79g2000cwp.googlegroups.com> References: <1155213953.799292.207930@p79g2000cwp.googlegroups.com> Message-ID: <44db317d$0$21150$7a628cd7@news.club-internet.fr> lcazarre at gmail.com wrote: > I am by no means a serious programmer (which will become evident as you > read this very message), except that I use VBA almost daily to automate > Excel spreadsheets. > > I do enjoy programming however and the only thing that prevented me > from learning a language other than VBA is the lack of a project. Until > today, I was not sure what I would do if I knew how to program in a > language such as Python. > > I now feel the need to develop a small program for myself. I have a > free subscription to Factiva (www.factiva.com), which gives me online > access to virtually all newspapers, magazines, etc. using a normal > internet browser. > > The bad thing is that I can only access the articles one by one. I wish > I could write a program that would: > - prompt me to choose a publication (let's say The Economist), > - find the latest publication, > - download automatically all the articles in that edition and finally > - combine and format the articles in a single Word document. > > This way, I will be able to print the magazine and read it on my way to > the office. > > Now my questions: > - is it legal? (I do have a subscription to Factiva. I do not intend to > distribute the printouts) For the legal part, you're on the wrong newsgroup. > - If so, can I use Python to automate this task? Should be mostly feasible. I can't tell for the conversion to Word (but is this necessary ?), but I don't see major difficulty for the other parts. FWIW, I'd start with the 2nd and 3rd points - and I'd eventually try and find out if these documents are accessible thru RSS feeds first, which would greatly simplifie the task. NB : urllib (in the standard lib) and other 3rd part packages like BeautifulSoup (html parser) or some rss reader may help. > Thank you. HTH From onurb at xiludom.gro Mon Aug 28 05:43:55 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 28 Aug 2006 11:43:55 +0200 Subject: Truly platform-independent DB access in Python? In-Reply-To: <1156748466.739709.117850@h48g2000cwc.googlegroups.com> References: <1156748466.739709.117850@h48g2000cwc.googlegroups.com> Message-ID: <44f2bade$0$13039$626a54ce@news.free.fr> bobrik wrote: > Hello, > > I am using the Python DB API for access to MySQL. But it is not > platform-independent It is. You don't have to change your Python code according to the OS or CPU. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From skip at pobox.com Mon Aug 28 23:23:41 2006 From: skip at pobox.com (skip at pobox.com) Date: Mon, 28 Aug 2006 22:23:41 -0500 Subject: How ahead are you guys in the (Python) real world? In-Reply-To: <1156821234.820929.299740@p79g2000cwp.googlegroups.com> References: <1156821234.820929.299740@p79g2000cwp.googlegroups.com> Message-ID: <17651.45885.893814.926663@montanaro.dyndns.org> Ray> Since I haven't used Python at work, I am using Python 2.5 right Ray> now. However I wonder, how fast are you guys moving from version Ray> to version at work? At my day job (a trading firm) we moved from 2.3 to 2.4 a couple months ago. At home I use whatever's in CVS. For my moonlighting job (mojam.com) I still use 2.3 because that's what /usr/bin/python is on the web server (which tummy.com administers) and I don't feel like messing with yet another separate install. Skip From brenNOSPAMbarn at NObrenSPAMbarn.net Tue Aug 8 14:42:55 2006 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: Tue, 8 Aug 2006 18:42:55 +0000 (UTC) Subject: matplotlib not plotting dates Message-ID: I just downloaded matplotlib and I was trying to do some simple date plots, but I'm running up against a puzzling error. Whenever I attempt to plot dates, I get an exception on line 157 of matplotlib/dates.py that says 'ValueError: need more than 0 values to unpack'. That line is: hour, remainder = divmod(24*remainder, 1) I don't understand how divmod can be returning 0 values. I inserted a statement into dates.py to "print divmod(24*remainder, 1)" and, mind-bogglingly, it actually printed "()" sometimes. The traceback indicates that this error is occuring when matplotlib tries to set up the axis labels for the date plot. I don't know enough about matplotlib to know exactly what it's doing, though. Does anyone have any ideas for how to fix this? This error occurs even with the matplotlib example scripts (e.g., date_demo1.py). I'm running it on Windows XP, Python 2.4, and my matplotlibrc file just has the default settings (TkAgg backend). -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From exogen at gmail.com Wed Aug 2 10:47:28 2006 From: exogen at gmail.com (Brian Beck) Date: Wed, 02 Aug 2006 10:47:28 -0400 Subject: Zipping files/zipfile module References: <1154483883.796081.35140@p79g2000cwp.googlegroups.com> <1154503406.601524.56390@75g2000cwc.googlegroups.com> <44d07e0e$1_2@news.bluewin.ch> Message-ID: Yves Lange wrote: > Other solutions: > you can try the rar command line from WinRar but it's not recommended. > This is a very slow manner to compress file. Are you sure? This worked about 4 times faster than the zip command line utility in Linux, compressing the same files... -- Brian Beck Adventurer of the First Order From andybak at gmail.com Wed Aug 9 07:57:01 2006 From: andybak at gmail.com (andybak) Date: 9 Aug 2006 04:57:01 -0700 Subject: setup.py when you can't write to site-packages? In-Reply-To: <4jtu9eF9mcl3U1@uni-berlin.de> References: <1155121231.384846.86090@i3g2000cwc.googlegroups.com> <4jtu9eF9mcl3U1@uni-berlin.de> Message-ID: <1155124620.968285.98770@75g2000cwc.googlegroups.com> Thanks Diez. For one thing I was getting setuptools mixed up with distutils. Then it occurred to me that this might be covered in the standard distutils docs (obvious I know but before I was thinking of it as a general Python problem and therefore wasn't sure where it might be documented) The solution was therefore right in plain view: http://docs.python.org/inst/alt-install-windows.html (despite the misleading url this page applies to Unix) (Must. Check. Docs. Before. Posting.) Diez B. Roggisch wrote: > andybak wrote: > > > There are several gaps in my Python knowledge, one of which is the what > > exactly setuptools does and how it works. > > > > I'm on a shared host so can't write to site-packages therefore most > > setup.py's fail. > > > > My strategy for pure python packages is to run setup.py locally and > > copy anything that gets put in site-packages across to the shared host > > somewhere in my Python path. I'm sure there is a better solution! > > > > What's the best approach for situations when you can't tamper with the > > Python install? > > If you've got setuptools installed, you can use the development mode + a > staging dir that you put in your PYTHONPATH. Then the copying is done for > you. > > Diez From lee at example.com Fri Aug 18 18:33:58 2006 From: lee at example.com (Lee Harr) Date: Fri, 18 Aug 2006 22:33:58 GMT Subject: plpython and pickle References: Message-ID: On 2006-08-17, Gerardo Herzig wrote: > Hi all, sory if this is kind of [OT], but cannot find the answer for > this behaviour > Might try on a postgres mailing list. I'd say it is more on topic there... > You are now connected to database "sessions". > sessions=# select * from getsessiondata('QQtEpLoKHnvbKGSpgJgYMPyCdHgXSi'); > getsessiondata > ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ > (dp0--ENTER--S---alucod-----ENTER--p1--ENTER--S---32009436-----ENTER--p2--ENTER--sS---respuestas_1-----ENTER--p3--ENTER--S---3-----ENTER--p4--ENTER--sS---respuestas_2-----ENTER--p5--ENTER--S---2-----ENTER--p6--ENTER--sS---respuestas_3-----ENTER--p7--ENTER--S---4-----ENTER--p8--ENTER--sS---submit-----ENTER--p9--ENTER--S---Responder-----ENTER--p10--ENTER--s. > data = plpy.execute("SELECT * from dblink('dbname=sessions', 'select * from getsessiondata(\'\'%s\'\')') as t1(session_data name); " % session_id)[0]["session_data"]; > plpy.notice(data) > """ > i got this > NOTICE: ("'(dp0--ENTER--S---alucod-----ENTER--p1--ENTER--S---32009436-----'",) Can you try just... SELECT * from dblink('dbname=sessions', 'select * from getsessiondata('QQtEpLoKHnvbKGSpgJgYMPyCdHgXSi'); > Im not even sure if this is a pickle, plpython nor postgresql issue or a dblink issue? From vasudevram at gmail.com Tue Aug 8 13:46:48 2006 From: vasudevram at gmail.com (vasudevram) Date: 8 Aug 2006 10:46:48 -0700 Subject: Info on continuations? In-Reply-To: <1155052039.984800.6070@75g2000cwc.googlegroups.com> References: <1155048104.107797.220630@b28g2000cwb.googlegroups.com> <1155052039.984800.6070@75g2000cwc.googlegroups.com> Message-ID: <1155059207.958747.324400@n13g2000cwa.googlegroups.com> Michele Simionato wrote: > vasudevram wrote: > > Hi, > > > > I am Googling and will do more, found some stuff, but interested to get > > viewpoints of list members on: > > > > Continuations in Python. > Thanks to all who replied. Vasudev From http Tue Aug 15 14:39:16 2006 From: http (Paul Rubin) Date: 15 Aug 2006 11:39:16 -0700 Subject: X windows and Python? Message-ID: <7xy7tpyhbf.fsf_-_@ruckus.brouhaha.com> I'd like to program my Python script to put a string into the X windows cut buffer. Can anyone suggest the simplest way to do that? Maybe I can do it by putting up a Tkinter text widget, sticking the string into it, and selecting it (I'm checking the docs) but uggh. I'd prefer not to have to put anything on the screen. I just want to put the string into the cut buffer so I can paste it into another program. Thanks for any suggestions. From deets at nospam.web.de Wed Aug 23 12:05:18 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 23 Aug 2006 18:05:18 +0200 Subject: Python + Java Integration References: Message-ID: <4l3cm2F33kfU1@uni-berlin.de> Chas Emerick wrote: > This may seem like it's coming out of left field for a minute, but > bear with me. > > There is no doubt that Ruby's success is a concern for anyone who > sees it as diminishing Python's status. One of the reasons for > Ruby's success is certainly the notion (originally advocated by Bruce > Tate, if I'm not mistaken) that it is the "next Java" -- the language > and environment that mainstream Java developers are, or will, look to > as a natural next step. > > One thing that would help Python in this "debate" (or, perhaps simply > put it in the running, at least as a "next Java" candidate) would be > if Python had an easier migration path for Java developers that > currently rely upon various third-party libraries. The wealth of > third-party libraries available for Java has always been one of its > great strengths. Ergo, if Python had an easy-to-use, recommended way > to use those libraries within the Python environment, that would be a > significant advantage to present to Java developers and those who > would choose Ruby over Java. Platform compatibility is always a huge > motivator for those looking to migrate or upgrade. While you might have a point with easing the transition for java developers might favor them python over ruby, you seem to mix a few things here, and forget about others: - ruby has no notion of java-library support. So if anything lures java developers from J2EE-land to rails, its the framework itself. Which, by my standards, is at least met if not excelled by TurboGears and Django. So it's marketing, but of a different kind, we need. - jython, after a period of seemingly inactivity, makes huge progress towards python2.2 and python2.3. Which will open up new possibilities just the other way round: use existing, powerful python libraries written in post-2.1 from jython, neatly integrating java and python. Now there is jRuby trying to do the same for ruby - but I never heard of it before (googled it for this post), so it seems not to be as important as jython certainly is Diez From honza.svec at gmail.com Fri Aug 11 05:31:37 2006 From: honza.svec at gmail.com (Jan Svec) Date: 11 Aug 2006 02:31:37 -0700 Subject: Read a file with open command In-Reply-To: <1155288288.954142.293000@i3g2000cwc.googlegroups.com> References: <1155288288.954142.293000@i3g2000cwc.googlegroups.com> Message-ID: <1155288697.170018.61160@m79g2000cwm.googlegroups.com> Hi, simply use file_obj = open ("D:\My documents\File.ods",'rb') for opening file in binary access mode, which is required for binary files on MS Windows. Honza jean-jeanot wrote: > I can access to a file with the command: > file_obj = open ( " D:\My documents\Textfile.txt",'r') > > When I now try to read a file with the following command: > > file_obj = open ("D:\My documents\File.ods",'r') it doesn't function. > The extension ods is coming from OpenOffice.org Calc. > > Why ? > > jean-jeanot From tomi.lindberg.NO_SPAM at pp.inet.fi.invalid Wed Aug 2 08:15:09 2006 From: tomi.lindberg.NO_SPAM at pp.inet.fi.invalid (Tomi Lindberg) Date: Wed, 02 Aug 2006 12:15:09 GMT Subject: Class definition within function In-Reply-To: <4jbitvF73bhvU1@uni-berlin.de> References: <4jbitvF73bhvU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > No, its not. Only inside of it. And the question really is: why? Thanks. And no need to worry, the question was intended as fully theoretical. -- Tomi Lindberg From gagsl-py at yahoo.com.ar Mon Aug 28 22:46:58 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 28 Aug 2006 23:46:58 -0300 Subject: Python web service ... In-Reply-To: <7d2580610608281645u65941eabwf4a8e74802b84976@mail.gmail.co m> References: <1156590455.555359.247410@h48g2000cwc.googlegroups.com> <32822fe60608281459i56784c8bo20b3cacba0852423@mail.gmail.com> <7d2580610608281645u65941eabwf4a8e74802b84976@mail.gmail.com> Message-ID: <7.0.1.0.0.20060828234133.05c79880@yahoo.com.ar> At Monday 28/8/2006 20:45, Nicolas G wrote: >If I want to run my program as a web service I need to setup a >webserver , am I right ? >Whars that difference ? can a webservice be run without a webserver ? Well, a webservice uses HTTP as its transport protocol, so you need an HTTP server, but you don't have to use a full-blown web server to implement it. SimpleHTTPServer in the standard library may be enough. Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From ray_usenet at yahoo.com Wed Aug 23 03:17:47 2006 From: ray_usenet at yahoo.com (Ray) Date: 23 Aug 2006 00:17:47 -0700 Subject: Python and STL efficiency In-Reply-To: <1hkil7z.dex1g6h2p4ltN%riko@despammed.com> References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <1hkh28d.xscw4v1y4v9a6N%riko@despammed.com> <1hkh6lb.6dsnh51lj8z96N%riko@despammed.com> <1156252193.524186.107520@b28g2000cwb.googlegroups.com> <1156299389.336939.211670@i42g2000cwa.googlegroups.com> <1156300663.405909.39350@74g2000cwt.googlegroups.com> <1hkil7z.dex1g6h2p4ltN%riko@despammed.com> Message-ID: <1156317467.901088.29530@h48g2000cwc.googlegroups.com> Mc Osten wrote: > In your test, you are looping 10000 times, we looped 1000000. > In Python tests with 10000 elements, it was about 10 ms. > > Moreover, we tried various Python and C++ configurations. Most of the > tests are done with Python 2.4, not 2.5. > And I used gcc4, that is to say the latest on my platform. Mine's VC 2005 Express--let me put the optimization parameters later and measure again when I get home. From tal.no.no.spam at gmail.com Sun Aug 27 08:58:27 2006 From: tal.no.no.spam at gmail.com (Tal Einat) Date: 27 Aug 2006 05:58:27 -0700 Subject: Avoiding if..elsif statements In-Reply-To: References: <1156545375.962486.49540@h48g2000cwc.googlegroups.com> <1156547346.647480.187910@b28g2000cwb.googlegroups.com> <1156665361.369767.277380@b28g2000cwb.googlegroups.com> Message-ID: <1156683507.577640.74350@75g2000cwc.googlegroups.com> Fredrik Lundh wrote: > Tal Einat wrote: > > > This will work great if all of your functions recieve the same > > argument(s). > > I assumed "every single function would be passing the same variables" > meant exactly that, of course. > > Right, as usual. I sort of missed that... ;) - Tal From rpdooling at gmail.com Tue Aug 8 07:46:42 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 8 Aug 2006 04:46:42 -0700 Subject: using python at the bash shell? In-Reply-To: <44d7e364$0$24980$c3e8da3@news.astraweb.com> References: <44d7e364$0$24980$c3e8da3@news.astraweb.com> Message-ID: <1155037602.675825.212990@h48g2000cwc.googlegroups.com> John Salerno wrote: > I like using Python for everything, and if I don't need to learn the > bash 'language', then I won't just yet. And like vim, Ipython works on both windows and ubuntu. rd From gregpinero at gmail.com Thu Aug 31 14:11:42 2006 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Thu, 31 Aug 2006 14:11:42 -0400 Subject: Basic import Questions (with bonus profiling question) In-Reply-To: References: <312cfe2b0608310849m6967e2cx259046143728b29e@mail.gmail.com> <312cfe2b0608311002s3c24cd42t1206ebdc198a69c7@mail.gmail.com> Message-ID: <312cfe2b0608311111h31cf3331wbd68b590b83ccf16@mail.gmail.com> On 8/31/06, Fredrik Lundh wrote: > what module is this? if it takes 5.5 seconds to import a single module, > something isn't quite right. Ok, I know it sounds bad but it has a good purpose! Basically it provides access to about 100mb of data. It serves as a cache of QuickBooks data so programs don't have to hit up QuickBooks which would take many hours for some huge queries. Normally the only programs to use it are long running processes so the 5 seconds is ok, and obviously much preferable to hitting up QuickBooks. -Greg From ziga.seilnacht at gmail.com Mon Aug 7 10:15:46 2006 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 7 Aug 2006 07:15:46 -0700 Subject: is it possible to dividing up a class in multiple files? In-Reply-To: References: Message-ID: <1154960146.685362.72900@b28g2000cwb.googlegroups.com> Martin H?fling wrote: > Hi there, > > is it possible to put the methods of a class in different files? I just > want to order them and try to keep the files small. > > Regards > Martin You could use something like this: """ Example usage: >>> class Person(object): ... def __init__(self, first, last): ... self.first = first ... self.last = last ... >>> john = Person('John', 'Smith') >>> jane = Person('Jane', 'Smith') >>> class Person(extend(Person)): ... def fullname(self): ... return self.first + ' ' + self.last ... >>> john.fullname() 'John Smith' >>> jane.fullname() 'Jane Smith' """ def extend(cls): extender = object.__new__(Extender) extender.class_to_extend = cls return extender class Extender(object): def __new__(cls, name, bases, dict): # check that there is only one base base, = bases extended = base.class_to_extend # names have to be equal otherwise name mangling wouldn't work if name != extended.__name__: msg = "class names are not identical: expected %r, got %r" raise ValueError(msg % (extended.__name__, name)) # module is added automatically module = dict.pop('__module__', None) if module is not None: modules = getattr(extended, '__modules__', None) if modules is None: modules = extended.__modules__ = [extended.__module__] modules.append(module) # replace the docstring only if it is not None doc = dict.pop('__doc__', None) if doc is not None: setattr(extended, '__doc__', doc) # now patch the original class with all the new attributes for attrname, value in dict.items(): setattr(extended, attrname, value) return extended Ziga From http Tue Aug 29 22:56:18 2006 From: http (Paul Rubin) Date: 29 Aug 2006 19:56:18 -0700 Subject: Allowing ref counting to close file items bad style? References: <9U6Jg.951$Xw6.283@trndny02> Message-ID: <7x4pvvylrh.fsf@ruckus.brouhaha.com> Dan writes: > Is this discouraged?: > > for line in open(filename): > Yes. > Can I count on the ref count going to zero to close the file? You really shouldn't. It's a CPython artifact. > I understand that the upcoming 'with' statement will obviate this > question, but how about without 'with'? f = open(filename) try: for line in f: finally: f.close() From thomas.grove at nepinc.com Thu Aug 31 11:48:27 2006 From: thomas.grove at nepinc.com (Tom Grove) Date: Thu, 31 Aug 2006 11:48:27 -0400 Subject: HTTPS Login Message-ID: <44F704CB.6040702@nepinc.com> I am trying to login to a secure website and I am having some difficulty understanding the process. Here is what I have with my limited knowledge of the subject: ##Start Code## #!/usr/bin/env python import urllib import urllib2 # Main params = urllib.urlencode({ "user" : "username", "pass" : "password" }) req = urllib2.Request("https://web.site.com/default.aspx", params) data = urllib2.urlopen(req) for line in data.readlines(): print line ##End Code## This just doesn't seem to work. It just brings me back to a login screen. If you can lend a hand it would be much appreciated. -Tom From chrisBrat at gmail.com Tue Aug 8 08:04:30 2006 From: chrisBrat at gmail.com (Chris Brat) Date: 8 Aug 2006 05:04:30 -0700 Subject: Looking for an intellisense with good help IDE for Python In-Reply-To: <1155022590.845074.256900@i42g2000cwa.googlegroups.com> References: <1155022590.845074.256900@i42g2000cwa.googlegroups.com> Message-ID: <1155038670.320761.20280@m73g2000cwd.googlegroups.com> I dont know if it will meet all your needs but SPE (Stani's Python Editor) is quite cool - has code completion. http://pythonide.stani.be metaperl wrote: > Hi, > > I would like an IDE that shows me all methods and functions I can call > on a particular data item. For instance, iter() can be called on any > sequence, but it is not a method. > > Nonetheless, I would like for something to show me every thing that I > can call on a particular data item. > > This includes % after a string. > > I would also like browseable help with good examples on whatever > methods and functions and operators it pops up. > > Thanks, > Terrence From hitesh287 at gmail.com Wed Aug 16 16:48:27 2006 From: hitesh287 at gmail.com (Hitesh) Date: 16 Aug 2006 13:48:27 -0700 Subject: Adding a char inside path string In-Reply-To: <1155760716.499472.189490@p79g2000cwp.googlegroups.com> References: <1155737700.290268.248250@i42g2000cwa.googlegroups.com> <1155744057.573884.111850@m73g2000cwd.googlegroups.com> <1155757548.080769.213490@p79g2000cwp.googlegroups.com> <1155759163.627377.72590@74g2000cwt.googlegroups.com> <12e70d6h4pb3l65@corp.supernews.com> <1155760716.499472.189490@p79g2000cwp.googlegroups.com> Message-ID: <1155761307.009983.260540@i42g2000cwa.googlegroups.com> Here is a mediocare solution. def TruncateString(s, Tindex): return string.ljust(s,Tindex){:Tindex] s = '\\serverName\\C:\\Folder Name1\\FolderName2\\example.exe -u ABC -g XYZ' Sindex = s.find(".exe") Sindex = Tindex +4 s1 = TruncateString(s, Sindex) Hitesh wrote: > anything after .exe should be truncated (or deleted). > > > Grant Edwards wrote: > > On 2006-08-16, Hitesh wrote: > > > > > That might work but what if I get (in future) a path name where > > > foldername (and in windows it is very common, someone might name a > > > folder something like "Screw You") with space? > > > > You must come up with a rigorous specification for what is and > > isn't allowed at the end of a path. > > > > Then delete the stuff that isn't allowed. > > > > -- > > Grant Edwards grante Yow! Hello? Enema > > at Bondage? I'm calling > > visi.com because I want to be happy, > > I guess... From fredrik at pythonware.com Tue Aug 22 07:52:35 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Aug 2006 13:52:35 +0200 Subject: Python and STL efficiency References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <1hkh28d.xscw4v1y4v9a6N%riko@despammed.com> Message-ID: "Mc Osten" wrote: > In fact Python here is faster. Suppose it has a really optimized set > class... Python's memory allocator is also quite fast, compared to most generic allocators... From thermostat at gmail.com Thu Aug 3 21:36:14 2006 From: thermostat at gmail.com (Dan) Date: 3 Aug 2006 18:36:14 -0700 Subject: md5 question Message-ID: <1154655374.571813.236870@75g2000cwc.googlegroups.com> I have a question regarding the md5 module. Is there a way in "initialize" the md5 to a hex value, and continue processing with that value. For example: In [13]:md5_h = md5.md5("Hello world") In [14]:md5_h.hexdigest() Out[14]:'3e25960a79dbc69b674cd4ec67a72c62' In [15]:md5_w = md5.md5("Hello") In [16]:md5_w.hexdigest() Out[16]:'8b1a9953c4611296a827abf8c47804d7' In [17]:md5_w.update(" world") In [18]:md5_w.hexdigest() Out[18]:'3e25960a79dbc69b674cd4ec67a72c62' now pretend I wanted to save the string '8b1a9953c4611296a827abf8c47804d7', and later create a new md5 object such that when I did md5_w.update(" world") it would then have the hex value '3e25960a79dbc69b674cd4ec67a72c62'. Is that possible? I've looked for initialization options in the documentation and searched c.l.p., but no luck. -Dan From mshewfelt at gmail.com Thu Aug 17 15:04:13 2006 From: mshewfelt at gmail.com (Mark Shewfelt) Date: 17 Aug 2006 12:04:13 -0700 Subject: Dynamic objects Message-ID: <1155841453.166739.75210@b28g2000cwb.googlegroups.com> Hello, I have implemented a series of classes representing a Building, its respective Equipment, and then various Components of that equipment like so (as you'll be able to tell, I'm a newbie): class Building: equipment = {} def AddEquipment( name, data ): equipment[ name ] = Equipment( data ) class Equipment: components = {} def AddComponent( name, data ): components[ name ] = Component( data ) class Component: data = "" These classes are used like so: test = Building() test.AddEquipment( "equipment 1", data ) test.AddEquipment( "equipment 2", data ) test.equipment["equipment 1"].AddComponent( "component 1", data ) test.equipment["equipment 1"].AddComponent( "component 2", data ) test.equipment["equipment 2"].AddComponent( "component 3", data ) But it appears as though the instance of "equipment 1" has ALL of the components in its components dictionary. I was hoping that the test.equipment["equipment 1"].components dictionary would only have those components that were assigned to "equipment 1". I have implemented __init__ functions for all of the classes, but all they do is initialize some data that I haven't shown here. I think I'm trying to use a C++ way of doing this (without the new operator) so if anyone would be so kind as to help with the Python way of doing this sort of thing I will be eternally grateful. Cheers, Mark Shewfelt From ds4ff1 at yahoo.com Tue Aug 8 16:40:59 2006 From: ds4ff1 at yahoo.com (ds4ff1z) Date: 8 Aug 2006 13:40:59 -0700 Subject: (easy question) Find and replace multiple items Message-ID: <1155069659.347944.111010@m79g2000cwm.googlegroups.com> Hello, i'm looking to find and replace multiple characters in a text file (test1). I have a bunch of random numbers and i want to replace each number with a letter (such as replace a 7 with an f and 6 with a d). I would like a suggestion on an a way to do this. Thanks From saketh.bhamidipati at gmail.com Thu Aug 3 13:33:57 2006 From: saketh.bhamidipati at gmail.com (Saketh) Date: 3 Aug 2006 10:33:57 -0700 Subject: distutils is not found Message-ID: <1154626437.432250.74210@i3g2000cwc.googlegroups.com> Under openSUSE 10.0, I installed Python 2.4.1. I executed a setup.py which imports distutils, but I received an error which gave an "ImportError: module not found" for distutils. I thought that distutils is part of the standard library under Python, but is there something that I am missing? Can I (or should I) install distutils manually? Thanks for the assistance. From steve at holdenweb.com Wed Aug 30 02:58:32 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 30 Aug 2006 07:58:32 +0100 Subject: What do you want in a new web framework? In-Reply-To: <1hkujsw.1kfwx315rpfd3N%aleax@mac.com> References: <1156100331.329889.216340@p79g2000cwp.googlegroups.com> <1156156636.515678.118210@75g2000cwc.googlegroups.com> <4jele2pe011di99c5dnq4olclglrkieggc@4ax.com> <1hkgnbt.ebn4o1111ftp0N%aleax@mac.com> <1hkujsw.1kfwx315rpfd3N%aleax@mac.com> Message-ID: <44F53718.2010302@holdenweb.com> Alex Martelli wrote: [...] > > .... > [...] youtube says: The url contained a malformed video id. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From catalin.marinas at gmail.com Fri Aug 25 09:32:35 2006 From: catalin.marinas at gmail.com (catalin.marinas at gmail.com) Date: 25 Aug 2006 06:32:35 -0700 Subject: Python-like C++ library In-Reply-To: <1156342782.435869.250350@75g2000cwc.googlegroups.com> References: <1156342782.435869.250350@75g2000cwc.googlegroups.com> Message-ID: <1156512755.794811.303540@74g2000cwt.googlegroups.com> Will McGugan wrote: > I'm forced to use C++ and STL at work, and consequently miss the ease > of use of Python. I was wondering if there was a C++ library that > implemented the fundamental objects of Python as close as possible, > perhaps using STL underneath the hood. Not copying Python but it has many useful features (and high quality code) - http://www.boost.org/ Catalin From tal.no.no.spam at gmail.com Sun Aug 27 12:17:16 2006 From: tal.no.no.spam at gmail.com (Tal Einat) Date: 27 Aug 2006 09:17:16 -0700 Subject: Defining constant strings In-Reply-To: <44f1bc61$0$26543$3a628fcd@textreader.nntp.hccnet.nl> References: <44f1bc61$0$26543$3a628fcd@textreader.nntp.hccnet.nl> Message-ID: <1156695435.968558.325380@m73g2000cwd.googlegroups.com> Hans wrote: > Hi, > > I want to define a couple of constant strings, like in C: > #define mystring "This is my string" > or using a const char construction. > > Is this really not possible in Python? > > Hans It is really not possible. The Pythonic way (as far as I have come to know it) is to stop trying to protect yourself from yourself, and just don't change something which should be constant. Good documentation (including in-code comments) and good design are better for preventing programming errors than defining things as constant. Actually, you can't really define anything as constant in C either. A #define can be overriden, a 'const' variable can be casted. These are merely conventions which are enforced to some degree by compilers, but can easily be worked around. There are conventions for constant values in Python too. Usually, variables with an all uppercase name are used. As for variables, functions, attributes, methods etc. which shouldn't be changed/used outside a certain module/class: these are usually prefixed with an underscore ("_"). These are not enforced by the interpreter at all, though. As a side note, Python strings are actually all constants, or "immutable" in Python-ish. The variables which reference string objects can be changed to reference any other object - that's the nature of Python variables. But the strings themselves don't change. - Tal From gelists at gmail.com Fri Aug 4 12:42:59 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Fri, 4 Aug 2006 13:42:59 -0300 Subject: Nested function scope problem References: <20060804094245.A9AF.SLAWOMIR.NOWACZYK.847@student.lu.se> <1okvniwl5zgqj.dlg@gelists.gmail.com> Message-ID: <1qcs7qgdceml6.dlg@gelists.gmail.com> On 2006-08-04 12:12:44, Antoon Pardon wrote: >> That's possible. I wouldn't expect too many C programmers to have any >> notion of "id of a variable". I, for example, never thought about such >> thing before this thread. > > But even in Python we don't speak of "id of a variable". It is not the > variable that has an id. It is the object that is currently attached to > the variable that has an id. Yes we can use "id of a variable" as a > shortcut for the correct formulation as long as you keep in mind that it > is not the variable itself that has an id. This sounds a bit like saying "yes we can use the term 'variable' as a shortcut for the correct formulation (object associated to a name) as long as we keep in mind that it is not actually a variable" :) Gerhard From aahz at pythoncraft.com Fri Aug 11 00:17:33 2006 From: aahz at pythoncraft.com (Aahz) Date: 10 Aug 2006 21:17:33 -0700 Subject: Warlord *this* Message-ID: http://groups.google.com/group/soc.motss/msg/a41fbe0c17342f46 -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." --Brian W. Kernighan From zeph_zhang at yahoo.co.uk Mon Aug 14 21:52:43 2006 From: zeph_zhang at yahoo.co.uk (Zeph) Date: Mon, 14 Aug 2006 21:52:43 -0400 Subject: Mega Newbie Questions: Probably FAQs In-Reply-To: <1155591083.461286.75380@i3g2000cwc.googlegroups.com> References: <1155591083.461286.75380@i3g2000cwc.googlegroups.com> Message-ID: ajaksu wrote: > Hoping this helps more than confuses, Thanks, these were the sort of answers I was looking for. I've programmed in Basic, AppleScript, Pascal and Usertalk (Userland Frontier), I've got a sense for development, it's just been a very, very long time ago. I do intend to start small and build up, but I want to front load my learning curve, usually makes the other side of the curve more productive. From faulkner612 at comcast.net Fri Aug 11 13:53:24 2006 From: faulkner612 at comcast.net (faulkner) Date: 11 Aug 2006 10:53:24 -0700 Subject: seeking the "Hello World" of Packages In-Reply-To: References: Message-ID: <1155318804.749265.75000@h48g2000cwc.googlegroups.com> yep, that's all a package is. if you have trouble importing, check your PYTHONPATH environment variable, or sys.path. Bell, Kevin wrote: > I'm trying to get an idea of how packages work and I've read about it in > the Py Tutorial and Nutshell, but I'm still craving a concrete example > that I can poke through. Does anyone have a really basic package that > does very little that I could look at? > > What I've gathered thus far is that a package is simply a directory, say > C:\MyPackage, that would contain __init__.py which tells Python to be > aware of all the other modules in C:\MyPackage. Am I correct? > > C:\MyPackage\ > \__init__.py > \justPrintHelloWorld.py > \multiply5By10.py > > Would I expect the following behavior?: > > >>>import MyPackage > >>>MyPackage.justPrintHelloWorld > "Hello World" > >>>MyPackage.multiply5by10 > 50 From mim_karimi at yahoo.com Mon Aug 7 06:28:11 2006 From: mim_karimi at yahoo.com (mehdi karimi) Date: Mon, 7 Aug 2006 03:28:11 -0700 (PDT) Subject: py2exe and pyparallel Message-ID: <20060807102811.6103.qmail@web32702.mail.mud.yahoo.com> Hi I want to convert a .py file into .exe with py2exe (I use Pyparallel(import parallel) in that program) after running setup.py py2exe this massage appear: "The following modules appear to be missing: ['parallelioctl' , 'paralleljava'] " how I can remove this Problem? thanks --------------------------------- See the all-new, redesigned Yahoo.com. Check it out. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gelists at gmail.com Fri Aug 11 10:03:53 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Fri, 11 Aug 2006 11:03:53 -0300 Subject: Nested function scope problem References: <20060809093215.EEDA.SLAWOMIR.NOWACZYK.847@student.lu.se> <816zp2meldzw$.dlg@gelists.gmail.com> <20060811110853.EFD5.SLAWOMIR.NOWACZYK.847@student.lu.se> Message-ID: <1si7pxih0vbsf.dlg@gelists.gmail.com> On 2006-08-11 07:48:33, Slawomir Nowaczyk wrote: > But let me try again, please (just one more time, if this doesn't work > either I am willing to admit I do not see a simple analogy between > Python and C variables :-) > > Python C > variable: a variable: a > value of variable: eval("a") dereference operator: *a > textual representation: "a" address operator: &a > id of object: id(a) value of variable: a > > Thus, equivalent operations would be: > > Python C > a = 1003 a = &three // (1) > id(a) a > b = 1004 b = &four > a == b # False *a == *b // false > id(a) == id(b) # False a == b // false > b = a b = a > a == b # True *a == *b // true > id(a) == id(b) # True a == b // true > a = 1001+1002 a = MallocNewIntFromValue( one+two ) > a == b # True *a == *b // true Probably not True; b refers to the 1003 object, a refers to the 2003 object. But that's just a minor "bug" in your selection of values :) Your intention was probably to make a = 1001+2 in the line above. > id(a) == id(b) # False / True (2) a == b // false / true > a = 1003+1004 a = MallocNewIntFromValue( three+four ) > a == b # False *a == *b // false > id(a) == id(b) # False a == b // false > > (1) one, two, three and four are constants, something like "const int > one = 1". That is because there is no "literal int object" in C > - the thing you would write as "1" is likely not to actually > exist at runtime. And you cannot take an address of it. > > (2) is actually True in CPython implementation for small integers, but > that's a minor detail. MallocNewIntFromValue might cache objects > as well. I don't have a problem with that analogy. I guess we also agree that it has its limits (as all analogies have). However, with this analogy, a and b /must/ be pointer variables in C; the analogy does not work if a and b are not pointers. Which brings me back to my earlier statement: if it is at all possible to create a useful analogy between Python variables and C variables, it is between Python variables and C /pointers/. There is still no useful analogy between Python variables and general C variables (i.e. non-pointer variables). Note that non-pointer variables can contain objects, not only simple types. But they still are not analog. Gerhard From h112211 at gmail.com Tue Aug 1 08:30:09 2006 From: h112211 at gmail.com (h112211 at gmail.com) Date: 1 Aug 2006 05:30:09 -0700 Subject: PyGreSQL, DLL search path, IDLE versus python command line Message-ID: <1154435409.727317.8590@p79g2000cwp.googlegroups.com> Hi all, I'm using the Windows version of Python 2.4.3 and everything worked okay until I installed PyGreSQL. Well, in fact the installation went fine, but when I try to run my script from IDLE I get: Traceback (most recent call last): File "\main.py", line 3, in -toplevel- import pgdb File "C:\Program Files\Python24\Lib\site-packages\pgdb.py", line 69, in -toplevel- from _pg import * ImportError: DLL load failed: The specified module could not be found. A quick surfing session suggested that this happens because libpq.dll cannot be found. However, if I start the Python command line (from the installer-created start menu shortcut) I can "import pgdb" without any errors whatsoever. And yes, the dir containing libpq.dll is in my windows path. Anyone know why the the command line finds everything but IDLE doesn't? From python.list at tim.thechases.com Mon Aug 28 12:25:05 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 28 Aug 2006 11:25:05 -0500 Subject: Operator Overloading Basics In-Reply-To: <1700BE453DBC09459A81AB53553E64CDDF0373@inexg.GRAPECITY.NET> References: <1700BE453DBC09459A81AB53553E64CDDF0373@inexg.GRAPECITY.NET> Message-ID: <44F318E1.7050300@tim.thechases.com> > obj1 = c1(1) > > obj1 + 10 # this works just fine > 10 + obj1 # throws exception > Q. What do I have to do to make the following line work? > > 10 + obj1 http://docs.python.org/ref/numeric-types.html You want to read the section on __radd__ (and it's other __r[whatever]__ variants) -tkc From kevin.bell at slcgov.com Fri Aug 11 13:48:04 2006 From: kevin.bell at slcgov.com (Bell, Kevin) Date: Fri, 11 Aug 2006 11:48:04 -0600 Subject: seeking the "Hello World" of Packages Message-ID: <2387F0EED10A4545A840B231BBAAC722608562@slcimail1.slcgov.com> I'm trying to get an idea of how packages work and I've read about it in the Py Tutorial and Nutshell, but I'm still craving a concrete example that I can poke through. Does anyone have a really basic package that does very little that I could look at? What I've gathered thus far is that a package is simply a directory, say C:\MyPackage, that would contain __init__.py which tells Python to be aware of all the other modules in C:\MyPackage. Am I correct? C:\MyPackage\ \__init__.py \justPrintHelloWorld.py \multiply5By10.py Would I expect the following behavior?: >>>import MyPackage >>>MyPackage.justPrintHelloWorld "Hello World" >>>MyPackage.multiply5by10 50 From penneys at bigfoot.com Sat Aug 19 17:20:08 2006 From: penneys at bigfoot.com (MrBlueSky) Date: 19 Aug 2006 14:20:08 -0700 Subject: timezones and time_t In-Reply-To: References: <1155931981.943667.214910@m73g2000cwd.googlegroups.com> Message-ID: <1156022408.163976.262080@75g2000cwc.googlegroups.com> Thanks for the reply. Unfortunately, a simple "+offset" type solution isn't really accurate enough for the kind of scenario I'm looking at. I'm often dealing with different timezones with DST changeovers on different dates or even different times of day! So I need industrial-strength timezone handling! Wrt your naming conventions... sorry, I'm a newbie to Python so not really qualified to comment. But what's a PEP? From sjdevnull at yahoo.com Mon Aug 28 18:06:02 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 28 Aug 2006 15:06:02 -0700 Subject: Is this a good idea or a waste of time? In-Reply-To: References: <1156449402.022781.292840@p79g2000cwp.googlegroups.com> <1156485945.967160.238790@m73g2000cwd.googlegroups.com> <44f322cd$1@nntp0.pdx.net> Message-ID: <1156802762.331853.80000@75g2000cwc.googlegroups.com> Antoon Pardon wrote: > There seem to be enough problems that work with ints but not with > floats. In such a case enforcing that the number you work with > is indeed an int seems fully appropiate. I've _never_ seen a case where enforcing types in the manner of the OP is appropriate. It fails with trivial wrappers like class myInt(int): def printFormatted(self): .......... Even looser checking with isinstance is rarely right. You may want to exclude floats, but that doesn't mean you want to exclude int-like objects that don't inherit from int. From fredrik at pythonware.com Wed Aug 23 15:37:02 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Aug 2006 21:37:02 +0200 Subject: Class instantiation In-Reply-To: References: Message-ID: Colin J. Williams wrote: > In the example below, with the disassembly following that, we run into > trouble with the line: > self.connect(fileID, mode= 'r') # open sheet in the read mode > > the traceback is: > Traceback (most recent call last): > File "C:\Documents and Settings\cjw\My Documents\OODev\tArray.py", > line 26, in __init__ > self.connect(fileID, mode= 'r') # open sheet in the read mode > NameError: global name 'fileID' is not defined > > At line 26, location 31, why is LOAD_GLOBAL generated for fileId, when > LOAD_FAST has done the job at locations 0 and 20? hint: Python is case-sensitive. From steven.bethard at gmail.com Mon Aug 14 13:19:44 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 14 Aug 2006 11:19:44 -0600 Subject: outputting a command to the terminal? In-Reply-To: References: <44df99f7$0$25025$c3e8da3@news.astraweb.com> Message-ID: Yu-Xi Lim wrote: > Steven Bethard wrote: >> import argparse # http://argparse.python-hosting.com/ >> import subprocess >> import sys > > Why not the standard lib's optparse? The page referenced above gives a variety of reasons, but the two most important things in this example are: argparse supports parsing of both positional and optional arguments, and argparse generates better usage messages. Since argparse supports positional arguments, I can write something like:: parser.add_argument('packages', ..., nargs='+', ...) and then the arparse module will enforce that at least one positional argument was given. With optparse, you'd do something like: options, args = parser.parse_args() if not args: parser.error('wrong number of arguments') Basically, with optparse, anything that involves positional arguments has to be handled by the user. It's also worth pointing out the better usage messages. Notice that the output looked like:: $ scriptname.py -h usage: scriptname.py [-h] [--save SAVE] package [package ...] positional arguments: package one of the packages to install optional arguments: -h, --help show this help message and exit --save SAVE a file to save the package names to With the optparse, you'd get something like:: $ scriptname.py -h usage: scriptname.py [OPTIONS] options: -h, --help show this help message and exit --save SAVE a file to save the package names to The argparse module knows how to create a meaningful usage message instead of just "%prog [OPTIONS]", and the argparse module knows about positional arguments, so you can have help messages for them too. Ok, enough propaganda for now. ;-) STeVe From pianomaestro at gmail.com Fri Aug 25 01:34:02 2006 From: pianomaestro at gmail.com (pianomaestro at gmail.com) Date: 24 Aug 2006 22:34:02 -0700 Subject: lazy arithmetic In-Reply-To: <1156481896.043165.84770@i3g2000cwc.googlegroups.com> References: <1156476992.102203.304450@p79g2000cwp.googlegroups.com> <1156481896.043165.84770@i3g2000cwc.googlegroups.com> Message-ID: <1156484042.437296.55890@m73g2000cwd.googlegroups.com> Simon Forman wrote: > > "Item.__add__ = Add" is a very strange thing to do, I'm not surprised > it didn't work. Yes it is strange. I also tried this even stranger thing: class Item(object): class __add__(object): def __init__(self, a, b=None): print self, a, b self.a = a self.b = b :) Simon. > > HTH, > ~Simon From fredrik at pythonware.com Thu Aug 24 07:28:53 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Aug 2006 13:28:53 +0200 Subject: Problem of function calls from map() References: <200608211350.k7LDoBJb032411@fe12.bluebottle.com> <2Gf*MkSor@news.chiark.greenend.org.uk> Message-ID: Steve Holden wrote: > Well I guess if people wanted to argue for keeping the functionals this > should be on the list ... who's arguing ? is this perhaps a little like the "now that we have lexical scoping, the default argument object binding trick is no longer needed" myth ? From sjmachin at lexicon.net Mon Aug 28 05:27:38 2006 From: sjmachin at lexicon.net (John Machin) Date: Mon, 28 Aug 2006 19:27:38 +1000 Subject: f2py on windows XP - "Unknown Switch"?? In-Reply-To: <1156754647.169794.272430@m79g2000cwm.googlegroups.com> References: <1156177095.867153.327380@h48g2000cwc.googlegroups.com> <1156629368.463878.138620@h48g2000cwc.googlegroups.com> <1156754647.169794.272430@m79g2000cwm.googlegroups.com> Message-ID: <44F2B70A.3080209@lexicon.net> On 28/08/2006 6:44 PM, Sile wrote: > Cheers John - > > I did finally getting f2py working on XP using MinGW, GnuFcompiler for > F77, and much help! However, having set up everything correctly I have > been told in work I now need to use F90. I have downloaded and > installed G95 MinGW in my MinGW directory and this isn't working now, > I'm not having much joy with this! When I check the available fortran > compilers in F2PY I get the following............... > > customize Gnu95FCompiler > > Could not locate executable f95 > > Executable f95 does not exist > > Could not locate executable f95 > > Executable f95 does not exist > > Could not locate executable f95 > > Executable f95 does not exist > > customize IntelVisualFCompiler > > Could not locate executable ifl > > Executable ifl does not exist > > customize G95FCompiler > > Couldn't match compiler version for 'G95 (GCC 4.0.3 (g95 0.90!) Aug 22 > 2006) Copyright (C) 2002-2005 Free Software Foundation, Inc.nG95 comes > with NO WARRANTY, to the extent permitted by law. You may redistribute > copies of G95under the terms of the GNU General Public License.For more > information about these > > ...............etc. > > > based on suggestions on the web I changed one line in g95.py to > version_pattern =r'G95.*\(GCC4.01)\(g95!) (?P<version>.\). > Unfortunately this didn't work for me. The problem seems to be with my > gcc version so I'm trying to find a way around this at the moment. Any > suggestions would be much appreciated, I have submitted this problem to > the f2py mailing list too. > Ummm shouldn't that be "GCC 4.0.1", not "GCC4.01" ??? Further that pattern seems as though it's been through some web garbling; for example "<" instead of "<", the parentheses don't match, the string isn't terminated by a "'", spaces missing, .... Can you post an ungarbled version of the original line (maybe the *whole* g95.py -- e-mail if it's too big) and what you changed it to, plus what your f95 compiler puts out when you run it with --version? Cheers, John From rosedb0 at gmail.com Thu Aug 3 11:45:47 2006 From: rosedb0 at gmail.com (hiaips) Date: 3 Aug 2006 08:45:47 -0700 Subject: Running queries on large data structure In-Reply-To: References: <200608022224.00925.email@christoph-haas.de> Message-ID: <1154619947.900116.88780@i3g2000cwc.googlegroups.com> Christoph, Several possibilities come to mind... >From your description, maybe something like Postgres, MySql, or sqlite would not be the best option. (However, I'm wondering what your query requirements are -- for example, if you really need the power of SQL, maybe you should just bite the bullet and map to an RDBMS schema, as painful as that may be. However, if you need to provide a minimal query interface, this may not be an issue.) Pickle seems like an option, but I don't have much experience with it and can't say. A couple of other possibilities: 1. What about storing your data in XML and using XQuery to facilitate queries? If your data is deeply nested, as you say, this may be a good match. 2. What about storing your data in the same syntax as a Python dictionary? Is that possibile? (If it is, then your data *is* your code, and you don't have to worry about parsing it.) I don't know whether any of this makes sense for your problem, but in any case, good luck. --hiaips From f.braennstroem at gmx.de Sat Aug 5 14:04:47 2006 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Sat, 5 Aug 2006 20:04:47 +0200 Subject: access abook addressbook with curses Message-ID: Hi, I want to get access to my abook address file with python. Does anyone have some python lines to achive this using curses? If not, maybe anybody has small python program doing it with a gui!? Greetings! Fabian From stylecomputers at gmail.com Tue Aug 15 03:20:13 2006 From: stylecomputers at gmail.com (Tyronem) Date: 15 Aug 2006 00:20:13 -0700 Subject: Best IDE for Python In-Reply-To: <1155593080.976094.33460@m79g2000cwm.googlegroups.com> References: <1155541849.350392.31190@h48g2000cwc.googlegroups.com> <1155593080.976094.33460@m79g2000cwm.googlegroups.com> Message-ID: <1155626413.196111.133370@75g2000cwc.googlegroups.com> Yep thanks all for your replies. and yes i meant free and open source software, left an s out :) Tryker wrote: > Gotta love PyScripter. Light, easy to use, free. > http://mmm-experts.com/Products.aspx?ProductID=4 > > stylecomputers at gmail.com wrote: > > Hi All, What do you find the best IDE for creating web applications in > > Python is? Preferably FOS IDE. > > > > Cheers From bj_666 at gmx.net Wed Aug 2 12:18:21 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 02 Aug 2006 18:18:21 +0200 Subject: Newbie Q: Class Privacy (or lack of) References: <44C586A2.4D4BFFEE@rotten.apple.commie> <1154080289.251993.137560@b28g2000cwb.googlegroups.com> Message-ID: In , Antoon Pardon wrote: > On 2006-07-28, Marc 'BlackJack' Rintsch wrote: >> This avoids the problem but you get others in return. And it's an >> abuse of `__slots__` which is meant as a way to save memory if you need >> really many objects of that type and not as "protection". > > I find that a strange purpose because when you are working on a class, > you don't necessarily know if you will ever know many instance of that > class. So should I use __slots__ in all my classes, just to be sure for > when someone wants many instances of one? No you should not use it unless you are sure there will be really many instances of that class. Putting __slots__ in the mix without a compelling reason is premature optimization. Ciao, Marc 'BlackJack' Rintsch From fpemberton133 at yahoo.com Sat Aug 12 13:31:34 2006 From: fpemberton133 at yahoo.com (f pemberton) Date: 12 Aug 2006 10:31:34 -0700 Subject: trouble with replace References: <1155401390.926925.252000@m79g2000cwm.googlegroups.com> Message-ID: <1155403894.003417.269870@i42g2000cwa.googlegroups.com> Marc 'BlackJack' Rintsch wrote: > In <1155401390.926925.252000 at m79g2000cwm.googlegroups.com>, f pemberton > wrote: > > > I've tried using replace but its not working for me. > > xdata.replace('abcdef', 'highway') > > xdata.replace('defgef', 'news') > > xdata.replace('effwer', 'monitor') > > `replace()` does not work in place. You have to bind the result to a name > like:: > > xdata = xdata.replace('abcdef', 'highway') > > Ciao, > Marc 'BlackJack' Rintsch lol, you probably will not believe me but I actually knew that already. I just forgot to add that part in my original post. When I try and replace what happens is the first replace works fine but when I try and do a second replace on a different part of the same string, the program will print the string a second time(which I do not want). How can you do 2 or more replaces in one line of code? From thattommyhall at gmail.com Sat Aug 19 06:58:35 2006 From: thattommyhall at gmail.com (thattommyhallll@gmail.com) Date: 19 Aug 2006 03:58:35 -0700 Subject: efficient memoize decorator? In-Reply-To: <1155970838.837378.304560@74g2000cwt.googlegroups.com> References: <1155931932.349283.27700@h48g2000cwc.googlegroups.com> <1155970838.837378.304560@74g2000cwt.googlegroups.com> Message-ID: <1155985115.153358.258110@h48g2000cwc.googlegroups.com> am i correct in thinking that psyco will just not accelerate, rather than break code it cannot deal with? that has been a pretty standard import on all my programs tom Ziga Seilnacht wrote: > thattommyhallll at gmail.com wrote: > > im plugging away at the problems at > > http://www.mathschallenge.net/index.php?section=project > > im trying to use them as a motivator to get into advanced topics in > > python. > > one thing that Structure And Interpretation Of Computer Programs > > teaches is that memoisation is good. > > all of the memoize decorators at the python cookbook seem to make my > > code slower. > > is using a decorator a lazy and inefficient way of doing memoization? > > can anyone point me to where would explain how to do it quickly. or is > > my function at fault? > > Your problem is that you are mixing psyco and memoize decorators; > psyco cannot accelerate inner functions that use nested scopes (see > http://psyco.sourceforge.net/psycoguide/unsupported.html ). > You could try using the memoize decorator from: > http://wiki.python.org/moin/PythonDecoratorLibrary , > which doesn't use functions with closures, or use Fredrik Lundh's > solution which puts memoization directly into the function. > > Ziga From sjmachin at lexicon.net Tue Aug 29 06:02:46 2006 From: sjmachin at lexicon.net (John Machin) Date: 29 Aug 2006 03:02:46 -0700 Subject: The lib email parse problem... References: <1156837260.222395.305960@b28g2000cwb.googlegroups.com> <1156841437.692537.68200@i42g2000cwa.googlegroups.com> <1156841950.866776.66400@b28g2000cwb.googlegroups.com> Message-ID: <1156845766.073634.28590@75g2000cwc.googlegroups.com> ???? wrote: > this is not enough. > > when a part is mulitpart/alternative, i must find out which sub part i > need, not all the subparts. so i must know when the alternative is > ended. > So you'll have to write your own tree-walker. It would seem that is_multipart(), get_content_type() and get_payload() are the important methods. Here's a quickly lashed-up example: def choose_one(part, html_ok=False): last = None for subpart in part.get_payload(): if html_ok or "html" not in subpart.get_content_type(): last = subpart return last def traverse(part, html_ok=False): mp = part.is_multipart() ty = part.get_content_type() print "multi:%r type:%r file:%r" % (mp, ty, part.get_filename("<>")) if mp: if ty == "multipart/alternative": chosen = choose_one(part, html_ok=html_ok) traverse(chosen, html_ok=html_ok) else: for subpart in part.get_payload(): traverse(subpart, html_ok=html_ok) import email pmsg = email.message_from_string(msg_text) for toggle in (True, False): print "--- html_ok is %r ---" % toggle traverse(pmsg, html_ok=toggle) With a suitable message, this produced: --- html_ok is True --- multi:True type:'multipart/alternative' file:'<>' multi:False type:'text/html' file:'<>' --- html_ok is False --- multi:True type:'multipart/alternative' file:'<>' multi:False type:'text/plain' file:'<>' From luismgz at gmail.com Tue Aug 22 13:25:36 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 22 Aug 2006 10:25:36 -0700 Subject: How to get database metadata information (i.e. existing tables and columns in tables) References: <1156248215.222902.60330@i3g2000cwc.googlegroups.com> Message-ID: <1156267536.694716.236990@m73g2000cwd.googlegroups.com> If you want to know the names of the fields on a recordset, you can use cursor.description. For example, lets say you have a connection to a MySQL database: con = MySQLdb.connect('localhost','root','','mydb') cur = con.cursor() cur.execute('select * from customers') result = cur.fetchall() fields = [i[0] for i in cur.description] ... Description gives a list with information about your recordset, being the first item the name of the field. Hope this helps... Luis Chris Brat wrote: > Hi, > > Is it possible to retrieve details about the database, specifically a > list of the tables in the database; and then to retrieve the columns > and their types for the tables? > > Is this dependant on the database? > > Thanks > Chris From jorge.vargas at gmail.com Tue Aug 29 09:40:44 2006 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Tue, 29 Aug 2006 09:40:44 -0400 Subject: Max OSX and Excel In-Reply-To: <1156805457.046711.31000@75g2000cwc.googlegroups.com> References: <32822fe60608281500l762b61ddqc6f3300ec1e296a6@mail.gmail.com> <1156805457.046711.31000@75g2000cwc.googlegroups.com> Message-ID: <32822fe60608290640t497e95a7xea345f8037537201@mail.gmail.com> On 28 Aug 2006 15:50:57 -0700, John Machin wrote: > Jorge Vargas wrote: > > On 8/28/06, Johanna Pfalz wrote: > > > To be more specific, I'm interested in reading in certain rows and columns > > > from an excel spreadsheet directly without converting the information to a > > > text file. I'd also like to be able to write directly to an excel > > > spreadsheet from python. > > AFAIK there is no Python tool that will let you "write directly to" an > *existing* xls file -- apart of course from running Excel on Windows > via COM. > > The Pyexcelerator package creates xls files. > > > ohh I found a nice tool for that a while ago but I haven't been able to test it. > > Because ....? > nothing related to it, it's just that I haven't had the time to dive into it. > > > > http://groups.google.com/group/comp.lang.python.announce/browse_thread/thread/5d0828d7762e3586 > > http://cheeseshop.python.org/pypi/xlrd > > http://www.lexicon.net/sjmachin/xlrd.htm > > The "rd" in "xlrd" is an abrv8n of "read" -- it doesn't write Excel > spreadsheets. > oh no wonder why with my quick look at the API I didn't saw any write methods :) do you have any plans of implementing wirte or at least read/write of xls docs? > > > > I'll love to read some feedback from you on it :) > > Perhaps I should post some user feedback on the package's "website" ;-) > that will be nice. > Cheers, > John > > -- > http://mail.python.org/mailman/listinfo/python-list > From jgarber at gmail.com Wed Aug 16 14:20:45 2006 From: jgarber at gmail.com (jgarber) Date: 16 Aug 2006 11:20:45 -0700 Subject: Segmentation Fault using MySQLdb and twisted Message-ID: <1155752444.942819.46530@m79g2000cwm.googlegroups.com> Hello, I just upgraded MySQLdb to the 1.2.0 version provided by Redhat Enterprise Linux ES4. At that point I began to get segfaults when importing twisted after MySQLdb, but not before. -- RedHat Enterprise Linux ES 4 (fully updated) Python 2.3.4 mysql-python (MySQLdb) version 1.2.0 twisted version 2.4.0 -- For example: [jason at lake ~]$ python Python 2.3.4 (#1, Feb 6 2006, 10:38:46) [GCC 3.4.5 20051201 (Red Hat 3.4.5-2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import MySQLdb >>> import twisted Segmentation fault [jason at lake ~]$ python Python 2.3.4 (#1, Feb 6 2006, 10:38:46) [GCC 3.4.5 20051201 (Red Hat 3.4.5-2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import twisted >>> import MySQLdb >>> Any ideas? Thanks! Jason Garber --------------------------------------------------------------------------------------------------------------------------- Here is the gdb backtrace of the event: [jason at lake zcore]$ gdb python GNU gdb Red Hat Linux (6.3.0.0-1.96rh) Copyright 2004 Free Software Foundation, Inc. GDB is free software, covered by the GNU General Public License, and you are welcome to change it and/or distribute copies of it under certain conditions. Type "show copying" to see the conditions. There is absolutely no warranty for GDB. Type "show warranty" for details. This GDB was configured as "i386-redhat-linux-gnu"...(no debugging symbols found) Using host libthread_db library "/lib/tls/libthread_db.so.1". (gdb) run Starting program: /usr/bin/python (no debugging symbols found) (no debugging symbols found) [Thread debugging using libthread_db enabled] [New Thread -1208486208 (LWP 4302)] (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) Python 2.3.4 (#1, Feb 6 2006, 10:38:46) [GCC 3.4.5 20051201 (Red Hat 3.4.5-2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) >>> import MySQLdb (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) >>> import twisted (no debugging symbols found) Program received signal SIGSEGV, Segmentation fault. [Switching to Thread -1208486208 (LWP 4302)] 0x00b849f8 in strcmp () from /lib/tls/libc.so.6 (gdb) bt #0 0x00b849f8 in strcmp () from /lib/tls/libc.so.6 #1 0x00494e9d in OBJ_NAME_new_index () from /lib/libcrypto.so.4 #2 0x0049122f in lh_free () from /lib/libcrypto.so.4 #3 0x004914ff in lh_insert () from /lib/libcrypto.so.4 #4 0x00495075 in OBJ_NAME_add () from /lib/libcrypto.so.4 #5 0x00499405 in EVP_add_cipher () from /lib/libcrypto.so.4 #6 0x00590bc7 in SSL_library_init () from /lib/libssl.so.4 #7 0x00969294 in init_ssl () from /usr/lib/python2.3/lib-dynload/_ssl.so #8 0x00d140f9 in _PyImport_LoadDynamicModule () from /usr/lib/libpython2.3.so.1.0 #9 0x00d11ea5 in PyImport_ImportFrozenModule () from /usr/lib/libpython2.3.so.1.0 #10 0x00d12303 in PyImport_ImportFrozenModule () from /usr/lib/libpython2.3.so.1.0 #11 0x00d12535 in PyImport_ImportFrozenModule () from /usr/lib/libpython2.3.so.1.0 #12 0x00d1299a in PyImport_ImportModuleEx () from /usr/lib/libpython2.3.so.1.0 #13 0x00cf1dee in _PyUnicodeUCS4_IsAlpha () from /usr/lib/libpython2.3.so.1.0 #14 0x00cca961 in PyCFunction_Call () from /usr/lib/libpython2.3.so.1.0 #15 0x00ca7637 in PyObject_Call () from /usr/lib/libpython2.3.so.1.0 #16 0x00cf92a0 in PyEval_CallObjectWithKeywords () from /usr/lib/libpython2.3.so.1.0 #17 0x00cfaca7 in _PyEval_SliceIndex () from /usr/lib/libpython2.3.so.1.0 #18 0x00cff196 in PyEval_EvalCodeEx () from /usr/lib/libpython2.3.so.1.0 #19 0x00cff45d in PyEval_EvalCode () from /usr/lib/libpython2.3.so.1.0 #20 0x00d107db in PyImport_ExecCodeModuleEx () from /usr/lib/libpython2.3.so.1.0 #21 0x00d10c0d in PyImport_ExecCodeModule () from /usr/lib/libpython2.3.so.1.0 #22 0x00d11e81 in PyImport_ImportFrozenModule () from /usr/lib/libpython2.3.so.1.0 #23 0x00d12303 in PyImport_ImportFrozenModule () from /usr/lib/libpython2.3.so.1.0 #24 0x00d12571 in PyImport_ImportFrozenModule () from /usr/lib/libpython2.3.so.1.0 #25 0x00d1299a in PyImport_ImportModuleEx () from /usr/lib/libpython2.3.so.1.0 #26 0x00cf1dee in _PyUnicodeUCS4_IsAlpha () from /usr/lib/libpython2.3.so.1.0 #27 0x00cca961 in PyCFunction_Call () from /usr/lib/libpython2.3.so.1.0 #28 0x00ca7637 in PyObject_Call () from /usr/lib/libpython2.3.so.1.0 #29 0x00cf92a0 in PyEval_CallObjectWithKeywords () from /usr/lib/libpython2.3.so.1.0 #30 0x00cfaca7 in _PyEval_SliceIndex () from /usr/lib/libpython2.3.so.1.0 #31 0x00cff196 in PyEval_EvalCodeEx () from /usr/lib/libpython2.3.so.1.0 #32 0x00cff45d in PyEval_EvalCode () from /usr/lib/libpython2.3.so.1.0 #33 0x00d107db in PyImport_ExecCodeModuleEx () from /usr/lib/libpython2.3.so.1.0 #34 0x00d10c0d in PyImport_ExecCodeModule () from /usr/lib/libpython2.3.so.1.0 #35 0x00d11e81 in PyImport_ImportFrozenModule () from /usr/lib/libpython2.3.so.1.0 #36 0x00d12303 in PyImport_ImportFrozenModule () from /usr/lib/libpython2.3.so.1.0 #37 0x00d127c7 in PyImport_ImportFrozenModule () from /usr/lib/libpython2.3.so.1.0 #38 0x00d12bad in PyImport_ImportModuleEx () from /usr/lib/libpython2.3.so.1.0 #39 0x00cf1dee in _PyUnicodeUCS4_IsAlpha () from /usr/lib/libpython2.3.so.1.0 #40 0x00cca961 in PyCFunction_Call () from /usr/lib/libpython2.3.so.1.0 #41 0x00ca7637 in PyObject_Call () from /usr/lib/libpython2.3.so.1.0 #42 0x00cf92a0 in PyEval_CallObjectWithKeywords () from /usr/lib/libpython2.3.so.1.0 #43 0x00cfaca7 in _PyEval_SliceIndex () from /usr/lib/libpython2.3.so.1.0 #44 0x00cff196 in PyEval_EvalCodeEx () from /usr/lib/libpython2.3.so.1.0 #45 0x00cff45d in PyEval_EvalCode () from /usr/lib/libpython2.3.so.1.0 #46 0x00d107db in PyImport_ExecCodeModuleEx () from /usr/lib/libpython2.3.so.1.0 #47 0x00d10c0d in PyImport_ExecCodeModule () from /usr/lib/libpython2.3.so.1.0 #48 0x00d11e81 in PyImport_ImportFrozenModule () from /usr/lib/libpython2.3.so.1.0 #49 0x00d12165 in PyImport_ImportFrozenModule () from /usr/lib/libpython2.3.so.1.0 #50 0x00d11eb1 in PyImport_ImportFrozenModule () from /usr/lib/libpython2.3.so.1.0 #51 0x00d12303 in PyImport_ImportFrozenModule () from /usr/lib/libpython2.3.so.1.0 #52 0x00d12535 in PyImport_ImportFrozenModule () from /usr/lib/libpython2.3.so.1.0 #53 0x00d1299a in PyImport_ImportModuleEx () from /usr/lib/libpython2.3.so.1.0 #54 0x00cf1dee in _PyUnicodeUCS4_IsAlpha () from /usr/lib/libpython2.3.so.1.0 #55 0x00cca961 in PyCFunction_Call () from /usr/lib/libpython2.3.so.1.0 #56 0x00ca7637 in PyObject_Call () from /usr/lib/libpython2.3.so.1.0 #57 0x00cf92a0 in PyEval_CallObjectWithKeywords () from /usr/lib/libpython2.3.so.1.0 #58 0x00cfaca7 in _PyEval_SliceIndex () from /usr/lib/libpython2.3.so.1.0 #59 0x00cff196 in PyEval_EvalCodeEx () from /usr/lib/libpython2.3.so.1.0 #60 0x00cff45d in PyEval_EvalCode () from /usr/lib/libpython2.3.so.1.0 ---Type to continue, or q to quit--- #61 0x00d18917 in PyErr_Display () from /usr/lib/libpython2.3.so.1.0 #62 0x00d19e37 in PyRun_InteractiveOneFlags () from /usr/lib/libpython2.3.so.1.0 #63 0x00d19f9a in PyRun_InteractiveLoopFlags () from /usr/lib/libpython2.3.so.1.0 #64 0x00d1aa67 in PyRun_AnyFileExFlags () from /usr/lib/libpython2.3.so.1.0 #65 0x00d1f78e in Py_Main () from /usr/lib/libpython2.3.so.1.0 #66 0x080485b2 in main () From http Tue Aug 1 10:57:21 2006 From: http (Paul Rubin) Date: 01 Aug 2006 07:57:21 -0700 Subject: fast pythonic algorithm question References: <1154443185.562918.140090@s13g2000cwa.googlegroups.com> Message-ID: <7x64hcjyge.fsf@ruckus.brouhaha.com> "Guyon Mor?e" writes: > if (((src_host,src_port, protocol) in dict or (dest_host, dest_port, > protocol) in dict) and starttime < time < endtime): > print "we have a winner" If you have enough memory to do it that way, what's the problem? From fredrik at pythonware.com Sun Aug 20 09:38:28 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Aug 2006 15:38:28 +0200 Subject: PIL problem: IOError: cannot identify image file In-Reply-To: <1156064822.900499.85580@p79g2000cwp.googlegroups.com> References: <1156063935.533140.18950@p79g2000cwp.googlegroups.com> <1156064822.900499.85580@p79g2000cwp.googlegroups.com> Message-ID: h112211 at gmail.com wrote: > Doh! Apparently Image.open() wants a path, not a file. So > > i = Image.open('c:\\image2.png') > > works fine. it works fine on files too, if you open them in *binary* mode. From http Thu Aug 24 18:44:58 2006 From: http (Paul Rubin) Date: 24 Aug 2006 15:44:58 -0700 Subject: sum and strings References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <1155922208.930580.135080@m79g2000cwm.googlegroups.com> <1156365271.487489.62640@m73g2000cwd.googlegroups.com> <44ECC789.1010202@tim.thechases.com> <44EDCFDE.9060604@tim.thechases.com> Message-ID: <7xr6z5lpn9.fsf@ruckus.brouhaha.com> Fredrik Lundh writes: > "join" doesn't use __add__ at all, so I'm not sure in what sense that > would be more predictable. I'm probably missing something, but I > cannot think of any core method that uses a radically different > algorithm based on the *type* of one argument. 3 ** 2, vs. 3 ** 2.5 Actually it's worse than depending on just the type: (-3.0) ** 2.0 works, while (-3.0) ** 2.5 throws an error. But you can do (-3.0) ** (2.5 + 0.0j) for yet another radically different algorithm. I'm not sure whether the Python spec requires (-3.0)**2.0 to work, or if it's just an implementation-specific hack. In most languages, it wouldn't work. From bearophileHUGS at lycos.com Sat Aug 26 09:01:50 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 26 Aug 2006 06:01:50 -0700 Subject: Learning Python In-Reply-To: <44f03c80$0$75042$14726298@news.sunsite.dk> References: <44f03c80$0$75042$14726298@news.sunsite.dk> Message-ID: <1156597310.493911.241160@i42g2000cwa.googlegroups.com> JAG CHAN: > As I had written earlier, I am trying to learn Python. > I chose IDLE as an editor to learn Python. > Now I find that it is an online editor. > It is not possible for me to be always on online while learning. > Kindly suggest me a suitable editor (for Windows XP) which does not require > me to be on online. Maybe your firewall tells you that IDLE asks for access to the net, but it's not an online sofware. You can use a different editor, like SPE, or if you want to start with something simpler you can try ActivePython, or probably it's even better a normal and very fast txt editor with a python grammar for colorization, with a macro added to run the script being edited. Bye, bearophile From st at tobiah.org Fri Aug 25 17:55:18 2006 From: st at tobiah.org (tobiah) Date: Fri, 25 Aug 2006 14:55:18 -0700 Subject: Open Office and Python In-Reply-To: <44ef44bb$0$8917$88260bb3@free.teranews.com> References: <44ef44bb$0$8917$88260bb3@free.teranews.com> Message-ID: <44ef64a2$0$8856$88260bb3@free.teranews.com> I should have pointed out that the delimiter is a tab right now. That's what I use in general, but I still call the files .csv files. Also this doesn't check for, or handle quoted fields. > I put together a little utility that you may find helpful > if I understand you correctly. It converts a .csv file > to a .xls file without the need for the GUI. -- Posted via a free Usenet account from http://www.teranews.com From jiangnutao at gmail.com Wed Aug 23 17:07:44 2006 From: jiangnutao at gmail.com (Jason Jiang) Date: Wed, 23 Aug 2006 14:07:44 -0700 Subject: setting a breakpoint in the module References: <1156366612.827337.256610@74g2000cwt.googlegroups.com> Message-ID: I'm using Python pdb module pdb.py. "Simon Forman" wrote in message news:1156366612.827337.256610 at 74g2000cwt.googlegroups.com... > Jason Jiang wrote: >> Hi, >> >> I have two modules: a.py and b.py. In a.py, I have a function called >> aFunc(). I'm calling aFunc() from b.py (of course I import module a >> first). >> The question is how to directly set a breakpoint in aFunc(). >> >> The way I'm doing now is to set a breakpoint in b.py at the line to call >> aFunc(), 'c' to it, then 's' to step in, then set the breakpoint inside >> aFunc() by 'b lineNumber'. It's too cumbersome. >> >> Thanks. >> Jason > > What debugger are you using? > > -- > http://mail.python.org/mailman/listinfo/python-list > From robert.kern at gmail.com Tue Aug 29 19:58:47 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 29 Aug 2006 18:58:47 -0500 Subject: NumPy 1.0b4 now available In-Reply-To: <1156892631.086347.274840@b28g2000cwb.googlegroups.com> References: <1156892631.086347.274840@b28g2000cwb.googlegroups.com> Message-ID: mensanator at aol.com wrote: > Travis E. Oliphant wrote: >> The 4th beta release of NumPy 1.0 has just been made available. >> >> NumPy 1.0 represents the culmination of over 18 months of work to unify >> the Numeric and Numarray array packages into a single best-of-breed >> array package for Python. >> >> NumPy supports all the features of Numeric and Numarray with a healthy >> dose of it's own improved features. > > So how come this support doesn't extend to making a numpy > version of NumTuT? Because NumTut has no redeeming value? Certainly none over this: http://www.scipy.org/Numpy_Example_List >> It's time to start porting your applications to use NumPy as Numeric is >> no longer maintained and Numarray will only be maintained for a few more >> months. > > Which would be a good reason to convert NumTut. No. NumTut would still need to be *useful*. >> Porting is not difficult especially using the compatibility layers >> numpy.oldnumeric and numpy.numarray and the alter_code1.py modules in >> those packages. > > Ah, I see. I'm supposed to convert it myself. > > So when I place my cursor over the link What link? > and it identifies the > link as "alter_code1.py" meaning it's a Python source file, > naturally I download it only to discover that it's not a source > code file but an .html file masquerading as a .py file. > > So when I followow the link and see some stupid management > system, I'm completely bewildered. What the fuck am I supposed > to do with this? Oh, wait...I can download in other formats. > > Only the "Plain Text" format isn't plain text. It strips off the web > page stuff but doesn't translate the codes such as < rendering > the alleged plain text un-runnable. Ok, I should have downloaded > "Original Format". Would it be too much trouble to explain all that? Why are you trying to download the file from the Trac source browser? Get it from the real numpy source distribution. > Oh, and when you run alter_code1.py, it does not, in fact, alter > the code. After "altering", the NumTut files continue to complain > that there is no module named "Numeric". Pardon me, but wasn't > alter_code1.py supposed to fix that? I guess not. Of course, you > can guess what happened next. Manually changing "Numeric" to > "numpy" fixes the import problem but it still won't run, something > about "types" not being defined. Yup, that's a bug. Apparently we're not detecting "from Numeric import *". The drop-in replacement for "Numeric" is not "numpy" but "numpy.oldnumeric". Making that replacement at least gets me to a RuntimeError in Tkinter. Which is exactly what I get with Numeric. Remember what I said about NumTut having no redeeming value? >> The full C-API of Numeric is supported as is the C-API >> of Numarray. >> >> More information is available at http://numpy.scipy.org > > Like the statement > > "There is a module called convertcode.py in NumPy that > can make the transition to NumPy easier (it will automatically > perform the search-and-replace style changes that need to > be made to python code that uses Numeric to make it work > with NumPy)." > > Which is a lie, there is no such module included in numpy. > Is alter_code1.py supposed to take its place? If so why hasn't > the Home Page been updated to reflect this? Are you volunteering to maintain the site? I'd be happy to set you up with access. >> NumPy Developers > > And you have the GALL to CHARGE for the documentation! No, he's charging for a book. It's not the only source of documentation out there, you know. http://www.scipy.org/Documentation If you think the freely available material is lacking, please contribute. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From f.braennstroem at gmx.de Sun Aug 6 11:25:57 2006 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Sun, 6 Aug 2006 17:25:57 +0200 Subject: access abook addressbook with curses References: Message-ID: Hi Ben, * Ben C wrote: > On 2006-08-05, Fabian Braennstroem wrote: >> Hi, >> >> I want to get access to my abook address file with python. >> Does anyone have some python lines to achive this using >> curses? If not, maybe anybody has small python program doing >> it with a gui!? > > You can just parse the abook addressbook with the ConfigParser, try > this: > > import os > from ConfigParser import * > > abook = ConfigParser() > abook.read(os.environ["HOME"] + "/.abook/addressbook") > > for s in abook.sections(): > print abook.items(s) Thanks! I found a different example too: import ConfigParser import string config = ConfigParser.ConfigParser() config.read("/home/fab/.abook/addressbook") # print summary print for number in [2,200]: print string.upper(config.get(str(number), "email")) print string.upper(config.get(str(number), "name")) print string.upper(config.get(str(number), "city")) print string.upper(config.get(str(number), "address")) but the problem seems to be that abook does not write every field, so I get an exception when there is a field missing: Traceback (most recent call last): File "configparser-example-1.py", line 13, in ? print string.upper(config.get(str(number), "city")) File "/usr/lib/python2.4/ConfigParser.py", line 520, in get raise NoOptionError(option, section) ConfigParser.NoOptionError: No option 'city' in section: '2' Section 2 looks like: [2] name=Andrs Gzi email=anes.oi at ik.e nick=oz Is there a workaround? Greetings! Fabian From rogue_pedro at yahoo.com Thu Aug 3 13:21:25 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 3 Aug 2006 10:21:25 -0700 Subject: What is the best way to print the usage string ? References: Message-ID: <1154625685.027648.133500@p79g2000cwp.googlegroups.com> Leonel Gayard wrote: > Hi all, > > I had to write a small script, and I did it in python instead of > shell-script. My script takes some arguments from the command line, > like this. > > import sys > args = sys.argv[1:] > if args == []: > print """Concat: concatenates the arguments with a colon (:) between them > Usage: concat arg1 [arg2...] > Example: concat a b c prints \"a.jar:b.jar:c/\"""" > sys.exit(1) > print reduce(lambda x, y: x + ':' + y, sys.argv[1:]) > > Notice that the string messes the indentation in my script. The > indentation is correct, and if the script is invoked without > arguments, the usage string is printed correctly. > > Now, how can I achieve the same result while keeping a clean > indentation ? How is this done in python world ? In C, I would do > this: > > ;; This buffer is for notes you don't want to save, and for Lisp evaluation. > ;; If you want to create a file, visit that file with C-x C-f, > ;; then enter the text in that file's own buffer. > > if (argc < N) { > printf("Usage: blah blah blah\n" > "Some more lines in the usage text\n" > "Some more lines here too\n"); > exit(1); > } > > The whitespace at the beginning of the string helps me keep the > indentation clean, and the construct "a" "b" is syntactic sugar that > allows me to create a large string without concatenating them at > runtime. > > How can I get this in Python ? > > []'s > Leonel Python also concatenates adjacent strings, but the "real" newlines between your strings will need to be escaped (otherwise, because the newlines are statement separators, you will have one print statement followed by string literals with the wrong indentation.) print "Usage: blah blah blah\n" \ "Some more lines in the usage text\n" \ "Some more lines here too." (Note that the final string literal newline is not needed since print will add one of it's own.) HTH, ~Simon From apardon at forel.vub.ac.be Mon Aug 28 17:29:55 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 28 Aug 2006 21:29:55 GMT Subject: Is this a good idea or a waste of time? References: <1156449402.022781.292840@p79g2000cwp.googlegroups.com> <1156485945.967160.238790@m73g2000cwd.googlegroups.com> <44f322cd$1@nntp0.pdx.net> Message-ID: On 2006-08-28, Scott David Daniels wrote: > Antoon Pardon wrote: >> On 2006-08-25, Simon Forman wrote: >>> ... >>> Generally asserts should be used to "enforce" invariants of your code >>> (as opposed to typechecking), or to check certain things while >>> debugging. >> >> I don't understand this argument. Can't type checking be seen as >> enforcing a code invariant? >> > But it is practically never the "right" invariant. And who decides what is and what is not the "right" invariant? > You don't usually > mean type(x) == int, but rather something like x is a prime between 2 > and 923. Or 5< x**4 < 429, or _something_ problem specific. saying > that x must be an int is almost always simultaneously too specific and > too general. There seem to be enough problems that work with ints but not with floats. In such a case enforcing that the number you work with is indeed an int seems fully appropiate. -- Antoon Pardon From johnjsal at NOSPAMgmail.com Fri Aug 4 10:36:28 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 04 Aug 2006 14:36:28 GMT Subject: programming is hard In-Reply-To: <1154665071.640304.201300@s13g2000cwa.googlegroups.com> References: <1154609819.083694.22200@m73g2000cwd.googlegroups.com> <1154623085.994132.126620@m73g2000cwd.googlegroups.com> <1154648416.036565.224320@p79g2000cwp.googlegroups.com> <1154653325.803973.292490@p79g2000cwp.googlegroups.com> <1154665071.640304.201300@s13g2000cwa.googlegroups.com> Message-ID: placid wrote: > mensanator at aol.com wrote: >> placid wrote: >>> Alas, all good arguments. >>> >>> I rest my case. >> After you've just been proven wrong? >> >> I wouldn't want you for my lawyer. > > Aha, lucky i wont be a lawyer. > lawyering is hard too ;) From larry.bates at websafe.com Wed Aug 23 16:47:29 2006 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 23 Aug 2006 15:47:29 -0500 Subject: Accessing application data portably In-Reply-To: References: Message-ID: <44ECBEE1.6040106@websafe.com> Tom E H wrote: > My Python application includes some data files that need to be accessed by > modules I distribute with it. > > Where can I put them, and how should I arrange my code, so that it works > across platforms? > > On Linux, I could install the data to "/usr/lib/myprogram/datafile", and > on Windows to "datafile" relative to where the executable (made by > py2exe) is installed. Then I could detect the operating system, and choose > appropriately. > > To be that explicit seems undesirable. Any cleverer ideas? > > Tom > > (Please CC me on replies: I'm not subscribed. The From address is munged) > I almost always send along an application.ini file and put the location of where my data is to be stored in that file instead of imbedding (or worse, hard-coding) it in the application program itself. I also put other parameters that the user might want to change that will change the behavior of my program (debugging, logging, etc.) there also. Then during installation I modify the option in this file with the install script. Something like: [init] debug=0 quiet=0 datafilepath=/usr/lib/myprogram/datafile or [init] debug=0 quiet=0 datafilepath=C:\Program Files\myprogram\datafile Then I use ConfigParser in my application to read this file and extract the parameters. Makes it easy for more experienced users (and me) to be able to easily relocate the datafile if they desire. On Windows I use Inno Installer and it can modify these options inside the .ini file during the installation so that datafilepath points to where my data actually will live. Works perfectly for me. -Larry Bates From squall_leonheart7 at netzero.net Wed Aug 30 12:54:16 2006 From: squall_leonheart7 at netzero.net (squall_leonheart7 at netzero.net) Date: Wed, 30 Aug 2006 16:54:16 GMT Subject: code for the graphics window? Message-ID: <20060830.095434.10554.687233@webmail18.nyc.untd.com> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From cipherpunk at gmail.com Thu Aug 10 04:15:59 2006 From: cipherpunk at gmail.com (Robert J. Hansen) Date: 10 Aug 2006 01:15:59 -0700 Subject: excel in unix? In-Reply-To: <1155197334.969268.95220@i42g2000cwa.googlegroups.com> References: <1155197334.969268.95220@i42g2000cwa.googlegroups.com> Message-ID: <1155197759.433662.105540@q16g2000cwq.googlegroups.com> > is it possible to create excel files using python in Unix env? Yes. An Excel file is just a sequence of bytes, and Python can write sequences of bytes just fine. So can many other languages, but why would you want to use anything but Python? That's a useless answer to your question, I know. Perhaps in the future you may wish to consider asking a more focused question: it helps people understand precisely what you want to know, and helps people avoid giving you true-but-useless answers. :) > if so, what module should i use? Python does not have built-in support for Excel-formatted data. Microsoft Excel is a closed source program with a proprietary data format, as evidenced by the extreme difficulty competing spreadsheet software has in correctly implementing the format. More than that, attempting to do so would very possibly open Python up to some unpleasant corners of IP law. I'd suggest using the formats of Gnumeric or OpenOffice, since those are open and fully documented. When you're done, just load them up in Gnumeric or OpenOffice and use those apps to export them to Microsoft Excel. OpenOffice is scriptable--I don't know about Gnumeric--so this will probably not be unduly painful. That said, I certainly haven't tried it. From jeff_barish at earthlink.net Thu Aug 24 18:31:10 2006 From: jeff_barish at earthlink.net (Jeffrey Barish) Date: Thu, 24 Aug 2006 16:31:10 -0600 Subject: Record Audio Analysis References: Message-ID: Frank LaFond wrote: > Jo Chase wrote: >> I would like to record audio from a mic and perform some basic analysis >> on >> the audio wave patterns produced. What would be the easiest way to >> accomplish this in Python? > > Take a look at http://pymedia.org > > I think it allows the features you want. > > Frank. Or try PySonic (http://pysonic.sourceforge.net/) if you prefer a package that actually works. -- Jeffrey Barish From amit.man at gmail.com Mon Aug 28 09:12:36 2006 From: amit.man at gmail.com (noro) Date: 28 Aug 2006 06:12:36 -0700 Subject: creating multiply arguments for a method. In-Reply-To: <1156691230.817916.324020@h48g2000cwc.googlegroups.com> References: <1156686964.216440.72530@p79g2000cwp.googlegroups.com> <1156691230.817916.324020@h48g2000cwc.googlegroups.com> Message-ID: <1156770755.961164.113020@i3g2000cwc.googlegroups.com> John Roth wrote: > noro wrote: > > Hi all, > > > > I use a method that accept multiply arguments ("plot(*args)"). > > so plot([1,2,3,4]) is accepted and plot([1,2,3,4],[5,6,7,8]) is also > > accepted. > > > > the problem is that i know the number of arguments only at runtime. > > Let say that during runtime i need to pass 4 arguments, each is a list, > > creating a set of lists and passing it to the method wont word since > > the interpartor thinks it is only 1 argument the contain a reference to > > a "list of lists", instede of number of arguments, each is a list. > > > > any suggestions? > > thanks > > amit > > Why do you want to do this? You'll have to do some > logic in your method body to determine how many > operands you have whether you explicitly pass a list or > whether you have the system break it apart into > separate parameters. > > Fredrick Lund's solution, using an * parameter in the > method definition, will produce a list that you have to > pull apart in the method. Doing the same in the method > call takes a single list of all of your parameters and then > distributes it among the parameters in the definition. > > I wouldn't bother with either one. Passing a list of my > real parameters as a single parameter is, in most > circumstances, easier and IMO clearer. > > John Roth I do not have much choise. I did not wirte the module, i just use it. thank you all for the help, amit From __peter__ at web.de Wed Aug 2 11:33:46 2006 From: __peter__ at web.de (Peter Otten) Date: Wed, 02 Aug 2006 17:33:46 +0200 Subject: looking for a regular expression References: <4PNQbI$7fW@bbs.wretch.cc> Message-ID: ?????b?????????H wrote: >> How about >> my_string = "We the people of the United States, in order to form a >> more perfect union, establish justice, insure domestic >> tranquility,......" >> print (x for x in my_string.split(",") if "justice" in x).next() >> This isn't a regular expression, but it gives what you're looking for. >> THN > > Thanks a lot! I have never thought of that. > > But what if there's not only commas, but also periods and semicolons? I > want to find words between 2 near by punctuations. I think it would make > it difficult to use split instead of regular expression. Reenter re. Use re.split(r"[.;\-,]", my_string) instead of my_string.split(","). Peter From aleax at mac.com Wed Aug 2 11:12:26 2006 From: aleax at mac.com (Alex Martelli) Date: Wed, 2 Aug 2006 08:12:26 -0700 Subject: Need a compelling argument to use Django instead of Rails References: <1153737715.165346.164310@p79g2000cwp.googlegroups.com> <1kfre1jz9qmo4$.11mk99olj3zfm$.dlg@40tude.net> <44c77b6c$0$14327$626a54ce@news.free.fr> <1gplk685cld7c.kbdh6drne8zq.dlg@40tude.net> <1153926981.028296.15100@p79g2000cwp.googlegroups.com> <44c7965d$0$14332$626a54ce@news.free.fr> <44c87a3f$0$673$626a54ce@news.free.fr> Message-ID: <1hjfn6v.17y7uuv1ydg7tgN%aleax@mac.com> Bruno Desthuilliers wrote: ... > >>And of course import hooks. > > > > Python?? Where? > > RTFM: > http://www.python.org/doc/2.3.5/lib/built-in-funcs.html Perhaps a better reference is . Alex From yxing at stanford.edu Thu Aug 17 00:15:37 2006 From: yxing at stanford.edu (Yi Xing) Date: Wed, 16 Aug 2006 21:15:37 -0700 Subject: MySQLdb installation error Message-ID: <62fe0ec8ec37ef0e3d23a5d36cbdb98c@stanford.edu> I log into the machine remotely. How do I check the Mac OSX version number under command line? Thanks. hiaips rosedb0 at gmail.com Wed Aug 16 01:23:10 CEST 2006 * Previous message: MySQLdb installation error * Next message: What would be the best way to run python client in the background * Messages sorted by: [ date ] [ thread ] [ subject ] [ author ] Yi Xing wrote: > Hi, > > I met the following error when I tried to install MySQLdb. I had no > problem installing numarray, Numeric, Rpy, etc. Does anyone know > what's the problem? Thanks! > > running install > running build > running build_py > creating build > creating build/lib.darwin-7.9.0-Power_Macintosh-2.4 > copying _mysql_exceptions.py -> > build/lib.darwin-7.9.0-Power_Macintosh-2.4 > creating build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb > copying MySQLdb/__init__.py -> > build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb > copying MySQLdb/converters.py -> > build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb > copying MySQLdb/connections.py -> > build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb > copying MySQLdb/cursors.py -> > build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb > copying MySQLdb/release.py -> > build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb > copying MySQLdb/times.py -> > build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb > creating build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb/constants > copying MySQLdb/constants/__init__.py -> > build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb/constants > copying MySQLdb/constants/CR.py -> > build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb/constants > copying MySQLdb/constants/FIELD_TYPE.py -> > build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb/constants > copying MySQLdb/constants/ER.py -> > build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb/constants > copying MySQLdb/constants/FLAG.py -> > build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb/constants > copying MySQLdb/constants/REFRESH.py -> > build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb/constants > copying MySQLdb/constants/CLIENT.py -> > build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb/constants > running build_ext > building '_mysql' extension > creating build/temp.darwin-7.9.0-Power_Macintosh-2.4 > gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp > -mno-fused-madd -fno-common -dynamic -DNDEBUG -g -O3 -Wall > -Wstrict-prototypes -I/usr/include/mysql > -I/Library/Frameworks/Python.framework/Versions/2.4/include/python2.4 > -c _mysql.c -o build/temp.darwin-7.9.0-Power_Macintosh-2.4/_mysql.o > -fno-omit-frame-pointer -arch i386 -arch ppc -pipe > -Dversion_info="(1,2,1,'final',2)" -D__version__="1.2.1_p2" > gcc: cannot read specs file for arch `i386' > error: command 'gcc' failed with exit status 1 What version of OSX are you running? From bobrien18 at yahoo.com Fri Aug 25 12:37:09 2006 From: bobrien18 at yahoo.com (KraftDiner) Date: 25 Aug 2006 09:37:09 -0700 Subject: get a line of text from a socket... Message-ID: <1156523827.971633.321830@m79g2000cwm.googlegroups.com> If you don't know how long your input data is going to be how can you at least treat it a text line at a time... like looking for new line in the data... Right now recv blocks. Yes I could do a select, but the examples seem a bit complicated for a simple line oriented input... From fakeaddress at nowhere.org Thu Aug 3 21:32:34 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 04 Aug 2006 01:32:34 GMT Subject: Windows vs. Linux In-Reply-To: References: <1154301694.445639.99580@m79g2000cwm.googlegroups.com> <44cddfb3$0$7761$7a628cd7@news.club-internet.fr> <1154531160.066733.71210@s13g2000cwa.googlegroups.com> Message-ID: Duncan Booth wrote: > bryanjugglercryptographer at yahoo.com wrote: > >> >From a WinXP command prompt: >> >> C:\> >> C:\>cd /windows/system32 >> >> C:\WINDOWS\system32> >> >> > Not from my Windows XP command prompt it doesn't. Do you have anything > strange installed on your system? Tons of strange stuff, yes, but I just tried it on a couple machines on display at BestBuy, and it worked as I showed it. Maybe a recent change. -- --Bryan From timr at probo.com Thu Aug 10 00:39:43 2006 From: timr at probo.com (Tim Roberts) Date: Thu, 10 Aug 2006 04:39:43 GMT Subject: do people really complain about significant whitespace? References: <1154986984.740638.241130@m79g2000cwm.googlegroups.com> <1155038374.803591.315480@m73g2000cwd.googlegroups.com> Message-ID: <5ndld299najsd1072jauejd322nikfo30b@4ax.com> Dennis Lee Bieber wrote: > > I forget what COBOL used, but it had a few fields of its own. Not in fixed columns. Surprisingly, layout in COBOL was more closely related to Python, in that indentation was significant, but the number of characters per indent was up to the programmer. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From miki.tebeka at gmail.com Tue Aug 8 15:31:52 2006 From: miki.tebeka at gmail.com (Miki) Date: 8 Aug 2006 12:31:52 -0700 Subject: Python Projects Continuous Integration In-Reply-To: <1154087739.722910.110310@b28g2000cwb.googlegroups.com> References: <1154087739.722910.110310@b28g2000cwb.googlegroups.com> Message-ID: <1155065512.572675.315940@b28g2000cwb.googlegroups.com> Hello Dave, > I'm just starting a development project in Python having spent time in > the Java world. I was wondering what tool advice you could give me > about setting up a continuous integration environment for the python > code: get the latest source, run all the tests, package up, produce the > docs, tag the code repository. I'm used to things like Maven and > CruiseControl in the Java world. If you are familiar with CruiseControl and Maven then it shouldn't be too complicated to write a Maven file that run the tests, package up, produce the docs. CruiseControl can take care of all the rest. I also found that writing a simple Continuous integration system myself was a very simple task in Python, it might be a good choice as well. (I resorted to this solution after giving up on trying to install Java on OpenBSD.) HTH, Miki http://pythonwise.blogspot.com/ From yxing at stanford.edu Mon Aug 14 14:32:17 2006 From: yxing at stanford.edu (Yi Xing) Date: Mon, 14 Aug 2006 11:32:17 -0700 Subject: Memory problem Message-ID: Hi, I need to read a large amount of data into a list. So I am trying to see if I'll have any memory problem. When I do x=range(2700*2700*3) I got the following message: Traceback (most recent call last): File "", line 1, in ? MemoryError Any way to get around this problem? I have a machine of 4G memory. The total number of data points (float) that I need to read is in the order of 200-300 millions. Thanks. From gregpinero at gmail.com Sat Aug 5 15:12:40 2006 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Sat, 5 Aug 2006 15:12:40 -0400 Subject: Backup GMAIL Messages with Python Message-ID: <312cfe2b0608051212w65e823f7u114da578fc464927@mail.gmail.com> I was wondering what methods you experts would reccomend for this task? Here are the options I have come up with so far: 1. Build something with the poblib library (http://docs.python.org/lib/module-poplib.html) --Any pointers on doing this? How to I get poplib to save messages in a standard format I can later import into Thunderbird, Outlook, etc? (mbox?) 2. Use libgmail --How stable is this package? Does it just use screenscraping? 3. Call Fetchmail from command line? --Does anyone know an easy way to do this? All I found was a 6 page tutorial! yikes! Much thanks for any advice you might have. I'm also open to options I haven't thought of too. -- Gregory Pi?ero Chief Innovation Officer Blended Technologies (www.blendedtechnologies.com) From jeremy+complangpython at jeremysanders.net Mon Aug 21 09:09:18 2006 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Mon, 21 Aug 2006 14:09:18 +0100 Subject: Python and STL efficiency References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> Message-ID: Licheng Fang wrote: > I was using VC++.net and IDLE, respectively. I had expected C++ to be > way faster. However, while the python code gave the result almost > instantly, the C++ code took several seconds to run! Can somebody > explain this to me? Or is there something wrong with my code? It must be the debugging, the compiler or a poor STL implementation. With gcc 4 it runs instantly on my computer (using -O2), even with 10x the number of values. If the problem is that C++ has to make lots of new strings, as other posters have suggested, then you could do something like const string foo = "What do you know?"; for (long int i=0; i<10000 ; ++i){ ???a.push_back(foo); ... } as many C++ implementations use reference counting for identical strings. Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From casevh at comcast.net Thu Aug 10 11:04:00 2006 From: casevh at comcast.net (casevh at comcast.net) Date: 10 Aug 2006 08:04:00 -0700 Subject: (newbie) Float() and high precision In-Reply-To: References: Message-ID: <1155222240.652403.266830@b28g2000cwb.googlegroups.com> wirecom at wirelessmeasurement.com wrote: > What's the best way to do higher precision maths than the standard Float()? For basic operations, look at Decimal(). If you need more speed, and basic operations, search for gmpy. If you need advanced functions, look at http://calcrpnpy.sourceforge.net/ and related tools. casevh From bignose+hates-spam at benfinney.id.au Wed Aug 30 03:02:44 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 30 Aug 2006 17:02:44 +1000 Subject: Coding style and else statements References: <44f355d6$0$8812$88260bb3@free.teranews.com> <1156898310.795476.187030@i3g2000cwc.googlegroups.com> Message-ID: <87y7t6u2nf.fsf@benfinney.id.au> "Carl Banks" writes: > However, I have rare cases where I do choose to use the else > (ususally in the midst of a complicated piece of logic, where it's > be more distracting than concise). In that case, I'd do something > like this: > > def foo(thing): > if thing: > return thing+1 > else: > return -1 > assert False To my eyes, that's less readable than, and has no benefit over, the following: def foo(thing): if thing: result = thing+1 else: result = -1 return result -- \ "Ours is a world where people don't know what they want and are | `\ willing to go through hell to get it." -- Donald Robert Perry | _o__) Marquis | Ben Finney From onurb at xiludom.gro Tue Aug 29 04:49:09 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 29 Aug 2006 10:49:09 +0200 Subject: How ahead are you guys in the (Python) real world? In-Reply-To: <1156821234.820929.299740@p79g2000cwp.googlegroups.com> References: <1156821234.820929.299740@p79g2000cwp.googlegroups.com> Message-ID: <44f3ff86$0$31016$626a54ce@news.free.fr> Ray wrote: > Since I haven't used Python at work, I am using Python 2.5 right now. > However I wonder, how fast are you guys moving from version to version > at work? As an illustration my ex-company just moved to Java 5, which > was released around... what, 2-3 years ago? (While I am running Java 6 > at home) > > Is it the same in the Python world? What version of Python is used in, > say, Google? Is it even 2.4 yet? > I can't tell for Google, and we're certainly a much much smaller company, but FWIW, we mostly use 2.4.3 (we still have a 2.3.x for compatibility with some old zope install). -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From steve at REMOVEME.cybersource.com.au Tue Aug 15 23:55:13 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 16 Aug 2006 13:55:13 +1000 Subject: proc A def/calls proc B: variable scoping rules. References: <1155685233.002415.184150@74g2000cwt.googlegroups.com> <1155692329.075173.49060@p79g2000cwp.googlegroups.com> <1155695497.999739.295650@m73g2000cwd.googlegroups.com> <1155698914.087129.67680@i42g2000cwa.googlegroups.com> Message-ID: On Tue, 15 Aug 2006 20:28:34 -0700, NevilleDNZ wrote: > > Steve Holden wrote: >> No. It's too horrible to contemplate without getting mild feelings of >> nausea. What exactly is it you are tring to achieve here (since I assume >> your goal wasn't to make me feel sick :-)? > > It is part of an algorithum: Every piece of code is part of an algorithm. What is the algorithm supposed to accomplish, apart from giving people a headache? I'm not saying that what you've done can't ever be useful, but I'm with Steve on this one. Yuck. -- Steven D'Aprano From tod at uchicago.edu Wed Aug 9 00:22:09 2006 From: tod at uchicago.edu (Tod Olson) Date: Tue, 08 Aug 2006 23:22:09 -0500 Subject: import logging fails on MacPython 2.4.3 Message-ID: Anyone have advice for importing the logging module using MacPython 2.4.3? MacPython installs the logging module in: /Library/Frameworks/Python.framework/Versions/2.4/lib/logging/ There's an __init__.py there and everything, but this directory is not in sys.path. I add it to sys.path as follows: >>> sys.path.append(os.path.join(sys.prefix, 'lib', 'logging')) >>> print sys.path[-1] /Library/Frameworks/Python.framework/Versions/2.4/lib/logging But even so, the logging module is not found: >>> import logging Traceback (most recent call last): File "", line 1, in -toplevel- import logging ImportError: No module named logging Now, I've been away from Python for some years, so I'm pretty rusty. Maybe there's something obvious I'm missing. Any advice on how to proceed would be welcome. Tod Olson Programmer/Analyst University of Chicago Library From fredrik at pythonware.com Thu Aug 31 12:40:47 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 31 Aug 2006 18:40:47 +0200 Subject: Searching a string and extract all occurancies of a substring In-Reply-To: <44F703C8.3080504@gmail.com> References: <44F703C8.3080504@gmail.com> Message-ID: Nico Grubert wrote: > in a text with no carriage returns I need to look for all occurancies of > this string: > > ... > > The ... can contain different values. I need to extract the string > between and . is this XML, or just something that looks a little like XML ? From skip at pobox.com Fri Aug 25 10:37:45 2006 From: skip at pobox.com (skip at pobox.com) Date: Fri, 25 Aug 2006 09:37:45 -0500 Subject: Best Practices for Python Script Development? In-Reply-To: <1156515299.257203.283170@m73g2000cwd.googlegroups.com> References: <1156471481.265329.291360@m79g2000cwm.googlegroups.com> <1156515299.257203.283170@m73g2000cwd.googlegroups.com> Message-ID: <17647.2873.164216.180965@montanaro.dyndns.org> >> `Pydoc `_ seems to be >> built around modules and I want to document scripts. Ant> Any python script *is* a python module. So pydoc is what you are Ant> after here. Assuming you name your scripts so that they are importable (e.g. "foobar.py" instead of "foo-bar.sh"). Skip From sjmachin at lexicon.net Mon Aug 7 09:09:54 2006 From: sjmachin at lexicon.net (John Machin) Date: 7 Aug 2006 06:09:54 -0700 Subject: How to get hours and minutes from 'datetime.timedelta' object? In-Reply-To: <1154948054.987468.202100@i3g2000cwc.googlegroups.com> References: <1154940942.707530.291130@m79g2000cwm.googlegroups.com> <1154942169.530491.150390@h48g2000cwc.googlegroups.com> <1154948054.987468.202100@i3g2000cwc.googlegroups.com> Message-ID: <1154956194.252771.27070@b28g2000cwb.googlegroups.com> Ant wrote: > John Machin wrote: > > Lad wrote: > > > Hello, > > > what is the best /easest way how to get number of hours and minutes > > > from a timedelta object? > ... > > >>> diff.days > > 0 > > >>> diff.seconds > > 52662 > > >>> diff.microseconds > > 922000 > > >>> minutes = (diff.seconds + diff.microseconds / 1000000.0) / 60.0 > > >>> minutes > > 877.71536666666668 > > I suspect what Lad wanted was something more like: 1. If that's what he wanted, it was a very peculiar way of asking. Do you suspect that he needs to be shown how to conver 877.7... minutes into hours, minutes and seconds??? 2. Please consider that the order of the result would be more conventionally presented as (hours, minutes, seconds) -- or do you suspect that the OP needs it presented bassackwards? > > >>> def secs_mins_hours(timed): > ... total_secs = timed.seconds > ... secs = total_secs % 60 > ... total_mins = total_secs / 60 > ... mins = total_mins % 60 > ... hours = total_mins / 60 > ... return (secs, mins, hours) > >>> aa=datetime.datetime(2006, 7, 29, 16, 13, 56, 609000) > >>> bb=datetime.datetime(2006, 8, 3, 17, 59, 36, 46000) > >>> td = aa - bb > >>> secs_mins_hours(td) > (39, 45, 1) > > I'm surprised that the timedelta class hasn't got secs, mins and hours > properties - they could be generated on the fly in a similar way. From rogue_pedro at yahoo.com Sat Aug 26 12:00:42 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 26 Aug 2006 09:00:42 -0700 Subject: rollover effect In-Reply-To: <1156607403.741240.25000@74g2000cwt.googlegroups.com> References: <1156607403.741240.25000@74g2000cwt.googlegroups.com> Message-ID: <1156608042.466471.210270@m73g2000cwd.googlegroups.com> groves wrote: > hi > I am trying to get a roll over effect on my canvas.(this is a virtual > program which will eventually fit into my final program) > > Exactly i have a text on my screen and I want to have a brief > discription across it whenever the user takes the mouse on it n hence > giving information about the type of text(event). > > Another thign i am looking for is to have a right click on that very > text as well > If somebody can put some light on it, then it would be really great for > my project. > Thank you in advance. What GUI system are you using? Peace, ~Simon From tim.peters at gmail.com Mon Aug 28 05:39:33 2006 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 28 Aug 2006 05:39:33 -0400 Subject: Misleading error message when opening a file (on Windows XP SP 2) In-Reply-To: References: Message-ID: <1f7befae0608280239k67e2d484h2b2c916511ece42d@mail.gmail.com> [Claudio Grondi] > Here an example of what I mean > (Python 2.4.2, IDLE 1.1.2, Windows XP SP2, NTFS file system, 80 GByte > large file): > > >>> f = file('veryBigFile.dat','r') > >>> f = file('veryBigFile.dat','r+') > > Traceback (most recent call last): > File "", line 1, in -toplevel- > f = file('veryBigFile.dat','r+') > IOError: [Errno 2] No such file or directory: 'veryBigFile.dat' > > Is it a BUG or a FEATURE? Assuming the file exists and isn't read-only, I bet it's a Windows bug, and that if you open in binary mode ("r+b") instead I bet it goes away (this wouldn't be the first large-file text-mode Windows bug). From cagedmonsterhaalditweg at gmail.com Sat Aug 19 09:07:46 2006 From: cagedmonsterhaalditweg at gmail.com (cage) Date: Sat, 19 Aug 2006 15:07:46 +0200 Subject: write eof without closing Message-ID: hello can i write a eof to a file descriptor without closing it? like: fd.write(EOF) or something grts, ruben From crystalattice at gmail.com Wed Aug 2 13:21:04 2006 From: crystalattice at gmail.com (crystalattice) Date: 2 Aug 2006 10:21:04 -0700 Subject: Pickle vs XML for file I/O References: <1154391849.335723.94480@s13g2000cwa.googlegroups.com> <1154392539.551356.70870@i3g2000cwc.googlegroups.com> <1154451307.232785.282080@m79g2000cwm.googlegroups.com> Message-ID: <1154539264.728714.247000@h48g2000cwc.googlegroups.com> Marc 'BlackJack' Rintsch wrote: > In <1154451307.232785.282080 at m79g2000cwm.googlegroups.com>, crystalattice > wrote: > > >> What are the problems you fear when using `shelve` by the way? > >> > > The ideas I got about shelve are mostly due to this thread: > > http://tinyurl.com/lueok. There weren't any other threads > > contradicting the information so I figured it has merit. > > Main complaint seemed to be that data might be corrupted when the program > terminates "abnormal" while writing the data. You have the very same > problem with pickle or XML serialization. If the program gets interrupted > after only half the data is written to disk you lose information. > > > Actually, not many people seem to use shelve very much; pickle is used > > more often so I decided to give it a try and see how it works for me. > > They have a slightly different use case. `pickle` stores single objects > and `shelve` is a sort of persistent dictionary that maps strings to > objects. So if you want to save a party of characters and load them back > together than pickle a list with those characters. If you want a database > of many characters the player can choose from than you might want to store > them in a `shelve`. > > Ciao, > Marc 'BlackJack' Rintsch Okay, that makes sense. I was able to figure out how to pickle yesterday. It's not as hard as I thought (obviously); my confusion originally came from thinking I needed to pickle each item of the class separately but I realized that pickling a class instance worked too. One other question though (hope it doesn't sound silly/stupid). Your suggestion to "pickle a party" using a list has me thinking: can a list store class instances? I imagine it can though I don't know if there may be bad juju if I tried, like data corruption or errors or something. I've only been using classes for a few weeks so I don't know very much about them. For example, if I wanted to store a party of characters, rather than pickling each person separately could I put each character instance in a list then pickle the list? Like this: char1 = Character() char2 = Character() char3 = Character() party = [char1, char2, char3] file = open("partyfile.dat", "w") pickle.dump(party, file) From henrybg at gmail.com Mon Aug 28 15:29:29 2006 From: henrybg at gmail.com (Benry) Date: 28 Aug 2006 12:29:29 -0700 Subject: Twisted server and protocol question Message-ID: <1156793369.290812.247200@m73g2000cwd.googlegroups.com> Hi guys. I hope I can discuss Twisted here. If not, direct me to the correct place please. My question(s): I'm working on a custom network protocol (application layer in TCP/IP model) for a custom network. Please don't try to talk me out of this. I'm limiting many of the other protocols, because this is in a highly secure network, and latency/bandwidth is key. The packet sizes are minimized by the protocol design, which is ideal. Anyway. I'm having some problems with figuring out what to include in the Protocol class, and what to handle in the server class. Basically, I'm using Telnet, SMTP, and FTP protocol python files as a reference, and each have different strutures and methods of doing similar things. Basically, the protocol I'm developing is very similar to Telnet, so I used this code as a base. It is necessary to have a state machine, but there is dynamic information to send as a response to some received messages. For example, the server may need to get information from a DB, and send it in a packet as a reponse to a request. I'll give you a sample implementation, and the remainder of the specific questions below: server = a client = b 1a = NEED, 1 - NEED is a request to send data from client to server, 1 is the option, or type of data 2b = HAVE, 1 - HAVE is a positive response 3a = NEED, 1 - re-iterated for the purpose of being a server. The line "1a" is initiated only by a UI command. The line "3a" is initiated by as a response to the request "2b". 4b = PASV, 1 - same as FTP. It's basically, "Well, I have data...what port can I send it on?" 4a = PORT, 1, 51000 - not the same as FTP. It's the command, option, and port number 5b = ACK - acknowledge ok...now they both disconnect, or stop communication on this port, and server dynamically opens port 51000 on port 51000: 6b - <> 7a - <> Questions I have: This is a state machine. The server has a class derived from the Protocol class whose methods are called prior to the Protocol's. For example, since the Server is using the derived Protocol class (let's say it's PProto), whenever a "dataReceived" is fired, PProto picks it up, and has to call Protocol's dataReceived handler explicitly. Where should all of this message handling take place? Should I split up the duties, like anything that's a singular response to one line should be in the Protocol class, and anything dynamic can be in the PProto class? What about dynamic ports? Where should this be implemented? The alternative is to have many connections on the one server port. Would this cause any issues, so that I could eliminate the PASV command altogether? I need to read the data being sent by the client. How can I correctly intercept this data without effecting the operation of the Protocol, and also so I can port the Protocol class to other applications without rewriting the server? I'm a newbie :). Thanks for your help. From felipe.lessa at gmail.com Tue Aug 1 21:58:10 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Tue, 01 Aug 2006 22:58:10 -0300 Subject: Convert string to mathematical function In-Reply-To: <1154483108.034363.112320@i42g2000cwa.googlegroups.com> References: <1154483108.034363.112320@i42g2000cwa.googlegroups.com> Message-ID: <1154483890.13409.26.camel@kenshin.CASA> Em Ter, 2006-08-01 ?s 18:45 -0700, jeremito escreveu: > I am extending python with C++ and need some help. I would like to > convert a string to a mathematical function and then make this a C++ > function. I may be wrong, but I don't think you can create new C++ functions on-the-fly. At least I had the impression that only VMs could do it (e.g. System.Reflection on .NET/Mono world and, of course, Python). > My one idea (although I don't > know how to implement it, I'm still new at this) is to pass to C++ a > pointer to a (Python) function. Will this work? I think it will, but I can't tell you how =). -- Felipe. From brian at sweetapp.com Mon Aug 14 02:35:52 2006 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 14 Aug 2006 08:35:52 +0200 Subject: Drawing a grid on a picture In-Reply-To: <5IUDg.314851$1Q1.70663@fe03.news.easynews.com> References: <5IUDg.314851$1Q1.70663@fe03.news.easynews.com> Message-ID: <44E019C8.9000900@sweetapp.com> Jive Dadson wrote: > I also found a reference to something called PIL. Maybe that's the > ticket. If so, where can I find it (with documentation)? Thanks. The will likely do what you want. And you can find it the same way that you would find anything online i.e. with google. But here is the link: http://www.pythonware.com/products/pil/ Cheers, Brian From olsongt at verizon.net Fri Aug 4 13:59:27 2006 From: olsongt at verizon.net (olsongt at verizon.net) Date: 4 Aug 2006 10:59:27 -0700 Subject: An interesting way to implement an abstract base class Message-ID: <1154714367.222984.147710@p79g2000cwp.googlegroups.com> This one made me smile. From: http://aima.cs.berkeley.edu/python/utils.html#Queue class Queue: """Queue is an abstract class/interface. There are three types: Stack(): A Last In First Out Queue. FIFOQueue(): A First In First Out Queue. PriorityQueue(lt): Queue where items are sorted by lt, (default <). Each type supports the following methods and functions: q.append(item) -- add an item to the queue q.extend(items) -- equivalent to: for item in items: q.append(item) q.pop() -- return the top item from the queue len(q) -- number of items in q (also q.__len()) Note that isinstance(Stack(), Queue) is false, because we implement stacks as lists. If Python ever gets interfaces, Queue will be an interface.""" def __init__(self): abstract def extend(self, items): for item in items: self.append(item) From python at rcn.com Tue Aug 1 22:53:13 2006 From: python at rcn.com (Raymond Hettinger) Date: 1 Aug 2006 19:53:13 -0700 Subject: Jumping over in the class hierarchy In-Reply-To: <44cf7481$0$24888$9b4e6d93@newsread4.arcor-online.net> References: <44cf7481$0$24888$9b4e6d93@newsread4.arcor-online.net> Message-ID: <1154487192.953594.323880@s13g2000cwa.googlegroups.com> Pupeno wrote: > I want to jump over a method in the class hierarchy, that is: If I have > class A(object), clas B(A), class C(B) and in C, I want a method to do > exactly what A does but not what B does in its reimplementation, would it > be correct to do: super(A, super(B, self)).method() in C ? You can use __bases__ to climb the class hierarchy: >>> class A(object): def f(self): print 1 >>> class B(A): def f(self): print 2 >>> class C(B): def f(self): print 3 def g(self): C.__bases__[0].__bases__[0].f(self) # go up two levels >>> c = C() >>> c.f() 3 >>> c.g() 1 Raymond From brown at esteem.com Wed Aug 9 20:01:41 2006 From: brown at esteem.com (Tom Brown) Date: Wed, 9 Aug 2006 17:01:41 -0700 Subject: serial ports, threads and windows In-Reply-To: <200608021602.25413.brown@esteem.com> References: <200608021602.25413.brown@esteem.com> Message-ID: <200608091701.42191.brown@esteem.com> On Wednesday 02 August 2006 16:02, Tom Brown wrote: > I've written a python app that r/w eight serial ports to control eight > devices using eight threads. This all works very nicely in Linux. I even > put a GUI on it using PyQt4. Still works nicely. > > Then I put the app on on a virtual Windows machine running inside of vmware > on the same Linux box. Vmware only lets me have four serial ports so I run > the app against four serial ports using four threads. The app did not > respond quick enough to data from the serial ports and eventually hung. > > So, I tried one serial port and the app still did not respond quick enough > to the single serial port. It eventually hangs. > > When the app hung, in each case, it was not hogging the cpu nor reading any > data off the serial ports. The task manager didn't show it was doing > anything at all. I haven't found the fix, but I have found the culprit. There are eight threads and eight edit widgets. Each thread is posting messages to an edit widget created for that thread (not by that thread). The messages are characters read off the serial port. I am actually posting a line at a time, not a character at a time. The idea is that the user can see what is happening on the serial port in the event something goes wrong that the application cannot recover from. When I modified the app so the threads were NOT posting messages, the app worked as expected. This was never an issue in Linux. So, does that mean that this is a Windows problem? Or a Qt4 problem? I am curious to know if anybody has written a python app with many threads posting messages to the main application. How well did it work? What gui toolkit did you use? Thanks, Tom From jcmendez at gmail.com Mon Aug 7 14:47:33 2006 From: jcmendez at gmail.com (jcmendez) Date: 7 Aug 2006 11:47:33 -0700 Subject: Resource temporarily unavailable launching idle under cygwin Message-ID: <1154976453.055076.186560@p79g2000cwp.googlegroups.com> Hello everyone. Trying to run idle from a cygwin session on Win2k (yuk, but I must) I'm getting the following error message. It seems something more Windoze-driven that Python driven, and I'm not and don't wanna be an expert on that OS. Since the group has a good mix of users in different platforms, perhaps someone can help. Python runs fine, my programs run fine, and I can edit in vim and run my code. However, would be nice to have idle available from time to time Thanks in advance!! $ idle 23367 [main] python2.4 1668 C:\cygwin\bin\python2.4.exe: *** fatal error - C:\ cygwin\bin\python2.4.exe: *** unable to remap C:\cygwin\bin\tk84.dll to same add ress as parent(0x18890000) != 0x18D20000 18 [main] python2.4 2236 fork: child 1668 - died waiting for dll loading, e rrno 11 Traceback (most recent call last): File "/usr/bin/idle", line 5, in ? main() File "/tmp/python.340/usr/lib/python2.4/idlelib/PyShell.py", line 1361, in mai n File "/tmp/python.340/usr/lib/python2.4/idlelib/PyShell.py", line 277, in open _shell File "/tmp/python.340/usr/lib/python2.4/idlelib/PyShell.py", line 962, in begi n File "/tmp/python.340/usr/lib/python2.4/idlelib/PyShell.py", line 372, in star t_subprocess File "/tmp/python.340/usr/lib/python2.4/idlelib/PyShell.py", line 350, in spaw n_subprocess File "/usr/lib/python2.4/os.py", line 552, in spawnv return _spawnvef(mode, file, args, None, execv) File "/usr/lib/python2.4/os.py", line 520, in _spawnvef pid = fork() OSError: [Errno 11] Resource temporarily unavailable As a sidenote, I sent twice this message as an email to comp.lang.python at googlegroups.com as instructed on the group digests, and it bounced immediately. Did this method of posting change? Thanks! Juan C. From jordan.taylor2 at gmail.com Sun Aug 20 21:51:34 2006 From: jordan.taylor2 at gmail.com (Jordan) Date: 20 Aug 2006 18:51:34 -0700 Subject: uploading files to file system/zipping/downloading problems In-Reply-To: <1156106962.684908.311950@m73g2000cwd.googlegroups.com> References: <1156106962.684908.311950@m73g2000cwd.googlegroups.com> Message-ID: <1156125094.182981.85200@i42g2000cwa.googlegroups.com> Assuming your upload_file.file.read() function works, the overwriting should be the only issue. Just want to point out that total_data += data is not advisable for this example (speed/efficiency issue, although i'm sure it could probably be even faster than what I replace it with if u decided to use arrays, but it's probably not worth it XD), and I think open() was replaced by file(), although they're probably interchangable. new code ----------------- total_data = ' ' temp_data = [] while True: data = upload_file.file.read(8192) if not data: break temp_data.append(data) total_data = ' '.join(temp_data) somefile = file(target_file_name, 'wb') somefile.write(total_data) f.close() ------------------- OriginalBrownster wrote: > I am currently uploading a file from a users computer to the file > system on my server using python, just reading the file and writing the > binaries. > > total_data=' ' > while True: > data = upload_file.file.read(8192) > if not data: > break > total_data += data > f = open(target_file_name, 'wb') > f.write(total_data) > f.close > > However when i download the file from the server it is not intact and > it cannot be opened. It is happening with every type of file. > > It seemed to be working before and now it is..maybe I goofed up and > deleted something. > However I can't seem to find it. > > any ideas?? From chris at kateandchris.net Wed Aug 9 12:34:06 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Wed, 9 Aug 2006 12:34:06 -0400 Subject: Eval (was Re: Question about using python as a scripting language) In-Reply-To: References: <73BFFFC6-760D-4794-9B5C-AA749287B78A@carnegielearning.com> <20060809150432.GA15121@kateandchris.net> Message-ID: <20060809163406.GC15121@kateandchris.net> On Wed, Aug 09, 2006 at 11:51:19AM -0400, Brendon Towle wrote: > On 9 Aug 2006, at 11:04 AM, Chris Lambacher wrote: > > How is your data stored? (site was not loading for me). > > In the original source HTML, it's like this (I've deleted all but the > beginning and the end of the list for clarity): > var table_body = [ > ["ATVI", "Activision, Inc.",12.75,0.150000,1.19,2013762,0.04,"N","N"] > ,["YHOO", "Yahoo! Inc.",27.7,0.260000,0.95,6348884,0.21,"N","N"] > ]; I didn't realize it was javascript syntax, a json implimentation would probably work for you: http://cheeseshop.python.org/pypi/simplejson > > More sophisiticated situations (like nested lists) may require something > like pyparsing. > > I could do that, or I could do something like the re.* trick mentioned by > another poster. But, doesn't it offend anyone else that the only clean way > to access functionality that's already in Python is to write long > complicated Python code? Python already knows how to extract a list object > from a string; why should I have to rewrite that? I don't disagree with you. The problem is that the obvious way to do it (eval) is a big security hole. In this case you are trusting that no one inserts themselves between you and the website providing you with code to EXECUTE. I have heard of people attempting to use the parser provided with python and examining the AST to do this, but I think that approach is even more complicated. > B. > > On Wed, Aug 09, 2006 at 10:23:49AM -0400, Brendon Towle wrote: > > Slawomir Nowaczyk noted: > #> Heck, whenever *is* it OK to use eval() then? > eval is like optimisation. There are two rules: > Rule 1: Do not use it. > Rule 2 (for experts only): Do not use it (yet). > So, that brings up a question I have. I have some code that goes > out to a > website, grabs stock data, and sends out some reports based on the > data. > Turns out that the website in question stores its data in the > format of a > Python list > ([1][1]http://quotes.nasdaq.com/quote.dll?page=nasdaq100, search > the source for "var table_body"). So, the part of my code that > extracts > the data looks something like this: > START_MARKER = 'var table_body = ' > END_MARKER = '];' > def extractStockData(data): > pos1 = data.find(START_MARKER) > pos2 = data.find(END_MARKER, pos1) > return eval(data[pos1+len(START_MARKER):END_MARKER]) > (I may have an off-by-one error in there somewhere -- this is from > memory, > and the code actually works.) > My question is: what's the safe way to do this? > B. > -- > Brendon Towle, PhD > Cognitive Scientist > +1-412-690-2442x127 > Carnegie Learning, Inc. > The Cognitive Tutor Company ? > Helping over 375,000 students in 1000 school districts succeed in > math. > References > Visible links > 1. [2]http://quotes.nasdaq.com/quote.dll?page=nasdaq100 > > -- > [3]http://mail.python.org/mailman/listinfo/python-list > > -- > Brendon Towle, PhD > Cognitive Scientist > +1-412-690-2442x127 > Carnegie Learning, Inc. > The Cognitive Tutor Company ? > Helping over 375,000 students in 1000 school districts succeed in math. > > References > > Visible links > 1. http://quotes.nasdaq.com/quote.dll?page=nasdaq100 > 2. http://quotes.nasdaq.com/quote.dll?page=nasdaq100 > 3. http://mail.python.org/mailman/listinfo/python-list From eugene at boardkulture.com Sun Aug 20 15:58:20 2006 From: eugene at boardkulture.com (3KWA) Date: 20 Aug 2006 12:58:20 -0700 Subject: What do you want in a new web framework? In-Reply-To: <1156100330.768482.326760@h48g2000cwc.googlegroups.com> References: <1156100330.768482.326760@h48g2000cwc.googlegroups.com> Message-ID: <1156103900.914492.187490@75g2000cwc.googlegroups.com> emrahayanoglu at gmail.com wrote: > Hello Everyone, > > Now, I'm working on a new web framework. I tried many test on the other > programming languages. Then i decided to use python on my web framework > project. > > Now i want to listen all of you. What do you want in that web > framework(Easy use of Database, Easy use of XML, GUI Designer, etc...)? > > I'm wating your answers. Thank you for all answers...! > > King Regards, > > Emrah Ayanoglu Don't want to sound too conservative but really nothing that either - Django - Turbogear - or the "myghty" Pylons (my personal favorite) cannot provide efficiently today! EuGeNe From thomas at mindz-i.co.nz Tue Aug 1 22:56:59 2006 From: thomas at mindz-i.co.nz (Thomas Thomas) Date: Wed, 2 Aug 2006 14:56:59 +1200 Subject: Zipping files/zipfile module Message-ID: <01d001c6b5df$54d46d20$346ea8c0@tintz.co.nz> Hi Stephen, some code that I have been using for a similar purpose. def addFolderToZip(myZipFile,folder): folder = folder.encode('ascii') #convert path to ascii for ZipFile Method for file in glob.glob(folder+"/*"): if os.path.isfile(file): print file myZipFile.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED) elif os.path.isdir(file): addFolderToZip(myZipFile,file) def createZipFile(filename,files,folders): curTime=strftime("__%Y_%m_%d", time.localtime()) filename=filename+curTime; print filename zipFilename=utils.getFileName("files", filename+".zip") myZipFile = zipfile.ZipFile( zipFilename, "w" ) # Open the zip file for writing for file in files: file = file.encode('ascii') #convert path to ascii for ZipFile Method if os.path.isfile(file): (filepath, filename) = os.path.split(file) myZipFile.write( file, filename, zipfile.ZIP_DEFLATED ) for folder in folders: addFolderToZip(myZipFile,folder) myZipFile.close() return (1,zipFilename) (success,filename)=createZipFile(planName,files,folders); hope it helps.. cheers ----------------------------------------------------- Thomas Thomas thomas at mindz-i.co.nz Phone. +64 7 855 8478 Fax. +64 7 855 8871 -------------- next part -------------- An HTML attachment was scrubbed... URL: From aking at mappi.helsinki.fi Thu Aug 3 17:42:00 2006 From: aking at mappi.helsinki.fi (aking at mappi.helsinki.fi) Date: Fri, 4 Aug 2006 00:42:00 +0300 Subject: help - iter & dict Message-ID: <1154641320.44d26da8d8605@www1.helsinki.fi> Quoting taleinat : > Ali writes: > > >> Im trying to iterate through values in a dictionary so i can find the > >> closest value and then extract the key for that value....what ive done > so far: > >> > >> def pcloop(dictionary, exvalue): > >> z = dictionary.itervalues() > >> y = z - exvalue > >> v = (y*y)**1/2 > >> if v < 0.001: > >> u = dictionary.get[z] > >> return u > > First of all, your code was broken everywhere... > > Unlike many other languages, Python is fun! Just fire up an interpreter > ("python" at the command line should work) and start playing around and > trying > stuff out. You would have quickly found that dictionary.itervalueS() > return an > iterator object (which must be iterated over), that dictionaries can be > accessed > either with brackets "[]" -or- with the .get() method, and more. > > If you're learning from a book, try everything you learn out at least > once in > the interpreter - that way you'll make sure you understand everything, > and > understand the syntax much faster (since the interpreter will -explain- > what > your syntax errors are). > > Second, Python has a built-in abs() method which returns the absolute > value of a > number - using it is simpler and more readable. > > > Tim Chase tim.thechases.com> writes: > > > if closest_value: > > if distance < closest_distance: > > closest_key = k > > closest_value = v > > closest_distance = distance > > else: > > closest_key = k > > closest_value = v > > closest_distance = distance > > return closest_key, closest_value > > This has a bug - if closest_value happens to be zero at some point, it > would be > overriden by the next value no matter what, since "if closest_value" > would be > false. You must explicitly check "if closest_value is not None:". > > Also the code could be simplified: > > if closest_value is None or distance < closest_distance: > closest_key = k > closest_value = v > closest_distance = distance > > > > > def findClosest2(dataset, target): > if not dataset: # a dict is considered false if empty, true otherwise > return (None,None) > > return reduce( > > lambda x,y: > > ((target - y[1]) ** 2 < > > (target - x[1]) ** 2) > > and y or x, dataset.items()) > > I would advise everyone still learning the basics to completely ignore > the > second function. Yes, it works, but this code is VERY confusing for a > beginner, > both because of the reduce (tough to grasp) and because of the confusing > and > bug-prone "and-or trick". (even though this is a classic use for reduce) > > - Tal Einat > a='maciogaiea at l.ntmtl'[::-1]; print reduce(lambda m,x:[m[i]+s[-1] for i,s > in > enumerate(sorted(m))],[list(a)]*len(a))[3] > > > -- > http://mail.python.org/mailman/listinfo/python-list > I know im a little bit over my head here but have survived up until now by books and debugging before the code runs. before last week the most lines of code ive written are .....4. Yes i think i can stick to simplest to understand for now and work round at a different time. Ive tried the code: def findClosest(dataset, target): closest_value = None closest_key = None closest_distance = None for k,v in dataset.items(): distance = (target - v) ** 2 if closest_value: if distance < closest_distance: closest_key = k closest_value = v closest_distance = distance else: closest_key = k closest_value = v closest_distance = distance return closest_key, closest_value Cpcb = input("\n\nPlease enter the carbon percentage value obtained from the microanalysis. If none, enter 0: ") print"\n\nCellulose Carbon Percentage is " + `Cpca` + "\n\nMaximum potential monomer carbon weight is " + `Cwmax` + "\n\nMaximum potential carbon percentage is " + `Cpcmax` + "\n\nPercentage difference between Cellulose and Maximum is " + `Cdiff` + "\n\n" CDS = findClosest(CDSitdict, Cpcb) print("\nThe DS value based on carbon content is " + `CDS` + "\n\n") here is a sample of the dictionary (normally 1000 iterations in there, all non zero and to 15 decimal places) and the sample value: Cpcb = 33.94 CDSitdict = {28.473823598317392: "'2.4869999999999832'", 40.06163037274758: "'0.2910000000000002'", 27.756248559438422: "'2.8349999999999964'", 33.2299196586726: "'1.1249999999999962'", 29.989685187220061: "'1.9139999999999677'", 31.502319473614037: "'1.490999999999983'", 28.487341570327612: "'2.480999999999983'", 30.017763818271245: "'1.9049999999999681'", 32.943466663842266: "'1.1789999999999943'", 30.520103712886584: "'1.7519999999999736'", 31.453205956498341: "'1.5029999999999826'", 29.484222697359598: "'2.084999999999968'", 28.413513489228706: "'2.5139999999999842'", 28.314852455260802: "'2.558999999999986'", 28.652931545003508: "'2.4089999999999803'"} heres the error i get after entering Cpcb Traceback (most recent call last): File "elementalDS.py", line 156, in ? CDS = findClosest(CDSitdict, Cpcb) File "elementalDS.py", line 142, in findClosest distance = (target - v) ** 2 TypeError: unsupported operand type(s) for -: 'float' and 'str' alicat at linux:~/Desktop> i also tried to format the key in the dictionary from a number to a string with single quotes but formatting with %s didnt work so i have used itera = "\'" + `DSit` + "\'" CDSitdict[Cpcmax] = itera ? maybe i can return the favours someday...lol a From mail at microcorp.co.za Wed Aug 16 02:58:56 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 16 Aug 2006 08:58:56 +0200 Subject: what is the keyword "is" for? References: <1155625097.784052.31330@p79g2000cwp.googlegroups.com> <1155681780.830614.86950@75g2000cwc.googlegroups.com> Message-ID: <006f01c6c102$bb1a5bc0$03000080@hendrik> "Dan Bishop" wrote: | Sybren Stuvel wrote [on the difference between is and ==]: | > Obviously "a is b" implies "a == b", | | Not necessarily. | | >>> a = b = 1e1000 / 1e1000 | >>> a is b | True | >>> a == b | False Huh? - wtf is this - I find this deeply disturbing - Sybren's explanation kind of was congruent with my own understanding, and this is just weird - Hendrik From hadeshuang at gmail.com Fri Aug 25 18:54:40 2006 From: hadeshuang at gmail.com (Pebblestone) Date: 25 Aug 2006 15:54:40 -0700 Subject: Python and STL efficiency In-Reply-To: <1156544382.789534.202680@p79g2000cwp.googlegroups.com> References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <1156533768.283454.48570@m73g2000cwd.googlegroups.com> <1156540873.326734.15600@i42g2000cwa.googlegroups.com> <1156543134.839425.254040@75g2000cwc.googlegroups.com> <1156544382.789534.202680@p79g2000cwp.googlegroups.com> Message-ID: <1156546480.385367.115760@b28g2000cwb.googlegroups.com> Sorry, I did some miscalculation.... what a shame..... bearophileHUGS at lycos.com wrote: > Pebblestone: > > >I heard that python's list is implemented as adjustable array. > > Correct, an array geometrically adjustable on the right. > > > >Here's my lisp implementation:< > > What's the memory size of a before computing b? You can compare it with > Python, that may need less memory (because the array contains > pointers). > > > >BTW, I couldn't install psyco on my system (ubuntu), gcc just prompt to me thousands of lines of errors and warnings.< > > Find a Win box ;-) It's already compiled for it (for Py 2.3, 2.4). > > > >Your python's example (use direct index array index) of my corresponding lisp code works slower than the version which use 'append'.< > > For me (a slow PC) it's almost twice faster, computer life is usually > complex. > For me using the esplicit allocation + Psyco makes that program about 4 > times faster (from 8 to 2 seconds). > > > >This let me think how python's list is implemented.< > > You also have to think how the * allocation is implemented and many > other things :-) > The list implementation is rather readable, Python sources are online > too. > > > >Anyway, python's list is surprisingly efficient.< > > But its access isn't that fast :-) Psyco helps. > > Bye, > bearophile From duncan.booth at invalid.invalid Sun Aug 6 14:59:39 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 6 Aug 2006 18:59:39 GMT Subject: Proposal: [... for ... while cond(x)] References: <1154879331.903490.106020@m73g2000cwd.googlegroups.com> <1154886383.696899.171490@i3g2000cwc.googlegroups.com> Message-ID: Eighty wrote: > > Duncan Booth wrote: >> Eighty wrote: >> >> > I suggest a new extension of the list comprehension syntax: >> > >> > [x for x in xs while cond(x)] >> > >> > which would be equivalent to >> > >> > list(itertools.takewhile(cond, xs)) >> > >> >> What would this syntax offer that: >> >> [x for x in takewhile(cond, xs)] >> >> doesn't currently offer? (Apart, that is, from saving you 3 >> characters of typing) > > The same thing that [f(x) for x in xs] offers that map(f, xs) doesn't, > and the same thing that [x for x in xs if f(x)] offers that filter(f, > xs) doesn't. It's more "pythonic". You can use an expression for cond > instead of a lambda. > > No, the list comprehension lets you write an expression directly avoiding a function call, and it also allows you to add in a condition which can be used to filer the sequence. Your proposal adds nothing. From gagsl-py at yahoo.com.ar Tue Aug 29 12:24:43 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 29 Aug 2006 13:24:43 -0300 Subject: A Sort Optimization Technique: decorate-sort-dedecorate In-Reply-To: References: <1156719092.603277.57390@b28g2000cwb.googlegroups.com> <1156723602.192984.49610@m79g2000cwm.googlegroups.com> <280820061150081729%jgibson@mail.arc.nasa.gov> Message-ID: <7.0.1.0.0.20060829132302.05c9e758@yahoo.com.ar> At Tuesday 29/8/2006 07:50, Joachim Durchholz wrote: >Wikipedia says it's going from 2NlogN to N. If a sort is massively >dominated by the comparison, that could give a speedup of up to 100% >(approximately - dropping the logN factor is almost irrelevant, what >counts is losing that factor of 2). In fact it's the other way - losing a factor of 2 is irrelevant, O(2N)=O(N). The logN factor is crucial here. Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From tal.no.no.spam at gmail.com Wed Aug 30 03:47:55 2006 From: tal.no.no.spam at gmail.com (Tal Einat) Date: 30 Aug 2006 00:47:55 -0700 Subject: Coding style and else statements In-Reply-To: References: <44f355d6$0$8812$88260bb3@free.teranews.com> <44f36bd2$0$16847$626a54ce@news.free.fr> <1156804096.616231.14990@74g2000cwt.googlegroups.com> <44f3768a$0$29491$626a54ce@news.free.fr> <1156886150.271268.126480@i3g2000cwc.googlegroups.com> Message-ID: <1156924075.903340.281890@b28g2000cwb.googlegroups.com> Sybren Stuvel wrote: > Tal Einat enlightened us with: > > Actually, the common work-around for this is: > > > > (thing and [thing+1] or [-1])[0] > > > > This works since non-empty lists are always considered true in > > conditional context. This is more generic, and IMO more readable. > > I think it's not readable at all. It's confusing - you create a > singleton list, only to extract the first element from it and discard > the list again. I'd rather read a proper if-statement. > I agree that an "if" statement is by far more readble; I was referring only to the dicussion of the "and-or trick", not the entire issue. I meant to say that: (thing and [thing+1] or [-1])[0] is more readable (IMO) than: thing != -1 and (thing and thing+1 or -1) or 0 - Tal From __peter__ at web.de Mon Aug 21 05:41:21 2006 From: __peter__ at web.de (Peter Otten) Date: Mon, 21 Aug 2006 11:41:21 +0200 Subject: What do you want in a new web framework? References: <1156100330.768482.326760@h48g2000cwc.googlegroups.com> Message-ID: emrahayanoglu at gmail.com wrote: > Now, I'm working on a new web framework. I tried many test on the other > programming languages. Then i decided to use python on my web framework > project. > > Now i want to listen all of you. What do you want in that web > framework(Easy use of Database, Easy use of XML, GUI Designer, etc...)? > > I'm wating your answers. Thank you for all answers...! Write it in PHP, Ruby, Java, anything -- but not in Python :-) Peter From antroy at gmail.com Fri Aug 25 10:14:59 2006 From: antroy at gmail.com (Ant) Date: 25 Aug 2006 07:14:59 -0700 Subject: Best Practices for Python Script Development? References: <1156471481.265329.291360@m79g2000cwm.googlegroups.com> Message-ID: <1156515299.257203.283170@m73g2000cwd.googlegroups.com> > `Pydoc `_ seems to be > built around modules and I want to document scripts. Any python script *is* a python module. So pydoc is what you are after here. > Version Control > =============== Subversion and Trac are a very good combination - Trac is a web-based view of the subversion repository as well as being a wiki and issue tracker. (Incidentally Trac is written in Python.) > Books > ===== > * Python Cookbook > * Programming Python I've found the Python Pocket reference very useful - I rarely use anything other than that and the online docs (though I found Python in a Nutshell and the cookbook very useful early on). From tjreedy at udel.edu Fri Aug 25 17:11:45 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 25 Aug 2006 17:11:45 -0400 Subject: Duck typing alows true polymorfisim References: <1156532721.879808.40990@i3g2000cwc.googlegroups.com> <1156534086.698353.81850@m73g2000cwd.googlegroups.com> Message-ID: "David Ells" wrote in message news:1156534086.698353.81850 at m73g2000cwd.googlegroups.com... > def increment(x): > return x += 1 'return x+1' works better ;-) tjr From btowle at carnegielearning.com Thu Aug 10 08:51:12 2006 From: btowle at carnegielearning.com (Brendon Towle) Date: Thu, 10 Aug 2006 08:51:12 -0400 Subject: Eval (was Re: Question about using python as a scripting language) In-Reply-To: References: Message-ID: <310C0D2C-B205-4926-9486-462B5278C069@carnegielearning.com> > Date: 9 Aug 2006 14:12:01 -0700 > From: "Simon Forman" > Subject: Re: Eval (was Re: Question about using python as a scripting > language) > To: python-list at python.org > Message-ID: <1155157921.662196.11210 at 75g2000cwc.googlegroups.com> > Content-Type: text/plain; charset="iso-8859-1" > > Fredrik Lundh posted a great piece of code to parse a subset of python > safely: > > http://groups.google.ca/group/comp.lang.python/browse_frm/thread/ > 8e427c5e6da35c/a34397ba74892b4e This, as it turns out, was the most helpful pointer of them all -- thanks! B. -- Brendon Towle, PhD Cognitive Scientist +1-412-690-2442x127 Carnegie Learning, Inc. The Cognitive Tutor Company ? Helping over 375,000 students in 1000 school districts succeed in math. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sonaldgr8 at gmail.com Wed Aug 30 07:55:27 2006 From: sonaldgr8 at gmail.com (sonald) Date: 30 Aug 2006 04:55:27 -0700 Subject: how can i change the text delimiter In-Reply-To: References: <1156929540.715287.123060@h48g2000cwc.googlegroups.com> <1156932106.948885.63980@i3g2000cwc.googlegroups.com> Message-ID: <1156938927.933389.101170@m73g2000cwd.googlegroups.com> Hi , thanks for the reply... fast csv is the the csv module for Python... and actually the string cannot be modified because it is received from a third party and we are not supposed to modify the data in any way.. for details on the fast CSV module please visit www.object-craft.com.au/projects/csv/ or import fastcsv csv = fastcsv.parser(strict = 1,field_sep = ',') // part of configuration and somewhere in the code... we are using data = csv.parse(line) all i mean to say is, csv.reader is nowhere in the code and somehow we got to modify the existing code. looking forward to ur kind reply ... Fredrik Lundh wrote: > "sonald" wrote: > > > Thanks for a quick response... > > E.g record is: "askin"em" > > that's usually stored as "askin""em" in a CSV file, and the csv module > has no problem handling that: > > >>> import csv, StringIO > >>> source = StringIO.StringIO('"askin""em"\n') > >>> list(csv.reader(source)) > [['askin"em']] > > to use another quote character, use the quotechar option to the reader > function: > > >>> source = StringIO.StringIO('|askin"em|\n') > >>> list(csv.reader(source, quotechar='|')) > [['askin"em']] > > > Also please note that the string cannot be modified at all. > > not even by the Python program that reads the data? sounds scary. > > what's fastcsv, btw? the only thing google finds with that name is a > Ruby library... > > From johannes.lochmann at googlemail.com Fri Aug 18 05:38:04 2006 From: johannes.lochmann at googlemail.com (Johannes Lochmann) Date: Fri, 18 Aug 2006 11:38:04 +0200 Subject: find item in wx.TreeListCtrl by pydata code snippet Message-ID: <200608181138.05888.johannes.lochmann@gmail.com> Hello list, here is a small code snippet to recursively search a wx.TreeListCtrl for an item with specific pydata. Feel free to comment! def recursiveFindItemByPydata(self, parent, pydata): ? ? item, cookie = self.GetFirstChild(parent) ? ? while item: ? ? ? ? if self.GetPyData(item) == pydata: ? ? ? ? ? ? ? ? return item ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? if self.ItemHasChildren(item): ? ? ? ? ? ? found = self.recursiveFindItemByPydata(item, pydata) ? ? ? ? ? ? if found is not None: ? ? ? ? ? ? ? ? return found ? ? ? ? ? ? ? ? ? ? ? item, cookie = self.GetNextChild(parent, cookie) ? ? return None HAND Johannes From duncan.booth at invalid.invalid Fri Aug 11 10:59:36 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Aug 2006 14:59:36 GMT Subject: hide python code ! References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155300852.497741.73230@74g2000cwt.googlegroups.com> <1155302527.634045.231950@75g2000cwc.googlegroups.com> Message-ID: Fuzzyman wrote: > Tim Chase wrote: > [snip....] >> However, it's better to have a good relationship with your >> customers and know that they will adhere to licensing conditions, >> rather than to try and strong-arm them into behaving a particular >> way. >> > > Don't forget that distributing your source code is more of a gift to > your competitors (and potential competitors) than it is to your > customers... > I believe Eric Raymond has argued that if your competitors are spending their time trying to work out how to adapt to using your software, that is time they aren't spending competing with you. So long as you make regular releases of your software you can ensure that they are always at least one step behind you. From psnim2000 at gmail.com Sat Aug 12 07:58:50 2006 From: psnim2000 at gmail.com (Chaos) Date: 12 Aug 2006 04:58:50 -0700 Subject: wxPython ListBook Class, Label Position w/ ImageList Message-ID: <1155383930.411326.10150@h48g2000cwc.googlegroups.com> By default the label position of an image list is below the image. Is there any way to change this? From jwentingathornetdotdemondotnl Wed Aug 30 14:18:52 2006 From: jwentingathornetdotdemondotnl (Jeroen Wenting) Date: Wed, 30 Aug 2006 20:18:52 +0200 Subject: Duck typing alows true polymorfisim References: <1156532721.879808.40990@i3g2000cwc.googlegroups.com> <1156533807.630662.12330@i42g2000cwa.googlegroups.com> Message-ID: <12fblk87ppk7ief@corp.supernews.com> "Simon Forman" wrote in message news:1156533807.630662.12330 at i42g2000cwa.googlegroups.com... > atbusbook at aol.com wrote: >> lets say you want a generic numerical algorithom like sum >> > What's your question? (Or, if no question, point?) :-) > Reads like the weekly "Ruby is better than Java because XXXXX" post. From jonsmirl at gmail.com Mon Aug 7 15:08:11 2006 From: jonsmirl at gmail.com (Jon Smirl) Date: Mon, 07 Aug 2006 15:08:11 -0400 Subject: Initializing the number of slots in a dictionary References: <1154903610.168312.289080@n13g2000cwa.googlegroups.com> <1f7befae0608062133m448854c4w33467aef0feaaa87@mail.gmail.com> Message-ID: On Mon, 07 Aug 2006 00:33:33 -0400, Tim Peters wrote: > ... > > [Jon Smirl] >> I know in advance how many items will be added to the dictionary. Most >> dictionary implementations I have previously worked with are more >> efficient if they know ahead of time how big to make their tables. > > Richard Jones spent considerable time investigating whether "pre-sizing" > lists and dicts in CPython could help, at the "Need For Speed" sprint > earlier this year. He didn't find a win worth getting; e.g., read the > section "List pre-allocation" at: > > http://wiki.python.org/moin/NeedForSpeed/Failures > > Trying it for dicts was also part of what he did, but I don't think > specifics about that were recorded on the Wiki. I was at the sprint, and > hoots of triumph from Richard's direction were conspicuous by absence > during his dict time ;-) > >> In this case I only need to do a presence test of the key, there is no >> actual data associated with the key. The table is used for detecting >> duplicate entries. Is there a more efficient to do this test that >> sticking an empty string into a dict? The keys are sha1.digest(). > > It's probably more common to set the value to None or 1, but it doesn't > really matter in reality. In theory, using 1 or an empty string relies on > the implementation accident that CPython stores those uniquely, while it's > guaranteed that None is a singleton object. > > BTW, is there a reason to use SHA instead of MD5? I ask because the > latter is 4 bytes shorter, and you apparently have a /lot/ of keys. http://git.or.cz/index.html git is the source code control tool used by the Linux kernel. It is optimized for distributed development. git is what the kernel developers wrote to replace Bitkeeper after the Bitkeeper license change. git identifies it's change sets with sha1 hashes. Distributed SCM is very important when working on large projects. With a distributed SCM nobody needs commit privs - everyone has their own complete copy of the repository. To get a change into a distribution you need to convince someone up the heirarchy to pull your changes into their repository. In the Linux world Linus makes the distributions. There are about 10 people in the next circle and about 100 in the circle after that. You need to convince one of them to accept your changes, but that's not very hard if your code makes sense. Distributed also means that you can pull changes from anyone else into your repository. So if you want to run Reiser4 and it isn't in the main Linus tree yet, just pull a copy from the namesys git tree into your local tree and everything will get merged. Python is using Subversion which is way better than CVS, but Subversion is still organized around a central repository with commit privs. If that repository disappears in an earthquake Python may be in trouble. If you give git a try you will also notice that it is way faster than subversion. > If you're using a current version of Python, you can save some memory by > using a builtin set object instead. The CPython implementation of sets is > very much like its implementation of dicts, but doesn't consume any memory > for the (non-existent) associated values. You also get a number of > operations useful on sets (like intersection and union). Sets may be a good option, I'll adjust the code for the next run. >> ... >> Since I am rerunning the conversion over and over anything simple that >> speeds it up is helpful. >> >> I already have 4GB RAM, it would take around 30GB to get everything in >> memory. >> >> Dictionaries are not a big problem for me, but there are many in use and >> they have millions of items in them. > > A peculiar suggestion: if you don't need to release system resources > cleanly at the end of a run, try doing: > > import os > os._exit(0) > > at the end. If you have dicts with millions of entries swapped to disk, > it /can/ consume major time just to page them all in again to decrement > the key & value refcounts if you let "clean shutdown" code determine > they've become trash. Bailing ungracefully can skip all that work (but > also skips other work, like letting the platform C I/O library close > still-open files gracefully). Jon Smirl jonsmirl at gmail.com From bignose+hates-spam at benfinney.id.au Fri Aug 11 20:43:13 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 12 Aug 2006 10:43:13 +1000 Subject: hide python code ! References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155300852.497741.73230@74g2000cwt.googlegroups.com> <1155338714.645665.150150@75g2000cwc.googlegroups.com> Message-ID: <87irkywzq6.fsf@benfinney.id.au> "Fuzzyman" writes: > Terry Reedy wrote: > > Let's clarify the question: "Dear Python programmers: please tell > > me for free how I can hide my code from you and others like you." > > And categorising their intent in this way I don't see how this categorises intent at all. It's clarifying what the question means. "Dear Python programmers" -- the message was to comp.lang.python. "please tell me for free" -- they have asked a question, and clearly expect an answer without further remuneration requirements or other payment. "how I can hide my code" -- this is exactly what they've asked. The only thing I can see in there you might object to is the "you and others like you". Here, "you" is "Python programmers". By hiding the source code to their programs, they will hide it from any Python programmers. Any one of their customers may want improvements to the program that they (the author) may not be motivated to work on, for whatever reason. No shame in that -- and no categorisation of intent. The customer can then ask any other Python programmer to make the improvements, offering whatever consideration is agreeable to both parties. If the source code is hidden, its *hidden from the Python programmer* and others like them. Nowhere in this has intent of the author been categorised. It makes clear some of the consequences of the proposed course of action. -- \ "I used to be a narrator for bad mimes." -- Steven Wright | `\ | _o__) | Ben Finney From finsignia at gmail.com Sun Aug 6 19:00:19 2006 From: finsignia at gmail.com (finsignia at gmail.com) Date: 6 Aug 2006 16:00:19 -0700 Subject: US: Python/Webware, Linux, SQL, PostgreSQL, HTML, XHTML, CSS, Javascript contract Message-ID: <1154905219.131599.147830@i3g2000cwc.googlegroups.com> A small consulting business in Champaign-Urbana (Illinois - we aren't all Illini fans) is trying to pull high callibre resources onto a Webware for Python project. We are a firm that delivers Ruby (please don't hate us more) and Python web applications to small-medium enterprises and fast growing startups. We are currently a small collective of Python and Ruby developers with previous lives in Java, C++ and Perl. We do not plan on expanding fast like many have tried to do in the past, but we are open to hiring great people on full-time in the future when we have consistently enough work year round for extra permanent consultants. One of our clients would really like us to ramp up development on their project. Unfortunately the consultants not already assigned to this client are already over-extended for the next 1-3 months or foreseeable future. So we are looking for two (2) part-time Python developers who would initially consider work as independent contractors (1099). Ideal candidates would have the following professional experience over the last 4-5 years: * 2+ years of Python experience, Python 2.4 is essential! * 3+ years Linux heavy user and some deployment and administration experience. * Solid OO design skills * SQLObject experience (1+ years would be ideal) * 6 months experience with one of the following: Django, TurboGears or Webware for Python. * 3+ years web application development in Python or Perl * 3+ years SQL against one of the following databases: PostgreSQL, MySQL, Oracle or Sybase * 3+ years HTML, XHTML, CSS, Javascript work. You don't need to be a Javascript/AJAX guru, but be able to work with it reasonably well to get by. Most of the work will be on the server-side! ONLY US citizens or green card legal US residents will be considered. Proof of this will be required before starting with us. NO THIRDY PARTIES. NO OFFSHORE SPAM PLEASE! If interested please let us know the following: * Availability: When can you start? How many hours per week can you dedicate? * Work Environment: Where do you work from (e.g. home office, living room, coffee shop)? What time zone are you in? What Operating System? What hours on what days in the week are you likely to be dedicated to working for us? Please let us know the CPU, RAM and HDD specs of the development workstation you would use for our project. * US status: US Citizen or Green Card? * Asking rate: What hourly rate are you interested in for this telecommuting project? * Resume: Please attach your resume in Word, RTF, PDF or OpenOffice.org (preferred) format along with the rest of the information requested to resumes at finsignia.com. The work environment questions are only used for us to determine if a telecommute agreement makes sense for both parties. If you have an awesome workstation/laptop, but work from a noisy construction site without broadband access, this arrangement would not likely work out for either party!:) Thanks! From onurb at xiludom.gro Mon Aug 28 06:00:40 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 28 Aug 2006 12:00:40 +0200 Subject: Pros/Cons of Turbogears/Rails? In-Reply-To: <1156740469.645955.52080@i3g2000cwc.googlegroups.com> References: <1156726071.579429.44650@b28g2000cwb.googlegroups.com> <1156740469.645955.52080@i3g2000cwc.googlegroups.com> Message-ID: <44f2bec8$0$5964$636a55ce@news.free.fr> Ray wrote: (snip) > Sadly, there are more Java guys who know about Ruby than Python, > despite the fact that Python predates Ruby by quite a few years... FWIW, Python is somewhat older than Java too... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From skip at pobox.com Wed Aug 9 10:33:43 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 9 Aug 2006 09:33:43 -0500 Subject: do people really complain about significant whitespace? In-Reply-To: <20060809162304.EF10.SLAWOMIR.NOWACZYK.847@student.lu.se> References: <9$lHo7FEZe2EFwf$@objmedia.demon.co.uk> <17625.60801.772730.330611@montanaro.dyndns.org> <20060809162304.EF10.SLAWOMIR.NOWACZYK.847@student.lu.se> Message-ID: <17625.62023.348590.937902@montanaro.dyndns.org> Slawomir> #> No. In that case Python makes it more readily apparent Slawomir> #> that your code is too complex. With C, Java, C++, Perl or Slawomir> #> FORTRAN you just smush everything over to the left and Slawomir> #> pretend it's not. ;-) Slawomir> Well, one space is sufficient indentations for Python, right? So even Slawomir> on 80 column screen, you can easily fit about 40 levels of nesting Slawomir> before it becomes a real problem :D Oh, sure. Hence the smiley in my post... Smileys all around. I'm happy. Skip From timr at probo.com Sat Aug 5 20:00:37 2006 From: timr at probo.com (Tim Roberts) Date: Sun, 06 Aug 2006 00:00:37 GMT Subject: looking for a regular expression References: <4POChV$9OC@bbs.wretch.cc> <5fg5d2t5c5j4s665bgut58s0diea3794u5@4ax.com> <1154664456.139117.309200@b28g2000cwb.googlegroups.com> Message-ID: "alex23" wrote: >Tim Roberts wrote: >> What is your signature supposed to be? It looks like you are trying to >> inject ANSI terminal escape sequences. The vast majority of Usenet >> participants are now reading these articles through GUI newsreaders or >> web-based readers which show this as 5 lines of unrecognizable line noise. > >It renders as (I'm guessing) Chinese through Firefox on an XP box with >East Asian Languages enabled. If you really want to see this the way >it's intended, then check out: >http://en.wikipedia.org/wiki/Wikipedia:Enabling_East_Asian_characters > >"The vast majority" of Usenet participants who need it will most likely >already have it. Try not to extrapolate too wildly from your individual >& clearly experiential evidence. No, it's more than that. I recognized that most of the string was intended to be Chinese, but there are ANSI terminal escape sequences sprinkled through there. Look at the start of the first line: "[1;30;40;m". No GUI app is going to render that. >???L???????????????c???G???D?????B?g?l?~?h?Q?????L?h?Q?k?L???????????D?g?l >???????o?w?????????H???W?????????????????O?????H???????H???h???i?o???????U >?o?N???|???????|?k???N?x?~???W?N?x?~?k???H?????B?????H?????H?s?d?_???????H >?????B???D?`?L?W?????p???U???????J???Y???u???U???N???????a???X?H?????S???? >???O???????l?????W?W???J???????N??210-64-83-167.adsl.dynamic.seed.net.tw?? -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From jarrod.roberson at gmail.com Thu Aug 31 21:54:24 2006 From: jarrod.roberson at gmail.com (fuzzylollipop) Date: 31 Aug 2006 18:54:24 -0700 Subject: Pros/Cons of Turbogears/Rails? In-Reply-To: <1157040293.903010.152250@m79g2000cwm.googlegroups.com> References: <1156726071.579429.44650@b28g2000cwb.googlegroups.com> <1156740469.645955.52080@i3g2000cwc.googlegroups.com> <1156768355.275370.129680@h48g2000cwc.googlegroups.com> <1157038022.237121.127780@m73g2000cwd.googlegroups.com> <1157040293.903010.152250@m79g2000cwm.googlegroups.com> Message-ID: <1157075664.178253.196130@m79g2000cwm.googlegroups.com> Paul Boddie wrote: > fuzzylollipop wrote: > > Paul Boddie wrote: > > > > fuzzylollipop wrote: > > > > > uh, no, Python predates Ruby by a good bit > > > > > Rails might be "older" than Turbogears but it still JUST went 1.0 > > > > > officially. > > > > > It can't be called "mature' by any defintition. > > > > > > Version numbers are a fairly useless general metric of project > > > maturity, taken in isolation. > > > > But 1.0 releases do mean something, it means the DEVELOPER of the > > package things it is just now ready for general consumption. That means > > something regardless of what the number is. > > In various open source circles, the mere usage of 1.0 may indicate some > kind of stability, but not necessarily maturity, or at least the desire > of the developers to persuade users that the code is ready for them to > use. nope in GENERAL usage, 1.x means that the developer is designating a version that is feature complete and stable. I never ever mentioned comparing version numbers between differing packages. MY POINT was the developers of Rails JUST RECENTLY decided that it was ready for general consumption compared to all the PREVIOUS Rails releases. And NONE of these frameworks has been used to power anything along the scale of what I work with on a daily basis. And speaking from experience, autogenerated "Active Object Pattern" frameworks dont' scale. And Rails is no exception. It didn't work 10 years ago when all the ORM vendors were selling ridiculously price "point and click" database application builders, what makes people think it will now? From you at cogeco.ca Mon Aug 14 23:52:24 2006 From: you at cogeco.ca (AlbaClause) Date: Mon, 14 Aug 2006 23:52:24 -0400 Subject: Mega Newbie Questions: Probably FAQs References: <1155591083.461286.75380@i3g2000cwc.googlegroups.com> Message-ID: Zeph wrote: > ajaksu wrote: > I do intend to start small and build up, but I want to front load my > learning curve, usually makes the other side of the curve more productive. Did you ever play on teeter-totters when you were a kid? I think that's what they're called. Those board like things that are balanced in the middle, one kid on each end, and as one kid goes up, the other kid goes down. Anyway, when I was a kid there was some teeter-totters in the yard at a nearby apartment complex, and there were some teeter-totters in the park behind my house. If you spend much time on these contraptions, you soon realize that simply going up and down is not very much fun. We'd often carry on in our activity as it was supposed to be, but, invariably, one of us would be sitting on the low end and looking up at our playmate. With an almost devilish grin, we'd hop off the teeter totter and send our good buddy crashing to the ground. Such wonderful childhood fun. Another activity that my brother and I took part in was shoplifting. We devised a clever way of hording candy from the checkout aisles at a local grocery store. What we'd do, is climb in under the conveyor belt cabinet and reach out and bring entire boxes of candy bars, etcetera in under the conveyor belt where we'd sit and eat away at our leisure. We never ever got caught, and we went through probably hundreds of dollars worth of candy. But we got greedy! Hope this helps rather than confuses you. -- -- There are several things that I will never be: * I will never be attracted to females. * I will never enjoy the company of others. Exactly how these realities bode for my enemy, is not of my concern. From gabrieladt at gmail.com Fri Aug 25 15:33:52 2006 From: gabrieladt at gmail.com (Gabriel - BR) Date: 25 Aug 2006 12:33:52 -0700 Subject: Disable close button in management window.(KDE- pyQT) In-Reply-To: <1156181021.742491.299650@75g2000cwc.googlegroups.com> References: <1155926338.062804.114260@i42g2000cwa.googlegroups.com> <1156033967.195411.42610@b28g2000cwb.googlegroups.com> <1156165430.193663.326490@i3g2000cwc.googlegroups.com> <1156181021.742491.299650@75g2000cwc.googlegroups.com> Message-ID: <1156534432.195798.323350@b28g2000cwb.googlegroups.com> Thank.... From gh at gregor-horvath.com Tue Aug 1 10:07:27 2006 From: gh at gregor-horvath.com (Gregor Horvath) Date: Tue, 01 Aug 2006 16:07:27 +0200 Subject: Best way to read, and analyze a log file? In-Reply-To: <1154440597.436863.131750@i3g2000cwc.googlegroups.com> References: <1154440597.436863.131750@i3g2000cwc.googlegroups.com> Message-ID: Hi, superflit at gmail.com schrieb: > I am reading a log file, and wondering what is the best way to read and > analize this. Look at: http://pyparsing.wikispaces.com/ There is also an example for parsing an apache log. -- Servus, Gregor http://www.gregor-horvath.com From metaperl at gmail.com Tue Aug 15 15:28:36 2006 From: metaperl at gmail.com (metaperl) Date: 15 Aug 2006 12:28:36 -0700 Subject: trying to reach kevin smith, author of plastex Message-ID: <1155670116.555782.222400@i3g2000cwc.googlegroups.com> Email to Kevin Smith regarding his plastex package failed. I hope he read this group. The tarball that he needs to reproduce the error is here: http://arc.livingcosmos.org/wolfram-fruit2/wolfram-fruit.tar.gz Hi, when attempting to type plastex wolfram-fruit.tex on the attached latex document, I got some errors. Also, I think the default HTML font for plastex could be "nicer" ...either that or some ready made easy to choose CSS for some common "nicer" font choices. Errors I got follow: terry at fyodor:~/domains/org/livingcosmos/arc/wolfram-fruit2$ plastex wolfram-fruit.tex plasTeX version 0.6 ( /home/terry/install/lib/python2.4/site- packages/plasTeX/Packages/article.pyc ).. ( /home/terry/install/lib/python2.4/site- packages/plasTeX/Packages/graphicx.pyc ) ( ./wrapfig.sty.. WARNING: unrecognized command/environment: z@ WARNING: Missing decimal in ./wrapfig.sty on line 32, treating as `0`. WARNING: Missing unit (expecting pt, pc, in, bp, cm, mm, dd, cc, sp, ex, em) in ./wrapfig.sty on line 32, treating as `pt` ................... WARNING: unrecognized command/environment: the WARNING: unrecognized command/environment: WF at everypar WARNING: unrecognized command/environment: @arrayparboxrestore ...... WARNING: unrecognized command/environment: string WARNING: unrecognized command/environment: newfloatlist ... )...................................................................... .................... WARNING: unrecognized command/environment: @ifnextchar INFO: Arguments of "WF at wr" don't match definition. Got "{" but was expecting "[" ([#1]#2). WARNING: unrecognized command/environment: WF at box WARNING: Missing number in ./wolfram-fruit.tex on line 327, treating as `0`. () .. WARNING: Missing number in ./wolfram-fruit.tex on line 327, treating as `0`. (< WF at box element at 0x1091752844>) WARNING: Missing number in ./wolfram-fruit.tex on line 327, treating as `0`. () WARNING: Missing number in on line 1, treating as `0`. () WARNING: Missing number in on line 1, treating as `0`. (<@ne element at 0x1091755052>) WARNING: Missing number in ./wolfram-fruit.tex on line 327, treating as `0`. () WARNING: Missing number in ./wolfram-fruit.tex on line 327, treating as `0`. () WARNING: Missing number in ./wolfram-fruit.tex on line 327, treating as `0`. () WARNING: Missing number in on line 1, treating as `0`. () WARNING: Missing number in on line 1, treating as `0`. (<@ne element at 0x1091769420>) .. INFO: Arguments of "WF at rapt" don't match definition. Got "{" but was expecting "[" ([#1]#2). WARNING: Missing decimal in ./wolfram-fruit.tex on line 327, treating as `0`. WARNING: Missing unit (expecting pt, pc, in, bp, cm, mm, dd, cc, sp, ex, em) in ./wolfram-fruit.tex on line 327, treating as `pt` WARNING: Missing decimal in ./wolfram-fruit.tex on line 327, treating as `0`. WARNING: Missing unit (expecting pt, pc, in, bp, cm, mm, dd, cc, sp, ex, em) in ./wolfram-fruit.tex on line 328, treating as `pt` ERROR: An error occurred while building the document object in ./wolfram- fruit.tex on line 328 (global name 'tok' is not defined) Traceback (most recent call last): File "/home/terry/install/bin/plastex", line 95, in ? main(sys.argv) File "/home/terry/install/bin/plastex", line 44, in main tex.parse() File "/home/terry/install/lib/python2.4/site-packages/plasTeX/TeX.py", line 378, in parse item.digest(tokens) File "/home/terry/install/lib/python2.4/site-packages/plasTeX/__init__.py", line 824, in digest item.digest(tokens) File "/home/terry/install/lib/python2.4/site-packages/plasTeX/Base/LaTeX/Sectioning.py", line 267, in digest item.digest(tokens) File "/home/terry/install/lib/python2.4/site-packages/plasTeX/Base/TeX/Text.py", line 55, in digest tokens.push(tok) NameError: global name 'tok' is not defined terry at fyodor:~/domains/org/livingcosmos/arc/wolfram-fruit2$ From gregpinero at gmail.com Thu Aug 31 12:06:03 2006 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Thu, 31 Aug 2006 12:06:03 -0400 Subject: How to Interpret Hotshot Stats Message-ID: <312cfe2b0608310906q569b06d2id4b5438e37ed5d0e@mail.gmail.com> Would someone mind giving me a quick explanation on what this is telling me? How much is 201 CPU seconds? Watching the clock the run seems to take 7 seconds all the way from clicking on the batch file to run my hotshot script. Does that mean most of that time was in loading the interpreter? Am I correct that there aren't any noticable bottlenecks here? 43 function calls in 201.725 CPU seconds Ordered by: internal time, call count ncalls tottime percall cumtime percall filename:lineno(function) 1 200.889 200.889 201.725 201.725 index.py:74(main) 1 0.187 0.187 0.430 0.430 content.py:458(handle_spage_browse _customers) 1 0.120 0.120 0.247 0.247 cgi.py:417(__init__) 1 0.092 0.092 0.111 0.111 content.py:155(HTML_HEADER) 8 0.075 0.009 0.118 0.015 cgi.py:576(getfirst) 2 0.053 0.027 0.053 0.027 webutils.py:42(input_text) 8 0.043 0.005 0.043 0.005 cgi.py:615(__contains__) 2 0.042 0.021 0.042 0.021 webutils.py:28(input_form_header) 2 0.040 0.020 0.040 0.020 webutils.py:33(input_form_footer) 1 0.039 0.039 0.039 0.039 cgi.py:732(skip_lines) 5 0.031 0.006 0.031 0.006 webutils.py:39(input_hidden) 1 0.026 0.026 0.094 0.094 cgi.py:627(read_urlencoded) 1 0.020 0.020 0.020 0.020 content.py:210(HTML_SIDEBAR) 1 0.015 0.015 0.020 0.020 stringio.py:120(read) 1 0.013 0.013 0.014 0.014 cgi.py:325(parse_header) 1 0.011 0.011 0.011 0.011 stringio.py:54(__init__) 1 0.009 0.009 0.009 0.009 cgi.py:190(parse_qsl) 2 0.008 0.004 0.008 0.004 os.py:434(__contains__) 1 0.007 0.007 0.007 0.007 content.py:245(HTML_FOOTER) 1 0.005 0.005 0.005 0.005 stringio.py:38(_complain_ifclosed) 1 0.002 0.002 0.002 0.002 cgi.py:331() 0 0.000 0.000 profile:0(profiler) Thanks, Greg From thomasbartkus at comcast.net Tue Aug 8 11:33:43 2006 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Tue, 8 Aug 2006 10:33:43 -0500 Subject: using python at the bash shell? References: <44d7e364$0$24980$c3e8da3@news.astraweb.com> Message-ID: "John Salerno" wrote in message news:44d7e364$0$24980$c3e8da3 at news.astraweb.com... > Hi all. I just installed Ubuntu and I'm learning how to use the bash > shell. Aside from the normal commands you can use, I was wondering if > it's possible to use Python from the terminal instead of the normal bash > commands (e.g. print instead of echo). My main reason for asking is that > I like using Python for everything, and if I don't need to learn the > bash 'language', then I won't just yet. The answer is yes and you are getting excellent tips from others. I am just validating your experience by saying that coming from Python is a barrier to my learning BASH. The more I work with Linux/BASH, the more I see how I might have used BASH to script something I have already done in Python. But the question that always comes up is why bother with BASH at all ;-) And with Python available everywhere, .... I've just reconsiled to pick up my BASH by osmosis and concentrate on (much!) cleaner scripting with Python. Thomas Bartkus From caolan at ldmf.net Wed Aug 23 18:12:49 2006 From: caolan at ldmf.net (Caolan) Date: Wed, 23 Aug 2006 15:12:49 -0700 Subject: in-memory-only file object from string Message-ID: The mmap module should do what you are looking for. It allows you to store data in memory (hence the name memory map) and treat it as both a string and a file. ________________________________ From: python-list-bounces+caolan=ldmf.net at python.org on behalf of bobrik Sent: Wed 8/23/2006 2:56 PM To: python-list at python.org Subject: in-memory-only file object from string Hello, how to create a file object whose contents I initialize from a string and which is purely in memory? I can make a workaround like this: filecontents = "Very interesting stuff ... " file = os.tmpfile () file.write (filecontents) file.seek (0) procedure (fileobject = file) but this creates a file on harddisk. Instead I would like to use something like: filecontents = "Very interesting stuff ... " file = stringfile (filecontents) procedure (fileobject = file) Is this possible somehow? I appreciate any help. -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From simon.hibbs at gmail.com Thu Aug 10 08:12:12 2006 From: simon.hibbs at gmail.com (Simon Hibbs) Date: 10 Aug 2006 05:12:12 -0700 Subject: Make Object Oriented? In-Reply-To: References: Message-ID: <1155211932.632684.185920@m73g2000cwd.googlegroups.com> I can't even vaguely concieve of how such a think could work, even at a trivial, hypothetical level. The code converter would ahve to actualy understand at a general level what the program does and how it does it, then come up with an orriginal way to solve the same problem using a different methodology. As to the simple case, even here, the converter would have to make inteligent decisions. Which methods and properties should it move to the base class, and which should it keep local? What criteria might it use for making such a choice? How could you be sure that the decisions it made would be useful or appropriate? Simon Hibbs From fredrik at pythonware.com Mon Aug 21 05:40:27 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Aug 2006 11:40:27 +0200 Subject: Help in using introspection to simplify repetitive code In-Reply-To: <1156151567.580811.55380@h48g2000cwc.googlegroups.com> References: <1156090845.875872.41220@75g2000cwc.googlegroups.com> <1156151567.580811.55380@h48g2000cwc.googlegroups.com> Message-ID: jsceballos at gmail.com wrote: > And they do take arguments, and a variable number of them, so AFAIK > hooking with __getattr__ or __getattribute__ will not work, as you can > only get the method name with that. why not just return the bound method *object* (a callable), and let the caller call that as usual (see Terry's last example). (hint: x.foo() can be written f=getattr(x,"foo"); f()) From david_wahler at bic.ky Sat Aug 19 11:38:41 2006 From: david_wahler at bic.ky (david_wahler at bic.ky) Date: 19 Aug 2006 10:38:41 -0500 Subject: =?utf-8?Q?Re:_Zope_3.3.0_beta_2_released=21?= Message-ID: <20060819153841.9108.qmail@BICSRV1011.bic.ky> I'll be out of the office until approximately August 20th. If you have any questions, please email support at bic.ky. -- David Wahler From lee at example.com Thu Aug 17 18:09:18 2006 From: lee at example.com (Lee Harr) Date: Thu, 17 Aug 2006 22:09:18 GMT Subject: drawingarea problem References: Message-ID: On 2006-08-16, Rafa? Janas wrote: > Is somebody try to paint filled boxes in drawingarea? > I don't know how to paint line or someting like this. > Maybe somebody have tutorial or samples? Your question could use a few more details (like what you have tried, what "drawingarea" is and what exactly is the problem), but I found this that might help: http://www.google.com/search?q=python+drawingarea http://www.pygtk.org/pygtk2tutorial/examples/drawingarea.py From rdiaz02 at gmail.com Sat Aug 26 18:09:02 2006 From: rdiaz02 at gmail.com (Ramon Diaz-Uriarte) Date: Sun, 27 Aug 2006 00:09:02 +0200 Subject: Python web service ... In-Reply-To: <1156608770.864092.169920@i3g2000cwc.googlegroups.com> References: <1156590455.555359.247410@h48g2000cwc.googlegroups.com> <1156608770.864092.169920@i3g2000cwc.googlegroups.com> Message-ID: <624934630608261509n313fa6dbp4af5c55b00e263db@mail.gmail.com> On 26 Aug 2006 09:12:50 -0700, NicolasG wrote: > > For a one-shot thing, plain old CGI might be enough. You can have a > > static HTML page with the form for the upload, have python do the > > image part, and generate the return HTML with the image with a python > > script. If you plan to do this a lot, or want fairly sophisticated > > stuff, or DB access underneath, authentication, etc, then you might > > want to look at any of the web framewoks. If you don't have the web > > server part already taken care of (e.g., you already have Apache up > > and running) then the web server framework can be more attractive. > > > > As for web frameworks there is a long list in the Python web site. > > Which framework fits you best might depend on what you want to > > accomplish now and in the future. You can try something simple and > > minimalist (and with docs that you can read in less than an afternoon) > > such as Karrigell, or try something more complex, such as Django, > > TurboGears, Pylons, CherryPy, etc. > > > > And then, you might try the CGI approach to begin with, and as your > > needs become more complex, move to a framework. (This has been our own > > path: we've used plain CGI for over a year for the web-based > > bioinformatics applications we've developed, that use R and Python for > > computations, and are now moving to framework). > > > > Good luck! > > > > R. > > > > -- > > Ramon Diaz-Uriarte > > At this time right now I prefer to do something that works the quickest > possible... > I never had any experience with CGI, do I need to set up a web server > for that ? Yes, you'd need to configure a web server. I don't know whether you are on windows or Unix/Linux, and that could seriously affect how easy it is to set up a web server. Most Linux distros make installing apache a piece of cake, but configuring Apache might not be trivial. Thus, maybe the fastest and easiest is, as other posters have suggested, to try Karrigell. > can you point me some usefull reading material so I can get a start ? > I will post for a comment at Zope , I had installed once and it was > very easy. Don't know if it will be easy too to get my job done... > But Zope seems to have a steep learning curve and it is a big system. It might be a huge hassle for what you want. Best, R. From steven.bethard at gmail.com Thu Aug 3 13:36:45 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 03 Aug 2006 11:36:45 -0600 Subject: What is the best way to print the usage string ? In-Reply-To: References: Message-ID: Leonel Gayard wrote: > Hi all, > > I had to write a small script, and I did it in python instead of > shell-script. My script takes some arguments from the command line, > like this. > > import sys > args = sys.argv[1:] > if args == []: > print """Concat: concatenates the arguments with a colon (:) between > them > Usage: concat arg1 [arg2...] > Example: concat a b c prints \"a.jar:b.jar:c/\"""" > sys.exit(1) > print reduce(lambda x, y: x + ':' + y, sys.argv[1:]) The short answer is to use textwrap.dedent:: >>> import textwrap >>> if True: ... print textwrap.dedent('''\ ... Concat: concatenates the arguments with a colon (:) between ... them ... Usage: concat arg1 [arg2...] ... Example: concat a b c prints "a.jar:b.jar:c/"''') ... Concat: concatenates the arguments with a colon (:) between them Usage: concat arg1 [arg2...] Example: concat a b c prints "a.jar:b.jar:c/" You also might consider using an argument parsing like argparse[1] to build your usage string for you: ------------------------------ concat.py ------------------------------ import argparse if __name__ == '__main__': parser = argparse.ArgumentParser( description='concatenates the arguments with a colon (:) ' 'between them') parser.add_argument('args', metavar='arg', nargs='+', help='one item to be concatenated') namespace = parser.parse_args() print ':'.join(namespace.args) ----------------------------------------------------------------------- $ concat.py usage: concat.py [-h] arg [arg ...] concat.py: error: too few arguments $ concat.py -h usage: concat.py [-h] arg [arg ...] concatenates the arguments with a colon (:) between them positional arguments: arg one item to be concatenated optional arguments: -h, --help show this help message and exit $ concat.py a b c Steve [1] http://argparse.python-hosting.com/ From slawomir.nowaczyk.847 at student.lu.se Wed Aug 9 06:54:20 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Wed, 09 Aug 2006 12:54:20 +0200 Subject: do people really complain about significant whitespace? In-Reply-To: <1154994477.450666.226550@b28g2000cwb.googlegroups.com> References: <1154991523.887791.9640@i42g2000cwa.googlegroups.com> <1154994477.450666.226550@b28g2000cwb.googlegroups.com> Message-ID: <20060809092719.EED6.SLAWOMIR.NOWACZYK.847@student.lu.se> On Mon, 07 Aug 2006 16:47:57 -0700 Jason wrote: #> It is annoying that certain communication channels do not respect #> white-space. I dislike using braces because I have to indicate my #> intentions twice: once for the compiler and once for humans. I must admit I do not get this "indicate intentions twice" argument, even though I heard it a number of times now... It's not that braces require more work or more typing or something, after all -- at least not if one is using a decent editor. Really, typing brace after function/if/etc should add newlines and indent code as required -- automatically. Actually, for me, it is even *less* typing in C and similar languages... I probably should teach my Emacs to automatically add newline after colon in Python, just as it does after a brace in C... As soon as I figure out how to deal with dictionary literals. Hmmm. -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From petdragon69-weather at yahoo.co.uk Mon Aug 28 05:02:40 2006 From: petdragon69-weather at yahoo.co.uk (PetDragon) Date: Mon, 28 Aug 2006 10:02:40 +0100 Subject: Firewire comms using Python? References: <4b6dnSo0jtHhXWzZnZ2dnUVZ8tadnZ2d@bt.com> <1156745271.067289.70540@m73g2000cwd.googlegroups.com> Message-ID: yeah man no joy there "Simon Forman" wrote in message news:1156745271.067289.70540 at m73g2000cwd.googlegroups.com... > Fraggle69 wrote: >> Hi, >> Does anyone have any idea of how I can use Python to get images from my >> firewire camera?? >> I am using python under winXP pro.... >> >> Cheers >> Fraggle > > Have you tried google? > > Peace, > ~Simon > From gagsl-py at yahoo.com.ar Mon Aug 14 17:31:58 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 14 Aug 2006 18:31:58 -0300 Subject: Newbie Python SQL In-Reply-To: <1155585295.185352.87190@b28g2000cwb.googlegroups.com> References: <1155585295.185352.87190@b28g2000cwb.googlegroups.com> Message-ID: <7.0.1.0.0.20060814182932.03a40ba0@yahoo.com.ar> At Monday 14/8/2006 16:54, len wrote: >Could someone recommend a tutoral, book, white paper, etc. I am trying >to write a python program which takes a CSV file and through SQL insert >update my SQL files. > >The SQL files contain a parent file with multiply child and >grandchildren plus various files for doing validation. I am using the >mxODBC module for access to the SQL files. I have, through the IDLE >connected done some simple queries and some testing of insert. > >I believe I am past the initial stage on the SQL stuff but just can't >get to the next level. I have picked up several python book, but all >take a very introductory approach. > >Any recommendation would be appreciated. I think you need an SQL/database course rather than a Python one. Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From dwai.lahiri at gmail.com Wed Aug 30 16:40:33 2006 From: dwai.lahiri at gmail.com (implicate_order) Date: 30 Aug 2006 13:40:33 -0700 Subject: py2exe for programs with excel COM objects In-Reply-To: <1156957480.182219.165010@h48g2000cwc.googlegroups.com> References: <1156957480.182219.165010@h48g2000cwc.googlegroups.com> Message-ID: <1156970433.541899.192960@e3g2000cwe.googlegroups.com> marijuanated at gmail.com wrote: > Is it possible to create a executable of a python program that refers > to Excel COM objects with the help of py2exe. Hi, I just used py2exe to create an executable. If you want to deliver the package with an installation wizard, just use Inno Setup tools (http://www.jrsoftware.org/). Look at an example of how to create the setup.py script and it's a no-brainer from that point on. From aries.shuaib at gmail.com Tue Aug 8 11:04:56 2006 From: aries.shuaib at gmail.com (Shuaib) Date: 8 Aug 2006 08:04:56 -0700 Subject: Tkinter module not found Message-ID: <1155049496.292471.37020@h48g2000cwc.googlegroups.com> Hey, Even though I freshly installed Tcl and Tk, python still seem to have problems accessing Tkinter module. Here is what says when I do "import Tkinter" == Traceback (most recent call last): File "", line 1, in ? ImportError: No module named Tkinter == Any ideas how to fix this problem? (Gentoo distribution) Thanks. From mwinrock at frontiernet.net Wed Aug 16 20:06:45 2006 From: mwinrock at frontiernet.net (Mark Winrock) Date: Thu, 17 Aug 2006 00:06:45 GMT Subject: How do I catch ExpatError exception? In-Reply-To: <1155771384.487253.152630@i42g2000cwa.googlegroups.com> References: <1155771384.487253.152630@i42g2000cwa.googlegroups.com> Message-ID: Shuaib wrote: > Hey! > > I am getting this exception. > > xml.parsers.expat.ExpatError > > But I am not able to catch it with "except > xml.parsers.expat.ExpatError:" It says "NameError: global name 'xml' is > not defined". > > I am also not able to catch it with "except ExpatError:" Gives > "NameError: global name 'xml' is not defined" > > How do I catch it? (I am parsing an xml file) Have you imported xml.parsers.expat to get it properly scoped? > > Also, how do I get the line number where an exception was thrown? > Try looking at the 'sys.exc_info' and the 'traceback' module documentation. Also see Python Cookbook recipe Recipe 8.6. Getting More Information from Tracebacks (Bryn Keller) > Thanks. > From ptmcg at austin.rr._bogus_.com Fri Aug 18 14:56:47 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 18 Aug 2006 18:56:47 GMT Subject: Type conversion? References: <1155915139.622448.178160@m73g2000cwd.googlegroups.com> <1155915914.141274.99020@m79g2000cwm.googlegroups.com> <1155921295.608755.269970@i3g2000cwc.googlegroups.com> Message-ID: "KraftDiner" wrote in message news:1155921295.608755.269970 at i3g2000cwc.googlegroups.com... > > In C++ you can cast one class type to another if you override the > operator= > Then you can convert one class type to another... > In Python it would appear that the left hand side of the assignment > operator > is not used to determine if a cast is necessary. > So how would I do this in python? Start by repeating 50 times: "Python is not C++". In Python, '=' is not an operator, it is a name binder, and is defined at the language level, not at the class level. > > a = classA() > b = classB() > b = a > > In the end b would end up just being a refrence to a > no conversion would have been done. > Just as you say, '=' will completely rebind the rhs value to the lhs name. Now one thing you *could* do is to do something tricky, like use one of the overridable inplace operators, like "<<=", which *is* definable by class. Here is a type casting class that does something like you are asking for. (Back in the CORBA days, <<= was used in the C++ binding to insert values into a CORBA::Any variable - I guess it looks like some sort of typographic hypodermic needle...) -- Paul class Caster(object): def __init__(self,typ): self.castType = typ self.value = self.castType() def cast(self,other): try: return self.castType(other) except Exception,e: print "Failed to cast '%s' as %s" % (other, self.castType.__name__) # define behavior for <<= operator def __ilshift__(self,other): self.value = self.cast(other) return self def __str__(self): return "(%s) %s" % (self.castType.__name__,self.value) z = Caster(int) print z z <<= 100 print z z <<= 3.14159 print z z <<= 'what the heck?' print z Prints: (int) 0 (int) 100 (int) 3 Failed to cast 'what the heck?' as int (int) None From aleax at mac.com Fri Aug 11 01:45:06 2006 From: aleax at mac.com (Alex Martelli) Date: Thu, 10 Aug 2006 22:45:06 -0700 Subject: __contains__ vs. __getitem__ References: <44da144b$0$21143$7a628cd7@news.club-internet.fr> <44dae8c3$0$21151$7a628cd7@news.club-internet.fr> Message-ID: <1hjvltd.12fxop3eded8wN%aleax@mac.com> Bruno Desthuilliers wrote: > David Isaac wrote: > >> Alan Isaac wrote: > >>> I have a subclass of dict where __getitem__ returns None rather than > >>> raising KeyError for missing keys. (The why of that is not important > > for > >>> this question.) > > > > "Bruno Desthuilliers" wrote: > >> Well, actually it may be important... What's so wrong with d.get('key') > >> that you need this behaviour ? > > > > I want to use the mapping with string interpolation. > > > Well, this makes sens... But then why not use a plain dict to collect > data, and wrap it in a special one just before using it for > interpolation ? ie: Using a single container (and being able to modify and use it fluidly) is simply handier. That's what defaultdict in Python 2.5 is for, btw. Alex From steven.bethard at gmail.com Thu Aug 3 01:41:32 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 2 Aug 2006 23:41:32 -0600 Subject: [ANN] The argparse module Message-ID: I'm pleased to announce initial availability of the argparse module, an optparse-inspired command line parser: http://argparse.python-hosting.com/ The argparse module can be downloaded as a single file, argparse.py, through the Browse Source link on the website. Argparse improves on optparse by: * handling both optional and positional arguments * supporting parsers that dispatch to sub-parsers * producing more informative usage messages * supporting arguments that consume any number of string args * allowing types and actions to be specified with simple callables instead of hacking class attributes like STORE_ACTIONS or CHECK_METHODS as well a number of other improvements on the optparse API. Just to whet your appetite: >>> parser = argparse.ArgumentParser(prog='PROG') >>> _ = parser.add_argument('--foo', type=int, choices=[1, 2, 3], ... help='optional with integer choices') >>> _ = parser.add_argument('--bar', nargs='?', const='C', default='D', ... help='optional with or without arg') >>> _ = parser.add_argument('baz', nargs='+', type=float, ... help='positional with one or more args') >>> parser.parse_args('--bar --foo 2 0.5 1.5'.split()) Namespace(bar='C', baz=[0.5, 1.5], foo=2) This is the first public presentation of this module, so the APIs are still subject to change. If you find it of interest, and you'd like to help improve it, I'd be glad to open the project up to more developers. Bug reports can be made through Trac at: http://argparse.python-hosting.com/newticket Steven Bethard From jmcmonagle at velseis.com.au Mon Aug 7 21:20:34 2006 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Tue, 08 Aug 2006 11:20:34 +1000 Subject: using python at the bash shell? In-Reply-To: <44d7e364$0$24980$c3e8da3@news.astraweb.com> References: <44d7e364$0$24980$c3e8da3@news.astraweb.com> Message-ID: <1155000034.5036.28.camel@kuepper.vels-int.com.au> On Mon, 2006-08-07 at 21:03 -0400, John Salerno wrote: > Hi all. I just installed Ubuntu and I'm learning how to use the bash > shell. Aside from the normal commands you can use, I was wondering if > it's possible to use Python from the terminal instead of the normal bash > commands (e.g. print instead of echo). >From a terminal window typing, python -c "print 'testing'" would produce the same results as echo 'testing' in bash shell, but obviously not as nice. > My main reason for asking is that > I like using Python for everything, and if I don't need to learn the > bash 'language', then I won't just yet. > Just type python and do your stuff in the python interpreter. This becomes your shell. This then got me thinking, how about making python your login shell. So I modified my shell login entry in /etc/passwd to /usr/bin/python, logged in and voila, I was presented with my friendly python shell upon opening a terminal window. So the answer is "Yes". -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From pedro.werneck at terra.com.br Wed Aug 9 08:40:37 2006 From: pedro.werneck at terra.com.br (Pedro Werneck) Date: Wed, 9 Aug 2006 09:40:37 -0300 Subject: singleton decorator In-Reply-To: <44D8889F.8010502@freakmail.de> References: <7008329d0608071633odfbf134n749c223293e3cb90@mail.gmail.com> <20060807212616.46fd3571.pedro.werneck@terra.com.br> <44D8889F.8010502@freakmail.de> Message-ID: <20060809094037.4073eecb.pedro.werneck@terra.com.br> On Tue, 08 Aug 2006 14:50:39 +0200 Wildemar Wildenburger wrote: > Or you could always just use the __new__() method instead of > __init__(), putting all your initialization into the above > except-block. If you replace 'cls._it = ...' with 'self = cls_it = > ...' you'll feel right at home too :). > > Anything 'unpythonic' (gosh how I hate that word ;)) about that, BTW? Yes. :) You'll have to make a custom Singleton class for each subclass you want to make a singleton, instead of just creating a custom _init method for each one of them. You can use the subclass __new__, but that's definitely 'unpythonic'. -- Pedro Werneck From listservs at mac.com Wed Aug 30 17:30:10 2006 From: listservs at mac.com (listservs at mac.com) Date: Wed, 30 Aug 2006 17:30:10 -0400 Subject: unit testing failure makes no sense Message-ID: I have some unit testing code in one of my modules that appears to run without an error, but the unit test fails anyhow. Have a look at the output below -- the TestResult seems to have no errors and no failures, yet I get a system exit. ------------------------------------------------------------------------ --- exceptions.SystemExit Traceback (most recent call last) /Users/chris/ /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/ unittest.py in __init__(self=, module='__main__', defaultTest=None, argv=['/usr/local/ bin/ipython'], testRunner=None, testLoader=) 757 self.progName = os.path.basename(argv[0]) 758 self.parseArgs(argv) --> 759 self.runTests() self.runTests = > 760 761 def usageExit(self, msg=None): /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/ unittest.py in runTests(self=) 795 self.testRunner = TextTestRunner (verbosity=self.verbosity) 796 result = self.testRunner.run(self.test) --> 797 sys.exit(not result.wasSuccessful()) global sys.exit = result.wasSuccessful = > 798 799 main = TestProgram SystemExit: False Type exit or quit to exit IPython (%Exit or %Quit do so unconditionally). Any ideas what is going wrong here? Here is my testing code: class MCMCTest(unittest.TestCase): def testCoalMiningDisasters(self): """Run coal mining disasters example sampler""" print 'Running coal mining disasters test case ...' # Create an instance of the sampler self.sampler = DisasterSampler() # Specify the nimber of iterations to execute iterations = 10000 thin = 2 burn = 5000 chains = 2 # Run MCMC simulation for i in range(chains): self.failUnless(self.sampler.sample(iterations, burn=burn, thin=thin, plot=True)) # Run convergence diagnostics self.sampler.convergence() # Plot autocorrelation self.sampler.autocorrelation() # Goodness of fit x, n = self.sampler.goodness(iterations/10)['overall'] self.failIf(x/n < 0.05 or x/n > 0.95) -- Christopher Fonnesbeck + Atlanta, GA + fonnesbeck at mac.com + Contact me on AOL IM using email address From bj_666 at gmx.net Tue Aug 15 05:57:17 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 15 Aug 2006 11:57:17 +0200 Subject: TypeError: 'module' object is not callable (newby question) References: <1155580968.024991.107040@i3g2000cwc.googlegroups.com> <0E5Eg.19638$yE1.18048@trndny02> Message-ID: In <0E5Eg.19638$yE1.18048 at trndny02>, Charles Russell wrote: > Another newby question: __name__ and __file__ appear to be > predefined variables. To look up their meaning in the manual, is there > some method less clumsy than grepping the whole collection of .html > source files? I can't find any comprehensive index. Here's the index of the reference manual: http://docs.python.org/ref/genindex.html Ciao, Marc 'BlackJack' Rintsch From steve at holdenweb.com Tue Aug 29 05:34:12 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 29 Aug 2006 10:34:12 +0100 Subject: The lib email parse problem... In-Reply-To: <1156842395.855885.183330@p79g2000cwp.googlegroups.com> References: <1156837260.222395.305960@b28g2000cwb.googlegroups.com> <1156841437.692537.68200@i42g2000cwa.googlegroups.com> <1156841950.866776.66400@b28g2000cwb.googlegroups.com> <1156842395.855885.183330@p79g2000cwp.googlegroups.com> Message-ID: ???? wrote: > supose a email part like this: > > Content-Type: Multipart/Alternative; > boundary="Boundary-=_iTIraXJMjfQvFKkvZlqprUgHZWDm" > > > --Boundary-=_iTIraXJMjfQvFKkvZlqprUgHZWDm > Content-Type: text/plain; charset="gb2312" > Content-Transfer-Encoding: 7bit > > abcd. > --Boundary-=_iTIraXJMjfQvFKkvZlqprUgHZWDm > Content-Type: text/html; charset="gb2312" > Content-Transfer-Encoding: quoted-printable > > .................. > --Boundary-=_iTIraXJMjfQvFKkvZlqprUgHZWDm-- > > the plain text is abcd, and the alternative content type is text/html, > i should prefer explain the html content, and i must not explaint the > two part ,so i want to get the boundary end. > > thanks all. > In other words, you *haven't* tried the email module. email.Parser can cope with arbitrarily complex message structures, including oddities like attachments which are themselves email messages containing their own attachments. Read the documentation and look for sample code, then get back to the list with questions about how to make email do what you want it to. Please don't ask us to re-invent existing libraries. that's why the libraries are there. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From rogue_pedro at yahoo.com Sun Aug 20 02:28:30 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 19 Aug 2006 23:28:30 -0700 Subject: [NEWB]: List with random numbers In-Reply-To: <1156054456.520655.49040@b28g2000cwb.googlegroups.com> References: <1156054456.520655.49040@b28g2000cwb.googlegroups.com> Message-ID: <1156055310.304498.231710@74g2000cwt.googlegroups.com> eltower wrote: > Hey all, > > I'm trying to write a program in Python for learning purposes which is > meant to: > > Generate a random number from 0 to 6 > Insert this random number to the end of a list unless the number is > already there > finish with a len(list) = 7 > > so far, I have this: > > import random > > random_list = [] > > while len(random_list) < 8: > j = random.randrange(6) > if (j in random_list): > continue > else: > random_list.append(j) > continue > > print random_list > > > however, I get stuck in an infinite loop. > > Any suggestions? > > Thank you in advance, > > Adri Maybe this would help: >>> while True: print random.randrange(6), 3 2 5 4 1 3 1 3 5 0 5 3 4 0 2 2 5 2 2 5 3 1 0 2 0 4 2 4 3 1 3 3 2 3 3 2 1 5 4 2 0 1 5 3 4 1 2 3 5 1 1 5 4 0 3 0 4 4 1 2 1 4 4 5 2 4 5 4 2 5 5 3 5 0 2 3 2 3 5 5 2 0 0 1 5 5 0 0 3 5 3 2 1 4 4 0 1 0 3 1 0 2 0 5 5 2 5 0 5 5 1 0 2 3 1 4 3 3 1 3 5 2 1 4 0 5 3 2 5 0 2 5 3 4 5 5 0 0 3 4 3 1 5 5 3 4 3 4 5 0 3 0 2 5 5 1 3 3 5 3 4 0 3 3 2 5 1 1 1 1 0 3 0 3 5 0 4 5 4 0 1 0 5 2 3 1 1 4 4 3 0 0 0 3 3 5 3 5 4 1 1 0 2 4 5 3 3 1 3 5 5 0 1 4 2 1 0 0 0 3 0 4 5 5 5 5 0 4 1 3 4 0 5 3 0 0 5 1 1 3 4 1 0 5 4 5 0 1 1 5 4 1 2 2 5 2 0 1 1 5 4 5 1 5 5 3 0 3 2 4 3 4 3 2 2 0 3 2 4 2 4 2 3 5 0 4 0 0 1 3 0 4 1 0 0 4 2 4 5 3 5 0 4 2 1 4 4 2 0 0 4 4 1 Traceback (most recent call last): File "", line 2, in -toplevel- print random.randrange(6), KeyboardInterrupt If not, try putting "print random_list" *inside* your while loop. HTH, ~Simon P.S. Take a look at the random.shuffle() function... :-) From alisonken1 at gmail.com Thu Aug 10 19:14:50 2006 From: alisonken1 at gmail.com (alisonken1) Date: 10 Aug 2006 16:14:50 -0700 Subject: String Formatting In-Reply-To: <1155242045.262819.322010@m73g2000cwd.googlegroups.com> References: <1155213326.679334.234880@i42g2000cwa.googlegroups.com> <1155242045.262819.322010@m73g2000cwd.googlegroups.com> Message-ID: <1155251689.960370.260690@h48g2000cwc.googlegroups.com> Sorry, missed an option in there: > def get_word(s, which=1, sep=','): > return s.split(sep)[which-1].strip() > > >>> > >>> get_word('bread, butter, milk') > 'milk' > > >>> >>> get_word('bread, butter, milk') 'bread' >>> get_word('bread, butter, milk', 3) 'milk' >>> get_word('bread is brown, butter is yellow, milk is white') 'bread is brown' >>> get_word('bread is brown, butter is yello, milk is white', 3) 'milk is white' From cginboston at hotmail.com Tue Aug 29 10:53:10 2006 From: cginboston at hotmail.com (Chaz Ginger) Date: Tue, 29 Aug 2006 14:53:10 GMT Subject: refering to base classes In-Reply-To: <1156862012.068397.284040@m73g2000cwd.googlegroups.com> References: <1156862012.068397.284040@m73g2000cwd.googlegroups.com> Message-ID: <44F454D6.5040606@hotmail.com> glenn wrote: > hi - Im quite new to python, wondering if anyone can help me understand > something about inheritance here. In this trivial example, how could I > modify the voice method of 'dog' to call the base class 'creatures' > voice method from with in it? > > class creature: > def __init__(self): > self.noise="" > def voice(self): > return "voice:" + self.noise > > class dog(creature): > def __init__(self): > self.noise="bark" > > def voice(self): > print "brace your self:" > > thanks > glenn > Try this: class dog(creature): ..... def voice(self): print "brace your self:" creature.voice(self) This should do it. From junkytownMAKNI at gmail.com Sat Aug 26 13:57:33 2006 From: junkytownMAKNI at gmail.com (SuperHik) Date: Sat, 26 Aug 2006 19:57:33 +0200 Subject: Learning Python In-Reply-To: <44f0540a$0$75041$14726298@news.sunsite.dk> References: <44f03c80$0$75042$14726298@news.sunsite.dk> <1156597310.493911.241160@i42g2000cwa.googlegroups.com> <44f0540a$0$75041$14726298@news.sunsite.dk> Message-ID: JAG CHAN wrote: > bearophileHUGS at lycos.com wrote in > news:1156597310.493911.241160 at i42g2000cwa.googlegroups.com: > >> JAG CHAN: >>> As I had written earlier, I am trying to learn Python. >>> I chose IDLE as an editor to learn Python. >>> Now I find that it is an online editor. >>> It is not possible for me to be always on online while learning. >>> Kindly suggest me a suitable editor (for Windows XP) which does not >>> require me to be on online. >> Maybe your firewall tells you that IDLE asks for access to the net, >> but it's not an online sofware. You can use a different editor, like >> SPE, or if you want to start with something simpler you can try >> ActivePython, or probably it's even better a normal and very fast txt >> editor with a python grammar for colorization, with a macro added to >> run the script being edited. >> >> Bye, >> bearophile >> > > Thanks for your response. > You are right. > Whenever I try to open IDLE, my zone firewall tells me pythonw.exe is > trying to access the trusted zone. > Whenever I try to open new IDLE window I get the following message: > "IDLE's subprocess didn't make connection.Either IDLE can't start a > subprocess or personal firewall software is blocking the connection." > I will be grateful if you kindly suggest a way out, then, I won't have to > install another editor. > Regards. Python uses what windows call "internal loopback device" wich is monitored by the firewall. So yes, it's a firewall thing, not the editor and you would get the same message using any editor... I suggest AcitvePython - easy, free, and comes with all the windows specific modules and extensions... From michiel at thingmajig.org Wed Aug 9 10:55:40 2006 From: michiel at thingmajig.org (Michiel Sikma) Date: Wed, 9 Aug 2006 16:55:40 +0200 Subject: do people really complain about significant whitespace? In-Reply-To: <1155134902.103617.71810@i3g2000cwc.googlegroups.com> References: <1154986984.740638.241130@m79g2000cwm.googlegroups.com> <87bqqwyumq.fsf@benfinney.id.au> <1155077965.100108.232790@m79g2000cwm.googlegroups.com> <44d9d949$0$14310$626a54ce@news.free.fr> <1155134902.103617.71810@i3g2000cwc.googlegroups.com> Message-ID: <0D58DDCA-ED67-4A6C-BF94-5C22359BEC4F@thingmajig.org> Op 9-aug-2006, om 16:48 heeft Carl Banks het volgende geschreven: > Even if this were legal code (it isn't), it's still more transparent > than some of the C code I've seen. > > > Carl Banks Still kind of too bad that means there won't ever be an International Obfuscated Python Code Contest. #define _ -F<00||--F-OO--; int F=00,OO=00;main(){F_OO();printf("%1.3f\n",4.*-F/OO/OO);}F_OO() { _-_-_-_ _-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_ _-_-_-_ } :) Michiel (source: http://www0.us.ioccc.org/years.html#1988) From bj_666 at gmx.net Tue Aug 15 02:54:27 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 15 Aug 2006 08:54:27 +0200 Subject: Memory problem References: <1155590938.397801.302110@h48g2000cwc.googlegroups.com> Message-ID: In , Yi Xing wrote: > Is there a way that I can define a two-dimensional array in > array.array()? Thanks. If you need more than one dimension you really should take a look at `numarray` or `numpy`. What are you going to do with the data once it's loaded into memory? Ciao, Marc 'BlackJack' Rintsch From tkirke at gmail.com Fri Aug 11 22:44:13 2006 From: tkirke at gmail.com (tkirke at gmail.com) Date: 11 Aug 2006 19:44:13 -0700 Subject: help with c <-> python buffer transfer In-Reply-To: <1155338689.873546.6930@i42g2000cwa.googlegroups.com> References: <1155335511.379184.200570@75g2000cwc.googlegroups.com> <1155338689.873546.6930@i42g2000cwa.googlegroups.com> Message-ID: <1155350653.626750.132450@74g2000cwt.googlegroups.com> John Machin wrote: > tkirke at gmail.com wrote: > > How does one transfer a buffer object from python -> c and back again > > (assuming the data gets modified)? > > I can't seem to get this or anything else to work, but am clueless as > > to what I'm doing wrong > > > > > > using namespace boost::python; > > Looks like C++, not C. > > > > > static PyObject * proc_buf(PyObject *self, PyObject *args) { > > [I'm not familiar with the boost gadget, but ...] Doesn't "static" mean > that this function is *not* externally visible Yes. It's C++. I've built python extensions with Boost Python successfully and copied the structure of most of this example from other people's code. > > > PyObject *resultobj; > > char* output_samples; > > int len; > > if (!PyArg_ParseTuple(args,"s#|l",&output_samples, &len)) { > > You have made the length an optional argument, but not initialised the > receiving variable "len". Nothing to do with your current problem, but > highly dangerous. > > > return NULL; /* wrong arguments provided */ > > } > > for (int i=0;i > output_samples[i] *= 2; // for example > > } > > This is updating the internal representation of the input in situ. Not > a very good idea at all. Take a copy. Return the updated copy. Thanks for the pointers... > > > resultobj = PyString_FromStringAndSize(output_samples, len); > > return resultobj; > > } This is the part I need help with. I've also used PyBuffer_... subroutines which gave similar problems. Thanks for all of your other comments, but I was hoping someone could just tell me what was wrong with the code without having to worry about all of the other things that could go wrong. For completeness here is the complete c++ module & python output //======================================================================= // Boost Includes //============================================================== #include #include #include #include #include // Using ======================================================================= using namespace boost::python; static PyObject * proc_buf(PyObject *self, PyObject *args) { PyObject *resultobj; char* output_samples; int len; if (!PyArg_ParseTuple(args,"s#|l",&output_samples, &len)) { return NULL; /* wrong arguments provided */ } for (int i=0;i From larry.bates at websafe.com Fri Aug 11 11:27:51 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 11 Aug 2006 10:27:51 -0500 Subject: some n00b question In-Reply-To: <1155305094.295652.218220@i3g2000cwc.googlegroups.com> References: <1155305094.295652.218220@i3g2000cwc.googlegroups.com> Message-ID: <44DCA1F7.5040400@websafe.com> Omar wrote: > I'm learning how to program python. a few questions > > a) I'm mostly interested in creating exe's that have to do with music > -- things to help me keep track of chord progressions, transpositions, > etc. can anyone point me in the direction of resources on this? > > b) I'm also interested in created GUI's sooner rather than later. Can > anyone point me to a fast track to doing GUI's on python? > > thanks > To create .exe's you will need to get py2exe: http://www.py2exe.org/ I would add +1 to wxPython. It takes a little while to get going, IMHO it is the best Python GUI for Windows (it is also cross- platform if that interests you). -Larry From rpdooling at gmail.com Fri Aug 18 22:57:11 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 18 Aug 2006 19:57:11 -0700 Subject: how do you get the name of a dictionary? In-Reply-To: References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> Message-ID: <1155956231.033517.22150@74g2000cwt.googlegroups.com> Tim Chase wrote: > How would you ask for the object? > > >>> print get_name(banana) > > you might as well write > > >>> print "banana" > Or there used to be a guy in this group who said it was like asking a cat for its name. He headbanged himself unconscious though, or so they say. http://tinyurl.com/hql6d rd From johnjsal at NOSPAMgmail.com Thu Aug 31 14:42:40 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 31 Aug 2006 18:42:40 GMT Subject: SQLObject or SQLAlchemy? Message-ID: Are there any major differences between these two? It seems they can both be used with TurboGears, and SQLAlchemy with Django. I'm just wondering what everyone's preference is, and why, and if there are even more choices for ORM. Thanks. From duncan.booth at invalid.invalid Sat Aug 26 09:35:09 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 26 Aug 2006 13:35:09 GMT Subject: mechanize, how send forms? References: <1156586954.498802.143960@m73g2000cwd.googlegroups.com> Message-ID: Kowalski wrote: > from mechanize import Browser > > br = Browser() > br.open("http://www.google.com") #example > > for form in br.forms(): > print form > > br.select_form(name="f") > br["q"] = "Blah" > > #??? > #response1=br.submit() > #??? > > Google publish an api for searching. Use that instead of trying to spoof the web interface. From jack at psynchronous.com Wed Aug 16 18:02:22 2006 From: jack at psynchronous.com (Jack Diederich) Date: Wed, 16 Aug 2006 18:02:22 -0400 Subject: PySequence_SetItem In-Reply-To: <1155764364.775366.76070@i3g2000cwc.googlegroups.com> References: <1155754847.392950.266180@h48g2000cwc.googlegroups.com> <1155755905.233229.93440@74g2000cwt.googlegroups.com> <1155761144.583994.260150@m73g2000cwd.googlegroups.com> <1155764364.775366.76070@i3g2000cwc.googlegroups.com> Message-ID: <20060816220222.GD5772@performancedrivers.com> On Wed, Aug 16, 2006 at 02:39:24PM -0700, John Machin wrote: > > Jack Diederich wrote: > > > Changing the PySequence_SetItem to PyList_SetItem and dropping the > > DECREF works for me too (PyList functions steal a reference). I also > > tried setting the list to length 1, still no dice. The PySequence > > version segs under 2.4 and 2.5. It segs even when the Int is changed > > to a String. > > > > Yikes, I'll poke around some more. > > Yikes indeed. > > Not the OP's problem, but a bug in the manual: example in the chapter > that the OP was reading acts as though the 2nd arg to PyObject_SetItem > is a C int (as it is for the List and Sequence varieties) -- it is in > fact a (PyObject *), which explains the SystemError that I got. The good news is that this is a documentation problem. When working at the C level you use the concrete API when you can (PyList_*) and at the abstract level (PySequence_*) only when someone passes you something and you don't know what it is, you only know it supports the Sequence API. The exmample should use the PyList API to construct the list. The Sequence API requires valid objects to work. Here the object is only half constructed and list_ass_item tries to DECREF the zeroth member which is NULL because the list isn't constructed yet. PyList_SetItem does an XDECREF (decrement only if the pointer isn't null) because it expects to be used that way. -Jack From olbion at gmail.com Tue Aug 15 04:07:14 2006 From: olbion at gmail.com (olbion at gmail.com) Date: 15 Aug 2006 01:07:14 -0700 Subject: Making a multithread app that runs several instances of whatever the app did before Message-ID: <1155629233.985335.56660@p79g2000cwp.googlegroups.com> Hi I've aquired a program written in Python, and without much knowledge of the language I'm trying to make some changes to it. The original program starts, runs a certain process and then finishes. I want to adapt it so that, at a certain stage of the process, a new process is started from scratch, running at the same time as the original one. When the original one is finished, it should exit without causing the newer process to stop. I've successfully achieved this using sys.popen methods to start separate processes, but come to realise that running seperate processes is not a very good solution, since it uses up more memory and becomes harder to manage. I'd like the same thing to be achieved using threads. I've come as far as being able to start the program which runs the first thread. My problem arrises when I want the new thread to be started. It seems that if I do this by calling a function from within the thread, I'm unable to stop the original thread whenever that finishes. I imagine that what I've achieved is something like: Start file (eg start.py) starts Thread 1 Thread 1 starts a new thread (Thread 2) and becomes the parent of that thread Thread 2 starts a new thread (Thread 3)... and so on I think that what I want is something like: Start file starts Thread 1 Thread 1 informs start file that a new thread should be started; start file starts Thread 2 ... and so on So, if my thinking so far is correct, how can a thread cause another thread to be started without becoming its parent? From jaysherby at gmail.com Tue Aug 8 22:16:38 2006 From: jaysherby at gmail.com (jaysherby at gmail.com) Date: 8 Aug 2006 19:16:38 -0700 Subject: newb question: file searching In-Reply-To: <1155089548.659249.216390@b28g2000cwb.googlegroups.com> References: <1155067111.892386.130610@n13g2000cwa.googlegroups.com> <1155084224.829101.63940@i42g2000cwa.googlegroups.com> <1155087242.679420.128830@m73g2000cwd.googlegroups.com> <1155087903.857917.127540@m79g2000cwm.googlegroups.com> <1155089548.659249.216390@b28g2000cwb.googlegroups.com> Message-ID: <1155089798.320117.292730@m79g2000cwm.googlegroups.com> I'm sorry. I didn't mean to offend you. I never thought your way was inferior. Justin Azoff wrote: > jaysherby at gmail.com wrote: > > I do appreciate the advice, but I've got a 12 line function that does > > all of that. And it works! I just wish I understood a particular line > > of it. > > You miss the point. The functions I posted, up until get_files_by_ext > which is the equivalent of your getFileList, total 17 actual lines. > The 5 extra lines give 3 extra features. Maybe in a while when you > need to do a similar file search you will realize why my way is better. > > [snip] > > The line I don't understand is: > > reversed(range(len(dirnames))) > > This is why I wrote and documented a separate remove_hidden function, > it can be tricky. If you broke it up into multiple lines, and added > print statements it would be clear what it does. > > l = len(dirnames) # l is the number of elements in dirnames, e.g. 6 > r = range(l) # r contains the numbers 0,1,2,3,4,5 > rv = reversed(r) # rv contains the numbers 5,4,3,2,1,0 > > The problem arises from how to remove elements in a list as you are > going through it. If you delete element 0, element 1 then becomes > element 0, and funny things happen. That particular solution is > relatively simple, it just deletes elements from the end instead. That > complicated expression arises because python doesn't have "normal" for > loops. The version of remove_hidden I wrote is simpler, but relies on > the even more obscure lst[:] construct for re-assigning a list. Both > of them accomplish the same thing though, so if you wanted, you should > be able to replace those 3 lines with just > > dirnames[:] = [d for d in dirnames if not d.startswith('.')] > > > -- > - Justin From sjmachin at lexicon.net Mon Aug 14 17:28:58 2006 From: sjmachin at lexicon.net (John Machin) Date: 14 Aug 2006 14:28:58 -0700 Subject: Memory problem In-Reply-To: References: Message-ID: <1155590938.397801.302110@h48g2000cwc.googlegroups.com> Yi Xing wrote: > I tried the following code: > > >>> i=0 > >>> n=2600*2600*30 > >>> a=array.array("f") > >>> while (i<=n): > .. i=i+1 > .. a.append(float(i)) Not a good idea. The array has to be resized, which may mean that a realloc won't work because of fragmentation, you're out of luck because plan B is to malloc another chunk, but that's likely to fail as well. > .. > Traceback (most recent call last): > File "", line 3, in ? > MemoryError > > to see the size of the array at the time of memory error: > >>>len(a) > 8539248. Incredible. That's only 34 MB. What is the size of your paging file? What memory guzzlers were you running at the same time? What was the Task Manager "Performance" pane showing while your test was running? What version of Python? FWIW I got up to len(a) == 122998164 (that's 14 times what you got) on a machine with only 1GB of memory and a 1523MB paging file, with Firefox & ZoneAlarm running (the pagefile was showing approx 300MB in use at the start of the test). > I use Windows XP x64 with 4GB RAM. Maybe there's a memory allocation problem with the 64-bit version. Maybe MS just dropped in the old Win95 memory allocator that the timbot used to fulminate about :-( Cheers, John From michiel at thingmajig.org Mon Aug 7 09:48:48 2006 From: michiel at thingmajig.org (Michiel Sikma) Date: Mon, 7 Aug 2006 15:48:48 +0200 Subject: is it possible to dividing up a class in multiple files? In-Reply-To: References: Message-ID: <3084484B-A0E4-42EB-A7B3-DE37ED2D79A9@thingmajig.org> Hi Martin, I don't think that's possible, since a file is executed when it is imported. If you load a file which contains a "partial" class, you will get an error because the indentation is incorrect, or the methods will be loaded in the wrong namespace. Regards, Michiel Op 7-aug-2006, om 15:41 heeft Martin H?fling het volgende geschreven: > Hi there, > > is it possible to put the methods of a class in different files? I > just > want to order them and try to keep the files small. > > Regards > Martin > -- > http://mail.python.org/mailman/listinfo/python-list From 31337one at gmail.com Tue Aug 1 18:26:31 2006 From: 31337one at gmail.com (31337one at gmail.com) Date: 1 Aug 2006 15:26:31 -0700 Subject: Coloring tkinter dialogs Message-ID: <1154471191.225705.275820@m73g2000cwd.googlegroups.com> If I use the dialog template for tkinter, how do I go about customizing its color? Thanks From jorge.vargas at gmail.com Thu Aug 31 23:06:01 2006 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Thu, 31 Aug 2006 23:06:01 -0400 Subject: SQLObject or SQLAlchemy? In-Reply-To: References: Message-ID: <32822fe60608312006h2e389d27ve9c9a0454fe65e33@mail.gmail.com> On 8/31/06, John Salerno wrote: > Are there any major differences between these two? It seems they can > both be used with TurboGears, and SQLAlchemy with Django. I'm just > wondering what everyone's preference is, and why, and if there are even > more choices for ORM. > they use two approach to the same problem. SO tries to tide each object to a table while SA lets you do the mapping. so each one has it's pros and cons. for example SA wins at using an existing db but SO wins at not worring about the db structure SO demands tables to have a primary single col int key which is manage by the API, while SA lets you mess with it a bit more. so you could say that SO takes care about many things so you don't have to worry about them, or other may say SO is too intrusive. In my experience SO is great for new projects and if you don't want to mess/optimize with the actual SQL queries (which is great for an ORM because IMO that is the main goal of ORMing) Now if you need to mess a lot with the db (either a existing one or need optimized queries) then SA is worth the extra effort, since making those things on SO is going uphill. > Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list > From jmdeschamps at gmail.com Sun Aug 6 18:52:02 2006 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 6 Aug 2006 15:52:02 -0700 Subject: Trouble displaying image with tkinter In-Reply-To: References: Message-ID: <1154904722.105028.243480@75g2000cwc.googlegroups.com> sj wrote: > I am just learning to use Tkinter and am having problems displaying image > files. I am able to display an image using tutorials (such as > http://www.daniweb.com/code/snippet296.html) But when I try my own code all > I get is an empty widget. What is wrong with the following program? > > > > from Tkinter import * > > class Foo(Frame): > > def __init__(self,master=None): > Frame.__init__(self,master) > self.pack() > self.createWidgets() > > > def createWidgets(self): > > self.qbutton = Button(self) > self.qbutton["text"] = "Quit" > self.qbutton["command"] = self.quit > self.qbutton.pack(side = "top") > > idata = > PhotoImage(file="/home/sj/documents/projects/xaed/images/cat_001.gif") > > canvas = Canvas(width=300,height=200) > canvas.pack(side="top",fill=BOTH,expand=YES) > canvas.create_image(50,10,image=idata,anchor=NW) > > ## lab = Label(self,image=idata) > ## lab.pack(side=TOP) > > > root = Tk() > app = Foo(root) > app.mainloop() > #app.destroy() If you keep a reference of the photoImage object then it will work! ... self.idata= PhotoImage(file="/home/sj/documents/projects/xaed/images/cat_001.gif") ... canvas.create_image(50,10,image=iself.data,anchor=NW) ... By making the PhotoImage an attribute of your object, you keep a reference that the garbage collector will NOT collect, So you're image will continue to exist and thus be rendered by the canvas. JM From bearophileHUGS at lycos.com Wed Aug 9 16:14:07 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 9 Aug 2006 13:14:07 -0700 Subject: technique to enter text using a mobile phone keypad (T9 dictionary-based disambiguation) In-Reply-To: <1155095477.440347.149350@m79g2000cwm.googlegroups.com> References: <1155095477.440347.149350@m79g2000cwm.googlegroups.com> Message-ID: <1155154447.409931.55750@p79g2000cwp.googlegroups.com> Justin Azoff: > It takes a second or two to read the list of words in, Nice solution. If you want to speed up the initialization phase you may use something like this (it requires a bit more memory, because lines contains all the words). Note that the words and numbers have the same sorting order, so you may use this to speed up the sorting a little, like doing it on words only (that is the lines list), but for small dictionaries sort is fast enough already, so this isn't much important. Note: you have to add another 9 to numbers, because z too is associated to 9. import string class Phone: def __init__(self): numbers = '22233344455566677778889999' convtable = string.maketrans(string.lowercase, numbers) lines = file("/usr/share/dict/words").read().lower().splitlines() words = [] for line in lines: word = line.strip() nums = word.translate(convtable) words.append( (nums, word) ) words.sort() self.dict = words p = Phone() Bye, bearophile From cginboston at hotmail.com Thu Aug 24 15:56:10 2006 From: cginboston at hotmail.com (Chaz Ginger) Date: Thu, 24 Aug 2006 15:56:10 -0400 Subject: When is a subclass not right? In-Reply-To: References: <1156387621.568779.191420@m73g2000cwd.googlegroups.com> <1156393371.550249.138930@75g2000cwc.googlegroups.com> <1156394781.155152.313080@i3g2000cwc.googlegroups.com> <44ede9b8$0$8925$88260bb3@free.teranews.com> Message-ID: <44EE045A.8080207@hotmail.com> Fredrik Lundh wrote: > please don't hit reply to arbitrary messages when you're posting new > messages; it messes up the message threading. > > Chaz Ginger wrote: > >> I was writing some code that used someone else class as a subclass. He >> wrote me to tell me that using his class as a subclass was incorrect. >> I am wondering under what conditions, if ever, does a class using a >> subclass not work. > > your terminology is confused: if you inherit from another class, *your* > class is the subclass, while the class you inherit from is known as a > "base class" or "super class". > > a subclass will share the instance namespace with the base class, which > means, among other things, that you may accidentally override internal > attributes and methods, and thus break the base class. > > and even if it appears to work now, it may break when you upgrade the > base class. or when you end up in a code path that you haven't tested > before. > > > Sorry for the threading screw up. I thought I had just hit the write button. I understand when my class overrides the super class. But that would just be "normal" class related things. I was wondering if there was something more subtle I am missing in Python class handling. Chaz From riko at despammed.com Tue Aug 22 19:31:01 2006 From: riko at despammed.com (Mc Osten) Date: Wed, 23 Aug 2006 01:31:01 +0200 Subject: Python and STL efficiency References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <1hkh28d.xscw4v1y4v9a6N%riko@despammed.com> <1156281418.697442.23000@i3g2000cwc.googlegroups.com> Message-ID: <1hki04u.1yzdus01uhhuucN%riko@despammed.com> Tim N. van der Leeuw wrote: > NB: Your code now tests for address-equality. Does it also still test > for string-equality? It looks to me that it does, but it's not quite > clear to me. It does it. set b(a.begin(), a.end()); set c; // well ordered set (b is ordered by address) for (set::iterator it=b.begin(); it!=b.end(); it++) c.insert(**it); copy(c.begin(), c.end(), ostream_iterator(cout, "\n")); When we populate the first set, we get rid of all strings with same object id/address (it test equality of pointers). Then we populate another set (and the default equality test is on strings). However, I would have written the code using a proper compare function rather than using two sets. In this particular case the number of elements of the first set is negligible in respect of the initial vector size, thus copying it again does not take a lot of time. But such code is optimized for the problem itself: in the real world I suppose we would have passed set a proper comparison function that checks address and then string equality. -- blog: http://www.akropolix.net/rik0/blogs | Uccidete i filosofi, site: http://www.akropolix.net/rik0/ | tenetevi riso e forum: http://www.akropolix.net/forum/ | bacchette per voi. From horpner at yahoo.com Thu Aug 24 08:39:46 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 24 Aug 2006 14:39:46 +0200 Subject: Python and STL efficiency References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <1hkh28d.xscw4v1y4v9a6N%riko@despammed.com> <1hkh6lb.6dsnh51lj8z96N%riko@despammed.com> <1156252193.524186.107520@b28g2000cwb.googlegroups.com> <1hkhexv.18m65rl61swqyN%riko@despammed.com> <1156265848.875774.251640@i42g2000cwa.googlegroups.com> <1156290607.269119.88710@b28g2000cwb.googlegroups.com> <1hkil6j.xm4l6y1kwo13dN%riko@despammed.com> <1156317315.946762.215690@p79g2000cwp.googlegroups.com> <1hkioxy.42be4c1lg0jq5N%riko@despammed.com> <1156320792.011620.141030@m79g2000cwm.googlegroups.com> <1hkitqt.c17kl5o30nr4N%riko@despammed.com> <1156340217.774595.282950@75g2000cwc.googlegroups.com> <1156343260.399048.182310@m73g2000cwd.googlegroups.com> <1hkjdnl.1pw8bkv892pxcN%riko@despammed.com> Message-ID: On 2006-08-23, Mc Osten wrote: > Ray wrote: >> Great to know that my model of how the world works is still >> correct! (at least in relation to Python and C++!) :) > > So please explain my results. I loop the same number of times. Those of you experiencing a temporary obsession with this topic are encouraged to study The Great Language Shootout, until the obsession goes away. ;) Your time might not be totally wasted; an opportunity to improve the Python solutions may present itself. http://shootout.alioth.debian.org/ -- Neil Cerutti Strangely, in slow motion replay, the ball seemed to hang in the air for even longer. --David Acfield From jiangnutao at gmail.com Wed Aug 23 21:26:55 2006 From: jiangnutao at gmail.com (Jason Jiang) Date: Wed, 23 Aug 2006 18:26:55 -0700 Subject: how to get file name of the running .py file References: <1156377386.047314.216020@i3g2000cwc.googlegroups.com> Message-ID: Thank you guys. Jason "Simon Forman" wrote in message news:1156377386.047314.216020 at i3g2000cwc.googlegroups.com... > Larry Bates wrote: >> Jason Jiang wrote: >> > Hi, >> > >> > How to get the name of the running .py file like the macro _FILE_ in C? >> > >> > Thanks. >> > Jason >> > >> > >> > >> import os >> import sys >> print sys.argv[0] >> >> or if you just want the script and not the full path >> >> print os.path.basename(sys.argv[0]) >> >> -Larry Bates > > Also, check out: > http://groups.google.ca/group/comp.lang.python/browse_frm/thread/712572b3c2f2cb13 > > Peace, > ~Simon > > -- > http://mail.python.org/mailman/listinfo/python-list > From krugman at t-online.de Sat Aug 19 09:34:06 2006 From: krugman at t-online.de (Frank Krugmann) Date: Sat, 19 Aug 2006 15:34:06 +0200 Subject: Zope hosting Message-ID: I'am searching a cheap ZPP Hoster. Some informations? Greetings Escorial2000 From bdesth.quelquechose at free.quelquepart.fr Sun Aug 6 07:00:40 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 06 Aug 2006 13:00:40 +0200 Subject: Using Python for my web site In-Reply-To: <1154542090.924003.47670@i3g2000cwc.googlegroups.com> References: <1154361480.915174.262720@b28g2000cwb.googlegroups.com> <44ce3a5c$0$18952$626a54ce@news.free.fr> <44d0e0a3$0$32434$626a54ce@news.free.fr> <1154542090.924003.47670@i3g2000cwc.googlegroups.com> Message-ID: <44d5c9c2$0$8599$636a55ce@news.free.fr> Paul Boddie a ?crit : > Bruno Desthuilliers wrote: > >>To make a long story short, my opinion is that the only sensible thing >>to do with Windows is to wipe it out and install an OS instead. > > > If you're convinced you won't be running Windows, why deal with the > problem so late in the game? Instead, order a system from a vendor who > won't ship an operating system you aren't going to use. Paul, I'm afraid you're answering to the wrong person here... FWIW, at my company, we made a deal with the local PC shop : we together maintain the gentoo-based distro that runs on our machines, and that he also offers to his other customers... From cginboston at hotmail.com Thu Aug 24 15:23:08 2006 From: cginboston at hotmail.com (Chaz Ginger) Date: Thu, 24 Aug 2006 19:23:08 GMT Subject: When is a subclass not right? In-Reply-To: References: <1156387621.568779.191420@m73g2000cwd.googlegroups.com> <1156393371.550249.138930@75g2000cwc.googlegroups.com> <1156394781.155152.313080@i3g2000cwc.googlegroups.com> <44ede9b8$0$8925$88260bb3@free.teranews.com> Message-ID: I was writing some code that used someone else class as a subclass. He wrote me to tell me that using his class as a subclass was incorrect. I am wondering under what conditions, if ever, does a class using a subclass not work. Here is an example. For instance the original class might look like: class A : def __init__(self,arg) : self.foo = arg def bar(self) : return self.foo And I defined a class B1 which looked like: class B1(A); def __init__(self,a1,a2) : self.c = a1 A.__init__(self,ag) He said I should use it this way: class B2: def __init__(self,a1,a2): self.c = a1 self.t = A(a2) def bar(self) : self.t.bar() Other than the obvious difference of B2 having an attribute 't', I can't see any other obvious differences. Is there something I am missing? TIA Chaz From duncanm255 at hotmail.com Mon Aug 7 14:47:52 2006 From: duncanm255 at hotmail.com (D) Date: 7 Aug 2006 11:47:52 -0700 Subject: Installing a Windows Printer Message-ID: <1154976472.754129.222830@i3g2000cwc.googlegroups.com> I would like to create a script for Windows 2000 that will create a Standard TCP/IP printer port and install a printer (I have the applicable printer drivers needed for the install on a network share). My plan is to use py2exe and distribute (also via network share) the script so that administrators, or even users, can easily install the printer. Is this possible? If so, I would appreciate it if someone could steer me in the right direction in terms of how to begin (i.e. libraries needed, sample code). Thanks! From duncan.booth at invalid.invalid Mon Aug 28 07:44:29 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Aug 2006 11:44:29 GMT Subject: when is a != foo.a? References: Message-ID: Chaz Ginger wrote: > Can someone explain what is really going on here? Think of 'from x import y' as an assignment. Roughly equivalent to: y = sys.modules['x'].y (except of course you don't have to have imported sys, and it will load the module 'x' if it hasn't already been imported.) > b.py ---------------------- > > from a import foo In other words: foo = a.foo foo in module b is initialised from a.foo, but it is a separate variable. So when a.foo is rebound that doesn't affect b.foo. > def b(): print foo > > c.py ---------------------- > > import a > from b import b and here: b = b.b > > print 'per a.a() ',a.foo > a.a(245) > print 'expect 245 ', a.foo > b() > From yxing at stanford.edu Tue Aug 15 19:05:34 2006 From: yxing at stanford.edu (Yi Xing) Date: Tue, 15 Aug 2006 16:05:34 -0700 Subject: MySQLdb installation error Message-ID: <4a60f6155fd2fa117438ab1b0864caf9@stanford.edu> Hi, I met the following error when I tried to install MySQLdb. I had no problem installing numarray, Numeric, Rpy, etc. Does anyone know what's the problem? Thanks! running install running build running build_py creating build creating build/lib.darwin-7.9.0-Power_Macintosh-2.4 copying _mysql_exceptions.py -> build/lib.darwin-7.9.0-Power_Macintosh-2.4 creating build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb copying MySQLdb/__init__.py -> build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb copying MySQLdb/converters.py -> build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb copying MySQLdb/connections.py -> build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb copying MySQLdb/cursors.py -> build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb copying MySQLdb/release.py -> build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb copying MySQLdb/times.py -> build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb creating build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -> build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.darwin-7.9.0-Power_Macintosh-2.4/MySQLdb/constants running build_ext building '_mysql' extension creating build/temp.darwin-7.9.0-Power_Macintosh-2.4 gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -fno-common -dynamic -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I/usr/include/mysql -I/Library/Frameworks/Python.framework/Versions/2.4/include/python2.4 -c _mysql.c -o build/temp.darwin-7.9.0-Power_Macintosh-2.4/_mysql.o -fno-omit-frame-pointer -arch i386 -arch ppc -pipe -Dversion_info="(1,2,1,'final',2)" -D__version__="1.2.1_p2" gcc: cannot read specs file for arch `i386' error: command 'gcc' failed with exit status 1 From dppdoran at gmail.com Thu Aug 31 10:24:01 2006 From: dppdoran at gmail.com (Dermot Doran) Date: Thu, 31 Aug 2006 16:24:01 +0200 Subject: How to avoid a warning message box when sending email via Outlook In-Reply-To: <1157021468.496429.165460@i3g2000cwc.googlegroups.com> References: <1157021468.496429.165460@i3g2000cwc.googlegroups.com> Message-ID: Hi Giles, Yep, the admin can override this. I've been doing some of my own hunting around and it would appear that you can: - Resolve this if you have admin rights. - Use Outlook Redemption http://www.dimastr.com/redemption/ - Use Extended MAPI - Install ClickYes http://www.contextmagic.com/ - Have the Enterprise migrate to Linux! Yes!! Thanks for responding! Cheers!! Dermot. P.S. Apologies for top posting (doing this quickly via GMail)! On 31 Aug 2006 03:51:08 -0700, Giles Brown wrote: > > Tim Golden wrote: > > > [Dermot Doran] > > > > | I'm very new to using win32com! I just want to send an email > > | message via Outlook. However, I keep getting an annoying > > | message box (generated by Outlook) indicating that my program > > | could be a virus. Does anybody know how to get around this? > > > > As far as I've ever been able to tell, you're stuck with it. > > Obviously, in a sense, since otherwise any would-be virus / > > zombie program would simply turn the option off before using > > Outlook to send out its emails! > > Can't remember the details, but last time I looked (a year ago) you > could avoid this if you changed a setting for the user at the exchange > server. I found this out by doing a bit of googling and > can't remember what I did, but managed to solve the same problem. > > Giles > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From samuraiblog at gmail.com Fri Aug 4 19:53:05 2006 From: samuraiblog at gmail.com (samuraisam) Date: 4 Aug 2006 16:53:05 -0700 Subject: MVC for wxWidgets or Tkinter? Message-ID: <1154735585.120218.243640@i3g2000cwc.googlegroups.com> Are there any MVC-framework-like libraries for wxWidgets or Tkinter for Python? If so, any experiences with using them? I need to develop a desktop application *fast* and experiences with the likes of Turbogears have taught me that you can indeed develop very fast with a framework and the MVC structure seems to work very well. Thanks, Sam From sile_brennan at hotmail.com Fri Aug 18 04:10:04 2006 From: sile_brennan at hotmail.com (Sile) Date: 18 Aug 2006 01:10:04 -0700 Subject: python-dev and setting up setting up f2py on Windows XP In-Reply-To: <1155772555.802594.252590@74g2000cwt.googlegroups.com> References: <1155744270.092818.256290@i42g2000cwa.googlegroups.com> <1155772555.802594.252590@74g2000cwt.googlegroups.com> Message-ID: <1155888603.941995.107850@i42g2000cwa.googlegroups.com> Hi John, Thank you very much for your help and resolving my issue with "python-dev". I'll hopefully get my problem sorted today, if not I'm sure I'll be back with more questions! The C compiler I'm using is Microsoft Visual Studio 8. I have been told there are potential compatibility issues between this, my version of python and my fortran compiler. I have to use python 2.3 as it is compatible with a CFD package I'm using. I've resinstalled python properley so I'll persevere with my exsisting C compiler this morning and try MINGW32 if I have no joy. Thanks again, Sile John Machin wrote: > Sile wrote: > > Hi, > > > > I've been trying to get f2py working on Windows XP, I am using Python > > 2.3. I'm new to python so I'm not too sure what I'm doing yet. I need > > the python-dev package to run f2py. I have been told this is just the > > header files and .dll and I need to put them somewhere my C compiler > > can find them. I've searched the web and none of the python-dev > > packages I've found are for windows. I was wondering is this > > automatically part of the windows version and if so how I set it up so > > my C compiler can find them. If it is not part of the standard package > > does anyone know where I can find it??? > > > > Any help at all would be much appreciated. > > The concept of "python-dev package" is a Debian concept which doesn't > apply to Windows. The standard installation on Windows provides the > header and library files that you need for interfacing with C. > > Don't put things where your C compiler can find them; do a standard > no-frills install of Python2.4 using the .msi installer and tell your C > compiler where the goodies are. > > E.g. using the MinGW32 gcc, you'd need things like: > > gcc -I\python24\include -lpython24 -L\python24\libs > [first is "i".upper(), second is "L".lower()] > > Which C compiler are you using? > > You will need to add "C:\Python24" to the path so that you can invoke > python easily; that will also enable anything else finding python24.dll > if you do a "me only" install of Python. > > So give that a whirl and if you have any dramas, come back with > questions ... > > HTH, > John From cwarren89 at gmail.com Sat Aug 19 12:19:20 2006 From: cwarren89 at gmail.com (cwarren89 at gmail.com) Date: 19 Aug 2006 09:19:20 -0700 Subject: write eof without closing In-Reply-To: <1156004047.038032.26120@b28g2000cwb.googlegroups.com> References: <12eeala1klcrtcf@corp.supernews.com> <1156004047.038032.26120@b28g2000cwb.googlegroups.com> Message-ID: <1156004359.966226.292010@m79g2000cwm.googlegroups.com> Actually, nevermind. It appears that receiving an EOF from a stream tells it when to stop 'reading', not necessarily that the stream is closed. What a weird behavior. From mturillo at gmail.com Tue Aug 22 14:48:44 2006 From: mturillo at gmail.com (Perseo) Date: 22 Aug 2006 11:48:44 -0700 Subject: Create a Multilanguage PDF in Python In-Reply-To: <4ku5d0Fdsn8fU1@uni-berlin.de> References: <1156073383.983914.149180@i3g2000cwc.googlegroups.com> <87mz9z4f8h.fsf@smsnet.pl> <1156108451.762961.70140@h48g2000cwc.googlegroups.com> <1156143575.547217.237270@p79g2000cwp.googlegroups.com> <1156172609.125230.218190@i42g2000cwa.googlegroups.com> <4ku5d0Fdsn8fU1@uni-berlin.de> Message-ID: <1156272524.800930.27710@p79g2000cwp.googlegroups.com> Nothing to do! I enable test2.py and the folder with 777 permission and I write at the top of the file the PYTHONPATH "#!/usr/bin/python" as you told me but it doesn't works as well. this is my organization: www.domain.com/python/reportlab/ [all files] www.domain.com/python/test2.py #!/usr/bin/python print "Content-Type: text/html\n\n" print "Hello World" from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfgen import canvas pdfmetrics.registerFont(TTFont('Verdana', 'Verdana.ttf')) c = canvas.Canvas("pl.pdf") c.setFont("Verdana", 12) c.drawString(100, 600, "Witaj, ?wiecie!".decode("iso-8859-2").encode("utf-8")) c.showPage() c.save() The verdana font doesn't exist in the reportlab fonts folder. I try to delete the rows where it is called like (registerFont, setFont) but nothing to do. any suggestion?! Diez B. Roggisch wrote: > Perseo wrote: > > > I can't upload in the PYTHONPATH but in a normal folder of our site. > > Exist another way to do it? > > PYTHONPATH is an environment variable. You can set it to arbitrary paths, > and python will look for module there, too. Or you modify sys.path before > you try the import. > > Diez From bearophileHUGS at lycos.com Mon Aug 14 06:26:15 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 14 Aug 2006 03:26:15 -0700 Subject: yet another noob question In-Reply-To: References: <1155492110.659011.196280@75g2000cwc.googlegroups.com> Message-ID: <1155551175.877475.175790@h48g2000cwc.googlegroups.com> Stargaming: > Also note that reduce will be removed in Python 3000. Then let's use it until it lasts! :-) bearophile From fredrik at pythonware.com Wed Aug 30 07:02:09 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 30 Aug 2006 13:02:09 +0200 Subject: Odd unicode() behavior References: <1156933750.471407.161400@i42g2000cwa.googlegroups.com> Message-ID: maport at googlemail.com wrote: > The behavior of the unicode built-in function when given a unicode > string seems a little odd to me: > >>>> unicode(u"abc") > u'abc' > >>>> unicode(u"abc", "ascii") > Traceback (most recent call last): > File "", line 1, in ? > TypeError: decoding Unicode is not supported > > I don't see why providing the encoding should make the function behave > differently when given a Unicode string. Surely unicode(s) ought to > bahave exactly the same as unicode(s,sys.getdefaultencoding())? nope. if you omit the encoding argument, unicode() behaves pretty much like str(), using either the __unicode__ method or __str__/__repr__ + decoding to get a Unicode string. see the language reference for details, e.g: http://pyref.infogami.com/unicode From martin at v.loewis.de Tue Aug 8 15:27:33 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 08 Aug 2006 21:27:33 +0200 Subject: #!/usr/bin/python or #!/usr/bin/env python? In-Reply-To: References: Message-ID: <44d8e5a5$0$5567$9b622d9e@news.freenet.de> John Salerno schrieb: > I understand the difference, but I'm just curious if anyone has any > strong feelings toward using one over the other? I use /usr/bin/env if I don't know what the operating system is; some systems don't have Python in /usr/bin. I use /usr/bin/pythonX.Y if I want a specific version on a specific operating system (typically Linux). I use /usr/bin/python when I'm too lazy to think about it thoroughly. Regards, Martin From robert.kern at gmail.com Thu Aug 24 10:44:53 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 24 Aug 2006 09:44:53 -0500 Subject: Concatenating arrays In-Reply-To: <1156410860.815262.25770@i3g2000cwc.googlegroups.com> References: <1156410860.815262.25770@i3g2000cwc.googlegroups.com> Message-ID: Sheldon wrote: > Good day everyone, > > I would like to know if anyone has a fast and concise way of > concatenating two 2D arrays of same dimensions? > Whenever I try: > > a = concatenate(b,c) That is not the correct signature. a = concatenate((b, c)) -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From wegein at gmail.com Wed Aug 2 21:15:57 2006 From: wegein at gmail.com (damacy) Date: 2 Aug 2006 18:15:57 -0700 Subject: exception handling; python program that interacts with postgresql db Message-ID: <1154567757.143305.19910@75g2000cwc.googlegroups.com> hi, there. i have this question which might sound quite stupid to some people, but here we go anyway. i have written a python program which interacts with a postgresql database. what it does is simply drops an existing database called 'mytempdb'. the code looks like below; link = subprocess.Popen(command, stdin = subprocess.PIPE, stdout = subprocess.PIPE, shell = True) link.communicate(password) link.wait() where command looks like "psql -h 127.0.0.1 -U postgres -W -f filename" and filename is the name of the file which contains a single SQL command which is "drop database mytempdb". the program works fine as long as a correct password is supplied, however, i have a problem if the password is incorrect since this exception is *not* handled within the scope of my program, instead, what is does is showing some error messages in the prompt. so my program, without knowing whether an errors has taken place or not, goes on to execute the next task. any clue? please let me know if you think the problem is not well addressed. =) thanks. have a nice one. From marco.wahl at gmail.com Tue Aug 29 02:04:08 2006 From: marco.wahl at gmail.com (Marco Wahl) Date: 28 Aug 2006 23:04:08 -0700 Subject: unit test for a printing method In-Reply-To: References: <1156780399.289589.58750@m73g2000cwd.googlegroups.com> <44f330ce$1@nntp0.pdx.net> Message-ID: <1156831448.829576.140240@h48g2000cwc.googlegroups.com> > [OP] What is the proper way to test (using unit test) a method that print > information? > [...] Fredrik Lundh writes: > > Scott David Daniels wrote: > >> For silly module myprog.py: >> def A(s): >> print '---'+s+'---' >> in test_myprog.py: >> import unittest >> from cStringIO import StringIO # or from StringIO ... > > why are you trying to reinvent doctest ? The OP asked for unit test. This could be read that the OP wants to use module unittest. From sjmachin at lexicon.net Sat Aug 12 20:32:00 2006 From: sjmachin at lexicon.net (John Machin) Date: 12 Aug 2006 17:32:00 -0700 Subject: Read a file with open command References: <1155288288.954142.293000@i3g2000cwc.googlegroups.com> <1155316508.381805.56520@m73g2000cwd.googlegroups.com> <1155389042.226429.126170@m79g2000cwm.googlegroups.com> Message-ID: <1155429120.678074.27400@i42g2000cwa.googlegroups.com> gslindstrom at gmail.com wrote: [snip] > My point is that this is a wonderful service you tutors provide, but > the Zappa signature may not be the best choice for this setting. This is *not* the tutor list. >Most people will read it and get a laugh (as did I), but how many have taken > it the way jean-jeanot did and walk away feeling insulted? How many > will not post a response expressing their feelings, never post a > question again or, worst case, decide Python is not for them? Possibly one, were he still alive: St Aloysius "of whom it is said in the book of the monk Eustachius that when he heard a man breaking wind with deafening noise he immediately burst into tears and could only be consoled by prayers" [from "The Good Soldier ?vejk ..." by Jaroslav Ha?ek [tr. Parrott (the Sir Cecil variety, not the Norwegian Blue)]] Cheers, John From srikrishnamohan at gmail.com Tue Aug 29 08:47:47 2006 From: srikrishnamohan at gmail.com (km) Date: Tue, 29 Aug 2006 18:17:47 +0530 Subject: subprocess woes Message-ID: Hi all, I have a strange question. a program on shell looks as follows: $cat test.fa |fasta34 -q @ s where test.fa contains a protein sequence (alphabets); s is the database to be searched and @ +indicates that the input is from stdin (ie., 'cat test.fa') now instead of 'cat test.fa' i take that input into a varaible and want to feed it to the +program. I have a sequence string in a variable named x, and use subprocess module to wrap this: ######code start ###### import subprocess as sp x = 'GSQIPSHYWKKNLWYYSHEIDGGCHNMW' p0 = sp.Popen(["echo",x], stdout=sp.PIPE) p1 = sp.Popen(["fasta34","-q","@",s],stdin=p0.stdout, stdout=sp.PIPE) output = p1.communicate()[0] print output ########code end##### Output for this code doesnt give me the result as the program senses the input as empty let me know where i am wrong. The idea is to pipe-input the string to the program as a variable as mentioned above. regards, KM From python.list at tim.thechases.com Thu Aug 24 12:12:14 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 24 Aug 2006 11:12:14 -0500 Subject: sum and strings In-Reply-To: References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <1155922208.930580.135080@m79g2000cwm.googlegroups.com> <1156365271.487489.62640@m73g2000cwd.googlegroups.com> <44ECC789.1010202@tim.thechases.com> Message-ID: <44EDCFDE.9060604@tim.thechases.com> >> Just because something is slow or sub-optimal doesn't mean it >> should be an error. > > that's not an error because it would be "slow or sub-optimal" to add > custom objects, that's an error because you don't understand how "sum" > works. > > (hint: sum != reduce) No, clearly sum!=reduce...no dispute there... so we go ahead and get the sum([q1,q2]) working by specifying a starting value sum([q1,q2], Q()): >>> class Q(object): ... def __init__(self, n=0, i=0,j=0,k=0): ... self.n = n ... self.i = i ... self.j = j ... self.k = k ... def __add__(self, other): ... return Q(self.n+other.n, ... self.i+other.i, ... self.j+other.j, ... self.k+other.k) ... def __repr__(self): ... return "" % ( ... self.n, ... self.i, ... self.j, ... self.k) ... >>> q1 = Q(1,2,3,5) >>> q2 = Q(7,11,13,17) >>> q1+q2 >>> sum([q1,q2]) Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand type(s) for +: 'int' and 'Q' >>> sum([q1,q2], Q()) Thus, sum seems to work just fine for objects containing an __add__ method. However, strings contain an __add__ method. >>> hasattr("", "__add__") True yet, using the same pattern... >>> sum(["hello", "world"], "") Traceback (most recent call last): File "", line 1, in ? TypeError: sum() can't sum strings [use ''.join(seq) instead] Which seems like an arbitrary prejudice against strings...flying in the face of python's duck-typing. If it has an __add__ method, duck-typing says you should be able to provide a starting place and a sequence of things to add to it, and get the sum. However, a new sum2() function can be created... >>> def sum2(seq, start=0): ... for item in seq: ... start += item ... return start ... which does what one would expect the definition of sum() should be doing behind the scenes. >>> # generate the expected error, same as above >>> sum2([q1,q2]) Traceback (most recent call last): File "", line 1, in ? File "", line 3, in sum2 TypeError: unsupported operand type(s) for +=: 'int' and 'Q' >>> # employ the same solution of a proper starting point >>> sum2([q1,q2], Q()) >>> # do the same thing for strings >>> sum2(["hello", "world"], "") 'helloworld' and sum2() works just like sum(), only it happily takes strings without prejudice. From help(sum): "Returns the sum of a sequence of numbers (NOT strings) plus the value of parameter 'start'. When the sequence is empty, returns start." It would be as strange as if enumerate() didn't take strings, and instead forced you to use some other method for enumerating strings: >>> for i,c in enumerate("hello"): print i,c Traceback (most recent call last): File "", line 1, in ? TypeError: enumerate() can't enumerate strings [use "hello".enumerator() instead] Why the arbitrary breaking of duck-typing for strings in sum()? Why make them second-class citizens? The interpreter is clearly smart enough to recognize when the condition occurs such that it can throw the error...thus, why not add a few more smarts and have it simply translate it into "start+''.join(sequence)" to maintain predictable behavior according to duck-typing? -tkc From bill.pursell at gmail.com Thu Aug 24 00:29:32 2006 From: bill.pursell at gmail.com (Bill Pursell) Date: 23 Aug 2006 21:29:32 -0700 Subject: how to get file name of the running .py file In-Reply-To: References: Message-ID: <1156393772.108493.116780@b28g2000cwb.googlegroups.com> Jason Jiang wrote: > Hi, > > How to get the name of the running .py file like the macro _FILE_ in C? There are many ways--IMO the easiest is with __file__: >>> print __file__ /home/bill/.pystart >>> [tmp]$ cat foo.py #!/usr/bin/env python print "The name of the file is:%s"%__file__ [tmp]$ ./foo.py The name of the file is:./foo.py From tim.leeuwvander at nl.unisys.com Mon Aug 21 08:55:34 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 21 Aug 2006 05:55:34 -0700 Subject: Help in using introspection to simplify repetitive code In-Reply-To: References: <1156090845.875872.41220@75g2000cwc.googlegroups.com> <1156151567.580811.55380@h48g2000cwc.googlegroups.com> Message-ID: <1156164934.464507.280300@i3g2000cwc.googlegroups.com> Fredrik Lundh wrote: > jsceballos at gmail.com wrote: > > > And they do take arguments, and a variable number of them, so AFAIK > > hooking with __getattr__ or __getattribute__ will not work, as you can > > only get the method name with that. > > why not just return the bound method *object* (a callable), and let the > caller call that as usual (see Terry's last example). > > (hint: x.foo() can be written f=getattr(x,"foo"); f()) > > > I can tell you from my experience that this works; I've used this before to make something very much like this proxy-class: class RequestCalculations(object): def __init__(self, request): self.serviceType, self.facade = makeMessageFacadeInstance(request) return def __getattr__(self, name): return getattr(self.facade, name) (rest of the code omitted) Cheers, --Tim From frikker at gmail.com Mon Aug 21 11:03:12 2006 From: frikker at gmail.com (frikker at gmail.com) Date: 21 Aug 2006 08:03:12 -0700 Subject: Python Syntax Highlighting Module Message-ID: <1156172592.903109.172520@p79g2000cwp.googlegroups.com> Hello, I have an idea for a project which involves an editor that supports syntax highlighting. This would be for any language, particularly php, html, css, etc. I would like to write this program using python. It would only make sense to base this upon existing open source code. My question is there a python module or examples on how to write a code editor which supports modulated syntax highlighting? Thank you, Blaine From fabiofz at gmail.com Tue Aug 8 09:36:19 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Tue, 8 Aug 2006 10:36:19 -0300 Subject: Looking for an intellisense with good help IDE for Python In-Reply-To: <1155022590.845074.256900@i42g2000cwa.googlegroups.com> References: <1155022590.845074.256900@i42g2000cwa.googlegroups.com> Message-ID: On 8 Aug 2006 00:36:30 -0700, metaperl wrote: > > Hi, > > I would like an IDE that shows me all methods and functions I can call > on a particular data item. For instance, iter() can be called on any > sequence, but it is not a method. > > Nonetheless, I would like for something to show me every thing that I > can call on a particular data item. > > This includes % after a string. > > I would also like browseable help with good examples on whatever > methods and functions and operators it pops up. > > Thanks, > Terrence > > Have you checked pydev: http://pydev.sf.net Cheers, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: From fhurley at gmail.com Tue Aug 1 11:41:46 2006 From: fhurley at gmail.com (fhurley at gmail.com) Date: 1 Aug 2006 08:41:46 -0700 Subject: Can't get LCHARVAR's with InformixDB In-Reply-To: References: <1154437329.471918.35150@h48g2000cwc.googlegroups.com> <1154438862.714569.9130@b28g2000cwb.googlegroups.com> Message-ID: <1154446906.915203.13790@m73g2000cwd.googlegroups.com> Carsten Haese wrote: > Could you possibly send me a minimal test script that shows the problem? > Also, in case it matters, I'd like to know which versions of IDS and > CSDK or Informix Connect you're using. Here's a sample script: sql = '''select msg_tx from dev_log''' import informixdb conn = informixdb.connect('mydb') cursor = conn.cursor() cursor.execute(sql) print 'description is <%s>' % cursor.description print cursor.fetchall() Output is: description is <('msg_tx', 'lvarchar', 0, 0, None, None, 1)> [('',), ('',), ('',), ('',), ('',), ('',)] But one of them should be: '''Something:SomethingElse - going for 221 possibilities [User: HOST-NAME\XYZZY]: Id OtherData 5878 C 5968 X 6732 V [many more lines like this] ''' Some hunting around, and I found this: C:\Program Files\Informix\Client-SDK\bin>esql IBM Informix CSDK Version 2.80, IBM Informix-ESQL Version 9.52.TC1 Not sure what IDS is... the Informix Server version is: 9.3 FC3, according to the DBA guy. Thanks much. From jo at durchholz.org Tue Aug 29 06:50:52 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Tue, 29 Aug 2006 12:50:52 +0200 Subject: A Sort Optimization Technique: decorate-sort-dedecorate In-Reply-To: <280820061150081729%jgibson@mail.arc.nasa.gov> References: <1156719092.603277.57390@b28g2000cwb.googlegroups.com> <1156723602.192984.49610@m79g2000cwm.googlegroups.com> <280820061150081729%jgibson@mail.arc.nasa.gov> Message-ID: Jim Gibson schrieb: > > The problem addressed by what is know in Perl as the 'Schwartzian > Transform' is that the compare operation can be an expensive one, > regardless of the whether the comparison uses multiple keys. Since in > comparison sorts, the compare operation will be executed N(logN) times, > it is more efficient to pre-compute a set of keys, one for each object > to be sorted. That need be done only N times. Wikipedia says it's going from 2NlogN to N. If a sort is massively dominated by the comparison, that could give a speedup of up to 100% (approximately - dropping the logN factor is almost irrelevant, what counts is losing that factor of 2). Regards, Jo From metaperl at gmail.com Wed Aug 30 11:18:13 2006 From: metaperl at gmail.com (metaperl) Date: 30 Aug 2006 08:18:13 -0700 Subject: Best Practices for Python Script Development? In-Reply-To: <1156515299.257203.283170@m73g2000cwd.googlegroups.com> References: <1156471481.265329.291360@m79g2000cwm.googlegroups.com> <1156515299.257203.283170@m73g2000cwd.googlegroups.com> Message-ID: <1156951093.869929.214750@74g2000cwt.googlegroups.com> Ant wrote: > > `Pydoc `_ seems to be > > built around modules and I want to document scripts. > > Any python script *is* a python module. So pydoc is what you are after > here. Yes, but Lundh's PythonDoc looks good too. I'm inclined to go with that. From antroy at gmail.com Mon Aug 7 11:16:17 2006 From: antroy at gmail.com (Ant) Date: 7 Aug 2006 08:16:17 -0700 Subject: screensaver in Python In-Reply-To: References: Message-ID: <1154963777.637581.306290@n13g2000cwa.googlegroups.com> daniel Van der Borght wrote: > Programming a screensaver in Python, where and/or how di I start ? Google for "python screensaver". The first link has a module to use... From izuzak at gmail.com Thu Aug 31 17:03:06 2006 From: izuzak at gmail.com (Ivan Zuzak) Date: 31 Aug 2006 14:03:06 -0700 Subject: sys.argv[0] doesn't always contain the full path of running script. In-Reply-To: References: <1156873037.590351.158120@i42g2000cwa.googlegroups.com> <1156967974.600841.148460@p79g2000cwp.googlegroups.com> Message-ID: <1157058186.293921.326600@m79g2000cwm.googlegroups.com> Joel Hedlund wrote: > Yes indeed! But the path to the module will not be the same as the path to > the script if you are currently in an imported module. Consider this: I thought that was the point - to get the full path of the running script? I see you use the terms "script" and "module" in different contexts, while I use them as: script = module = file. I can't say which is right, though :). Cheers, ivan From onurb at xiludom.gro Wed Aug 9 07:46:14 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 09 Aug 2006 13:46:14 +0200 Subject: Session implementation for Python In-Reply-To: References: Message-ID: <44d9cb06$0$21148$7a628cd7@news.club-internet.fr> Vlad Dogaru wrote: > Hello, > > is there any PHP-like implementation for sessions in Python? I fear > that writing my own would be seriously insecure, besides I could > actually learn a lot by inspecting the code. > > The reason I am asking is that I would like to implement simple scripts > which require login with CGI (no mod_python or Django -- I want to > learn CGI first). http://jonpy.sourceforge.net/ From no at spam.com Tue Aug 29 12:47:33 2006 From: no at spam.com (DH) Date: Tue, 29 Aug 2006 11:47:33 -0500 Subject: M$ windows python libs installed in arbitrary directories forcustomized python distributions In-Reply-To: References: <44f31d35$0$17268$9b622d9e@news.freenet.de> Message-ID: Fredrik Lundh wrote: > alf wrote: > >> ok, let me clarify, by M$ I meant Micro$oft. > > http://www.catb.org/~esr/faqs/smart-questions.html#writewell > > > And by /F, you mean fuck off? http://www.libervis.com/blogs/15/Jastiv/eric_raymond_and_the_rtfm_jerks http://www.codinghorror.com/blog/archives/000603.html From ajaksu at gmail.com Sat Aug 12 12:22:07 2006 From: ajaksu at gmail.com (ajaksu) Date: 12 Aug 2006 09:22:07 -0700 Subject: matplotlib, wxPanel inside a wxPanel References: <1155391052.938133.284080@b28g2000cwb.googlegroups.com> Message-ID: <1155399727.044367.99770@m79g2000cwm.googlegroups.com> Sam wrote: > Hello, Hi there Sam :) > I'm beginning to think that what i'm trying to do isn't actually > possible, and that i'll need to put it in a frame instead, which is a > pity. Indeed, if that is the case... as I'll need to do exactly that! But see below ;) > On the other hand, when i create graph_panel and put this inside of > main_panel, NavigationToolbar2 does not work. The graph and toolbar are > both displayed, but none of the buttons on the toolbar do anything. I've been bitten by things that sounded similar to this and were related to sloppy cut'n'paste that resulted in different hierarchies of wx elements. If you post your code we can try to spot mistakes like those. As a general advice, go for a clean frame with a main_panel, a graph_panel and sprinkle "print" statements (specially around events) to find out what is happening. > Can anyone please advise if what i'm trying to do is possible and if > so, provide a small example? I'm running windows XP, python 2.4, > wxpython 2.6. I'll try to get around that one later today, but on win98 :) Daniel From danielobrien at gmail.com Tue Aug 22 19:27:10 2006 From: danielobrien at gmail.com (Daniel O'Brien) Date: 22 Aug 2006 16:27:10 -0700 Subject: What are decorated functions? In-Reply-To: References: Message-ID: <1156289230.801158.305000@b28g2000cwb.googlegroups.com> PEP 318 provides some great examples: http://www.python.org/dev/peps/pep-0318/ For more information no the decorator pattern in general: http://en.wikipedia.org/wiki/Decorator_pattern How one actually makes use of decorators beyond the above is an exercise of imagination. Wolfgang Draxinger wrote: > I'm just reading the python language reference and came around > the term "decorated functions", but I have no idea, for what > they could be used. > > Any reply gracefully accepted. > > Wolfgang Draxinger > -- > E-Mail address works, Jabber: hexarith at jabber.org, ICQ: 134682867 > GPG key FP: 2FC8 319E C7D7 1ADC 0408 65C6 05F5 A645 1FD3 BD3E From onurb at xiludom.gro Thu Aug 10 11:55:22 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Thu, 10 Aug 2006 17:55:22 +0200 Subject: do people really complain about significant whitespace? In-Reply-To: References: <1154991523.887791.9640@i42g2000cwa.googlegroups.com> <1154994477.450666.226550@b28g2000cwb.googlegroups.com> <1155124820.123151.140580@p79g2000cwp.googlegroups.com> <9$lHo7FEZe2EFwf$@objmedia.demon.co.uk> <1155133454.975325.237770@b28g2000cwb.googlegroups.com> Message-ID: <44db56ea$0$21150$7a628cd7@news.club-internet.fr> Stephen Kellett wrote: > In message <1155133454.975325.237770 at b28g2000cwb.googlegroups.com>, Carl > Banks writes >> Stephen Kellett wrote: >> I don't really understand how a closing brace helps here. Care to >> explain why it helps you? > >> (Deeply nested long functions are evil anyways. If you have such a > > I didn't write deeply nested. I wrote multiple levels of indentation. > They are not the same thing (they can be, but they don't have to be). A > lot of code gets to 3 or 4 levels of indentation quite easily. I > wouldn't call that deeply nested, not by a long shot. > > To answer your first question: In C++/Ruby/Pascal you'd have something > like this > > function() > { > loop1() > { > blah > blah > > loop2() > { > blah > > loop3() > { > blah > } > > blah > } > } > > otherloop() > { > blah > } > } > > and in Python that gets to > > function() > loop1() > blah > blah > > loop2() > blah > > loop3() > blah > > blah3 > > otherloop() > blah > > I really dislike that the end of loop2 is implicit rather than > explicit. Well, one can argue that since Python grammar defines that a code block ends with the first following non-blank line that one indentation level less, it's perfectly explicit !-) But practically speaking : > If its implicit you have to look for it. Indeed. And yes, I agree that it's not that good wrt/ readability for any complex or long block. OTOH, nothing prevents you to add a "# end " comment where appropriate - FWIW, I used to do it in C after the closing brace for any lengthy block (and code blocks tend to be longer in C than in Python). From anthra.norell at tiscalinet.ch Fri Aug 11 12:41:53 2006 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Fri, 11 Aug 2006 18:41:53 +0200 Subject: using python to edit a word file? References: <87slk4tp45.fsf@smsnet.pl> Message-ID: <021d01c6bd65$0dbd63a0$0201a8c0@mcuf7> No one could do it any better. Good for you! - Frederic ----- Original Message ----- From: "John Salerno" Newsgroups: comp.lang.python To: Sent: Friday, August 11, 2006 4:08 PM Subject: Re: using python to edit a word file? > Anthra Norell wrote: > > John, > > > > I have a notion about translating stuff in a mess and could help you with the translation. But it may be that the conversion > > from DOC to formatted test is a bigger problem. Loading the files into Word and saving them in a different format may not be a > > practical option if you have many file to do. Googling for batch converters DOC to RTF I couldn't find anything. > > If you can solve the conversion problem, pass me a sample file. I'll solve the translation problem for you. > > > > Frederic > > What I ended up doing was just saving the Word file as an XML file, and > then writing a little script to process the text file. Then when it > opens back in Word, all the formatting remains. The script isn't ideal, > but it did the bulk of changing the numbers, and then I did a few things > by hand. I love having Python for these chores! :) > > > > import re > > xml_file = open('calendar.xml') > xml_data = xml_file.read() > xml_file.close() > > pattern = re.compile(r'(\d+)') > > def subtract(match_obj): > date = int(match_obj.group(1)) - 1 > return '%s' % date > > new_data = re.sub(pattern, subtract, xml_data) > > new_file = open('calendar2007.xml', 'w') > new_file.write(new_data) > new_file.close() > -- > http://mail.python.org/mailman/listinfo/python-list From petr.jakes at tpc.cz Tue Aug 8 18:45:46 2006 From: petr.jakes at tpc.cz (=?windows-1250?Q?Petr_Jake=9A?=) Date: Wed, 9 Aug 2006 00:45:46 +0200 Subject: technique to enter text using a mobile phone keypad (T9 dictionary-based disambiguation) Message-ID: <58243619.20060809004546@tpc.cz> I have a standard 12-key mobile phone keypad connected to my Linux machine as a I2C peripheral. I would like to write a code which allows the text entry to the computer using this keypad (something like T9 on the mobile phones) According to the http://www.yorku.ca/mack/uist01.html dictionary-based disambiguation is coming in the mind. With dictionary-based disambiguation, each key is pressed only once. For example, to enter the, the user enters 8-4-3-0. The 0 key, for SPACE, delimits words and terminates disambiguation of the preceding keys. The key sequence 8-4-3 has 3 ? 3 ? 3 = 27 possible renderings (see Figure 1). The system compares the possibilities to a dictionary of words to guess the intended word. I would like to ask some guru here to give me the direction which technique (Python functionality) or which strategy to use to solve this riddle. Thanks for your advices and comments Regards Petr Jakes From amadeusz.jasak at gmail.com Sat Aug 19 15:33:24 2006 From: amadeusz.jasak at gmail.com (amadeusz.jasak at gmail.com) Date: 19 Aug 2006 12:33:24 -0700 Subject: Stopping all threads from other thread Message-ID: <1156016004.845028.266500@74g2000cwt.googlegroups.com> Hello, it is possible to stop all threads (application) from thread of application: App |-MainThread |-WebServer |-CmdListener # From this I want to stop App The sys.exit isn't working... Amadeusz Jasak (Poland) From jiangnutao at gmail.com Wed Aug 23 14:32:50 2006 From: jiangnutao at gmail.com (Jiang Nutao) Date: Wed, 23 Aug 2006 11:32:50 -0700 Subject: swapping numeric items in a list References: <7.0.1.0.0.20060823152758.03e17610@yahoo.com.ar> Message-ID: <00d801c6c6e2$8a8924b0$900a14ac@corp.intusurg.com> This is what I got in the debugger: (Pdb) aa=array('b', [126, 55, 71, 112]) (Pdb) aa array('b', [126, 55, 71, 112]) (Pdb) aa.byteswap() (Pdb) aa array('b', [126, 55, 71, 112]) ----- Original Message ----- From: "Gabriel Genellina" To: "Jiang Nutao" Cc: Sent: Wednesday, August 23, 2006 11:28 AM Subject: Re: swapping numeric items in a list > At Wednesday 23/8/2006 14:44, Jiang Nutao wrote: > >>array.byteswap() won't work for me easily. I tried this before my 1st >>post. >>I defined >> >> aa = array('H', [0x12, 0x34, 0x56, 0x78]) >> >>Then did byteswap aa.byteswap(). The result was >> >> array('H', [0x1200, 0x3400, 0x5600, 0x7800]) >> >>You can see it byteswapped within each item. > > Use array('b') or 'B'. 'H' are two-byes integers. > > > > Gabriel Genellina > Softlab SRL > > > > > __________________________________________________ > Pregunt?. Respond?. Descubr?. > Todo lo que quer?as saber, y lo que ni imaginabas, > est? en Yahoo! Respuestas (Beta). > ?Probalo ya! http://www.yahoo.com.ar/respuestas > > From nick at craig-wood.com Fri Aug 18 04:30:03 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Fri, 18 Aug 2006 03:30:03 -0500 Subject: Subprocess confusion: how file-like must stdin be? References: <9sker3-7g8.ln1@lairds.us> <8skae2l0or9g5d53jdj9g4bafandib75qa@4ax.com> Message-ID: Dennis Lee Bieber wrote: > On Thu, 17 Aug 2006 17:16:25 +0000, claird at lairds.us (Cameron Laird) > declaimed the following in comp.lang.python: > > > Question: > > import subprocess, StringIO > > > > input = StringIO.StringIO("abcdefgh\nabc\n") > > Here you override the builtin function "input()" > > # I don't know of a compact, evocative, and > > # cross-platform way to exhibit this behavior. > > # For now, depend on cat(1). > > p = subprocess.Popen(["cat"], stdout = subprocess.PIPE, > > stdin = response) > > Here you specify the non-existant "response" Assume the OP meant to write this >>> import subprocess, StringIO >>> inp = StringIO.StringIO("abcdefgh\nabc\n") >>> p = subprocess.Popen(["cat"], stdout = subprocess.PIPE, stdin = inp) Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/subprocess.py", line 534, in __init__ (p2cread, p2cwrite, File "/usr/lib/python2.4/subprocess.py", line 830, in _get_handles p2cread = stdin.fileno() AttributeError: StringIO instance has no attribute 'fileno' >>> -- Nick Craig-Wood -- http://www.craig-wood.com/nick From laurent.pointal at limsi.fr Wed Aug 2 04:22:22 2006 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Wed, 02 Aug 2006 10:22:22 +0200 Subject: how to stop python In-Reply-To: <1154340133.801422.169690@p79g2000cwp.googlegroups.com> References: <1154340133.801422.169690@p79g2000cwp.googlegroups.com> Message-ID: victor a ?crit : > or if u want explicit exit of program then use: > > import sys > sys.exit(1) > > or > > raise SystemExit, 'message' There is also the (not recommanded - see docs, but it exists) os._exit(n) function. A+ Laurent. From larry.bates at websafe.com Mon Aug 14 18:08:38 2006 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 14 Aug 2006 17:08:38 -0500 Subject: Memory problem In-Reply-To: References: <85mdnb4jzcpTRH3ZnZ2dnUVZ_t6dnZ2d@comcast.com> Message-ID: Yi Xing wrote: > On a related question: how do I initialize a list or an array with a > pre-specified number of elements, something like > int p[100] in C? I can do append() for 100 times but this looks silly... > > Thanks. > > Yi Xing > Unlike other languages this is seldom done in Python. I think you should probably be looking at http://numeric.scipy.org/ if you want to have "traditional" arrays of floats. -Larry From johnjsal at NOSPAMgmail.com Wed Aug 30 09:48:39 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 30 Aug 2006 13:48:39 GMT Subject: How ahead are you guys in the (Python) real world? In-Reply-To: <1156821234.820929.299740@p79g2000cwp.googlegroups.com> References: <1156821234.820929.299740@p79g2000cwp.googlegroups.com> Message-ID: Ray wrote: > However I wonder, how fast are you guys moving from version to version > at work? Interesting question. Just as a curious follow-up (not being someone who works in the programming world), why does it take so long to move to the latest version, especially when there aren't (I don't think) any changes that would break existing code, such as moving to Python 2.4 from 2.2 or 2.3? Thanks. From st at tobiah.org Wed Aug 30 16:34:47 2006 From: st at tobiah.org (tobiah) Date: Wed, 30 Aug 2006 13:34:47 -0700 Subject: csv module strangeness. In-Reply-To: <44f5e870$0$8814$88260bb3@free.teranews.com> References: <44f5e870$0$8814$88260bb3@free.teranews.com> Message-ID: <44f5e947$0$8814$88260bb3@free.teranews.com> Ok, I'm an idiot. I didn't even pass my dialect object to the reader() call. So now it works, but it is still strange about the absent defaults. Tobiah > This runs, but the delimiter is still the comma. > When list.csv is comma delim, it works correctly, > but when list.csv has tab separated values, I > get back a single field with the entire line in it. > > I suppose I must be doing something horribly wrong. > > Thanks, > > Tobiah > -- Posted via a free Usenet account from http://www.teranews.com From miller.cary at gmail.com Sun Aug 6 21:12:14 2006 From: miller.cary at gmail.com (Cary Miller) Date: Sun, 6 Aug 2006 19:12:14 -0600 Subject: embedding console in wxpython app In-Reply-To: <1154898390.542838.45710@i42g2000cwa.googlegroups.com> References: <1154898390.542838.45710@i42g2000cwa.googlegroups.com> Message-ID: On 6 Aug 2006 14:06:30 -0700, Janto Dreijer wrote: > > I'm writing a Linux filemanager using wxPython. I'd like to embed a > bash console inside it. I have found the Logilab pyqonsole > (http://www.logilab.org/projects/pyqonsole), but it uses PyQT. > > Does anyone know how to do this from wx? > Is it possible to embed a PyQT widget inside wxPython? I had the same problem. Never figured out how to do it with wx but did get it with pygtk. #!/usr/bin/python import pygtk pygtk.require('2.0') import gtk, vte window = gtk.Window() window.resize(600,700) window.show() term = vte.Terminal() pid = term.fork_command('bash') term.set_emulation('xterm') term.show() window.add(term) window.show_all() window.connect("destroy", lambda w: gtk.main_quit()) gtk.main() Let me know if you find a way to do it with wx. -------------- next part -------------- An HTML attachment was scrubbed... URL: From redefined.horizons at gmail.com Fri Aug 4 16:41:06 2006 From: redefined.horizons at gmail.com (Redefined Horizons) Date: Fri, 4 Aug 2006 13:41:06 -0700 Subject: Which Python API for PostgreSQL? Message-ID: I have been working with PostgreSQL for a while, and have just made the move to Python a couple of months ago. I noticed that there are at least 2 Python API's to PostgreSQL. I have looked at PygreSQL and PostgrePy. What are the advanatages and disadvantages of each? Which one do you use? What do you like about it? I appreciate any information that will help me to choose the best API. I plan on designing some data-entry applications in PyGTK that work with Python. My server will be running on a Linux box, but most of the clients will be connecting on MS Windows boxes. Thanks, Scott Huey From onurb at xiludom.gro Thu Aug 3 05:56:24 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Thu, 03 Aug 2006 11:56:24 +0200 Subject: Can Your Programming Language Do This? Joel on functional programming and briefly on anonymous functions! In-Reply-To: References: Message-ID: <44d1c849$0$14341$626a54ce@news.free.fr> Casey Hawthorne wrote: > Can Your Programming Language Do This? And the answer is "yes, of course" !-) > Joel on functional programming and briefly on anonymous functions! > > http://www.joelonsoftware.com/items/2006/08/01.html > > -- > Regards, > Casey -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From ramasubramani.g at gmail.com Thu Aug 3 09:32:35 2006 From: ramasubramani.g at gmail.com (Rama) Date: Thu, 3 Aug 2006 19:02:35 +0530 Subject: Datetime question In-Reply-To: <4jea1mF7kic5U1@uni-berlin.de> References: <1154607991.404201.23400@p79g2000cwp.googlegroups.com> <4jea1mF7kic5U1@uni-berlin.de> Message-ID: <3f8d3ac50608030632x6cfbb0adm287d95b840141f02@mail.gmail.com> > > > In a datetime object I would like to change days and hours. > > you'd been pointed to the resources yesterday - please read manuals > carefully! > > a = datetime.datetime(2006, 8, 12, 10, 13, 56, 609000) > b = a + datetime.timedelta(days=-2, hours=-4) But wont this create a new object? Whereas if you want to modify the same object, should we not be using replace? Or does it not matter in the global picture? >>> a = datetime.datetime(2006, 8, 12, 10, 13, 56, 609000) >>> b = a + datetime.timedelta(days=-2, hours=-4) >>> >>> >>> id(a) 21838592 >>> id(b) 21836312 >>> a.replace(day=a.day + 1) datetime.datetime(2006, 8, 13, 10, 13, 56, 609000) >>> id(a) 21838592 >>> thanks, Rama -------------- next part -------------- An HTML attachment was scrubbed... URL: From meyer at acm.org Mon Aug 7 19:33:31 2006 From: meyer at acm.org (Andre Meyer) Date: Tue, 8 Aug 2006 01:33:31 +0200 Subject: singleton decorator Message-ID: <7008329d0608071633odfbf134n749c223293e3cb90@mail.gmail.com> While looking for an elegant implementation of the singleton design pattern I came across the decorator as described in PEP318 . Unfortunately, the following does not work, because decorators only work on functions or methods, but not on classes. def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance @singleton class MyClass: ... Am I missing something here? What is the preferred pythonic way of implementing singleton elegantly? Thanks for your help Andr? -------------- next part -------------- An HTML attachment was scrubbed... URL: From slawomir.nowaczyk.847 at student.lu.se Fri Aug 4 09:55:51 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Fri, 04 Aug 2006 15:55:51 +0200 Subject: regex question In-Reply-To: <1983a3190608031410n71eaa4d1s2a3db7c10c519b88@mail.gmail.com> References: <1983a3190608031410n71eaa4d1s2a3db7c10c519b88@mail.gmail.com> Message-ID: <20060804155355.EE7C.SLAWOMIR.NOWACZYK.847@student.lu.se> On Thu, 03 Aug 2006 22:10:55 +0100 Gabriel Murray wrote: #> Hello, I'm looking for a regular expression .... Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. -- Jamie Zawinski Therefore: def test(data): format, index = 'abcd', 0 for c in data: i = format.index(c) if i > index+1: return False index = i return index==format.index('d') Could be made faster if format was made a dictionary or if one wanted to compare characters directly. Writing (and profiling) left as an exercise for a reader. -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) A mind is like a parachute. It doesn't work unless it's open. From furbybrain at blueyonder.co.uk Sun Aug 27 16:24:12 2006 From: furbybrain at blueyonder.co.uk (Furbybrain) Date: Sun, 27 Aug 2006 20:24:12 GMT Subject: IDLE on Mac OS X Message-ID: I'm running 10.3.9 and I've just installed Python 2.4. IDLE won't start- it bounces in the dock once or twice then goes away. I'm new to Python, and I'm trying to learn. Thanks. From tjreedy at udel.edu Sun Aug 6 23:14:32 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 6 Aug 2006 23:14:32 -0400 Subject: easy question about join method References: <1154914663.090280.55700@b28g2000cwb.googlegroups.com> Message-ID: The easy way to get one answer for buildin funcs and methods is the help function in the interactive interpreter (and Idle's and probably other imitations thereof) is, for example, >>> help(str.join) Help on method_descriptor: join(...) S.join(sequence) -> string Return a string which is the concatenation of the strings in the sequence. The separator between elements is S. To remind how to use 'help', 'help' is more informative than 'help(help)' ;-) Terry Jan Reedy From grante at visi.com Tue Aug 8 16:20:46 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 08 Aug 2006 20:20:46 -0000 Subject: binary conversion issues References: <1155052353.499099.293840@i3g2000cwc.googlegroups.com> <12dhgcq77sdkr47@corp.supernews.com> <1155067198.385178.153560@i3g2000cwc.googlegroups.com> Message-ID: <12dhsgub0ot4qb0@corp.supernews.com> On 2006-08-08, godavemon wrote: > You guys are awesome! I had to set the 'b' flag when writing the > binaries. > > file_obj = open('filename.bin', 'wb') > > instead of just using 'w' > > It worked fine for all of the other 10 binary files I made, > but had a small error with one of them. In that one file's > case it wrote out an extra 4 bytes in the middle somewhere. > Strange. If you leave off the 'b' (and you're running on windows), any byte written to the output file that has a value of 0x0A will get converted to the two byte sequence 0x0A 0x0D. The extra bytes in the resulting file are the 0x0D bytes that were inserted after any 0x0A bytes in the written data. If the data you write doesn't have any 0x0A bytes, then nothing gets changed, and your file contains what you expect. If the data does does have 0x0A bytes, you get an extra 0x0D inserted after each one. (It wasn't _that_ wild-ass a guess, since a lot of people get tripped up by the line-ending conversion issue.) -- Grant Edwards grante Yow! Is it clean in other at dimensions? visi.com From claudio.grondi at freenet.de Thu Aug 31 13:11:46 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Thu, 31 Aug 2006 19:11:46 +0200 Subject: simultaneous copy to multiple media In-Reply-To: <1157031319.315438.4950@b28g2000cwb.googlegroups.com> References: <1157031319.315438.4950@b28g2000cwb.googlegroups.com> Message-ID: lannsjo at gmail.com wrote: > I need a program that simultaneously can copy a single file (1 GB) from > my pc to multiple USB-harddrives. Why not just use: copy c:\file.ext u:\file.exe in one shell and in another copy c:\file.ext v:\file.exe where u: and v: are the USB drives? There is usually not much gain on USB when on Windows, especially in case of a single file which fits into memory (and the file cache) to do it 'simultaneously'. This subject was discussed here already in the past: http://mail.python.org/pipermail/python-list/2005-March/271985.html Claudio Grondi > > I have searched the internet and only found one program that does this > on > http://mastermind.com.pl/multicopy/ > > but this link doesnt work anymore???? somebody that can help me, is > there any other programs out there. > From rogue_pedro at yahoo.com Tue Aug 1 20:51:01 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 1 Aug 2006 17:51:01 -0700 Subject: Get age of a file/dir References: <1154473622.749202.100300@75g2000cwc.googlegroups.com> <1154478221.479090.25960@i42g2000cwa.googlegroups.com> Message-ID: <1154479861.585357.83000@m73g2000cwd.googlegroups.com> url81-1 wrote: > Actually this has nothing to do with datetime.datetime -- he's asking > how to find the created time of the directory. > > Python has a builtin module called "stat" (afer sys/stat.h) which > includes ST_ATIME, ST_MTIME, ST_CTIME members which are times accessed, > modified, and created, respectively. > > Best, > Earle Ady > > Jim wrote: > > Carl J. Van Arsdall wrote: > > > I've been looking around the OS module and I haven't found anything > > > useful yet. Does anyone know how to get the age of a file or directory > > > in days? I'm using unix and don't seem to find anything that will help > > > me. The only function that comes close so far is > > > > > > os.path.getctime(path) > > > > > > > > > However this only gets creation time on Windows, on Unix it gets the the > > > time of the last change. Any ideas? > > > > > > Thanks! > > > > > > -carl > > > > > > -- > > > > > > Carl J. Van Arsdall > > > cvanarsdall at mvista.com > > > Build and Release > > > MontaVista Software > > > > Hi, > > You should check out the datetime module. And convert dates to an > > ordinal number. > > today = datetime.date.today().toordinal() > > age = today - datetime.date(year, month, day).toordinal() > > Jim No, the st_ctime member isn't the creation time on *nix, from the os module docs: "st_ctime (platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows)" I hope somebody does post a solution to this, as I'd like to know how to get the creation time of a file on linux, et. al. It may be impossible: http://www.faqs.org/faqs/unix-faq/faq/part3/section-1.html Peace, ~Simon From jzgoda at o2.usun.pl Wed Aug 30 14:18:57 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Wed, 30 Aug 2006 20:18:57 +0200 Subject: ANN: Templayer 1.3 - HTML templating library In-Reply-To: References: Message-ID: Ian Ward napisa?(a): > Templayer was created to offer an alternative to the more common ways of > generating dynamic HTML: embedding code within the HTML or embedding > HTML within code. Instead of mixing HTML and Python, two rich and > extremely expressive languages, Templayer adds a small amount of syntax > to each and keeps the two separate and coherent. Yay, this gives us $FFFF templating engines for Python, which matches $FFFF web frameworks! I'm glad to see such great movement, we'll get better with $FFFF O-R mappers, what we should achieve soon. Apart from joking, it's nice to have any choice. ;) -- Jarek Zgoda http://jpa.berlios.de/ From grover.uk at gmail.com Sat Aug 26 12:09:14 2006 From: grover.uk at gmail.com (groves) Date: 26 Aug 2006 09:09:14 -0700 Subject: rollover effect In-Reply-To: <1156608042.466471.210270@m73g2000cwd.googlegroups.com> References: <1156607403.741240.25000@74g2000cwt.googlegroups.com> <1156608042.466471.210270@m73g2000cwd.googlegroups.com> Message-ID: <1156608554.489516.243640@h48g2000cwc.googlegroups.com> Simon Forman wrote: > groves wrote: > > hi > > I am trying to get a roll over effect on my canvas.(this is a virtual > > program which will eventually fit into my final program) > > > > Exactly i have a text on my screen and I want to have a brief > > discription across it whenever the user takes the mouse on it n hence > > giving information about the type of text(event). > > > > Another thign i am looking for is to have a right click on that very > > text as well > > If somebody can put some light on it, then it would be really great for > > my project. > > Thank you in advance. > > What GUI system are you using? > > Peace, > ~Simon I am using python IDLE From Tim.Gallagher at gd-ais.com Tue Aug 29 14:27:44 2006 From: Tim.Gallagher at gd-ais.com (Gallagher, Tim (NE)) Date: Tue, 29 Aug 2006 14:27:44 -0400 Subject: Questoin about outlook calendar Message-ID: <794CB73454A59D488ED061055AA2820745D424@miaa01-mail01.ad.gd-ais.com> I am trying to pull all my information from outlook calendar so I can send calendar information to my phone via email. I have created a python script that will gather Outlook Calendar information and display it. I am new to python and this is something that I am working on so I can get better. Here is the problem, I am trying to get the recurring calendar entries and I am getting many errors. Here is what I have so far. [##START##] import win32com.client import time import datetime outlook = win32com.client.Dispatch("Outlook.Application") namespace = outlook.GetNamespace("MAPI") appointments = namespace.GetDefaultFolder(9).Items #print appointments.count x = 4 # This is a number for one of the calendar entries print appointments[x] print appointments[x].start print appointments[x].end print appointments[x].RecurrenceState print appointments[x].EntryID print appointments[x].IsRecurring recItem = appointments[x].GetRecurrencePattern print recItem #?--------- Getting Error [##END##] The last line I am getting an error >> I am not sure what to do with that. Here is what Microsoft has to say about the GetRecurrencePattern. Set objPattern = objItem.GetRecurrencePattern Wscript.Echo "Start time: " & objPattern.StartTime Wscript.Echo "Start date: " & objPattern.PatternStartDate Wscript.Echo "End date: " & objPattern.PatternEndDate I have tried recItem.StartTime and that gives me an error Traceback (most recent call last): File "U:\scripts\python\outlook\calendar_v1.py", line 21, in ? print recItem.StartTime AttributeError: 'function' object has no attribute 'StartTime' I am not sure what to do in order to display the items within recItem. Thanks for the help, -T From siona at chiark.greenend.org.uk Fri Aug 4 09:41:25 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 04 Aug 2006 14:41:25 +0100 (BST) Subject: What is the best way to print the usage string ? References: Message-ID: There's been a good lot of response to the problem originally stated, but no-one's pointed out that: >print reduce(lambda x, y: x + ':' + y, sys.argv[1:]) is a confusing (and slow) way of writing: print ':'.join(sys.argv[1:]) -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From steven.bethard at gmail.com Tue Aug 15 01:29:27 2006 From: steven.bethard at gmail.com (steven.bethard at gmail.com) Date: Tue, 15 Aug 2006 05:29:27 +0000 (GMT) Subject: python-dev Summary for 2006-07-01 through 2006-07-15 Message-ID: <20060815052929.C51B21E4003@bag.python.org> python-dev Summary for 2006-07-01 through 2006-07-15 ++++++++++++++++++++++++++++++++++++++++++++++++++++ .. contents:: [The HTML version of this Summary is available at http://www.python.org/dev/summary/2006-07-01_2006-07-15] ============= Announcements ============= ------------------- Python 2.5 schedule ------------------- Python continues to make progress towards Python 2.5 final. See `PEP 356`_ for more details and the full schedule. .. _PEP 356: http://www.python.org/dev/peps/pep-0356/ Contributing threads: - `TRUNK FREEZE for 2.5b2, tomorrow Tuesday 11th, 00:00 UTC `__ - `Subject: RELEASED Python 2.5 (beta 2) `__ - `TRUNK is UNFROZEN. `__ -------------------------- ctypes in the Python trunk -------------------------- Martin v. Lowis successfully imported the ctypes history into the Python trunk, so ctypes now shares its repository with the rest of Python. Thanks everyone for your hard work! Contributing threads: - `Moving the ctypes repository to python.org `__ - `Subversion outage Friday 15:00 GMT `__ - `SVN write access is back `__ - `Extended Subversion outage: Friday 16:40 GMT `__ ========= Summaries ========= ------------------------- Rebinding non-local names ------------------------- A bug in the Python trunk that allowed augmented assignment to rebind names in outer scopes initiated a new discussion about how to allow Python code to rebind non-local names, e.g.:: def counter(n=0): def increment(i=1): n += i # change the n in counter return n return increment Guido definitely didn't like the idea of introducing a new rebinding operator, e.g. ``:=`` or ``.=``. Phillip J. Eby suggested that a dot prefix to the name could indicate rebinding, e.g.:: def counter(n=0): def increment(i=1): .n += i return .n return increment Guido felt uncomfortable with this proposal because it would mean that in referencing a value the only difference between ``.NAME`` and ``NAME`` was whether or not the name was assigned to at another place in the same function. This ambiguity could be avoided by requiring all references to names in outer scopes to be prefixed by the dot, but that seemed like too large of a change for Python. There was also some discussion of trying to reuse the global keyword, but most folks felt that ``outer`` or ``nonlocal`` was a better name:: def counter(n=0): def increment(i=1): nonlocal n n += i return n return increment Guido requested a PEP on the subject, but at the time of this summary, none was available. Contributing threads: - `2.5 and beyond `__ - `Lexical scoping in Python 3k `__ - `Explicit Lexical Scoping (pre-PEP?) `__ -------------------------------------- Python and backwards incompatibilities -------------------------------------- A `complaint by Greg Black`_ about Python introducing backward incompatibilities started a long discussion about how Python developers could stay in better touch with existing user code. Greg Black's code had relied on undocumented behavior in time.strftime() that had allowed zeros to be passed in as default values. When that behavior changed in Python 2.4, Greg's code (along with a number of other people's code) was broken. Python core didn't have any unittests for the behavior, so no tests started failing when the change was made. Glyph suggested adding a mechanism so that user projects could submit buildslaves to run their test suites when changes are made to Python. The goal here would be to identify any de facto coding standards that weren't tested for in Python's test suite. If a change to Python caused major projects like Twisted or Zope to start failing dramatically, that change should be reconsidered even if it didn't break any documented behavior. People generally thought this was a great idea, particularly since it might catch some of these changes earlier than alpha or beta releases. There was also some concern that the Python 2.5 release cycle had been sped up too much and users hadn't had enough time to report errors. However, adding more beta releases (which seemed to be the major suggestion) also adds more work for release managers and requires more schedule coordination so that all the release managers can be available. People also had the mistaken impression that the trunk of Python was not so stable, particularly because they had assumed that non-green buildbots meant an unusable Python. In general, non-green buildbots typically mean that some part of the test suite is failing, not that the interpreter could not be built. A.M. Kuchling suggested adding some of the `checkin policies discussion`_ to the release announcements to make this more obvious. .. _complaint by Greg Black: http://www.gbch.net/gjb/blog/software/discuss/python-sucks.html .. _checkin policies discussion: http://www.python.org/dev/tools/ Contributing threads: - `User's complaints `__ - `changing time.strftime() to accept 0s (was: User's complaints) `__ - `Community buildbots (was Re: User's complaints) `__ - `Community buildbots `__ ------------------------------ Restricted execution in Python ------------------------------ Discussion continued on Brett Cannon's PhD thesis aimed at adding restricted execution to Python. Instead of trying to cripple objects like ``file``, a number of people suggested making ``file()`` and ``open()`` return different objects in restricted mode. This would require separating out some capabilities, so that, for example, a file-like object could be returned that didn't support writing. Michael Chermside suggested implementing a new type in C that stores its data privately, and requires the user to provide access-checking functions in order to make the private data visible. That way you could implement new access restrictions from pure Python code, by simply creating appropriate instances of the new type. Ka-Ping Yee asked about protecting one piece of Python code from another, but Guido and Brett suggested that the virtual machine probably couldn't provide such barriers. Brett's current progress is available in the bcannon-sandboxing branch. Contributing threads: - `For sandboxing: alternative to crippling file() `__ - `doc for new restricted execution design for Python `__ - `branch for sandox work created: bcannon-sandboxing `__ - `In defense of Capabilities [was: doc for new restricted execution design for Python] `__ - `what can we do to hide the 'file' type? `__ - `Restricted execution: what's the threat model? `__ - `Capabilities / Restricted Execution `__ - `second draft of sandboxing design doc `__ --------------------------------- Getting the current thread frames --------------------------------- Tim Peters snuck in a late feature, ``sys._current_frames()`` which returns a dict mapping each thread's id to that thread's current Python frame. Some people wanted to expose ``head_mutex`` instead to avoid introducing a new function, but that may not exist, depending on the build type. Given that Zope had been trying to emulate something like this for a while, it's impossible to do correctly in an extension module because the appropriate internals are not available, and it's essential for debugging deadlocks, the feature was eventually approved and checked in. Contributing thread: - `"Missing" 2.5 feature `__ -------------------- Time-out in URL Open -------------------- Facundo Batista asked about adding a timeout argument to ``urllib2.urlopen()``. People generally liked the idea, but since it would be a new feature, it would have to wait until Python 2.6. There was an `existing patch` modifying httplib, ftplib, telnetllib, poplib and smtplib in this way, but it needed updating for Python 2.6. .. _existing patch: http://bugs.python.org/723312 Contributing thread: - `Time-out in URL Open `__ ------------------------------------------- zlib module build failure on Mac OSX 10.4.7 ------------------------------------------- Skip Montanaro had some trouble building the zlib module from Python trunk on Mac OSX. Turns out he had an old static libz.a on the path, and that was getting found instead of the newer dynamic library. Ronald Oussoren checked in a patch to configure that should correctly set HAVE_ZLIB_COPY even if there is an old static library sitting around. At the same time, he suggested that maybe '-Wl,-search_path_first' should be added to the default LDFLAGS on OSX so that the OSX linker doesn't look for a dylib anywhere on the path before looking for a static library. Contributing thread: - `zlib module build failure on Mac OSX 10.4.7 `__ -------------------------------- Command line args in Python 3000 -------------------------------- Greg Ewing suggested that ``sys.argv`` could be split into the program name (``sys.argv[0]``) and the arguments (``sys.argv[1:]``). People liked this idea, and pointed out that it would be handy when there's no real program name, e.g. when exec is used with an inode number as is possible on some Unices. This was also accompanied by a discussion about splitting sys into more coherent subsets, e.g. immutable and mutable objects. Guido asked for people to hold off on this discussion until Brett had a clearer idea what pieces would need to be split off for restricted execution. Contributing thread: - `Handling of sys.args (Re: User's complaints) `__ -------------------------- Import semantics in Jython -------------------------- Jython had been following the Java convention that sub-packages were imported when their parent package was imported. Guido had suggested that at least Python packages in Jython should import with the standard Python semantics. During this fortnight, Guido checked back in with the Jython folks to see if they'd made their mind up about this. Frank Wierzbicki, the new maintainer for Jython, said that he won't have a chance to fix this until after Jython 2.3 is out, but both he and Samuele Pedroni suggested that it was a change that needed to be made. Contributing thread: - `Import semantics `__ ----------------------------------------------- ImportWarnings for directories without __init__ ----------------------------------------------- After the substantial discussion last fortnight on whether or not warnings should be issued if a directory was not imported because it was missing an __init__.py file, Anthony Baxter suggested that the best course of action was to suppress the ImportWarning by default, and allow users to unsuppress it in their sitecustomize.py file. Contributing threads: - `ImportWarning flood `__ - `ImportWarning decision `__ ----------------------------------- Putting doctest code into footnotes ----------------------------------- Benji York posted a `patch for doctest`_ that teaches doctest about ReST-style footnotes so that you can write documentation like:: After initializing the system [#init]_ it is possible to retrieve status information: >>> system.status() 'good to go' [snip some of the doctest] .. [#init] Initialize the system: >>> system = System() >>> system.init() People liked the idea, and Benji promised to update the patch for the 2.5 version of doctest. .. _patch for doctest: http://tinyurl.com/nekam Contributing thread: - `Doctest and Footnotes `__ ------------------------------- Using urllib.quote with unicode ------------------------------- Stefan Rank pointed out that ``urllib.quote()`` fails with a strange KeyError on unicode stings. He suggested either raising a TypeError or automatically encoding to UTF-8 as suggested in http://www.w3.org/International/O-URL-code.html. John J Lee pointed questioned whether this was generally accepted as the Right Thing, given `RFC 2617`_, `RFC 2616`_ and the recent discussion about a `uriparse module`_. In the end, people seemed to agree that the safest thing would be to raise an exception. .. _RFC 2617: http://www.ietf.org/rfc/rfc2617.txt .. _RFC 2616: http://www.ietf.org/rfc/rfc2616.txt .. _uriparse module: http://www.python.org/dev/summary/2006-06-01_2006-06-15/#rfc-3986-uniform-resource-identifiers-uris Contributing thread: - `urllib.quote and unicode bug resuscitation attempt `__ ----------------------------------- Borderline cases for ints and longs ----------------------------------- Neil Schemenauer asked if -2147483648 (``-sys.maxint - 1``)should be an int or a long. In Python 2.4 it was an int, but in the trunk, it was a long. Tim Peters explained that -2147483648 is not actually an int literal -- it is a long literal with a unary minus. Nonetheless, practicality beat purity, and Neal Norwitz and Neil Schemenauer put together a fix to make it an int again. You can still defeat the patch with something like ``eval('-(%s)' % str(-sys.maxint - 1)[1:])``, but no one seemed too worried about that. Contributing thread: - `Unary minus bug `__ --------------------------------- Adding list.get() and tuple.get() --------------------------------- Russell E. Owen asked about adding a ``.get()`` method to lists and tuples that would return a default value if the index was out of range. Most people seemed to think that wanting such a method was a bad code smell and Raymond Hettinger suggested that it could be replaced in Python 2.5 with a simple ``seq[i] if len(seq) > i else default``. Contributing thread: - `get for lists and tuples? `__ ----------------------------- Adding a __dir__ magic method ----------------------------- Tomer Filiba suggested adding a ``__dir__()`` magic method that would be called by ``dir()``. The default one on ``object`` would do the normal search through ``__dict__`` and the superclasses, and subclasses of ``object`` could override this to add attributes that are harder to find, e.g. pseudo-attributed implemented through ``__getattr__``. Everyone liked the idea and Guido said it could be added for Python 2.6. Contributing thread: - `introducing __dir__? `__ ----------------------------------------------------- pydoc support for attributes defined with PyGetSetDef ----------------------------------------------------- Barry Warsaw pointed out that pydoc couldn't handle attributes defined with PyGetSetDef because there was no corresponding type in the types module. He found a similar problem with "member_descriptor" types like ``datetime.timedelta.days``. The latter was particularly a problem because the datetime module was not importable in the types module because the types module is imported before the platform-specific extension module directory is on sys.path. He suggested a `fix for pydoc`_ that would introduce a _types module coded in C that could make the appropriate types available. .. _fix for pydoc: http://bugs.python.org/1520294 Contributing thread: - `Support for PyGetSetDefs in pydoc `__ ================ Deferred Threads ================ - `Python Style Sheets ? Re: User's complaints `__ ================== Previous Summaries ================== - `Cleanup of test harness for Python `__ - `PEP 328 and PEP 338, redux `__ - `Empty Subscript PEP on Wiki - keep or toss? `__ - `More Switch: Explicit freezing `__ - `Proposal to eliminate PySet_Fini `__ - `Switch and static, redux `__ =============== Skipped Threads =============== - `traceback regression `__ - `sys.settrace() in Python 2.3 vs. 2.4 `__ - `Bug in stringobject? `__ - `weakattr `__ - `how long to wait for expat to incorporate a fix to prevent a crasher? `__ - `LOAD_CONST POP_TOP `__ - `Another 2.5 bug candidate? `__ - `DRAFT: python-dev summary for 2006-06-01 to 2006-06-15 `__ - `Proposed beta 2 changes (Q for Anthony/Neal) `__ - `2.5b1 Windows install `__ - `Patch for commands.py to provide callback `__ - `import screwiness `__ - `zipfile.ZipFile('foo.zip', 'a'): file not found -> create? `__ - `Musings on concurrency and scoping ("replacing" Javascript) `__ - `About a month until PSF call for test trackers closes! `__ - `test_ctypes failure on Mac OS X/PowerPC 10.3.9 (Panther) `__ - `[slighly OT] Native speakers and hurting brains `__ - `exception too expensive? `__ - `Weekly Python Patch/Bug Summary `__ - `xml issue in 2.5 `__ - `Fix for Lib/test/leakers/test_gestalt.py `__ - `Discussion on Lib/test/crashers/ `__ - `Add new PyErr_WarnEx() to 2.5? `__ - `Klocwork analysis of source if we want it `__ - `easy_install `__ - `subprocess.CalledProcessError.errno (#1223937) `__ - `Minor: Unix icons for 2.5? `__ - `PEP 356: python.org/sf/1515343 resolution `__ - `Autoloading? (Making Queue.Queue easier to use) `__ - `Long options support `__ - `Behavior change in subprocess.py `__ - `Proposal: Add Sudoku Solver To The "this" Module `__ - `The buffer() function `__ - `Partial support for dlmodule.c in 64-bits OSes `__ - `IDLE - firewall warning `__ ======== Epilogue ======== This is a summary of traffic on the `python-dev mailing list`_ from July 01, 2006 through July 15, 2006. It is intended to inform the wider Python community of on-going developments on the list on a semi-monthly basis. An archive_ of previous summaries is available online. An `RSS feed`_ of the titles of the summaries is available. You can also watch comp.lang.python or comp.lang.python.announce for new summaries (or through their email gateways of python-list or python-announce, respectively, as found at http://mail.python.org). This python-dev summary is the 8th written by Steve Bethard. To contact me, please send email: - Steve Bethard (steven.bethard at gmail.com) Do *not* post to comp.lang.python if you wish to reach me. The `Python Software Foundation`_ is the non-profit organization that holds the intellectual property for Python. It also tries to advance the development and use of Python. If you find the python-dev Summary helpful please consider making a donation. You can make a donation at http://python.org/psf/donations.html . Every cent counts so even a small donation with a credit card, check, or by PayPal helps. -------------------- Commenting on Topics -------------------- To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! ------------------------- How to Read the Summaries ------------------------- That this summary is written using reStructuredText_. Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo :); you can safely ignore it. We do suggest learning reST, though; it's simple and is accepted for `PEP markup`_ and can be turned into many different formats like HTML and LaTeX. .. _python-dev: http://www.python.org/dev/ .. _SourceForge: http://sourceforge.net/tracker/?group_id=5470 .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _c.l.py: .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _PEP Markup: http://www.python.org/peps/pep-0012.html .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _PSF: .. _Python Software Foundation: http://python.org/psf/ .. _archive: http://www.python.org/dev/summary/ .. _RSS feed: http://www.python.org/dev/summary/channews.rdf From fredrik at pythonware.com Tue Aug 22 17:53:02 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Aug 2006 23:53:02 +0200 Subject: how do you get the name of a dictionary? In-Reply-To: <1156283135.985893.186500@m73g2000cwd.googlegroups.com> References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> <1156264475.968894.221710@p79g2000cwp.googlegroups.com> <1156266720.205126.284050@i3g2000cwc.googlegroups.com> <1156268752.574983.123520@75g2000cwc.googlegroups.com> <1156281268.865624.302070@b28g2000cwb.googlegroups.com> <1156283135.985893.186500@m73g2000cwd.googlegroups.com> Message-ID: jojoba wrote: >> no, you're just wasting a lot of bandwidth making it clear that you just >> cannot be bothered to learn how things actually work. > > Wow Fredrick! Are you serious? yes. From fredrik at pythonware.com Mon Aug 14 05:40:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 14 Aug 2006 11:40:39 +0200 Subject: Strange problem with Tkinter... photos don't show on first iteration. References: <1155541228.511218.128500@m79g2000cwm.googlegroups.com> Message-ID: aldonnelley at gmail.com wrote: > Just having a weird problem with tkinter. I'm trying to make a gui that > shows results from an image search, with a "forward" and "back" button > so the user can compare results from different pages. All that's > working fine... > The problem I'm having is that the images don't show onscreen the first > time the "first page" of results shows up. When I click the "search > again" button, and have more than the original results page to toggle > between, the images __do__ show up on the "first page" of results. (and > on the second, etc, etc.) > Which is to say, there's no error messages, and on the first "page", > the first time it's shown, the Toplevel formats correctly, and there > are spaces where the images should be that are the correct size, > just... no images. > It's baffling me. Perhaps someone can help. this is explained in the Python FAQ, and also in the note at the bottom of this page: http://effbot.org/tkinterbook/photoimage.htm From h112211 at gmail.com Wed Aug 2 02:26:54 2006 From: h112211 at gmail.com (h112211 at gmail.com) Date: 1 Aug 2006 23:26:54 -0700 Subject: DLL search path, IDLE versus command line Message-ID: <1154500014.499327.160950@s13g2000cwa.googlegroups.com> Hi, Does anyone have any clues why I can import a module (pgdb) from the python command line, but trying to run a script doing it from IDLE I get "ImportError: DLL load failed: The specified module could not be found."? How does the search path differ between IDLE and the Python command line? I'm using Python 2.4.3 on Windows. From DirkHagemann at gmail.com Mon Aug 21 10:14:35 2006 From: DirkHagemann at gmail.com (Dirk Hagemann) Date: 21 Aug 2006 07:14:35 -0700 Subject: MS SQL Server: NT Authentication. Possible? In-Reply-To: <1156164544.513073.242290@i3g2000cwc.googlegroups.com> References: <1156164544.513073.242290@i3g2000cwc.googlegroups.com> Message-ID: <1156169675.734453.286700@74g2000cwt.googlegroups.com> Very strange. It works when I directly run the script, but when I use this script as a CGI-script on a webserver, I get this error: File "D:\Web\test\adodbapi.py", line 224, in connect raise DatabaseError(e) adodbapi.DatabaseError: (-2147352567, 'Exception occurred.', (0, 'Microsoft OLE DB Provider for SQL Server', "Login failed for user '(null)'. Reason: Not associated with a trusted SQL Server connection.", None, 0, -2147467259), None) The script on the webserver is started with the user who is logged on to the client-computer (not a webserver-user). I checked this with username = os.environ.get('REMOTE_USER') in the script. What's wrong when a webserver runs this script?! Dirk From zutesmog at gmail.com Tue Aug 29 00:12:44 2006 From: zutesmog at gmail.com (zutesmog at gmail.com) Date: 28 Aug 2006 21:12:44 -0700 Subject: Desktop Notification/Alerts In Python In-Reply-To: <1156781259.354526.142680@m79g2000cwm.googlegroups.com> References: <1156781259.354526.142680@m79g2000cwm.googlegroups.com> Message-ID: <1156824764.230695.36450@i3g2000cwc.googlegroups.com> Chaos wrote: > I am looking for ways to have a Desktop Alert, like the one most IM > Messengers have (MSN, AIM) at the lower right above the taskbar. Can > anyone point me to the right resources to use? I am not sure exactly what you are looking for but I assume you are using windows, so I would suggest you make sure you have Mark Hammonds win32all (http://www.python.net/crew/mhammond/win32/) installed and have a look at the demos there. T From flingfly at gmail.com Thu Aug 3 23:10:22 2006 From: flingfly at gmail.com (yy x) Date: Fri, 4 Aug 2006 11:10:22 +0800 Subject: two embedded problem. one maybe is python bug. Message-ID: hi,all, the content of a.py : #coding:gb2312 #/usr/local/bin/python import random print random.randint(0,10) the c program: #include int main() { Py_Initialize(); PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('.')"); PyRun_SimpleString("import a"); Py_Finalize(); return 0; } the gcc cmd line: g++ -o a a.c -I/usr/local/include/python /usr/local/lib/libpython -lm -lpthread -ldl First problem: when i run the a, the error msg is : Traceback (most recent call last): File "", line 1, in ? File "./a.py", line 1 SyntaxError: encoding problem: with BOM but if i first import a.py through the python cmd line. This problem disappears.(but second problem appears)(now I think the a import a.pyc not a.py) I think it's python bug, isn't it? Second problem, Traceback (most recent call last): File "", line 1, in ? File "a.py", line 3, in ? import random File "/usr/local/lib/python2.4/random.py", line 44, in ? from math import log as _log, exp as _exp, pi as _pi, e as _e ImportError: /usr/local/lib/python2.4/lib-dynload/math.so: undefined symbol: PyExc_OverflowError. Pls give me some advice, i am crazy.thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From gregpinero at gmail.com Sat Aug 5 18:37:35 2006 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Sat, 5 Aug 2006 18:37:35 -0400 Subject: Backup GMAIL Messages with Python In-Reply-To: <1154816823.543334.242930@75g2000cwc.googlegroups.com> References: <1154816823.543334.242930@75g2000cwc.googlegroups.com> Message-ID: <312cfe2b0608051537o37bc54b2te2c3f414d3f13dd6@mail.gmail.com> On 5 Aug 2006 15:27:03 -0700, Simon Forman wrote: > Out of curiosity, why do you want to _backup_ a gmail account? (I use > my gmail account to backup files and documents I never want to lose.) > I could think of some reasons, but I'm wondering what yours are. : ) Here are a few: 1. Google could turn evil someday (and delete everyones' data?) 2. Google coud lose or delete data by accident 3. You could lose your internet connection for an extended period of time 4. You may want to move to a different email software in the future and am not able to export from Google calendar at that time(see reason 1) Update on my question: getmail looks like another option: http://pyropus.ca/software/getmail/ but not cross platform? -Greg From fredrik at pythonware.com Wed Aug 30 10:01:27 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 30 Aug 2006 16:01:27 +0200 Subject: How ahead are you guys in the (Python) real world? References: <1156821234.820929.299740@p79g2000cwp.googlegroups.com> Message-ID: John Salerno wrote: > when there aren't (I don't think) any changes that would break existing code, in practice, in a large enough system, there's always something. (external libraries are a common problem, especially if you have to rebuild them, or update them to a new version to work around some incompatibility, and then end up with your code being incompatible with the new version, etc) From gagsl-py at yahoo.com.ar Tue Aug 29 00:58:02 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 29 Aug 2006 01:58:02 -0300 Subject: eval() woes In-Reply-To: <1156824826.778486.251380@74g2000cwt.googlegroups.com> References: <1156735954.796051.290600@i3g2000cwc.googlegroups.com> <1156740704.380857.76670@i42g2000cwa.googlegroups.com> <1156817948.765024.13770@p79g2000cwp.googlegroups.com> <1156824826.778486.251380@74g2000cwt.googlegroups.com> Message-ID: <7.0.1.0.0.20060829014755.043150e0@yahoo.com.ar> At Tuesday 29/8/2006 01:13, rdrink wrote: > File "the_farmer2.py", line 112, in equate > iL = int(parts[1]) >ValueError: invalid literal for int(): - So parts[1] is '-'. Try adding a few print statements; I'd add a try/except around those lines, printing parts, I bet it's not what you expect it to be. The problem appears to be in the calling code, not on this function. >equate() was called 500 times... in some cases with the list 'parts' >equaling things like ['0',2','3','0'], so I have no reason to believe >that the problem is with the way the list is being passed in... but I >could be wrong) ...like above, where you missed a quote. > Can anyone see something I can't? Not on the code fragment you posted. Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From fredrik at pythonware.com Fri Aug 25 02:00:44 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Aug 2006 08:00:44 +0200 Subject: pickling and endianess In-Reply-To: References: Message-ID: Chandrashekhar kaushik wrote: > Can an object pickled and saved on a little-endian machine be unpickled > on a big-endian machine ? yes. the format uses a known byte order. From sile_brennan at hotmail.com Mon Aug 28 04:44:07 2006 From: sile_brennan at hotmail.com (Sile) Date: 28 Aug 2006 01:44:07 -0700 Subject: f2py on windows XP - "Unknown Switch"?? In-Reply-To: <1156629368.463878.138620@h48g2000cwc.googlegroups.com> References: <1156177095.867153.327380@h48g2000cwc.googlegroups.com> <1156629368.463878.138620@h48g2000cwc.googlegroups.com> Message-ID: <1156754647.169794.272430@m79g2000cwm.googlegroups.com> Cheers John - I did finally getting f2py working on XP using MinGW, GnuFcompiler for F77, and much help! However, having set up everything correctly I have been told in work I now need to use F90. I have downloaded and installed G95 MinGW in my MinGW directory and this isn't working now, I'm not having much joy with this! When I check the available fortran compilers in F2PY I get the following............... customize Gnu95FCompiler Could not locate executable f95 Executable f95 does not exist Could not locate executable f95 Executable f95 does not exist Could not locate executable f95 Executable f95 does not exist customize IntelVisualFCompiler Could not locate executable ifl Executable ifl does not exist customize G95FCompiler Couldn't match compiler version for 'G95 (GCC 4.0.3 (g95 0.90!) Aug 22 2006) Copyright (C) 2002-2005 Free Software Foundation, Inc.nG95 comes with NO WARRANTY, to the extent permitted by law. You may redistribute copies of G95under the terms of the GNU General Public License.For more information about these ...............etc. based on suggestions on the web I changed one line in g95.py to version_pattern =r'G95.*\(GCC4.01)\(g95!) (?P<version>.\). Unfortunately this didn't work for me. The problem seems to be with my gcc version so I'm trying to find a way around this at the moment. Any suggestions would be much appreciated, I have submitted this problem to the f2py mailing list too. thanks, Sile From nospam at invalid.com Sat Aug 12 14:21:39 2006 From: nospam at invalid.com (Jack) Date: Sat, 12 Aug 2006 11:21:39 -0700 Subject: Looking for a text file based wiki system written in Python References: Message-ID: Thanks! Because it was so well known, I thought it was database-based :) > http://moinmoin.wikiwikiweb.de/ Any good and simple text file-based blog system in Python? From celiadoug at mchsi.com Mon Aug 28 00:35:45 2006 From: celiadoug at mchsi.com (Doug Stell) Date: Mon, 28 Aug 2006 04:35:45 GMT Subject: ASN.1 encoder & decoder References: <7xd5ao4cip.fsf@ruckus.brouhaha.com> Message-ID: Thanks Paul. This is exactly the type andlevel of implementation that I was looking for. I will look at the other implementation again. On 25 Aug 2006 16:32:46 -0700, Paul Rubin wrote: >Doug Stell writes: >> Can anyone provide guidance on building an ASN.1 decoder and encoder >> in Python? This does not have to be a general purpose implementation, >> drivenf from an ASN.1 template. It can be dedicated hard coded to a >> particular template. > >There might be some useful code in www.trevp.com/tlslite . From bearophileHUGS at lycos.com Wed Aug 9 19:33:40 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 9 Aug 2006 16:33:40 -0700 Subject: technique to enter text using a mobile phone keypad (T9 dictionary-based disambiguation) In-Reply-To: <1155164070.665244.193080@b28g2000cwb.googlegroups.com> References: <1155095477.440347.149350@m79g2000cwm.googlegroups.com> <1155154447.409931.55750@p79g2000cwp.googlegroups.com> <1155156341.298792.188280@75g2000cwc.googlegroups.com> <1155164070.665244.193080@b28g2000cwb.googlegroups.com> Message-ID: <1155166420.058201.81630@n13g2000cwa.googlegroups.com> John Machin: > 2. All responses so far seem to have missed a major point in the > research paper quoted by the OP: each word has a *frequency* associated > with it. When there are multiple choices (e.g. "43" -> ["he", "if", > "id", ...]), the user is presented with the choices in descending > frequency order. I haven't missed it; if you use the instrumeted PAQ compressor approach, you gain the frequency information and more :-) Bye, bearophile From jcollett at oshtruck.com Wed Aug 9 10:51:58 2006 From: jcollett at oshtruck.com (Hoop) Date: 9 Aug 2006 07:51:58 -0700 Subject: beginner questions on embedding/extending python with C++ In-Reply-To: <1155082873.772175.285300@n13g2000cwa.googlegroups.com> References: <1155029311.885266.131980@m73g2000cwd.googlegroups.com> <1155082873.772175.285300@n13g2000cwa.googlegroups.com> Message-ID: <1155135118.175279.80760@n13g2000cwa.googlegroups.com> Hi All, I am in the process also of trying to call Python script from a C++ windows app. I have looked at the Boost site and am currently reading over the Embedding portion of the tutorial. A question I have is that there appear to be about 4 or 5 Boost items avaiable for download. Which one should be downloaded to do the embedding? Thanks Jeff Qun Cao wrote: > Thanks for all the good pointers! > I am still reading throught them, but Boost seems to be the way to go! > > Roman Yakovenko wrote: > > On 8 Aug 2006 02:28:31 -0700, Qun Cao wrote: > > > Hi Everyone, > > > > > > I am a beginner on cross language development. My problem at hand is to > > > build a python interface for a C++ application built on top of a 3D > > > game engine. The purpose of this python interface is providing a > > > convenient scripting toolkit for the application. > > > > As for me, Boost.Python is the way to go. > > > > Fortunately you are not the first one, and I hope not the last one :-) : > > > > http://language-binding.net/pyplusplus/quotes.html#who-is-using-pyplusplus > > 1. Python-OGRE > > * http://lakin.weckers.net/index_ogre_python.html > > * http://tinyurl.com/mvj8d > > > > 2. http://cgkit.sourceforge.net/ - contains Python bindings for Maya C++ SDK > > > > 3. PyOpenSG - https://realityforge.vrsource.org/view/PyOpenSG/WebHome > > The goal of PyOpenSG is to provide python bindings for the OpenSG > > scene graph. > > > > > Since the main program is still going to be the C++ application, I > > > guess we need to embedding the python scripts in the C++ code. > > > > Boost.Python is the only tool that provides complete functionality( > > extending and > > embedding ). Also I think cgkit is dealing with the problem too. > > > > > But for this to work, the python code needs to know the Player class, > > > is it right? > > > > Right. > > > > Does that mean I need to build a python wrapper class for > > > Player and "import Player" in the python code? But because this > > > application is built on top of a game engine, Player class inherits > > > many classes from there, I cannot possibly wrapping them all, right? > > > > It depends on how much functionality you want to export. > > > > > Also, some global objects are probably needed in this code of adding > > > players, how can the python code access them? > > > > Boost.Python provides the functionality you need. > > > > > Btw, if you can point me to any source code of non-trivial projects > > > utilizing SWIG/Boost.Python, that would be very helpful. I found the > > > examples on the tutorials are far too simple. > > > > Those are tutorials, they should be simple, right :-) ? > > > > -- > > Roman Yakovenko > > C++ Python language binding > > http://www.language-binding.net/ From grante at visi.com Fri Aug 4 18:30:34 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 04 Aug 2006 22:30:34 -0000 Subject: Programming Games with python, I know this subject was disccused need help References: <1154725931.106708.180120@s13g2000cwa.googlegroups.com> <1154726144.395949.306950@m73g2000cwd.googlegroups.com> <1154726703.387186.31170@m73g2000cwd.googlegroups.com> Message-ID: <12d7ikajr6mv694@corp.supernews.com> On 2006-08-04, Over G wrote: >> http://www.pygame.org/news.html >> http://sourceforge.net/projects/pyallegro/ > Still can you shad more light on the second link, what is project > allegro ? Following a couple links on that second page gets you here: http://alleg.sourceforge.net/ -- Grant Edwards grante Yow! As President I at have to go vacuum my coin visi.com collection! From chrispatton at gmail.com Fri Aug 4 17:19:57 2006 From: chrispatton at gmail.com (Chris) Date: 4 Aug 2006 14:19:57 -0700 Subject: super quick question Message-ID: <1154726397.778270.28810@75g2000cwc.googlegroups.com> is there a prettier way to do this? string[:len(string)-1] thanks! From johnjsal at NOSPAMgmail.com Mon Aug 14 14:40:44 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 14 Aug 2006 18:40:44 GMT Subject: outputting a command to the terminal? In-Reply-To: <1155580175.313400.136900@m79g2000cwm.googlegroups.com> References: <44df99f7$0$25025$c3e8da3@news.astraweb.com> <44dfc1cb$0$2397$c3e8da3@news.astraweb.com> <1155580175.313400.136900@m79g2000cwm.googlegroups.com> Message-ID: Simon Forman wrote: > It's simple, short, and to-the-point. The equivalent python script > would be much longer, for no appreciable gain. I write most of my tiny > little helper scripts in python, but in this case, bash is the clear > winnar. (And on *nix. man pages are your best friend. Plus you get to > feel all l33t when you grok them. lol) Thanks for the info! I might grudgingly decide to use a bash script in this case. :) And yes, it seems every time I ask a Linux question, everyone points me to a man page. Sometimes I find them difficult to decipher, but they are still a great help. From daftspaniel at gmail.com Wed Aug 9 16:55:13 2006 From: daftspaniel at gmail.com (daftspaniel at gmail.com) Date: 9 Aug 2006 13:55:13 -0700 Subject: knowing when file is flushed to disk References: Message-ID: <1155156913.608591.202260@b28g2000cwb.googlegroups.com> John Pote wrote: > Is there some way from my Python script to know when the data is actually on > the disk. BTW server OS is Linux. Presumably calling flush() and close() on > the output file will initiate the disk write, but do they wait for the > actual disk write or immediately return leaving the OS to do the write when > it sees fit? All you can do in Python (or similar) is call flush & close and hope for the best :-) There are many factors outwith the control of the language e.g. * Library behaviour * OS behaviour * Hardware cache on the disk itself That said, I've only found it an issue when a computer is under heavy load. Hope this helps, Davy Mitchell http://www.latedecember.com/sites/personal/davy/ From jeremy+complangpython at jeremysanders.net Mon Aug 21 06:36:53 2006 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Mon, 21 Aug 2006 11:36:53 +0100 Subject: Small Troll on notation of variables over time References: Message-ID: Hendrik van Rooyen wrote: > What do you guys think? You could get something similar using an object, such as class Hist(object): def __init__(self): self.vals = [None] def __call__(self, index=-1): return self.vals[index] def set(self, val): self.vals.append(val) a = Hist() a.set(5) print a() a.set('hi there') print a() print a(-2) Which prints 5 hi there 5 -- Jeremy Sanders http://www.jeremysanders.net/ From skip at pobox.com Thu Aug 10 10:46:37 2006 From: skip at pobox.com (skip at pobox.com) Date: Thu, 10 Aug 2006 09:46:37 -0500 Subject: Eval (was Re: Question about the use of python as a scripting language) In-Reply-To: <16E7238C-8601-4A9D-B244-E9D8668966DE@carnegielearning.com> References: <17627.14233.684281.17915@montanaro.dyndns.org> <16E7238C-8601-4A9D-B244-E9D8668966DE@carnegielearning.com> Message-ID: <17627.18125.510532.334070@montanaro.dyndns.org> Brendon> A shortcut occurs to me; maybe someone can tell me what's wrong Brendon> with my reasoning here. It seems that any string that is unsafe Brendon> to pass to eval() must involve a function call, and thus must Brendon> contain an opening paren. Given that I know that the data I Brendon> expect contains no parens, would people expect this code to be Brendon> safe: Unfortunately, no. If I define a class which has properties, attribute assignment can involve arbitrary numbers of function calls. Skip From mail at microcorp.co.za Thu Aug 3 05:10:57 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Thu, 3 Aug 2006 11:10:57 +0200 Subject: Programming newbie coming from Ruby: a few Python questions References: <1154494954.082706.283750@b28g2000cwb.googlegroups.com><44d06f9f$0$19127$626a54ce@news.free.fr><1154539223.873418.286830@i42g2000cwa.googlegroups.com><1154539652.256975.155200@i3g2000cwc.googlegroups.com><1154549436.073418.202840@s13g2000cwa.googlegroups.com> <8st2d299bsqakp9vv2660djpokhbc4q2fk@4ax.com> Message-ID: <00af01c6b6e5$9a81c640$03000080@hendrik> "Dennis Lee Bieber" wrote: | On Wed, 02 Aug 2006 22:25:35 +0200, Jarek Zgoda | declaimed the following in comp.lang.python: | | > | > At the end of day we will be these who count bodies. ;) | | o/~ Listen children, to a story | that was written long ago | 'bout a kingdom, on a mountain | and the valley far below ... o/~ | -- Oh the mountain sheep were sweeter, but the valley sheep were fatter, we therefore deemed it meeter, to carry off the latter.. From richie at entrian.com Thu Aug 17 10:16:09 2006 From: richie at entrian.com (Richie Hindle) Date: Thu, 17 Aug 2006 15:16:09 +0100 Subject: List match In-Reply-To: <1155823451.766317.7640@74g2000cwt.googlegroups.com> References: <1155823451.766317.7640@74g2000cwt.googlegroups.com> Message-ID: [Stephen] > [...] compare 2 lists and generate a new list that does not copy similar > entries. An example below > > list= ["apple", "banana", "grape"] > list2=["orange","banana", "pear"] > > now I want to compare these lits and generate a third list after > comparison > > list3 would be ["apple", "banana","grape","orange", "pear"] Use sets: >>> from sets import Set as set # For compatibility with Python 2.3 >>> one = ["apple", "banana", "grape"] >>> two = ["orange","banana", "pear"] >>> print list(set(one) | set(two)) ['grape', 'apple', 'orange', 'pear', 'banana'] -- Richie Hindle richie at entrian.com From iapain at gmail.com Sat Aug 26 17:17:24 2006 From: iapain at gmail.com (iapain) Date: 26 Aug 2006 14:17:24 -0700 Subject: Python web service ... In-Reply-To: <1156590455.555359.247410@h48g2000cwc.googlegroups.com> References: <1156590455.555359.247410@h48g2000cwc.googlegroups.com> Message-ID: <1156627044.347724.299540@i42g2000cwa.googlegroups.com> > My question is how difficult is to set up a web server that can run > python easy ? should I try ZOPE or there is something better in mind ? Just install Apache and run Python as CGI thats the best solution I found for my apps. Thats the best and faster way to move python apps on web. From djoefish at gmail.com Sat Aug 19 19:00:27 2006 From: djoefish at gmail.com (djoefish) Date: 19 Aug 2006 16:00:27 -0700 Subject: install patch on windows In-Reply-To: <1156019674.571704.196780@i42g2000cwa.googlegroups.com> References: <1156014103.715131.143360@i3g2000cwc.googlegroups.com> <1156017314.249545.296940@h48g2000cwc.googlegroups.com> <1156017655.849634.95240@p79g2000cwp.googlegroups.com> <87y7tka3ev.fsf@gmail.com> <1156019674.571704.196780@i42g2000cwa.googlegroups.com> Message-ID: <1156028427.176375.265940@h48g2000cwc.googlegroups.com> djoefish wrote: > Jorge Godoy wrote: > > "djoefish" writes: > > > > > Tim Golden wrote: > > >> djoefish wrote: > > >> > Does anyone know how to install a patch on Winodws? For example, I want > > >> > to install the patch 'ocmalloc-free-arenas.diff' in Python 2.3. > > >> > > >> You can get patch (and quite a lot besides) for win32 from > > >> the UnxUtils project: > > >> > > >> http://sourceforge.net/projects/unxutils > > >> > > >> TJG > > > > > > Thanks, but that project seems to be dead.... > > > > The files there didn't work? > > > > -- > > Jorge Godoy > > > not exactly...there are NO files there. Butfrom the forums I found out > about GNUWin32, which has a 'patch' program for windows. I amd trying > it now to see if it works. I now have a 'patch' program and I am able to patch on windows. Thanks for the help. From muppadivya at gmail.com Thu Aug 10 01:28:20 2006 From: muppadivya at gmail.com (Ch3ru5) Date: 9 Aug 2006 22:28:20 -0700 Subject: Regd:Video Converter Programming In-Reply-To: <1155164376.036405.231040@n13g2000cwa.googlegroups.com> References: <1155092497.011057.219180@m79g2000cwm.googlegroups.com> <1155098914.953285.48410@i42g2000cwa.googlegroups.com> <12djo0melsc5icb@corp.supernews.com> <1155164376.036405.231040@n13g2000cwa.googlegroups.com> Message-ID: <1155187700.869574.18460@75g2000cwc.googlegroups.com> HI, Thanks all for replies . I am sorry for a confusion of the question . But what i wanted to know is in general in any programming language , how you go about writing a video converter . The basic flow of code . that's it . I will look into the resources in a particular language of my choice later . I am not clear as to how to proceed in any language . placid wrote: > Grant Edwards wrote: > > On 2006-08-09, placid wrote: > > > > >> I want to write an avi to flv converter in php but i am a complete > > >> newbie to it. > > > > > via a Google search for "python video convert" i found the following > > > > > > http://pymedia.org/ > > > > Except he wants to write it in PHP. > > > > Not sure why he's asking us about it here in c.l.python. > > > well if i see a post on comp.lang.python, then i assume its related to > python and thats what my brain did! From bedouglas at earthlink.net Wed Aug 2 09:50:11 2006 From: bedouglas at earthlink.net (bruce) Date: Wed, 2 Aug 2006 06:50:11 -0700 Subject: upgrading python... Message-ID: <0b0d01c6b63a$9359eba0$0301a8c0@Mesa.com> hi. i'min a situation where i might need to upgrade python. i have the current version of python for FC3. i might need to have the version for FC4. i built the version that's on FC4 from the python source RPM. however, when i simply try to install the resulting RPM, the app gives me dependency issues from apps that are dependent on the previous/current version of python. i'm trying to figure out if there's a 'best' way to proceed. do i simply do the install, and force it to overwrite the current version of python? is there a way to point 'yum' at my new python RPM, and let yum take care of dealing with any dependcy issues? and how would yum handle weird dependency issues with RPMs that don't exist.. does yum have the ability to actually build required apps from source? comments/thoughts/etc... thanks -bruce ps. the reason for this is that i'm looking at some of the newer functionality in the 2.4 version of python over the 2.3 From Sebastien.Boisgerault at gmail.com Wed Aug 2 11:31:11 2006 From: Sebastien.Boisgerault at gmail.com (=?iso-8859-1?q?S=E9bastien_Boisg=E9rault?=) Date: 2 Aug 2006 08:31:11 -0700 Subject: ElementTree and Unicode In-Reply-To: References: <1154530195.741884.34350@h48g2000cwc.googlegroups.com> Message-ID: <1154532671.351968.142890@b28g2000cwb.googlegroups.com> Richard Brodie wrote: > "S?bastien Boisg?rault" wrote in message > news:1154530195.741884.34350 at h48g2000cwc.googlegroups.com... > > >>>> element = Element("string", value=u"\x00") > > I'm not as familiar with elementtree.ElementTree as I perhaps > should be. However, you appear to be trying to insert a null > character into an XML document. Should you succeed in this > quest, the resulting document will be ill-formed, and any > conforming parser will choke on it. I am trying to embed an *arbitrary* (unicode) strings inside an XML document. Of course I'd like to be able to reconstruct it later from the xml document ... If the naive way to do it does not work, can anyone suggest a way to do it ? SB From gelists at gmail.com Tue Aug 8 19:56:50 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Tue, 8 Aug 2006 20:56:50 -0300 Subject: do people really complain about significant whitespace? References: <1154986984.740638.241130@m79g2000cwm.googlegroups.com> <2AY13sCznQ2EFw8+@objmedia.demon.co.uk> Message-ID: <4ezrol8iqzcc.dlg@gelists.gmail.com> On 2006-08-08 19:02:27, Stephen Kellett wrote: > In message , > Gerhard Fiedler writes >>conclusion for me: they must not like self-documenting code... :) > > Oh dear. So if the code is wrong it is self documenting? ?? I'm not sure you are actually responding to what I wrote. I did not make any affirmation about a relationship between correctness of code and its self-documenting properties. > Comments document what the code should do. > The code shows what the code actually does. That's only in theory like this, and then only in a bad theory. I'm sure in 23 years you have seen as many code comments as I have that documented what a previous version of the code should have done... > Also from a maintenance perspective reading comments is a lot faster than > reading the code. This depends a lot on the code, the comments and the reader. I prefer code that reads as fast or faster than inline comments and coders that read code as fast as comments :) (I'm not talking about useful header comments. But even these can be made a lot more succinct through appropriate coding.) > There is no such thing as self-documenting code. But there is well-written code that is as much as reasonably possible self-documenting, meaning easy to read and understand, with a clear structure, helpful names, appropriate types (where applicable) etc etc. Come on, if you have been in the business for 23 years you know what I mean. "Self-documenting" -- as used by me -- is always meant as a goal to be approached gradually, not a state where you are or not; "as much as possible" is always implied, the question is "more or less" not "whether or not". I thought that was somehow obvious... :) > People that say they don't need to document their code because its self > documenting - no hire. People that need a line of comment for every line of code -- no hire either :) It's the right balance. This is not really a subject for quick shots. And it is utterly off-topic for my post. Here's the long version of what I wrote: Python's indent-based code structure is more self-documenting than for example the brace-based structure of C in the following way. In C, it is common practice to document the code structure by indenting. Indenting in C is mere /documentation/ -- it is not required for the code to work as written, but it is required (or commonly considered required) to document its structure. When done properly, it's part of the "self-documentation" of C code: you don't write a bunch of white space-stripped C and then document the structure of that blob; you document the structure in the code by correctly indenting it. However, it is easy to write C code where the indenting and the structure are out of sync. (I know that there are tools for that, but still...) In Python, the indenting is not a documentation convention dissociated from the code structure, it /is/ the code structure. In that sense, Python code is more "self-documenting" than C. Gerhard From asincero at gmail.com Sat Aug 19 13:45:44 2006 From: asincero at gmail.com (asincero) Date: 19 Aug 2006 10:45:44 -0700 Subject: How to catch these kind of bugs in Python? Message-ID: <1156009543.993046.76720@75g2000cwc.googlegroups.com> Is there anyway to catch the following type of bug in Python code: message = 'This is a message' # some code # some more code if some_obscure_condition: nessage = 'Some obscure condition occured.' # yet more code # still more code print message In the above example, message should be set to 'Some obscure condition occured.' if some_obscure_condition is True. But due to a lack of sleep, and possibly even being drunk, the programmer has mistyped message. These types of bugs would easily be caught in languages that have a specific keyword or syntax for declaring variables before use. I'm still fairly new to using Python on a more than casual basis, so I don't know if Python has anyway to help me out here. -- Arcadio From thomas at thomas-lotze.de Tue Aug 1 14:31:26 2006 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Tue, 01 Aug 2006 20:31:26 +0200 Subject: Semantics of propagated exceptions References: Message-ID: Sorry for not answering such a long time. It's because my question originated from a discussion within our company which moved out of focus shortly after I posted, and over waiting for some response from them before replying here, I forgot about it. Steve Holden wrote: >> - f might catch E exceptions from the implementation and raise some >> other error in their stead, maybe with an appropriate message or >> treating the traceback in some helpful way. This destroys the original >> exception. >> > My "solution", of course, takes this approach. Good to see that my "gut feeling" as to the most pythonic approach seems to coincide with the answers I've received ;o) -- Thomas From metaperl at gmail.com Wed Aug 16 11:14:58 2006 From: metaperl at gmail.com (metaperl) Date: 16 Aug 2006 08:14:58 -0700 Subject: Question on extracting doc strings from .py files Message-ID: <1155741298.453417.254960@h48g2000cwc.googlegroups.com> If you type: >>> import os; help(os) Then you see the following (see below). But I don't understand where the line "MODULE DOCS http://www.python.org/doc/current/lib/module-os.html " is encoded in os.py anywhere. If you search for the words 'module-os.html' you find nothing. Ditto for 'MODULE DOCS' --- output follows --- Help on module os: NAME os - OS routines for Mac, DOS, NT, or Posix depending on what system we're o n. FILE /usr/lib/python2.4/os.py MODULE DOCS http://www.python.org/doc/current/lib/module-os.html DESCRIPTION This exports: - all functions from posix, nt, os2, mac, or ce, e.g. unlink, stat, etc. - os.path is one of the modules posixpath, ntpath, or macpath - os.name is 'posix', 'nt', 'os2', 'mac', 'ce' or 'riscos' - os.curdir is a string representing the current directory ('.' or ':') - os.pardir is a string representing the parent directory ('..' or '::') From deets at nospam.web.de Thu Aug 24 12:43:20 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 24 Aug 2006 18:43:20 +0200 Subject: String formatting with nested dictionaries In-Reply-To: <1156436560.040352.162580@b28g2000cwb.googlegroups.com> References: <1156436560.040352.162580@b28g2000cwb.googlegroups.com> Message-ID: <4l6399FeihrU1@uni-berlin.de> linnorm at gmail.com schrieb: > I've got a bit of code which has a dictionary nested within another > dictionary. I'm trying to print out specific values from the inner > dict in a formatted string and I'm running into a roadblock. I can't > figure out how to get a value from the inner dict into the string. To > make this even more complicated this is being compiled into a large > string including other parts of the outer dict. > > mydict = {'inner_dict':{'Value1':1, 'Value2':2}, 'foo':'bar', > 'Hammer':'nails'} > > print "foo is set to %(foo)s - Value One is: %(inner_dict['Value1'])s > and Value Two is: %(inner_dict['Value2'])s -- Hammers are used to pound > in %(Hammer)s" % mydict > > The above fails looking for a key named 'inner_dict['Value1']' which > doesn't exist. > > I've looked through the docs and google and can't find anything > relating to this. Because it is not supported. You can only use one level of keys, and it must be strings. So you have to do it like this: print "foo is set to %(foo)s - Value One is: %(inner_dict['Value1'])s and Value Two is: %(inner_dict['Value2'])s -- Hammers are used to poundin %(Hammer)s" % dict(Hammer=mydict['Hammer'], Value1=mydict["inner_dict"]["Value1"], Value2=mydict["inner_dict"]["Value2"]) Diez From bdesth.quelquechose at free.quelquepart.fr Mon Aug 28 16:38:23 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 28 Aug 2006 22:38:23 +0200 Subject: how to get the os file icon for a given content-type? In-Reply-To: <1156759387.819060.266380@m73g2000cwd.googlegroups.com> References: <1156753983.080547.306100@h48g2000cwc.googlegroups.com> <44f2b8cc$0$11818$636a55ce@news.free.fr> <1156759387.819060.266380@m73g2000cwd.googlegroups.com> Message-ID: <44f35184$0$6709$636a55ce@news.free.fr> neoedmund a ?crit : please don't top-post (corrected) > Bruno Desthuilliers wrote: > >>neoedmund wrote: >>Please repeat the whole question in the message body >> >>=>how to get the os file icon for a given content-type? >> >>>any simple method? >> >>This is specific to your OS (and FWIW, there's nothing like a "file >>icon" on the OS I'm using). >> > So what? Java 5.0 has the method, why python has not? There are a lot of things that Java has an Python don't. And a lot of things that Python has and Java don't. And FWIW, I'd really like to know how the Java implementation of such a 'feature' would work on a system where there's *no* 'os file icon' associated to a given content-type. From pavlovevidence at gmail.com Sat Aug 19 22:57:54 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 19 Aug 2006 19:57:54 -0700 Subject: sum and strings References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <7xr6zel2r2.fsf@ruckus.brouhaha.com> <1155971485.709068.255140@b28g2000cwb.googlegroups.com> <1156038134.216383.80960@h48g2000cwc.googlegroups.com> Message-ID: <1156042674.557669.120650@h48g2000cwc.googlegroups.com> Rhamphoryncus wrote: > It's also worth stressing (not in response to your post, but others) > that sum([[1],[2],[3]], []) is just as bad as attempting to sum > strings, both conceptually (it's not mathematical addition), and > performance-wise. Don't do it. :) Interesting. I would have guessed that, internally, sum was implemented with in-place operations (except for the first operation, which would have to be non-in-place so that it wouldn't modify a mutable initial value). But looking at the source, I see that I would have guessed wrongly: it does not use in-place operations. So, although lists are optimized for growing, sum would end up creating a new list each iteration anyways. Thus it does have the same penalty that strings would have. Good to know. Obviously, sum can't check for every possible type that would be inefficient, but at least it could check for common builtins (str, list, tuple). That it only checks for strings suggests to me that this really is just a case of protecting the unwary. Concatenating strings is common enough, and the drawbacks of using sum bad enough, that a special case was considered justified. Lists and tuples, though theoretically they have the same issues as strings, probably don't justify a special case because they're not as common. > I believe the prefered method to flatten a list of lists is this: > > shallow = [] > for i in deep: > shallow.extend(i) > > Yes, it's three lines. It's also very easy to read. reduce() and > sum() are not. sum() is really for numerical uses; people ought to just stick to using it that way. Carl Banks From __peter__ at web.de Wed Aug 2 07:38:01 2006 From: __peter__ at web.de (Peter Otten) Date: Wed, 02 Aug 2006 13:38:01 +0200 Subject: Behavior on non definded name in Cheetah References: Message-ID: Paolo Pantaleo wrote: > 2006/8/2, Stephan Diehl : >> Paolo Pantaleo wrote: >> > [I hope I am posting to the right place] >> > >> > I have a cheetah template something like this: >> > >> > x is: $x >> > y is: $y >> > z is: $z >> > >> > [Actually more complicated] >> > >> > If for example $y is not defined I get an exception and the parsing >> > of the template stops. Is there any way to substitute $y with an emty >> > string and making cheeta going on with parsing? >> > >> > Thnx >> > PAolo >> > >> >> http://cheetahtemplate.org/docs/users_guide_html_multipage/language.namemapper.missing.html >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > Actually I wanted to keep things simple for who writes the template, > so I am using this workaround: I define a class > > class ClassMapper: > def __init__(self,dict={}): > self.__dict=dict > def getValue(self,str): > try: > return self.__dict[str] > except KeyError: > return "" > > x=ClassMapper(dict) > Template(definition, searchList=[{"info":x.getValue}]) > > > > so the user should do > > $info("name") > > Maybe I could define a class that implements a dictionary and doesn''t > raise an exception for a key not present... but it seems to > complicated. You mean something like from Cheetah.Template import Template class Dict(dict): def __getitem__(self, key): return self.get(key, "") template = """\ x is $x y is $y z is $z """ print Template(template, searchList=[Dict(x="x", y="y")]) You can also make a debugging version: class Dict(dict): def __getitem__(self, key): return self.get(key, "#missing key: %r#" % key) Peter From sjmachin at lexicon.net Mon Aug 7 16:22:03 2006 From: sjmachin at lexicon.net (John Machin) Date: 7 Aug 2006 13:22:03 -0700 Subject: How to get hours and minutes from 'datetime.timedelta' object? In-Reply-To: <1154960599.138371.82350@m79g2000cwm.googlegroups.com> References: <1154940942.707530.291130@m79g2000cwm.googlegroups.com> <1154942169.530491.150390@h48g2000cwc.googlegroups.com> <1154948054.987468.202100@i3g2000cwc.googlegroups.com> <1154956194.252771.27070@b28g2000cwb.googlegroups.com> <1154960599.138371.82350@m79g2000cwm.googlegroups.com> Message-ID: <1154982123.798662.222790@m73g2000cwd.googlegroups.com> Ant wrote: > John Machin wrote: > ... > > 1. If that's what he wanted, it was a very peculiar way of asking. Do > > you suspect that he needs to be shown how to conver 877.7... minutes > > into hours, minutes and seconds??? > > Chill dude, It wasn't an attack :-) I didn't think it was. > > The datetime class has hour, minute and second attributes that give the > values of each as being in range(24) (hours) and range(60). i.e. > integers. So an educated guess leads me to the conclusion that it is > similar functionality that he wants from the timedelta class. > > > 2. Please consider that the order of the result would be more > > conventionally presented as (hours, minutes, seconds) -- or do you > > Very good point. That would have been a tricky issue for the OP, and > for that I apologise. > > > suspect that the OP needs it presented bassackwards? > > I think that you have that last word muddled. Not quite ass-backward, > but close ;-) On the contrary. It means "ass-backward, and then some". Google "dictionary bassackwards" and read the first few hits. Cheers, John From mail at microcorp.co.za Thu Aug 3 03:17:41 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Thu, 3 Aug 2006 09:17:41 +0200 Subject: Is there an obvious way to do this in python? References: <1154541495.486057.316740@i3g2000cwc.googlegroups.com> Message-ID: <016e01c6b6cd$2f276660$03000080@hendrik> "Yu-Xi Lim" wrote: | Simon Forman wrote: | >> Or has all this been done already? - and no I don't want a web server and php | >> and browsers and Java and html or xml... - I want to write something that works | >> simply and reliably - its just short message accounting type data... | >> | >> - Hendrik | > | > Don't reinvent the wheel. Use a database... | > | > You probably don't want to hear this, but what you just described is a | > GUI client front-end with a database backend. The time it takes to | > download, install, and learn to use, say, postgres will be similar to | > the time you'd spend implementing what you've described above, but with | > at least 10 to 100 times the payoff. | > | > | > As for updating the client on the fly, one strategy would be to keep | > the "dynamic" code in it's own module and have the clients reload() | > that module when you upload a new version of it to the client machines. | | Yes, indeed, using a database with a GUI front end is the best way to | get "something that works simply and reliably." Writing everything in | Python isn't always the best solution. Python, however, is very good at | interfacing with most existing applications and thus makes a great "glue." | | Using a proper DB system would give up transactions, multiple users, and | access control, which you have said you required, and probably more | features which you hadn't realized you needed but soon will when you | scale up beyond a toy system (optimized queries, backups, load | balancing, encrypted connections, etc). Can I not use the ssl module for encrypting the connections? - Please also understand that the system is aimed at small to medium companies, in house - >From my perspective the only valid reason to use a database would be for the ease of reporting - the files are not large - and the speed of a dict lookup in python is hard to beat for normal transaction processing... | | As for updating the applications, why not just put them on the server | for each "user"/client to retrieve? There are of course several ways of | retrieving the centrally stored GUI program, and most likely you're | thinking Windows file sharing (which would require restarting the client NO! the last thing on my mind - want a dynamic process similar to banking terminals - see my response to Simon please | whenever updates are available). But don't rule out HTTP. Among the I have been shying away from this - due to mental laziness - but obviously I have to look at it - thanks | benefits of web apps are the ability to update the application on the | fly and deploy it quickly. And no, web apps don't necessarily mean PHP, | Java or XML. You can easily use plain HTML and Python to create the GUI | and interface it with the database. AJAX may be th buzzword now, but it | isn't necessary for everything. Thanks will *have* to look at html From http Thu Aug 31 14:01:29 2006 From: http (Paul Rubin) Date: 31 Aug 2006 11:01:29 -0700 Subject: GC and security References: <44F61EEB.8040207@optonline.net> <7x4pvtpxnc.fsf@ruckus.brouhaha.com> <44F63356.6060400@optonline.net> <7xlkp5h91p.fsf@ruckus.brouhaha.com> Message-ID: <7xy7t4ss1y.fsf@ruckus.brouhaha.com> Les Schaffer writes: > keys are on a USB drive key ring. gpg accesses the key ring as needed, > but in a separate process. and gpg is done with its work early on in our > app lifetime. comes back at end to encrypt and then app is done. gpg is fairly careful about passphrases. Why are you collecting the passphrase in the Python app instead of letting gpg handle it? > > Keep in mind that the weakest part of this application is likely to be > > the passphrase itself. Is there a way to get rid of it? > > we got some suggestions from other parts of this thread. or do you mean > getting rid of the need for a passphrase? the passhprase protects the > private key on the USB drive. Yes, I mean get rid of the need for a passphrase, though since the encrypted key is accessible on the USB drive, there's no way around it. With smart cards it's generally considered ok to use a short PIN instead of a passphrase; the card itself enforces a maximum # of incorrect guesses. > > Is this data on a laptop? Why do you want to do encryption in the > > application, instead of using an encrypted file system? ...> > but the main reason? we were asked to encrypt the MySQL tables carrying > sensitive information. Does using an encrypted FS not take care of that? Also, I think there are some FS's that use the Windows Crypto API (CAPI) either for bulk encryption or for key management, so you can use secure passphrases, hardware tokens, or whatever. > USB drive holds the GPG key. the drive must be inserted at start of > application, and must be pulled after authentication otherwise the app > warns and shuts down. The USB drive carries a digital signature, and > also encrypted identifying information for the user. This is better than nothing but it's very easy to duplicate a USB key, either intentionally or by spilling the contents through a routine backup procedure, etc. A crypto token (USB dongle or smart card) is way preferable for this type of thing. GPG has smart card support that you might be able to use: http://www.g10code.com/p-card.html http://www.gnupg.org/(en)/howtos/card-howto/en/smartcard-howto-single.html You might want to discuss this on sci.crypt, where specialists hang out. As is fairly typical in these situations, it would help a lot if you could describe the application in more detail. From pavlovevidence at gmail.com Thu Aug 10 08:03:44 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 10 Aug 2006 05:03:44 -0700 Subject: do people really complain about significant whitespace? In-Reply-To: <1155210185.163476.149610@p79g2000cwp.googlegroups.com> References: <1154986984.740638.241130@m79g2000cwm.googlegroups.com> <87bqqwyumq.fsf@benfinney.id.au> <1155077965.100108.232790@m79g2000cwm.googlegroups.com> <44d9d949$0$14310$626a54ce@news.free.fr> <1155134902.103617.71810@i3g2000cwc.googlegroups.com> <1155210185.163476.149610@p79g2000cwp.googlegroups.com> Message-ID: <1155211424.702496.163340@75g2000cwc.googlegroups.com> gslindstrom at gmail.com wrote: > Carl Banks wrote: > > Although Python doesn't do this, it is possible to mandate a specific > > indent (4 spaces, say), or at least a reasonable consistent indent > > I like running reindent.py (found in your Python source directory under > Tools/Scripts) which cleans up indentations, trailing whitespace, and > other things. We run our entire source directory through reindent > before we check it into our library. A very nice routine courtesy of > Tim Peters, I believe. The very fact the code reindenters exist should tell you that fixed indent is superior. :) Carl Banks From jack at psynchronous.com Wed Aug 16 17:23:06 2006 From: jack at psynchronous.com (Jack Diederich) Date: Wed, 16 Aug 2006 17:23:06 -0400 Subject: PySequence_SetItem In-Reply-To: <1155761144.583994.260150@m73g2000cwd.googlegroups.com> References: <1155754847.392950.266180@h48g2000cwc.googlegroups.com> <1155755905.233229.93440@74g2000cwt.googlegroups.com> <1155761144.583994.260150@m73g2000cwd.googlegroups.com> Message-ID: <20060816212306.GC5772@performancedrivers.com> On Wed, Aug 16, 2006 at 01:45:44PM -0700, John Machin wrote: > Bill Pursell wrote: > > Bill Pursell wrote: > > > > Also note that the problem goes away if I replace > > the call to PySequence_SetItem with: > > PySequence_SetItem(l, 0, PyInt_FromLong(1L)); > > Are you sure? It should make absolutely no difference. > > My experience so far: > 1. crashes in call to PySequence_SetItem > 2. removed py_DECREF, s/Sequence/List/ -> works OK > 3. added code to test return value from PyWhatever_SetItem [you should > *always* test for error], s/Sequence/Object/ -> PyObject_SetItem call > returns -1, PyErr_Print -> "SystemError: null argument to internal > routine" Changing the PySequence_SetItem to PyList_SetItem and dropping the DECREF works for me too (PyList functions steal a reference). I also tried setting the list to length 1, still no dice. The PySequence version segs under 2.4 and 2.5. It segs even when the Int is changed to a String. Yikes, I'll poke around some more. -Jack From lsumnler at gmail.com Thu Aug 10 17:28:10 2006 From: lsumnler at gmail.com (len) Date: 10 Aug 2006 14:28:10 -0700 Subject: semi-Newbie question In-Reply-To: <1155240906.769756.294620@74g2000cwt.googlegroups.com> References: <1155229897.356144.183750@m79g2000cwm.googlegroups.com> <1155240906.769756.294620@74g2000cwt.googlegroups.com> Message-ID: <1155245290.532108.75560@75g2000cwc.googlegroups.com> I appoligize I don't think I have done a very good job of explaining my problem. I work in the an insurance company that sells non standard auto. We have an in house policy management system that uses MySQL for the data storage. An individual policy consists of a policy header and 1 to n drivers, 1 to n vehicles and 1 to n coverage records per vehicle. A third party company will sell a policy and place it with our company. They collect all of the information on their system and then send this information to us as a CSV file (one file per policy). **This CSV file is like an XML file and is formated as followes; 1st field is a tagname 2nd field is a scope 3rd field is a value see example "totalpolicypremium","pol0","1584" "quotenumber","pol0","5" "address1","pol0","123 Testing Street" "address2","pol0","" "apartmentnumber","pol0","" "cellphone","pol0","( ) -" ... "annualmiles","car1","0" "antilock","car1","A" "antitheft","car1","1" "bodytype","car1","4D" "buybackpip","car1","N" "carphone","car1","N" "city","car1","ALEXANDRIA" "coaccdeathlimit","car1","0" ... "annualmiles","car2","0" "antilock","car2","N" "antitheft","car2","1" "bodytype","car2","4D" "buybackpip","car2","N" "carphone","car2","N" "city","car2","ALEXANDRIA" ... "address1","drv1","123 Testing Street" "address2","drv1","" "agerated","drv1","0" "banklienjudgstat","drv1","N" "cellphone","drv1","( ) -" "city","drv1","Testing City" "cluestatus","drv1","N" etc The third party company sent me a file that contained all of their valid tagnames and scope which I then took and create a crossreference file with three fields: xreffile tagname (key) scopy SQL_fieldname The program I am writing is nothing more than a conversion program to take the value out of the CSV file and map it into the appropriate field in my SQL files. Rather than creating some huge if than else (there are over 1000 tagnames) I created the xreffile. Now when I read a record from the tagfile I use the data in the tagname field to lookup the tagname in my xreffile. The data in the SQL_fieldname is the fieldname in my SQL files I want to place the data from the tagfile in the tagfile.value field into this field in my SQL files; data referenced by(xreffile.SQL_fieldname) = tagfile.value what I see as the problem is I want to use what is the data reference by xreffile.SQL.fieldname and now make it part of the python code as a reference variable in an assignement code statement. I hope this helps Len Sumnler Unique Insurance davideugenewarren at gmail.com wrote: > Do you absolutely need to use variables? A dictionary would serve if > each case has a unique identifier. > > client_info_dict = {} > > for i in tagfile: > tagname,scope,value = i.replace('"','').split(',') # split fields, > strip redundant characters > client_info_dict.setdefault(scope,{}) # set up an empty nested > dict for the unique ID > client_info_dict[scope][tagname] = value # set the tagname's value > > Then client info can be retrieved from the dictionary using unique IDs > and stereotyped tags (with .get() if some tags are not always present). > I won't make any claims about the efficiency of this approach, but it > works for me. > > len wrote: > > Hi all > > > > I have a file that I receive from another party which is basicly a csv > > file containing the following type of information; > > > > Tagname Scope Value > > "first_name","POL01","John" > > "last_name","POL01","Doe" > > "birthday","POL01","04/03/61" > > etc > > > > I need to convert this file info into my file format used in my > > application. > > > > I have been given a file from the other company that gives me all of > > the tagname that could be used and their scope. I want to build a > > table which would have all of the various tagnames, scope, and put a > > fieldname equivalent in the fieldname in my file structure in my > > application. Then read through the vendors csv file index into my > > table file and get the field name of where to move the data into my > > data structure. > > > > Here is my question? basicly I need to get the data referenced by > > fieldname variable in my table and then use that data as a variable > > name in a python assignment statement. Thus changing the actual python > > code at each iteration through the lines in the csv file. > > > > for i in tagfile > > find tagname in tagtable > > > > *** the following line of code would change through each iteration *** > > myfirst = value > > > > *** next iteration > > mylast = value > > > > *** next iteration > > mybirth = value > > > > etc > > > > I hope this make sense. I remember seeing something like this > > somewhere. > > > > Any help appreciated. > > > > Len Sumnler > > Unique Insurance From fredrik at pythonware.com Fri Aug 25 09:24:08 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Aug 2006 15:24:08 +0200 Subject: performance of dictionary lookup vs. object attributes References: <7008329d0608250138m3207567elf3e32ee67cb5eb2a@mail.gmail.com> <7008329d0608250603v3b94d321p52f6dc2ac841b796@mail.gmail.com> Message-ID: Andre Meyer wrote: > So, what it means is that the test is not meaningful, because of the > different way that object attributes are accessed (not as o.x, which > could be compiled). correct, but you may be overestimating what the compiler can do. here's the byte code for the various cases: # x.attr 2 0 LOAD_FAST 0 (x) 3 LOAD_ATTR 0 (attr) 6 POP_TOP # getattr(x, "attr") 3 7 LOAD_GLOBAL 1 (getattr) 10 LOAD_FAST 0 (x) 13 LOAD_CONST 1 ('attr') 16 CALL_FUNCTION 2 19 POP_TOP # x.__getattribute__("attr") 4 20 LOAD_FAST 0 (x) 23 LOAD_ATTR 2 (__getattribute__) 26 LOAD_CONST 1 ('attr') 29 CALL_FUNCTION 1 32 POP_TOP the LOAD_ATTR instruction uses a much faster code path to get at the internal dictionary, while the getattr() and __getattribute__ forms needs to do extra work to get to the actual attribute lookup. > Nevertheless, the general impression remains that dicts *are* faster > than objects, because attribute lookup uses dicts itself. Is that > correct? correct. once the interpreter gets to actually do the lookup, the performance is identical (and the dictionary implementation is *extremely fast*). it's the stuff that needs to be done to get there that differs. From kentilton at gmail.com Thu Aug 17 12:06:00 2006 From: kentilton at gmail.com (Ken Tilton) Date: Thu, 17 Aug 2006 12:06:00 -0400 Subject: The Semicolon Wars as a software industry and human condition In-Reply-To: <1155822175.534005.100490@75g2000cwc.googlegroups.com> References: <1155822175.534005.100490@75g2000cwc.googlegroups.com> Message-ID: <0u0Fg.345$fE5.316@newsfe11.lga> Xah Lee wrote: > > ? What Languages to Hate, Xah Lee, 2002 > http://xahlee.org/UnixResource_dir/writ/language_to_hate.html Nonsense. This is technology, not religion. Technologists in fact have a responsibility to identify and use the best tools available. Xah, you are getting soft in your old age. :) hth, kenny -- Cells: http://common-lisp.net/project/cells/ "I'll say I'm losing my grip, and it feels terrific." -- Smiling husband to scowling wife, New Yorker cartoon From jzgoda at o2.usun.pl Thu Aug 3 15:58:30 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Thu, 03 Aug 2006 21:58:30 +0200 Subject: OS independent files In-Reply-To: References: <1154632873.085941.281850@75g2000cwc.googlegroups.com> Message-ID: Tim Chase napisa?(a): > Well, there in os.path you'll find expanduser() so you can do things like > >>>> homedir = os.path.expanduser("~") >>>> filename = os.path.join(homedir, "myfiles", "myfile.dat") > > Seems to work well for me. On Windows, this is consistent between releases (i.e. you'll end up elsewhere on W2k Pro, W2k Server, Win XP and W2003). -- Jarek Zgoda http://jpa.berlios.de/ From Tim.Gallagher at gd-ais.com Fri Aug 18 17:12:28 2006 From: Tim.Gallagher at gd-ais.com (Gallagher, Tim (NE)) Date: Fri, 18 Aug 2006 17:12:28 -0400 Subject: Search or compai problem Message-ID: <794CB73454A59D488ED061055AA282073CB92A@miaa01-mail01.ad.gd-ais.com> I am new to python and I want to compare 2 strings, here is my code: [start] import active_directory import re lstUsers = [] users = active_directory.root() for user in users.search ("sn='gallagher'"): lstUsers.append(user.samAccountName) print "----------------------------------------" lstUsers.sort() ## Printing out what is inside of the arrar(list) x = 0 while x < len(lstUsers): if re.compile(lstUsers[x]).match("None",0): print "Somthing here" x = x + 1 [/end] When I do the: if re.compile(lstUsers[x]).match("None",0): print "Somthing here" Some of the items in lstUsers[x] are the word None. I am not sure why I cant do this I want to compare lstUsers[x] to the word "None", how can I do this. Thanks Timothy F. Gallagher CSC Systems Engineer From bjourne at gmail.com Thu Aug 31 21:16:54 2006 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Fri, 1 Sep 2006 03:16:54 +0200 Subject: SQLObject or SQLAlchemy? In-Reply-To: References: Message-ID: <740c3aec0608311816t230223b2i502e62f162b1253c@mail.gmail.com> I think this post by the author of SQLAlchemy perfectly summarizes the differences between the two ORMs: http://article.gmane.org/gmane.comp.python.sqlalchemy.user/1072/ -- mvh Bj?rn From david at boddie.org.uk Sat Aug 19 20:32:47 2006 From: david at boddie.org.uk (David Boddie) Date: 19 Aug 2006 17:32:47 -0700 Subject: Disable close button in management window.(KDE- pyQT) References: <1155926338.062804.114260@i42g2000cwa.googlegroups.com> Message-ID: <1156033967.195411.42610@b28g2000cwb.googlegroups.com> Gabriel - BR wrote: > Hi,,, > Is possible disable the close button in KDE management window? Using > python+qt? Can you say exactly which window you're talking about? The "Control Center" or something else? David From lgoh at optonline.net Sat Aug 26 13:55:06 2006 From: lgoh at optonline.net (leo) Date: Sat, 26 Aug 2006 13:55:06 -0400 Subject: marshal and unmarshal Message-ID: <7W%Hg.3545$k%3.270@newsfe12.lga> Hi, following is marshal and unmarshal script import marshal strng = """ print 'hello world' """ code = compile(strng, "", "exec") data = marshal.dumps(code) strng0 = marshal.loads(data) print repr(data) print "-"*100 print strng0 ###Result: 'c\x00\x00\x00\x00\x01\x00\x00\x00s\x0f\x00\x00\x00\x7f\x00\x00\x7f\x02\x00d\x00\x00GHd\x01\x00S(\x02\x00\x00\x00s\x0b\x00\x00\x00hello worldN(\x00\x00\x00\x00(\x00\x00\x00\x00(\x00\x00\x00\x00(\x00\x00\x00\x00s\x07\x00\x00\x00s\x01\x00\x00\x00?\x02\x00s\x00\x00\x00\x00' ---------------------------------------------------------------------------------------------------- ", line 2> Question: 1. why unmarshal data is ", line 2> not 'c\x00\x00\x00\x00\x01\x00\x00\x00s\x0f\x00\x00\x00\x7f\x00\x00\x7f\x02\x00d\x00\x00GHd\x01\x00S(\x02\x00\x00\x00s\x0b\x00\x00\x00hello worldN(\x00\x00\x00\x00(\x00\x00\x00\x00(\x00\x00\x00\x00(\x00\x00\x00\x00s\x07\x00\x00\x00s\x01\x00\x00\x00?\x02\x00s\x00\x00\x00\x00' 2. how safe is the compiled and serialize data. 'c\x00\x00\x00\x00\x01\x00\x00\x00s\x0f\x00\x00\x00\x7f\x00\x00\x7f\x02\x00d\x00\x00GHd\x01\x00S(\x02\x00\x00\x00s\x0b\x00\x00\x00hello worldN(\x00\x00\x00\x00(\x00\x00\x00\x00(\x00\x00\x00\x00(\x00\x00\x00\x00s\x07\x00\x00\x00s\x01\x00\x00\x00?\x02\x00s\x00\x00\x00\x00' From webraviteja at gmail.com Sat Aug 26 15:29:02 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 26 Aug 2006 12:29:02 -0700 Subject: Python web service ... In-Reply-To: References: <1156590455.555359.247410@h48g2000cwc.googlegroups.com> Message-ID: <1156620542.837019.120080@m79g2000cwm.googlegroups.com> Tim Williams wrote: > > At this time right now I prefer to do something that works the quickest > > possible... > > I never had any experience with CGI, do I need to set up a web server > > for that ? > > can you point me some usefull reading material so I can get a start ? > > I will post for a comment at Zope , I had installed once and it was > > very easy. Don't know if it will be easy too to get my job done... > > If you need a quick-start and short learning curve, Karrigell is the > one to go for. You can have the beginnings of your own site/web-app > running within minutes of downloading it. > > It now has better CGI handling too - if you must go that route :) > > www.karrigell.com > > I recommend the Karrigell tour also, click on the icon next to each > example to see how each one is coded, and it has a file upload example > that should get you started. > > http://karrigell.no-ip.info/demo/frame_tour_en.htm > > :) I second Karrigell on simplicity. Zope despite recent improvements, still has a steep learning curve. From jhefferon at smcvt.edu Tue Aug 1 19:44:41 2006 From: jhefferon at smcvt.edu (Jim) Date: 1 Aug 2006 16:44:41 -0700 Subject: XML parsing and writing In-Reply-To: <1154111594.276996.161800@b28g2000cwb.googlegroups.com> References: <1154111594.276996.161800@b28g2000cwb.googlegroups.com> Message-ID: <1154475881.302874.282780@75g2000cwc.googlegroups.com> c00i90wn wrote: On first write of the xml everything goes > as it should but on subsequent writes it starts to add more and more > unneeded newlines to it making it hard to read and ugly. Pretty make it pretty by putting in newlines (and spaces) that are not in the original data. That is, if you have text "John Smith" associated with the element then pretty gives you something like John Smith here with an extra two newlines and some whitespace indentation. (I don't recall 100% when it puts in stuff, but the point of pretty is to put in extra stuff.) You need to strip out the extra stuff (or print it out not pretty; can you get a viewer that buffs-up a notbuff file so you are seeing pretty but the data isn't actually pretty?). Jim From maxm at mxm.dk Tue Aug 29 05:09:24 2006 From: maxm at mxm.dk (Max M) Date: Tue, 29 Aug 2006 11:09:24 +0200 Subject: The lib email parse problem... In-Reply-To: <1156841950.866776.66400@b28g2000cwb.googlegroups.com> References: <1156837260.222395.305960@b28g2000cwb.googlegroups.com> <1156841437.692537.68200@i42g2000cwa.googlegroups.com> <1156841950.866776.66400@b28g2000cwb.googlegroups.com> Message-ID: <44f40379$0$14045$edfadb0f@dread15.news.tele.dk> ???? wrote: > this is not enough. > > when a part is mulitpart/alternative, i must find out which sub part i > need, not all the subparts. so i must know when the alternative is > ended. Have you tried the email module at all? -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 From rochester1976 at gmail.com Fri Aug 4 11:36:39 2006 From: rochester1976 at gmail.com (Rochester) Date: Fri, 04 Aug 2006 11:36:39 -0400 Subject: Python open a named pipe == hanging? References: <1hjic95.ojxkeuodeqbtN%aleax@mac.com> Message-ID: Thank you for your advise. So, it turns out that fifos are quite useless in Python programming then, which is quite disappointing to me :-( I am not saying that I _have to_ use fifo, afterall it is a rather odd thingy not in fasion since the last iceage... I am just disappointed by the fact that the old plain Bash seems to excel Python in this special aspect. I am new to Python and much more comfortable in Bash programming. A simple Bash script like this would take the advantage of a fifo, hence reduce the overhead of unneccesarry temporary files creation: #!/bin/bash mkfifo my_fifo echo "this is a string in my fifo!" > my_fifo & cat my_fifo rm my_fifo Isn't it neat? Anyway, I think every scripting language has its pros and cons. Bash is probably more flexible in dealing with fifos and multiway pipes (through the magic menchanism of process substitution). Thank you! On Thu, 03 Aug 2006 22:13:56 -0400, Alex Martelli wrote: From ask at me Sat Aug 12 09:18:14 2006 From: ask at me (alf) Date: Sat, 12 Aug 2006 09:18:14 -0400 Subject: iterator wrapper In-Reply-To: <7x1wrmwz96.fsf@ruckus.brouhaha.com> References: <8cednRaDbu_RkkDZnZ2dnUVZ_sKdnZ2d@comcast.com> <1155339879.395139.182050@m73g2000cwd.googlegroups.com> <1155340917.733325.74780@i3g2000cwc.googlegroups.com> <7x1wrmwz96.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > alf writes: > >>>|>> I = ([n] for n in i) >> >>This is nice but I am iterating thru hude objects (like MBs) so you know ... > > > I don't understand the objection-- the above is entirely correct and > produces the same iterator you'd get from > > def wrap(i): > for x in i: > yield [x] > I = wrap(i) > > You could also use > > import itertools > I = itertools.imap(lambda x: [x], i) > > which again does the same thing. I did see [] instead of () :-). this was a source of confusion. okay, we have 3 functionally equal solution - which is most pythonic :-) .... seroiusly ... -- alf From jspeis at gmail.com Mon Aug 7 15:39:37 2006 From: jspeis at gmail.com (Jon) Date: 7 Aug 2006 12:39:37 -0700 Subject: Installing a Windows Printer In-Reply-To: <1154976472.754129.222830@i3g2000cwc.googlegroups.com> References: <1154976472.754129.222830@i3g2000cwc.googlegroups.com> Message-ID: <1154979577.627013.215790@m79g2000cwm.googlegroups.com> Hi D, I would suggest that you look here http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdi/prntspol_7mgj.asp at AddPort and and AddPrinter. Though I have not tried to use them in python, I would assume that using win32com [http://www.python.net/crew/mhammond/win32/Downloads.html] or the like you'd be able to make use of those functions. Jon D wrote: > I would like to create a script for Windows 2000 that will create a > Standard TCP/IP printer port and install a printer (I have the > applicable printer drivers needed for the install on a network share). > My plan is to use py2exe and distribute (also via network share) the > script so that administrators, or even users, can easily install the > printer. Is this possible? If so, I would appreciate it if someone > could steer me in the right direction in terms of how to begin (i.e. > libraries needed, sample code). Thanks! From duncan.booth at invalid.invalid Tue Aug 22 03:57:48 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 22 Aug 2006 07:57:48 GMT Subject: how do you get the name of a dictionary? References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> Message-ID: jojoba wrote: > However, does it not seem reasonable to ask python: > > Given a dicitionary, Banana = {} > return one or more strings, > where each string is the name(s) of the reference(s) to Banana. > > why is this not sane?!?! > what am i missing here? Some time back I posted some code which would do exactly that, but it is not nice, and it is buggy, but if you want to play with it: http://groups.google.co.uk/group/comp.lang.python/tree/browse_frm/thread/394ba5b48f83ebfb/237dc92f3629dd9a >>> import varname >>> Banana = {} >>> class C: ... classFruit = [{}, Banana] ... >>> def names(x): ... for s in varname.object_info(x): ... print s ... >>> names(Banana) __main__.C.classFruit[1] __main__.Banana __main__.names()x The problem as others have said is that there are a lot of namespaces in Python (module globals, classes, instances, local variables of active functions, ...), and the only way to find which names refers to an object is to search the relevant namespaces. There is some information which can help: for any object you can get a list of all objects that refer to it, and that can be used to trace backwards until you find a namespace at which point you still have to search the namespace to find out which name refers to the object. Of course doing all this creates lots of new references and infinite loops both of which you have to ignore. From jelleferinga at gmail.com Mon Aug 14 07:38:57 2006 From: jelleferinga at gmail.com (jelle) Date: 14 Aug 2006 04:38:57 -0700 Subject: Best IDE for Python In-Reply-To: References: <1155541849.350392.31190@h48g2000cwc.googlegroups.com> Message-ID: <1155555537.877334.61030@75g2000cwc.googlegroups.com> I think SPE is a terrible complete and efficient IDE! From anthony at python.org Fri Aug 4 00:41:24 2006 From: anthony at python.org (Anthony Baxter) Date: Fri, 4 Aug 2006 14:41:24 +1000 Subject: RELEASED Python 2.5 (beta 3) Message-ID: <200608041441.32253.anthony@python.org> On behalf of the Python development team and the Python community, I'm happy to announce the third BETA release of Python 2.5. This is an *beta* release of Python 2.5. As such, it is not suitable for a production environment. It is being released to solicit feedback and hopefully discover bugs, as well as allowing you to determine how changes in 2.5 might impact you. If you find things broken or incorrect, please log a bug on Sourceforge. In particular, note that changes to improve Python's support of 64 bit systems might require authors of C extensions to change their code. More information (as well as source distributions and Windows and Universal Mac OSX installers) are available from the 2.5 website: http://www.python.org/2.5/ There's been over 50 fixes since the second beta. This large number of changes meant we felt more comfortable cutting a third beta release, rather than charging ahead to the release candidate. As of this release, Python 2.5 is now in *feature freeze*. Unless absolutely necessary, no functionality changes will be made between now and the final release of Python 2.5. The plan is that this will be the final beta release (no, really, this time for sure (probably)). We should now move to one or more release candidates, leading to a 2.5 final release early August. PEP 356 includes the schedule and will be updated as the schedule evolves. At this point, any testing you can do would be greatly, greatly appreciated. The new features in Python 2.5 are described in Andrew Kuchling's What's New In Python 2.5. It's available from the 2.5 web page. Amongst the language features added include conditional expressions, the with statement, the merge of try/except and try/finally into try/except/finally, enhancements to generators to produce a coroutine kind of functionality, and a brand new AST-based compiler implementation. New modules added include hashlib, ElementTree, sqlite3, wsgiref and ctypes. In addition, a new profiling module "cProfile" was added. Enjoy this new release, Anthony Anthony Baxter anthony at python.org Python Release Manager (on behalf of the entire python-dev team) -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 198 bytes Desc: not available URL: From ptmcg at austin.rr._bogus_.com Mon Aug 21 11:55:23 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 21 Aug 2006 15:55:23 GMT Subject: Problem of function calls from map() References: Message-ID: "Dasn" wrote in message news:mailman.9606.1156169593.27775.python-list at python.org... > > Hi, there. > > 'lines' is a large list of strings each of which is seperated by '\t' > >>> lines = ['bla\tbla\tblah', 'bh\tb\tb', ... ] > > I wanna split each string into a list. For speed, using map() instead > of 'for' loop. Try this. Not sure how it stacks up for speed, though. (As others have suggested, if 'for' loop is giving you speed heartburn, use a list comprehension.) In this case, splitUsing is called only once, to create the embedded function tmp. tmp is the function that split will call once per list item, using whatever characters were specified in the call to splitUsing. -- Paul data = [ "sldjflsdfj\tlsjdlj\tlkjsdlkfj", "lsdjflsjd\tlsjdlfdj\tlskjdflkj", "lskdjfl\tlskdjflj\tlskdlfkjsd", ] def splitUsing(chars): def tmp(s): return s.split(chars) return tmp for d in map(splitUsing('\t'), data): print d From cjw at sympatico.ca Wed Aug 23 15:21:31 2006 From: cjw at sympatico.ca (Colin J. Williams) Date: Wed, 23 Aug 2006 15:21:31 -0400 Subject: Class instantiation Message-ID: In the example below, with the disassembly following that, we run into trouble with the line: self.connect(fileID, mode= 'r') # open sheet in the read mode the traceback is: Traceback (most recent call last): File "C:\Documents and Settings\cjw\My Documents\OODev\tArray.py", line 26, in __init__ self.connect(fileID, mode= 'r') # open sheet in the read mode NameError: global name 'fileID' is not defined At line 26, location 31, why is LOAD_GLOBAL generated for fileId, when LOAD_FAST has done the job at locations 0 and 20? I would appreciate advice. Colin W. class arSpread(object): def __init__(self, fileId= None, ar= None): if fileId: if ar is not None: print fileId self.connect(fileID, mode= 'r') # open sheet in the read mode else: self.connect(fileID, mode= 'w') # open the sheet in the write mode if ar is not None: self.setArray(ar) [Dbg]>>> dis.disassemble(arSpread.__init__.im_func.func_code) 23 0 LOAD_FAST 1 (fileId) 3 JUMP_IF_FALSE 64 (to 70) 6 POP_TOP 24 7 LOAD_FAST 2 (ar) 10 LOAD_GLOBAL 2 (None) 13 COMPARE_OP 9 (is not) 16 JUMP_IF_FALSE 28 (to 47) 19 POP_TOP 25 20 LOAD_FAST 1 (fileId) 23 PRINT_ITEM 24 PRINT_NEWLINE 26 25 LOAD_FAST 0 (self) 28 LOAD_ATTR 4 (connect) 31 LOAD_GLOBAL 5 (fileID) 34 LOAD_CONST 1 ('mode') 37 LOAD_CONST 2 ('r') 40 CALL_FUNCTION 257 43 POP_TOP 44 JUMP_ABSOLUTE 71 >> 47 POP_TOP From limodou at gmail.com Mon Aug 21 00:58:09 2006 From: limodou at gmail.com (limodou) Date: Mon, 21 Aug 2006 12:58:09 +0800 Subject: A Editor Feature for Extending Selection based on Language Syntax In-Reply-To: <1156135784.964866.190530@i3g2000cwc.googlegroups.com> References: <1155822175.534005.100490@75g2000cwc.googlegroups.com> <1156135784.964866.190530@i3g2000cwc.googlegroups.com> Message-ID: <505f13c0608202158k262fca68s5a2120dea5eeeb3@mail.gmail.com> On 20 Aug 2006 21:49:45 -0700, Xah Lee wrote: > can anyone give me a guide about writing a short elisp function? (for > non-emacs readers, this message will describe a editor feature i think > will be very beneficial to spread this concept.) > > i want to write a function such that, when run, highlight a region > between the nearest left and right delimiters. Delimiters are any of > parenthesis, square brackets, or single and double quotes etc. When the > function is run again, it extends the selection to the next enclosing > delimiters. > > So, in this way, a user can repeatedly press a keyboard shortcut and > extend the selection. This functionality can be found in NewEdit (http://wiki.woodpecker.org.cn/moin/NewEdit), first put the caret in middle of delimeters, such as ''""(){}[], then press Ctrl+E, the text between delimeters will be selected. And there are two direction of selection, left first and right first(Ctrl+Shift+E). If you press Ctrl+Alt+E again, the the delimeters will be selected. > > This is feature of BBEdit/TextWrangler on the Mac, which extend > selection to the nearest outer parenthesis. This is also a feature of > the Mathematica editor, which actually extend selection to the nearest > syntactical unit in the language, not just paired delimiters. > > What i wanted this for is mostly in editing HTML/XML, where one press > can select the content, another press will include the enclosing tags, > another press extends the selection to the next outer content, and > another press include that tags too, and so on. > NewEdit can not support this feature now. -- I like python! My Blog: http://www.donews.net/limodou My Django Site: http://www.djangocn.org NewEdit Maillist: http://groups.google.com/group/NewEdit From rogue_pedro at yahoo.com Tue Aug 29 03:03:40 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 29 Aug 2006 00:03:40 -0700 Subject: naive misuse? (of PyThreadState_SetAsyncExc) In-Reply-To: <1156804741.964769.98030@i42g2000cwa.googlegroups.com> References: <1156720585.068907.244240@i3g2000cwc.googlegroups.com> <1156804741.964769.98030@i42g2000cwa.googlegroups.com> Message-ID: <1156835020.341064.106540@b28g2000cwb.googlegroups.com> johan2sson at gmail.com wrote: > johan2sson at gmail.com wrote: > > The documentation for PyThreadState_SetAsyncExc says "To prevent naive > > misuse, you must write your own C extension to call this". Anyone care > > to list a few examples of such naive misuse? > > No? I'll take that then as proof that it's impossible to misuse the > function. > > Thanks, > Johan I *was* going to say that if you didn't already know the answer to that question then your use would almost certainly be naive. But I thought that'd be more nasty than funny, so I bit my tongue. ~Simon From rzantow at gmail.com Thu Aug 24 19:04:17 2006 From: rzantow at gmail.com (Rick Zantow) Date: Thu, 24 Aug 2006 19:04:17 -0400 Subject: When is a subclass not right? References: <1156387621.568779.191420@m73g2000cwd.googlegroups.com> <1156393371.550249.138930@75g2000cwc.googlegroups.com> <1156394781.155152.313080@i3g2000cwc.googlegroups.com> <44ede9b8$0$8925$88260bb3@free.teranews.com> <44EE0F9C.1030200@hotmail.com> Message-ID: Gabriel Genellina wrote in news:mailman.9831.1156458295.27775.python-list at python.org: > At Thursday 24/8/2006 17:44, Chaz Ginger wrote: > >>That is merely a logical use of OO after all when would a car and an >>orange be the same? > > Uh... what's the point...? > By example, an orange inside a car would be modeled using > composition, never inheritance. I've heard of cars that seem to inherit from the *lemon* class, though. Not a good object model, that. -- rzed From rogue_pedro at yahoo.com Fri Aug 11 23:00:13 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 11 Aug 2006 20:00:13 -0700 Subject: iterator wrapper In-Reply-To: References: <8cednRaDbu_RkkDZnZ2dnUVZ_sKdnZ2d@comcast.com> <1155339879.395139.182050@m73g2000cwd.googlegroups.com> <1155340917.733325.74780@i3g2000cwc.googlegroups.com> Message-ID: <1155351613.395862.211900@74g2000cwt.googlegroups.com> alf wrote: > Simon Forman wrote: > > >>>>>class LW(object): # ListWrapper > >>... def __init__(self, i): > >>... self.theiter = i > >>... def next(self): > >>... return [self.theiter.next()] > > > I hoped one lamda would take care of it but looks like it is a simplest > choice. > > > |>> I = ([n] for n in i) > > This is nice but I am iterating thru hude objects (like MBs) so you know ... > > > Thx for responding ... > > > A. No, I don't know... :-) My friend, I think you've misunderstood. Observe: |>> L = [n for n in range(3)] |>> G = (n for n in range(3)) |>> L [0, 1, 2] |>> G |>> L.next() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'list' object has no attribute 'next' |>> G.next() 0 List comprehensions [] create lists, generator comprehensions () create generators. Generator comprehensions work "just-in-time", pulling items from whatever they're iterating over as they themselves are iterated over, as I hope this example makes clear: |>> i = iter(xrange(3)) |>> G = ([n] for n in i) |>> G.next() [0] |>> i.next() 1 |>> G.next() [2] |>> G.next() Traceback (most recent call last): File "", line 1, in ? StopIteration So, ([n] for n in i) is indeed sufficient to your needs, as I understand them. BTW, the ()'s of a function call serve to create generator comprehensions: |>> sum(n * 2 for n in range(3)) 6 Neat, eh? HTH, ~Simon "Some say it is better to give than to receive. We say it is better to take than to receive. Note the subtle difference." From fredrik at pythonware.com Thu Aug 24 03:33:57 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Aug 2006 09:33:57 +0200 Subject: Problem with tokenize module and indents In-Reply-To: <44ECC8A1.6020607@zoominternet.net> References: <44ECC8A1.6020607@zoominternet.net> Message-ID: Tim wrote: > I ran into a problem with a script i was playing with to check code > indents and need some direction. It seems to depend on if tabsize is > set to 4 in editor and spaces and tabs indents are mixed on consecutive > lines. Works fine when editors tabsize was 8 regardless if indents are > mixed. > > # nano -T4 tabspacing_4.py > class Test: > """triple quote""" #indent is 1 tab > def __init__(self, msg): #indent is 4 spaces << > this gets reported as a dedent when there is no change in indent level http://pyref.infogami.com/lexical-analysis First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight (this is intended to be the same rule as used by Unix). The total number of spaces preceding the first non-blank character then determines the line's indentation. From fredrik at pythonware.com Fri Aug 25 18:04:48 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 26 Aug 2006 00:04:48 +0200 Subject: random writing access to a file in Python In-Reply-To: References: <5a9ue2lrjh214ecmme09fsodhm3ico1ntm@4ax.com> Message-ID: Claudio Grondi wrote: > I was smart enough to try it first on a very small file wondering what > was happening. Python documentation and even Google search after 'random > file access in Python' were not helpful as there was no example and no > hint available. one would think that the repeated use of the word "truncate" in the documentation for open/file would have provided the necessary hints: "'w' for writing (truncating an existing file)" "Modes 'r+', 'w+' and 'a+' open the file for updating (note that 'w+' truncates the file)" From mturillo at gmail.com Mon Aug 21 11:01:22 2006 From: mturillo at gmail.com (Perseo) Date: 21 Aug 2006 08:01:22 -0700 Subject: No subject In-Reply-To: References: <1156109528.138808.179610@i42g2000cwa.googlegroups.com> Message-ID: <1156172481.987548.90360@i3g2000cwc.googlegroups.com> Hi Keith Perkins Yes of course but we are looking for a developer who help us too. Keith Perkins wrote: > wrote: > > Hi guys, > > > > we are looking for a python developer for a European project. This > > project is multilangual and free it is called EuroCv and it need a > > module for exporting data in PDF. As web developer I try to create this > > module but It's too complicate for me. Check out the service > > www.eurocv.eu for more details. Contact us by Skype chat system our > > nick is eurocv. > > > > Thanks > > > have you looked at the reportlab module? http://www.reportlab.org/ From claudio.grondi at freenet.de Mon Aug 28 05:15:11 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Mon, 28 Aug 2006 11:15:11 +0200 Subject: Misleading error message when opening a file (on Windows XP SP 2) In-Reply-To: References: Message-ID: Marc 'BlackJack' Rintsch wrote: > In , Claudio Grondi wrote: > > >>Here an example of what I mean >>(Python 2.4.2, IDLE 1.1.2, Windows XP SP2, NTFS file system, 80 GByte >>large file): >> >> >>> f = file('veryBigFile.dat','r') >> >>> f = file('veryBigFile.dat','r+') > > > You mention the file size and gave a "speaking" name to that file -- does > the file size matter? Yes, it does. I haven't tested it yet, but I suppose 2 or 4 GByte threshold value. > > >>Traceback (most recent call last): >> File "", line 1, in -toplevel- >> f = file('veryBigFile.dat','r+') >>IOError: [Errno 2] No such file or directory: 'veryBigFile.dat' >> >>Is it a BUG or a FEATURE? > > > It's the error number Windows returns for that operation. So you just try to say: "it's not Python fault - it's just another bug of the damn Microsoft Windows operating system", right? Claudio Grondi From skip at pobox.com Wed Aug 9 10:13:21 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 9 Aug 2006 09:13:21 -0500 Subject: do people really complain about significant whitespace? In-Reply-To: <9$lHo7FEZe2EFwf$@objmedia.demon.co.uk> References: <1154991523.887791.9640@i42g2000cwa.googlegroups.com> <1154994477.450666.226550@b28g2000cwb.googlegroups.com> <1155124820.123151.140580@p79g2000cwp.googlegroups.com> <9$lHo7FEZe2EFwf$@objmedia.demon.co.uk> Message-ID: <17625.60801.772730.330611@montanaro.dyndns.org> >> of the driving principles behind Python is that, because code will be >> read more often than written, readability is more important. Stephen> In which case, for long functions with multiple levels of Stephen> indentation Python fails compared to languages that use braces Stephen> or END or end; etc. No. In that case Python makes it more readily apparent that your code is too complex. With C, Java, C++, Perl or FORTRAN you just smush everything over to the left and pretend it's not. ;-) Skip From bounces at foo.org Tue Aug 29 22:40:05 2006 From: bounces at foo.org (Dan) Date: Wed, 30 Aug 2006 02:40:05 GMT Subject: Allowing ref counting to close file items bad style? Message-ID: <9U6Jg.951$Xw6.283@trndny02> Is this discouraged?: for line in open(filename): That is, should I do this instead?: fileptr = open(filename) for line in fileptr: fileptr.close() Can I count on the ref count going to zero to close the file? How about a write case? For example: class Foo(list): def __init__(self): self.extend([1, 2, 3, 4]) def write(self, fileptr): for item in self: fileptr.write("%s\n" % item) foo_obj = Foo() foo_obj.write(open("the.file", "w")) Is my data safer if I explicitly close, like this?: fileptr = open("the.file", "w") foo_obj.write(fileptr) fileptr.close() I understand that the upcoming 'with' statement will obviate this question, but how about without 'with'? /Dan -- dedded att verizon dott net From hitesh287 at gmail.com Wed Aug 16 17:09:09 2006 From: hitesh287 at gmail.com (Hitesh) Date: 16 Aug 2006 14:09:09 -0700 Subject: Adding a char inside path string In-Reply-To: <1155762455.273148.43320@i42g2000cwa.googlegroups.com> References: <1155737700.290268.248250@i42g2000cwa.googlegroups.com> <1155744057.573884.111850@m73g2000cwd.googlegroups.com> <1155757548.080769.213490@p79g2000cwp.googlegroups.com> <1155759163.627377.72590@74g2000cwt.googlegroups.com> <12e70d6h4pb3l65@corp.supernews.com> <1155760716.499472.189490@p79g2000cwp.googlegroups.com> <12e71hnet3e7c99@corp.supernews.com> <1155762054.479806.265310@b28g2000cwb.googlegroups.com> <1155762455.273148.43320@i42g2000cwa.googlegroups.com> Message-ID: <1155762548.954499.240310@i3g2000cwc.googlegroups.com> There was a typo. I corrected it. Hitesh wrote: > How about this: > > def TruncateString(s, Tindex): > return string.ljust(s,Tindex){:Tindex] > > > s = '\\serverName\\C:\\Folder Name1\\FolderName2\\example.exe -u ABC -g > > XYZ' > try: > Sindex = s.find(".exe") > if Sindex > 0: > Sindex = Sindex + 4 > s1 = TruncateString(s, Sindex) > except: > pass > > > hj > > > > Hitesh wrote: > > I post a crappy solution but I can add few more stuff to make it fail > > proof. > > i.e. I can search for ".exe -u" > > But if someone names folder like "folder.exe u". This script could > > fail. > > Or if in padded garbase I get ".exe u" > > > > These are two known issues I have to takcle. > > > > Thanks everyone for your help. > > > > > > > > Grant Edwards wrote: > > > On 2006-08-16, Hitesh wrote: > > > > > > > anything after .exe should be truncated (or deleted). > > > > > > That will fail if any directory names contain the string > > > ".exe", but if that's what you want, it's trivial enough: > > > > > > for s in ["asdfasdf.exe -u", "soemthing/else", "asdf.exe/qwerqwer/qwerqwer.exe"]: > > > print `s`, > > > i = s.find(".exe") > > > print i, > > > if i >= 0: > > > s = s[:i+4] > > > print `s` > > > > > > -- > > > Grant Edwards grante Yow! Yow! It's some people > > > at inside the wall! This is > > > visi.com better than mopping! From sonaldgr8 at gmail.com Thu Aug 31 03:25:38 2006 From: sonaldgr8 at gmail.com (sonald) Date: 31 Aug 2006 00:25:38 -0700 Subject: how can i change the text delimiter In-Reply-To: References: <1156929540.715287.123060@h48g2000cwc.googlegroups.com> <1156938927.933389.101170@m73g2000cwd.googlegroups.com> Message-ID: <1157009138.684850.302570@m79g2000cwm.googlegroups.com> Hi, I am using Python version python-2.4.1 and along with this there are other installables like: 1. fastcsv-1.0.1.win32-py2.4.exe 2. psyco-1.4.win32-py2.4.exe 3. scite-1.63-setup.exe We are freshers here, joined new... and are now into handling this module which validates the data files, which are provided in some predefined format from the third party. The data files are provided in the comma separated format. The fastcsv package is imported in the code... import fastcsv and csv = fastcsv.parser(strict = 1,field_sep = ',') can u plz tell me where to find the parser function definition, (used above) so that if possible i can provide a parameter for text qualifier or text separator or text delimiter.. just as {field_sep = ','} (as given above) I want to handle string containing double quotes (") but the problem is that the default text qualifier is double quote Now if I can change the default text qualifier... to say pipe (|) the double quote inside the string may be ignored... plz refer to the example given in my previous query... Thanks.. Fredrik Lundh wrote: > "sonald" wrote: > > > fast csv is the the csv module for Python... > > no, it's not. the csv module for Python is called "csv". > > > and actually the string cannot be modified because > > it is received from a third party and we are not supposed to modify the > > data in any way.. > > that doesn't prevent you from using Python to modify it before you pass it to > the csv parser, though. > > > for details on the fast CSV module please visit > > > > www.object-craft.com.au/projects/csv/ or > > that module is called "csv", not "fastcsv". and as it says on that page, a much > improved version of that module was added to Python in version 2.3. > > what Python version are you using? > > From onurb at xiludom.gro Mon Aug 28 05:36:39 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 28 Aug 2006 11:36:39 +0200 Subject: Truly platform-independent DB access in Python? In-Reply-To: <1156755732.005451.170070@h48g2000cwc.googlegroups.com> References: <1156748466.739709.117850@h48g2000cwc.googlegroups.com> <1156755732.005451.170070@h48g2000cwc.googlegroups.com> Message-ID: <44f2b929$0$11818$636a55ce@news.free.fr> lbolognini at gmail.com wrote: > bobrik wrote: >> I am using the Python DB API for access to MySQL. But it is not >> platform-independent - I need a module not included in Python by >> default - python-mysql, and it uses a compiled binary _mysql.so. So it >> is not platform-independent because for each web-server on different >> platform, I would have to download it and extra compile it specifically >> for that platform. Do you know of any Python solution for MySQL access >> that is 100% platform-independent? > > Probably SqlAlchemy > http://www.sqlalchemy.org/ Probably not - I fail to see how SqlAlchemy could talk to MySQL without the MySQL/Python binding. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From rogue_pedro at yahoo.com Wed Aug 9 16:19:42 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 9 Aug 2006 13:19:42 -0700 Subject: converting a nested try/except statement into try/except/else In-Reply-To: References: Message-ID: <1155154782.885182.7580@n13g2000cwa.googlegroups.com> John Salerno wrote: > I'm starting out with this: > > try: > if int(text) > 0: > return True > else: > self.error_message() > return False > except ValueError: > self.error_message() > return False > > I rewrote it as this: > > try: > int(text) > except ValueError: > self.error_message() > return False > else: > return True > > I think it's much cleaner, but obviously I lost the test in the original > if statement. > > So my question is, can I still retain this second structure and still > test for > 0, but not have any extra nesting? > > Thanks. What about the version I gave you 8 days ago? ;-) http://groups.google.ca/group/comp.lang.python/msg/a80fcd8932b0733a It's clean, does the job, and doesn't have any extra nesting. Peace, ~Simon From max at alcyone.com Tue Aug 8 20:03:17 2006 From: max at alcyone.com (Erik Max Francis) Date: Tue, 08 Aug 2006 17:03:17 -0700 Subject: How to reverse tuples in a list? In-Reply-To: <1155081671.728757.228050@p79g2000cwp.googlegroups.com> References: <1155081671.728757.228050@p79g2000cwp.googlegroups.com> Message-ID: <-eGdnfRwGIfYu0TZnZ2dnUVZ_vKdnZ2d@speakeasy.net> Noah wrote: > But it seems like there should be a clever way to do this with > a list comprehensions. Problem is I can't see how to apply > reverse() to each tuple in the list because reverse() a > list method (not a tuple method) and because it operates > in-place (does not return a value). This kind of wrecks doing > it in a list comprehension. What I'd like to say is something like > this: > y = [t.reverse() for t in y] > Even if reverse worked on tuples, it wouldn't work inside a > list comprehension. Why would you want to do it with list comprehensions? Use reversed: >>> t = (1, 2, 3) >>> u = tuple(reversed(t)) >>> u (3, 2, 1) -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis The quickest way of ending a war is to lose it. -- George Orwell, 1903-1950 From cliff at develix.com Thu Aug 3 12:24:56 2006 From: cliff at develix.com (Cliff Wells) Date: Thu, 03 Aug 2006 09:24:56 -0700 Subject: Using Python for my web site In-Reply-To: References: <1154361480.915174.262720@b28g2000cwb.googlegroups.com> <1154409902.320511.114320@75g2000cwc.googlegroups.com> <1154416278.20290.183.camel@devilbox> <1hqlf4twmexrt$.dlg@gelists.gmail.com> <1154454290.20290.189.camel@devilbox> Message-ID: <1154622296.20290.340.camel@devilbox> On Thu, 2006-08-03 at 15:51 +0200, paul k?lle wrote: > Cliff Wells wrote: > > > For myself, I handle user-installation of TurboGears pretty much like I > > do all user-installed Python packages: using setuptools. Any user who > > uses easy_install or 'python setup.py install' gets their packages > > automatically installed into a subdirectory of their home directory and > > that takes precedence over the system installed packages. Works like a > > charm. > May I ask how you handle clashes with packages already installed in > site-packages? Once I tried something like ~/lib/python and set up > distutils accordingly, easy_install wouldn't work if the package was > installed system-wide... I followed these instructions: http://peak.telecommunity.com/DevCenter/EasyInstall#administrator-installation So far I've had no issues with package clashes. Regards, Cliff -- From shadowcaster.bbs at bbs.wretch.cc Wed Aug 2 11:13:06 2006 From: shadowcaster.bbs at bbs.wretch.cc (¨ì©³¦b²Ö¤°»ò°Ú¡H) Date: 02 Aug 2006 15:13:06 GMT Subject: looking for a regular expression Message-ID: <4PNQbI$7fW@bbs.wretch.cc> ? ???thn at mail.utexas.edu (Thomas Nelson)????? > How about > my_string = "We the people of the United States, in order to form a > more perfect union, establish justice, insure domestic > tranquility,......" > print (x for x in my_string.split(",") if "justice" in x).next() > This isn't a regular expression, but it gives what you're looking for. > THN Thanks a lot! I have never thought of that. But what if there's not only commas, but also periods and semicolons? I want to find words between 2 near by punctuations. I think it would make it difficult to use split instead of regular expression. -- ????????????????????????????????????? ????????????????????????????????????? ????????????????????????????????????? ????????????????????????????????????? ????????????????? 59-104-2-142.adsl.dynamic.seed.net.tw? From exarkun at divmod.com Sun Aug 13 10:25:08 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sun, 13 Aug 2006 10:25:08 -0400 Subject: start a multi-sockets server (a socket/per thread) with different ports but same host In-Reply-To: <1155445160.805336.136010@i3g2000cwc.googlegroups.com> Message-ID: <20060813142508.1717.846968715.divmod.quotient.21691@ohm> On 12 Aug 2006 21:59:20 -0700, zxo102 wrote: >Jean-Paul, > I just start to learn Twisted. Here is my simple case: I can find >the data sent by clients in dataReceived but I don't know which >client/which port the data is from. After I know where the data comes >from, I can do different things there, for example, write them into >different files via bsddb. I am not sure if it is the correct way to >do it. > > > def dataReceived(self, data): > # Accumulate the new data in our list > self.received.append(data) > # And then echo the entire list so far back to the client > self.transport.write(''.join(data)) > > print "============> data: ", data > print " which Port? : ", self.factory.port # unforunately it is >an object here. Check out self.transport.getHost(). It, too, is an object, with a 'port' attribute. You may also want to glance over the API documentation: http://twistedmatrix.com/documents/current/api/ Jean-Paul From ejensen at visi.com Wed Aug 9 20:14:26 2006 From: ejensen at visi.com (Ed Jensen) Date: Thu, 10 Aug 2006 00:14:26 -0000 Subject: do people really complain about significant whitespace? References: <1154986984.740638.241130@m79g2000cwm.googlegroups.com> Message-ID: <12dkuj2507rh5ae@corp.supernews.com> infidel wrote: > Where are they-who-hate-us-for-our-whitespace? Are "they" really that > stupid/petty? Are "they" really out there at all? "They" almost sound > like a mythical caste of tasteless heathens that "we" have invented. > It just sounds like so much trivial nitpickery that it's hard to > believe it's as common as we've come to believe. I like Python, but I do wish it used braces instead, if only because every editor I'm likely to use supports brace matching, which makes it easy to (for example) jump to the bottom or top of a block. From paul at boddie.org.uk Mon Aug 28 08:32:35 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 28 Aug 2006 05:32:35 -0700 Subject: Pros/Cons of Turbogears/Rails? References: <1156726071.579429.44650@b28g2000cwb.googlegroups.com> <1156740469.645955.52080@i3g2000cwc.googlegroups.com> Message-ID: <1156768355.275370.129680@h48g2000cwc.googlegroups.com> Ray wrote: > fuzzylollipop wrote: > > uh, no, Python predates Ruby by a good bit > > Rails might be "older" than Turbogears but it still JUST went 1.0 > > officially. > > It can't be called "mature' by any defintition. Version numbers are a fairly useless general metric of project maturity, taken in isolation. > But at least in most developers' perception, it is (not necessarily in > the absolute sense, but perhaps relative to Django or Turbogears). > Mind, it doesn't even need to be true, we're talking of perception > here. So actual maturity isn't important when using a technology: it's "perceived maturity" that counts, right? Any continuation down that particular path of reasoning surely leads you to the point where you claim, in concert with the developers, that increasing levels of inconvenience caused by gratuitous changes or broken documentation is not caused by bugs or general immaturity but by "features". I guess this is the definition of "opinionated software" that some people are so excited about. [...] > Sadly, there are more Java guys who know about Ruby than Python, > despite the fact that Python predates Ruby by quite a few years... > (this must be that Bruce Tate dude's fault! ) If you only listen to Bruce Tate et al, I imagine you could have the above impression, but I'd be interested to see hard facts to back up those assertions. Paul From danielwong at berkeley.edu Mon Aug 14 17:07:05 2006 From: danielwong at berkeley.edu (danielx) Date: 14 Aug 2006 14:07:05 -0700 Subject: selecting base class from user input In-Reply-To: References: <1155523781.860117.203140@h48g2000cwc.googlegroups.com> Message-ID: <1155589625.152790.39020@m79g2000cwm.googlegroups.com> Jackson wrote: > Thanks for the reply. > > danielx wrote the following on 2006-08-13 19:49: > > Is your declaration of ABC supposed to have some_super as one of the > > base classes? Your constructor has some_super as a parameter. What is > > this supposed to mean in light of the declaration for ABC? > > Indeed, my goal is to have the base class of ABC determined dynamically > via a parameter passed into the constructor. > > > > If you are trying to customize the base class of ABC by passing an > > argument to the constructor of ABC, you should probably reconsider. If > > constructing one instance of ABC can change ABC (the class) itself, > > then the behavior of other instances will be affected as well. No > > programmer can stay sane if he creates instances of a class that could > > suddenly change its behavior (due to someone else's code). > > Fortunately, the ABC class is not very useful. In fact, it was mostly > just to be used to store particular examples of the user-specified base > class. So all method calls would be from the base class only. > > > > > What you could do instead is to create a function which constructs > > classes based on the arguments it recieves. Then, you'll be able to > > create instances of the generated classes (all this meta-thinking is > > huring my brain ;). I am talking about something like this: > > > > def createClass(name, base): > > exec "class %s(%s): pass" % (name, base) > > return eval( "name" ) > > In fact, this is exactly what I ended up doing. > > def example(base): > if base == SomeClass: > # call SomeClass.__init__(self) > # build example as it would look in SomeClass > > elif base == SomeOtherClass: > # call SomeOtherClass.__init__(self) > # build example as it would in SomeOtherClass > > > Can you please tell us why you are doing this? My curiosity is killing > > me! > > > > So here is a good example: > > I have 4 classes: > > Lion(Animal): > Ant(Animal): > Bee(Animal): > Human(Animal): > > which are all subclasses of some superclass called Animal. Now I want > to define an occupation. For example, Worker. A worker can exist as any > of the 4 classes above. Their constructors are different and I might > want to add certain features. > > My first thought was to create a class called "Worker" and have the base > class determined by a variable which is passed into the constructor. What you should keep in mind though, is the "is-a" relationship that subclasses are supposed to have with their parents. "worker is a lion" does not make sense. What you want instead is LionWorker. You'll end up doing only a little more typing than if you had a general Worker class, but I don't think it will be much more. If your *Worker classes have really simple bodies, you might be able to automate the creation of your *Worker classes by doing something like the createClass function (ie, by creating the classes dynamically instead of using the class statement). I also discovered another way to dynamically create classes, described in this article (the article talks about other things as well): http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html I'm not sure if this will help you, but it's definitely interesting. > Most of the method calls will come from the Animal superclass anyway, > but some method calls might come from the Lion class, for example. > > Now I realize this would drive a programmer crazy...because a Lion might > have a roar() method whereas a Human might have a holler() method. But > so long as the user knew which argument they passed in, it shouldn't be > too difficult to keep track of it. > > So for example (again, I know what I am typing doesn't actually work)... > > Worker(some_animal): > def __init__(self,some_animal): > # change the base class to some_animal > > if some_animal == Lion: > # give the lion a big mane > > if some_animal == Ant: > # make the ant dumb > > if some_animal == Bee: > # make the bee know how to dance > > if some_animal == Human > # give the human a hardhat > > def work(self, hours): > # tell the animal to work for the specified number of hours > if some_animal == Lion: > self.cat_nap(hours) > if some_animal == Ant: > self.walk_back_and_forth(hours) > if some_animal == Bee: > self.buzz_and_dance(hours) > if some_animal == Human: > self.use_hammer_on_coworker(hours) > # notice, a Human does not have a cat_nap method > > def take_lunch(location): > > .... > > and so on. So the thought is that a Worker can exist in many different > forms: as a lion, as an ant, as a bee, and as a human. And I might want > a single worker class that represents them all. > > Hopefully this makes sense. > > > Another meta-thought: Hopefully I've beaten everyone else to the punch > > about that question. Is it just me, or will a reply with such a > > question always tell the original poster that what he wants to do MUST > > be flawed? I hope I have been gentler than this. > > > > :-) There is no need to be too gentle. We are all here to learn (or > help). So I am fairly happy with the def solution...any comments on True, but that doesn't mean you have to stand a rude response. I'm just hoping for a little more courtesy than what I've seen. > this? But a Worker is an noun, and it seems like the proper way to do > this is to make the Worker into a class...so that I can define methods > like "work", "take_lunch", etc. However, I have no idea how I should do > this. Perhaps someone can recommend a procedure. > > thanks. From vasudevram at gmail.com Tue Aug 8 13:51:31 2006 From: vasudevram at gmail.com (vasudevram) Date: 8 Aug 2006 10:51:31 -0700 Subject: ANN: xtopdf: PDF creation / conversion toolkit: alpha release of v1.3 Message-ID: <1155059491.123743.104460@75g2000cwc.googlegroups.com> Hi group, ANN: xtopdf: PDF creation / conversion toolkit: alpha release of v1.3 This is actually a somewhat preliminary announcement, but may be of interest to developers / users who know Python and/or have earlier checked out my xtopdf PDF creation / conversion toolkit ( http://sourceforge.net/projects/xtopdf): I've released (via my own web site, not yet properly packaged/documented and put on the SourceForge site, that will be done in some days), the next version of xtopdf: v1.3. This version adds support for conversion of CSV, TDV (Tab Delimited Values) and XLS (limited support) to PDF. v1.3 also adds some GUI tools written using wxPython (v1.0 had only command-line tools and a library for developers). Users/developers will need to install wxPython and properly configure it to work with their Python installation before they can use these GUI tools. This is fairly straightforward on Windows using the .MSI or .EXE (can't remember which it is right now) installer for wxPython, but on Linux, you'll need to know how to handle the tools that are used to build packages from source code, i.e. make, configure, etc. Also, wxPython is a medium-sized package - it took around an hour or two to fully build on my reasonably fast PC. So be patient (get yourself a coffee or two, or do something else in another Linux console / window while wxPython builds :-) Those who know even basic Python should be able to install and run both xtopdf v1.0 and the new stuff in v1.3, at least for the command-line tools (the programs are quite simple). Main SourceForge site for xtopdf v1.0: http://sourceforge.net/projects/xtopdf URL for xtopdf v1.3 on my web site: http://www.dancingbison.com/xtopdf-1.3.zip URL for xtopdf v1.0 on my web site: http://www.dancingbison.com/xtopdf-1.0.tar.gz wxPython site: http://wxpython.org xtopdf requires both Python and the open source version of the ReportLab toolkit. ReportLab site: http://www.reportlab.org xtopdf was developed using ReportLab v1.17, should work with all v1.x, may or may not work (not tested yet) with v2.x. More details (for Windows) are available in a guide here: http://itext.ugent.be/library/question.php?id=41 I'd appreciate any feedback, about bugs (v1.3 is tested but not a lot yet, that will be done in next some days), or how / what for anyone is using it. Apart from the "proper" packaging/documenting and upload to SourceForge (and my web site), I shall be writing and posting more about how to use it, etc. in the coming days. Enjoy, and Thanks Vasudev =========================== Vasudev Ram Software consulting and training http://www.dancingbison.com =========================== From jaysherby at gmail.com Sun Aug 27 15:56:22 2006 From: jaysherby at gmail.com (Putty) Date: 27 Aug 2006 12:56:22 -0700 Subject: Conway's Life Implementation Message-ID: <1156708582.474508.209360@75g2000cwc.googlegroups.com> Hi. I was going to write an implementation of John Conway's Life game using Python and Tk, but I soon found that Tk just didn't cut the mustard for memory usage, management, and the like for such a project, so I've found my best GUI bet for my project is wxPython and not pygame. Anybody have any advice thus far? Anyway, my real question is if anybody knows of any tutorials or source code from other implementations and other languages that may prove useful? From faulkner612 at comcast.net Tue Aug 22 20:39:23 2006 From: faulkner612 at comcast.net (faulkner) Date: 22 Aug 2006 17:39:23 -0700 Subject: swapping numeric items in a list In-Reply-To: References: Message-ID: <1156293563.701558.35420@h48g2000cwc.googlegroups.com> for i in xrange(0, len(your_list), 2): your_list[i], your_list[i + 1] = your_list[i + 1], your_list[i] Jiang Nutao wrote: > Hi, > > I simplify my problem like below > > To convert list > aa = [0x12, 0x34, 0x56, 0x78] > into > [0x34, 0x12, 0x78, 0x56] > > How to do it fast? My real list is huge. > > Thanks a lot. > Jason From geli at tasmail.com Mon Aug 21 00:06:51 2006 From: geli at tasmail.com (gel) Date: 20 Aug 2006 21:06:51 -0700 Subject: What would be the best way to run python client in the background In-Reply-To: <1156131192.693874.204390@b28g2000cwb.googlegroups.com> References: <1155625271.858914.175780@m73g2000cwd.googlegroups.com> <1156131192.693874.204390@b28g2000cwb.googlegroups.com> Message-ID: <1156133211.300891.262650@m73g2000cwd.googlegroups.com> Ravi Teja wrote: > gel wrote: > > Hi > > I have written a python client server app that keeps an eye on > > processes starting and ending on a client and makes decision on what to > > do based on information from the server end. I want to run the client > > end of the app more or less invisibly (no console) on the XP clients > > when ever a users logs on. What would be the best way to get this > > done? A bit more info on the purpose of the app... it is to act as a > > licence server, where we have a limited number of licences for software > > and the software installed on all PCs. The app will only allow a pre > > defined number of clients to run the software at any one time. > > To run a python script without a console - use *.pyw extension. > > But from what you stated you perhaps don't want to do this. Whether you > deploy this check as a service (through py2exe for example) or a > straight script, the users may simply kill it if they want to bypass > the check. Plus it is not common to use a seperate persistant process > to check for licenses. A better way is to incorporate the check > directly into the process of the software. The reason for the a seperate persistant check is because it will be used to enable software to be installed in whole lab of PCs but only allow a predifined number to run the software at any time one time. And then when a user stop using the software a licence will become available to for someone else on the same or another PC to use the software. The reason that the process of the software being check is not used is because it will be used for software written by other people. I hope this makes what and why a little clearer. Let me know if you think that I have misunderstoood you. From deets at nospam.web.de Tue Aug 15 08:19:54 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 15 Aug 2006 14:19:54 +0200 Subject: pickling or xml or other? References: <1155644089.337508.14940@75g2000cwc.googlegroups.com> Message-ID: <4kdsfaFb53ejU1@uni-berlin.de> placid wrote: > Hi all, > > I have an application were i want the user to "configure" some settings > which are variables within different classes. > > My question is should i just pickle out these variables to a file in > some particular order then read it back. Or use xml to save the config > values ? Which one scales better if settings increase? > > Other sugestions? ConfigParser. And "scaling" of something that by definition is supposed to be written by humans isn't a matter here. What matters is that a config-file can be edited on the commandline using vi (or the editor of your choice) - a pickle can't. So I'd certainly advise against the pickling. Diez From robin at reportlab.com Thu Aug 17 12:13:47 2006 From: robin at reportlab.com (Robin Becker) Date: Thu, 17 Aug 2006 17:13:47 +0100 Subject: Python2.5 RC1 vs sgmlop.c In-Reply-To: <44E49471.3010004@holdenweb.com> References: <44E48D25.2000900@chamonix.reportlab.co.uk> <44E49471.3010004@holdenweb.com> Message-ID: <44E495BB.1050000@chamonix.reportlab.co.uk> Steve Holden wrote: > Robin Becker wrote: ....... >> Has anyone got any clue what the problem might be or a fixed version of the code? > > I'm guessing this might be to do with the changes that have been made to > enable 64-bit readiness in the code, but I couldn't suggest specifics. > > Suspect all pointers and integers first :-) ..... Indeed Steve, but it was in fact PyMem_DEL vs PyObject_NEW. Just replaced three PyMem_DEL's with PyObject_FREE and things now work again. The free I suspected wasn't involved at all. -- Robin Becker From wildemar at freakmail.de Tue Aug 8 08:50:39 2006 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Tue, 08 Aug 2006 14:50:39 +0200 Subject: singleton decorator In-Reply-To: <20060807212616.46fd3571.pedro.werneck@terra.com.br> References: <7008329d0608071633odfbf134n749c223293e3cb90@mail.gmail.com> <20060807212616.46fd3571.pedro.werneck@terra.com.br> Message-ID: <44D8889F.8010502@freakmail.de> Pedro Werneck wrote: >>>> class Singleton(object): > ... def __new__(cls, *args, **kwds): > ... try: > ... return cls._it > ... except AttributeError: > ... cls._it = object.__new__(cls, *args, **kwds) > ... return cls._it > > But __init__ will be called once for each time you call A, even if it's > always the same instance returned. If this is a problem, you'll need > another method to use for initialization and call it only once. > Or you could always just use the __new__() method instead of __init__(), putting all your initialization into the above except-block. If you replace 'cls._it = ...' with 'self = cls_it = ...' you'll feel right at home too :). Anything 'unpythonic' (gosh how I hate that word ;)) about that, BTW? c.u. wildemar From duncan.booth at invalid.invalid Wed Aug 16 15:18:01 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 Aug 2006 19:18:01 GMT Subject: Documentation Question About Depricated String Functions References: <1155754352.767469.211380@m73g2000cwd.googlegroups.com> Message-ID: Hitesh wrote: > In python doc -- 4.1.4 Deprecated string functions -- I read that "The > following list of functions are also defined as methods of string and > Unicode objects; see ``String Methods'' (section 2.3.6) for more > information on those. You should consider these functions as > deprecated, although they will not be removed until Python 3.0. The > functions defined in this module are: " and there is a whole list of > functions. If these functions are deprecated what is the replacement > for them? I couldn't find that info in the doc. Any links will be > helpful. You did find the info in the doc - you quoted it above: The functions are deprecated: use the string methods (see section 2.3.6) instead. From brjohan at gmail.com Tue Aug 22 02:22:56 2006 From: brjohan at gmail.com (BrJohan) Date: 21 Aug 2006 23:22:56 -0700 Subject: Python for EXIF-info-additions ? In-Reply-To: References: <4kmp5jFctg9cU1@individual.net> Message-ID: <1156227776.173530.222870@m79g2000cwm.googlegroups.com> Bruno Dilly wrote: > I think you can find what do you need into this repository, it's a > creative commons tool: > https://svn.berlios.de/svnroot/repos/cctools/publisher/branches/flickr-storage-branch/ > > take a look in the follow directory: > ccpublisher/jpeg/ > > I'm not sure if it's what you want, let me know. > > See you, > > Dilly > After glancing through the code I think it offers all - or most of - what I need. Thank you! /Bror J. From fredrik at pythonware.com Thu Aug 31 05:56:12 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 31 Aug 2006 11:56:12 +0200 Subject: Need Python for Linux (Suse 10.1) In-Reply-To: <7.0.1.0.2.20060831020826.05688418@rcblue.com> References: <7.0.1.0.2.20060831020826.05688418@rcblue.com> Message-ID: Dick Moores wrote: > I've got a friend interested in trying out Python. I sent him to > http://www.python.org/download/linux/ but he's uncertain as to what to > download. He's rather get a new download than use what was on his Suse > disk. His box is an x86. > > Any chance Python 2.4.3 compressed source tarball > would be > suitable for him? absolutely. unpack, type "./configure", and then "make altinstall", and you're off (use "python2.4" to start the newly installed interpreter). alternatively, and recommended, is to grab the latest build from SuSE's package repository. From bdesth.quelquechose at free.quelquepart.fr Wed Aug 9 18:23:43 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 10 Aug 2006 00:23:43 +0200 Subject: converting a nested try/except statement into try/except/else In-Reply-To: <44da4329$0$702$626a54ce@news.free.fr> References: <44da4329$0$702$626a54ce@news.free.fr> Message-ID: <44da5e3f$0$19111$626a54ce@news.free.fr> Bruno Desthuilliers a ?crit : > John Salerno a ?crit : > (snip) or of course the dead simple: try: if int(text) <= 0: raise ValueError except ValueError: self.error_message() return False else: return True BTW, you really should have a look at FormEncode... From srlamb at gmail.com Thu Aug 17 17:15:23 2006 From: srlamb at gmail.com (Scott Lamb) Date: 17 Aug 2006 14:15:23 -0700 Subject: Curried class methods? References: <1155779616.228836.153470@p79g2000cwp.googlegroups.com> Message-ID: <1155849323.840938.306730@74g2000cwt.googlegroups.com> Thanks, Antoon and Carl. Just tried your solutions - both work and are much cleaner than mine. From nicogrubert at gmail.com Thu Aug 31 11:44:08 2006 From: nicogrubert at gmail.com (Nico Grubert) Date: Thu, 31 Aug 2006 17:44:08 +0200 Subject: Searching a string and extract all occurancies of a substring Message-ID: <44F703C8.3080504@gmail.com> Hi there, in a text with no carriage returns I need to look for all occurancies of this string: ... The ... can contain different values. I need to extract the string between and . Example text: This is a test. A test. /www/mydoc1 And I need to extraxt /www/mydoc1 and /www/mydoc2 from this text. /foo/bar/doc From this text I need to get a list with this: ["/www/mydoc1", "/foo/bar/doc"] What's the best way to do this? I'll need to use Python: 2.3.5 Thanks in advance, Nico From jicman at gmail.com Fri Aug 11 11:15:18 2006 From: jicman at gmail.com (jiccab) Date: 11 Aug 2006 08:15:18 -0700 Subject: using an already running COM object with Dispatch In-Reply-To: <1154850807_30525@sp6iad.superfeed.net> References: <1154715278.972215.295040@75g2000cwc.googlegroups.com> <1154850807_30525@sp6iad.superfeed.net> Message-ID: <1155309318.308902.293750@m73g2000cwd.googlegroups.com> Roger Upole wrote: > "jiccab" wrote in message news:1154715278.972215.295040 at 75g2000cwc.googlegroups.com... > > Greetings. > > > > with the following code, > > > > olApp = Dispatch("Outlook.Application") > > > > I am capable of getting a new instance of Outlook running. I would > > like to be able to use the instance that is already running, if exists, > > otherwise open a new one. > > > > Has anyone being able to do this? > > You should be able to use > win32com.client.GetActiveObject('outlook.application') > and fall back to a normal Dispatch if it fails. > > Roger Yes indeed. Thanks. here is the code: from win32com.client.dynamic import Dispatch from win32com.client import GetActiveObject def OutlookPointer(): try: olApp = GetActiveObject("Outlook.Application") except: olApp = Dispatch("Outlook.Application") return olApp op = OutlookPointer() From wegein at gmail.com Wed Aug 23 22:47:01 2006 From: wegein at gmail.com (damacy) Date: 23 Aug 2006 19:47:01 -0700 Subject: all ip addresses of machines in the local network Message-ID: <1156387621.568779.191420@m73g2000cwd.googlegroups.com> hi, there. i have a problem writing a program which can obtain ip addresses of machines running in the same local network. say, there are 4 machines present in the network; [a], [b], [c] and [d] and if i run my program on [a], it should be able to find "host names" and "ip addresses" of the other machines; [b], [c] and [d]? i have read some threads posted on this group, however, they only work for localhost, not the entire network. any hints if possible? thanks for your time. regards, damacy From deets at nospam.web.de Sun Aug 27 11:43:28 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 27 Aug 2006 17:43:28 +0200 Subject: How to let a loop run for a while before checking for break condition? In-Reply-To: References: <4ldfp0F1csmpU1@uni-berlin.de> <4ldiacF1ckeeU1@uni-berlin.de> <4ldovvF1dgtrU1@uni-berlin.de> Message-ID: <4ldst0F1fdqpU1@uni-berlin.de> Fredrik Lundh schrieb: > Diez B. Roggisch wrote: > > > No doubt that changing the flag asynchronously is a gain by delegating > > the timing code to the OS. Yet the while loop still has a condition - > > you could as well set a flag in the signal handler an do it like this: > > if the OP is obsessed with performance, why are you arguing that he > "could as well" use a slower solution ? Maybe because it is the better solution in case of anything that has more than one line of work to do? The Exception can interrupt everywhere, the flag determines the point of interruption precisely. >> This is on my machine about 1.5 times slower than func1, but much more >> readable > > polling a global state flag being "much more readable" than handling an > exception in the usual way? surely you're joking. > > are you sure you're posted the code you're writing about, btw. that "or > True" looks a bit suspicious. Yeah, that should have been a False - I added that after copying a first version without that, instead of replacing it with the modified original that I created to see what impact the short-circuiting "or" had. Diez From johnjsal at NOSPAMgmail.com Thu Aug 10 14:15:34 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 10 Aug 2006 18:15:34 GMT Subject: using python to edit a word file? Message-ID: I figured my first step is to install the win32 extension, which I did, but I can't seem to find any documentation for it. A couple of the links on Mark Hammond's site don't seem to work. Anyway, all I need to do is search in the Word document for certain strings and either delete them or replace them. Easy enough, if only I knew which function, etc. to use. Hope someone can push me in the right direction. Thanks. From gabrielg_laburando at yahoo.com.ar Thu Aug 31 11:06:56 2006 From: gabrielg_laburando at yahoo.com.ar (Gabriel G) Date: Thu, 31 Aug 2006 12:06:56 -0300 Subject: a question about my script In-Reply-To: <20060831130109.54725.qmail@web56501.mail.re3.yahoo.com> References: <7.0.1.0.0.20060829041316.03da8e20@yahoo.com.ar> <20060831130109.54725.qmail@web56501.mail.re3.yahoo.com> Message-ID: <7.0.1.0.0.20060831120404.05176720@yahoo.com.ar> At Thursday 31/8/2006 10:01, alper soyler wrote: >I changed the script as you wrote below: > > >directory = 'pub/kegg/genomes' Sorry, in the original comment I said "change it to be an absolute path" but didn't write it well. This line should read: directory = '/pub/kegg/genomes' Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From ptmcg at austin.rr._bogus_.com Wed Aug 9 19:50:11 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 09 Aug 2006 23:50:11 GMT Subject: imputil + pyparsing -> Python-based DSL Message-ID: Wilson Fowlie sent me an e-mail describing James Theile's presentation at the Vancouver Python Workshop, using imputil to create simple DSL's. I thought that by creating a DSL grammar and making it part of an imputil hook, you could generate Python source code to implement the corresponding classes and methods to implement the DSL behavior. My first experiment was a state machine generator. From a simple state machine for a traffic light: TrafficLight = { Red -> Green; Green -> Yellow; Yellow -> Red; } My imputil import hook generates the corresponding classes and state transition logic to implement the state machine, enabling this code: import stateMachine import trafficLight tl = trafficLight.Red() for i in range(10): print tl, print ("STOP","GO")[tl.carsCanGo] tl.crossingSignal() tl.delay() print tl = tl.nextState() This page has more examples, plus the source code: http://www.geocities.com/ptmcg/python/stateMachine.html. -- Paul From hitesh287 at gmail.com Wed Aug 16 16:14:48 2006 From: hitesh287 at gmail.com (Hitesh) Date: 16 Aug 2006 13:14:48 -0700 Subject: Adding a char inside path string In-Reply-To: References: <1155737700.290268.248250@i42g2000cwa.googlegroups.com> <1155744057.573884.111850@m73g2000cwd.googlegroups.com> <1155757548.080769.213490@p79g2000cwp.googlegroups.com> Message-ID: <1155759288.200496.275960@75g2000cwc.googlegroups.com> >>> s = '\\serverName\C:\Folder Name1\FolderName2\example.exe -u ABC -g XYZ' >>> p = s.split(" ", 1)[0] >>> p '\\serverName\\C:\\Folder' hj Larry Bates wrote: > Sounds like you can split the string on a space and throw > away the right side: > > s='\\serverName\C:\FolderName1\FolderName2\example.exe' -u ABC -g XYZ > p=s.split(" ", 1)[0] > print p > > '\\serverName\C:\FolderName1\FolderName2\example.exe' > > Larry Bates > > Hitesh wrote: > > > > > > Hi, > > > > Everything is working fine and dandy but I ran across another issue > > here. > > Some of the path comes with some extra chars padded at the end. > > i.e. > > > > '\\serverName\C:\FolderName1\FolderName2\example.exe' -u ABC -g XYZ > > abcdef > > > > Now those padded chars are not constant all the time. It can be > > anything. > > Only common denometer in each string that comes with those padded chars > > is that it is after .exe and then there is space and then 99% of the > > time it is -u and then there can be anything, I meant its dynemic after > > that. > > > > so I am using string1.find(".exe") and could retrive the index but > > don't know how to get rid any garbase after index + 4 > > > > hj > > > > > > Dennis Lee Bieber wrote: > >> On 16 Aug 2006 09:00:57 -0700, "Hitesh" declaimed > >> the following in comp.lang.python: > >> > >>> Thank you Fredrik. That works for a string. > >>> But I am getting list of tuples from DB. > >>> > >>> rows = [('\\serverName\C:\FolderName1\FolderName2\example.exe',), > >>> ('\\serverName\C:\FolderName1\FolderName2\example2.exe',), > >>> ('\\serverName\C:\FolderName1\FolderName2\example3.exe',), > >>> ('\\serverName\C:\FolderName1\FolderName2\example4.exe',)] > >>> > >>> I tried this: > >>> for i in rows: > >>> row = str(i) > >>> path = row.replace("C:" , "c$") > >>> print path > >>> > >>> I am getting path something like > >>> > >>> ('\\serverName\c$:\FolderName1\FolderName2\example.exe',) > >>> > >>> How on the earth I can remove those paranthesis? > >>> > >> By accessing the contents of the tuple, not the tuple itself > >> > >>>>> rows = [('\\serverName\C:\FolderName1\FolderName2\example.exe',), > >> ... ('\\serverName\C:\FolderName1\FolderName2\example2.exe',), > >> ... ('\\serverName\C:\FolderName1\FolderName2\example3.exe',), > >> ... ('\\serverName\C:\FolderName1\FolderName2\example4.exe',)] > >>>>> rows > >> [('\\serverName\\C:\\FolderName1\\FolderName2\\example.exe',), > >> ('\\serverName\\C:\\FolderName1\\FolderName2\\example2.exe',), > >> ('\\serverName\\C:\\FolderName1\\FolderName2\\example3.exe',), > >> ('\\serverName\\C:\\FolderName1\\FolderName2\\example4.exe',)] > >>>>> modRows = [itm[0].replace("C:", "C$") for itm in rows] > >>>>> modRows > >> ['\\serverName\\C$\\FolderName1\\FolderName2\\example.exe', > >> '\\serverName\\C$\\FolderName1\\FolderName2\\example2.exe', > >> '\\serverName\\C$\\FolderName1\\FolderName2\\example3.exe', > >> '\\serverName\\C$\\FolderName1\\FolderName2\\example4.exe'] > >> -- > >> Wulfraed Dennis Lee Bieber KD6MOG > >> wlfraed at ix.netcom.com wulfraed at bestiaria.com > >> HTTP://wlfraed.home.netcom.com/ > >> (Bestiaria Support Staff: web-asst at bestiaria.com) > >> HTTP://www.bestiaria.com/ > > From fluxent at gmail.com Fri Aug 11 08:08:52 2006 From: fluxent at gmail.com (fluxent at gmail.com) Date: 11 Aug 2006 05:08:52 -0700 Subject: timeout calling local sendmail References: <1154963394.878933.80540@h48g2000cwc.googlegroups.com> Message-ID: <1155298132.377389.149000@74g2000cwt.googlegroups.com> That seems applicable to writing an SMTP server/daemon, but is it necessary for a script client calling a local SendMail daemon? Tim Williams wrote: > > > RFC 1123 > > http://www.freesoft.org/CIE/RFC/1123/109.htm > > I find that a timeout of 120 seconds is the bare minimum. If the > timeout is too short you get a condition where the email is received > succesfully but appears to the sending server to have failed and a > retry may occur - so the recipient gets multiple copies. > > HTH :) From mailme.grover at gmail.com Mon Aug 28 22:22:50 2006 From: mailme.grover at gmail.com (mailme.grover at gmail.com) Date: 28 Aug 2006 19:22:50 -0700 Subject: NEED HELP Message-ID: <1156818170.279428.312250@h48g2000cwc.googlegroups.com> Below is my code, which is kind of virtual and with its help ill use it in my main project. Now what i am looking for is can anybody write all the code inside a class...so that I can reuse it. I am kind of novice...n kind of stuc with that. from Tkinter import * root = Tk() w = Label(root, text="Right-click to display menu", width=40, height=20) w.pack() # create a menu popup = Menu(root, tearoff=0) popup.add_radiobutton(label="SourceIP", command= hello) # , command=next) etc... popup.add_radiobutton(label="DestIP", command= hello) popup.add_radiobutton(label="Reporter'sIP", command= hello) popup.add_radiobutton(label="Observer'sIP", command= hello) popup.add_separator() popup.add_radiobutton(label="Home") def do_popup(event): # display the popup menu try: popup.post(event.x_root, event.y_root) finally: # make sure to release the grab (Tk 8.0a1 only) popup.grab_release() def hello(event= None): print "hello" w.bind("", do_popup) b = Button(root, text="Quit", command=root.destroy) b.pack() mainloop() THANKS A LOT From sjmachin at lexicon.net Thu Aug 3 23:59:48 2006 From: sjmachin at lexicon.net (John Machin) Date: 3 Aug 2006 20:59:48 -0700 Subject: Problem reading/writing files In-Reply-To: <1154661460.803694.241220@s13g2000cwa.googlegroups.com> References: <1154661460.803694.241220@s13g2000cwa.googlegroups.com> Message-ID: <1154663988.871166.112930@s13g2000cwa.googlegroups.com> smeenehan at hmc.edu wrote: > This is a bit of a peculiar problem. First off, this relates to Python > Challenge #12, so if you are attempting those and have yet to finish > #12, as there are potential spoilers here. > > I have five different image files shuffled up in one big binary file. > In order to view them I have to "unshuffle" the data, which means > moving bytes around. Currently my approach is to read the data from the > original, unshuffle as necessary, and then write to 5 different files > (2 .jpgs, 2 .pngs and 1 .gif). > > The problem is with the read() method. If I read a byte valued as 0x00 > (in hexadecimal), the read method returns a character with the value > 0x20. I doubt it. What platform? What version of Python? Have you opened the file in binary mode i.e. open('thefile', 'rb') ?? Show us the relevant parts of your code, plus what caused you to conclude that read() changed data on the fly in an undocumented fashion. > When printed as strings, these two values look the same (null and > space, respectively), Use the repr() function when you want to see what's *really* in an object: #>>> hasnul = 'a\x00b' #>>> hasspace = 'a\x20b' #>>> print hasnul, hasspace a b a b #>>> print repr(hasnul), repr(hasspace) 'a\x00b' 'a b' #>>> > but obviously this screws with the data and makes > the resulting image file unreadable. I can add a simple if statement to > correct this, which seems to make the .jpgs readable, but the .pngs > still have errors and the .gif is corrupted, which makes me wonder if > the read method is not doing this to other bytes as well. > > Now, the *really* peculiar thing is that I made a simple little file > and used my hex editor to manually change the first byte to 0x00. When > I read that byte with the read() method, it returned the correct value, > which boggles me. > > Anyone have any idea what could be going on? Alternatively, is there a > better way to shift about bytes in a non-text file without using the > read() method (since returning the byte as a string seems to be what's > causing the issue)? "seems to be" != "is" :-) There is no simple better way. We need to establish what you are actually doing to cause this problem to seem to happen. Kindly answer the questions above ;-) Cheers, John From elpX at adsihqX.com Mon Aug 28 18:01:32 2006 From: elpX at adsihqX.com (Dr. Pastor) Date: Mon, 28 Aug 2006 15:01:32 -0700 Subject: Best IDE for Python In-Reply-To: <1155555537.877334.61030@75g2000cwc.googlegroups.com> References: <1155541849.350392.31190@h48g2000cwc.googlegroups.com> <1155555537.877334.61030@75g2000cwc.googlegroups.com> Message-ID: <1156801807_2285@sp6iad.superfeed.net> Please advise how to uninstal SPE. Regards, Dr. Pastor. jelle wrote: > I think SPE is a terrible complete and efficient IDE! > ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From olsongt at verizon.net Wed Aug 9 16:22:56 2006 From: olsongt at verizon.net (olsongt at verizon.net) Date: 9 Aug 2006 13:22:56 -0700 Subject: #!/usr/bin/python or #!/usr/bin/env python? In-Reply-To: References: Message-ID: <1155154976.016662.284460@i42g2000cwa.googlegroups.com> Aahz wrote: > In article , > John Salerno wrote: > > > >I understand the difference, but I'm just curious if anyone has any > >strong feelings toward using one over the other? I was reading that a > >disadvantage to the more general usage (i.e. env) is that it finds the > >first python on the path, and that might not be the proper one to use. I > >don't know if that's a real issue most of the time, but it's at least > >something to consider. > > The main argument against the env method is that I've seen a fair number > of sysadmins claim that it's less secure. I'm not competent to judget > that claim myself, but I prefer to play safe and stay away from env. > -- > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ > Basically, someone could inject an arbirtrary script called 'python' into your path that does whatever (rm -fr /) under your user context when you run the script. But the same thing would happen if you run 'python test.py' instead of '/usr/local/bin/python test.py' to run a script that doesn't have a she-bang or hasn't been flagged as executable. Some admins will use a fully-qualified path for every command to guard against this; I think that can be overkill. From daniel.huangfei at gmail.com Tue Aug 15 04:34:21 2006 From: daniel.huangfei at gmail.com (daniel) Date: 15 Aug 2006 01:34:21 -0700 Subject: what is the keyword "is" for? In-Reply-To: <44E182DA.20602@v.loewis.de> References: <1155625097.784052.31330@p79g2000cwp.googlegroups.com> <44e16d6a$1@nntp0.pdx.net> <1155629086.617707.132900@b28g2000cwb.googlegroups.com> <44E182DA.20602@v.loewis.de> Message-ID: <1155630861.833751.19910@m73g2000cwd.googlegroups.com> Martin v. L?wis wrote: > daniel wrote: > > when I tried to check the stuff out, found sth interesting that if you > > define variables in a style like this: > > a = b = ['a', 'b'] > > changing one list affects the other, and they still refer to same > > object. in fact, seems all compound types (dictionary for instance) > > behave in this way. > > > > however, when list is replaced with other built-in types like integers > > : > > a = b = 3 > > changing one of them cause the two objects differ... > > Ah, but make a difference between "change a variable", and "change an > object". > > py> a = b = [1,2,3] > py> a[0] = 6 # don't change the variable a, just change the object > py> a > [6, 2, 3] > py> b > [6, 2, 3] > py> a=[7,8,9] # change the variable a; > # it's now a different object than b mm, python runtime might allocate a new chunk of memory for this... but might not for the previous operation.. > py> a > [7, 8, 9] > py> b > [6, 2, 3] > > For some objects, "change the object" is impossible. If you have > > a = b = 3 > > then there is no way to change the object 3 to become 4 (say); > integer objects are "immutable". So for these, to make a change, > you really have to change the variable, not the value. > sounds reasonable, I tried tuple which is also immutable, it behaves the same as integers. > Regards, > Martin tks Martin... From dingbat at codesmiths.com Tue Aug 8 11:56:18 2006 From: dingbat at codesmiths.com (Andy Dingley) Date: 8 Aug 2006 08:56:18 -0700 Subject: do people really complain about significant whitespace? In-Reply-To: References: <1154986984.740638.241130@m79g2000cwm.googlegroups.com> Message-ID: <1155052578.265714.10640@b28g2000cwb.googlegroups.com> Thomas Guettler wrote: > I like python, but sometimes i don't like that python allows > spaces and tabs. It would be easier if you had less choice and > must use four spaces. That's the nice thing about Python. It doesn't care about indentation distance, it just wants "some" and "consistent". I like the idea that "humans see the whitespace as significant anyway, so document the fact and use it" (I presume this came from Occam). What I don't like so much is that the _ends_ of blocks are less visually obvious. From outstretchedarm at hotmail.com Fri Aug 11 12:11:38 2006 From: outstretchedarm at hotmail.com (Omar) Date: 11 Aug 2006 09:11:38 -0700 Subject: some n00b question In-Reply-To: <1155311428.686693.193040@i3g2000cwc.googlegroups.com> References: <1155305094.295652.218220@i3g2000cwc.googlegroups.com> <1155311428.686693.193040@i3g2000cwc.googlegroups.com> Message-ID: <1155312698.409649.310300@i3g2000cwc.googlegroups.com> Gerard Flanagan wrote: > Omar wrote: > > I'm learning how to program python. a few questions > > > > a) I'm mostly interested in creating exe's that have to do with music > > -- things to help me keep track of chord progressions, transpositions, > > etc. can anyone point me in the direction of resources on this? > > > > b) I'm also interested in created GUI's sooner rather than later. Can > > anyone point me to a fast track to doing GUI's on python? > > > > thanks > > Hi Omar > > are you aware of lilypond, used for typesetting music? (not what you > asked about I know!). 'lilycomp' is a simple (tkinter) gui for > creating lilypond markup, maybe some ideas there. > > http://lilypond.org/web/ > > http://lilycomp.sourceforge.net/ > > hope that helps. > > Gerard thank you Larry and thank you Gerard! People on this forum are apparantly quite cool. From david_wahler at bic.ky Tue Aug 8 08:53:29 2006 From: david_wahler at bic.ky (david_wahler at bic.ky) Date: 8 Aug 2006 07:53:29 -0500 Subject: =?utf-8?Q?Re:_Dr._Dobb's_Python=2DURL=21_=2D_weekly_Python_news_and_links_=28Aug__8=29?= Message-ID: <20060808125329.4098.qmail@BICSRV1011.bic.ky> I'll be out of the office until approximately August 20th. If you have any questions, please email support at bic.ky. -- David Wahler From rogue_pedro at yahoo.com Sat Aug 26 12:16:40 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 26 Aug 2006 09:16:40 -0700 Subject: rollover effect In-Reply-To: <1156608554.489516.243640@h48g2000cwc.googlegroups.com> References: <1156607403.741240.25000@74g2000cwt.googlegroups.com> <1156608042.466471.210270@m73g2000cwd.googlegroups.com> <1156608554.489516.243640@h48g2000cwc.googlegroups.com> Message-ID: <1156609000.477885.289150@h48g2000cwc.googlegroups.com> groves wrote: > Simon Forman wrote: > > groves wrote: > > > hi > > > I am trying to get a roll over effect on my canvas.(this is a virtual > > > program which will eventually fit into my final program) > > > > > > Exactly i have a text on my screen and I want to have a brief > > > discription across it whenever the user takes the mouse on it n hence > > > giving information about the type of text(event). > > > > > > Another thign i am looking for is to have a right click on that very > > > text as well > > > If somebody can put some light on it, then it would be really great for > > > my project. > > > Thank you in advance. > > > > What GUI system are you using? > > > > Peace, > > ~Simon > > > I am using python IDLE IDLE's a IDE not a GUI, you can develop scripts with it that use many different GUI systems. Are you using Tkinter? (If so, Python MegaWidgets, Pmw, is a great resource. It has rollover tooltips. http://pmw.sourceforge.net/ ) HTH, ~Simon From fredrik at pythonware.com Mon Aug 28 11:47:29 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 28 Aug 2006 17:47:29 +0200 Subject: Truly platform-independent DB access in Python? In-Reply-To: <1156779665.977489.300090@74g2000cwt.googlegroups.com> References: <1156748466.739709.117850@h48g2000cwc.googlegroups.com> <1156779665.977489.300090@74g2000cwt.googlegroups.com> Message-ID: Boris Du?ek wrote: > So the only solution for me at this moment is to use jython and from > there use Java JDBC API (sorry :-) so who installed Java for you? From swangdb at auburn.edu Mon Aug 21 15:45:27 2006 From: swangdb at auburn.edu (swangdb) Date: 21 Aug 2006 12:45:27 -0700 Subject: Mailman - Sendmail problem In-Reply-To: <1156185577.165019.305040@74g2000cwt.googlegroups.com> References: <1156185577.165019.305040@74g2000cwt.googlegroups.com> Message-ID: <1156189527.586577.283840@h48g2000cwc.googlegroups.com> Okay, I removed the "DELIVERY_MODULE = 'Sendmail`" line from mm_cfg.py and used the default "DELIVERY_MODULE = 'SMTPDirect'" and it now it worked, I sent a message to the mailing list and received a copy. This was probably right in front of me the whole time. swangdb wrote: > I have a Sun Server running Solaris 10 and Sendmail 8.13.7. I have > Majordomo and Listproc installed on this server and they work. I have > several production majordomo and listproc mailing lists installed on > this server and they work. > > I am trying to get Mailman to work on this server and so far, no luck. > I installed the software (Mailman 2.1.8 and Python 2.4.3), reconfigured > mm_cfg.py, started the software, added the cron entries, created a test > mailing list, added the list information to /etc/aliases, ran > newaliases and subscribed myself. When I send a message to the list, > it doesn't send me a copy of the message (I am the only subscriber to > the list). If I look on the list's web site, the message I sent is > contained in the archives. > > In the Mailman error log, I get messages similar to the following when > I send a message to the mailing list: > *** > Aug 21 12:52:07 2006 (3871) SHUNTING: > 1156182726.7459469+ce82b7624960d1de5eea043fee45821044e3dfec > Aug 21 13:28:00 2006 (3871) Uncaught runner exception: Use of the > Sendmail.py delivery module is highly discouraged > Aug 21 13:28:00 2006 (3871) Traceback (most recent call last): > File "/usr/local/mailman/Mailman/Queue/Runner.py", line 111, in > _oneloop > self._onefile(msg, msgdata) > File "/usr/local/mailman/Mailman/Queue/Runner.py", line 167, in > _onefile > keepqueued = self._dispose(mlist, msg, msgdata) > File "/usr/local/mailman/Mailman/Queue/OutgoingRunner.py", line 73, > in _dispose > self._func(mlist, msg, msgdata) > File "/usr/local/mailman/Mailman/Handlers/Sendmail.py", line 71, in > process > assert 0, 'Use of the Sendmail.py delivery module is highly > discouraged' > AssertionError: Use of the Sendmail.py delivery module is highly > discouraged > *** > > It's funny, Sendmail.py is included with the program source, but the > documentation says that "Use of the Sendmail.py delivery module is > highly discouraged." Is it possible to use Mailman with sendmail > without using Sendmail.py? I'd like to use sendmail if possible. > > Thanks for any help you can give! > > -- > David Swanger > swangdb at auburn.edu From sjmachin at lexicon.net Wed Aug 16 18:41:30 2006 From: sjmachin at lexicon.net (John Machin) Date: 16 Aug 2006 15:41:30 -0700 Subject: Calling a python script, and getting the returned result in C In-Reply-To: <1155764701.509056.207140@h48g2000cwc.googlegroups.com> References: <1155764701.509056.207140@h48g2000cwc.googlegroups.com> Message-ID: <1155768090.801185.101990@75g2000cwc.googlegroups.com> Shuaib wrote: > Hi! > > I have a python script which returns an Integer value. How do I call > this script from a C programe, and use the result returned? To avoid confusion and possible irrelevant responses, please say which of the following options best matches your requirement: (a) your Python script is capable of being run from the command line, and "returns" an integer value by calling sys.exit(that_value) -- you wish to execute the script from a C program [the same way you would execute a shell script / awk script / ...] and pick up the return value [which may be limited by the OS to range(0, 128)] (b) your script is a module, containing a function that returns an integer. You wish to create an embedded Python interpreter, import yourmodule, call yourmodule.yourfunc, convert the returned Python int to a C int, and use it. (c) none of the above Cheers, John From psnim2000 at gmail.com Mon Aug 28 12:07:39 2006 From: psnim2000 at gmail.com (Chaos) Date: 28 Aug 2006 09:07:39 -0700 Subject: Desktop Notification/Alerts In Python Message-ID: <1156781259.354526.142680@m79g2000cwm.googlegroups.com> I am looking for ways to have a Desktop Alert, like the one most IM Messengers have (MSN, AIM) at the lower right above the taskbar. Can anyone point me to the right resources to use? From webraviteja at gmail.com Sat Aug 19 07:21:30 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 19 Aug 2006 04:21:30 -0700 Subject: Text to MP3 using pyTTS - Non-programmer question In-Reply-To: <1155927552.548657.234930@i42g2000cwa.googlegroups.com> References: <1155904799.935486.105460@i3g2000cwc.googlegroups.com> <1155927552.548657.234930@i42g2000cwa.googlegroups.com> Message-ID: <1155986490.358588.154610@74g2000cwt.googlegroups.com> seyeRMReyes at gmail.com wrote: > Thanks for the script. Are there any online python intrepreters? > > I'd like to play around with the script. I don't have access to my home > PC. You probably will have to wait till you get to yours. There were some AJAXian ones but I doubt that you will find a free (assuming that you meant that) online interpreter on a MS Windows box that allows you to install your modules and give you an FTP or such account to get the recorded file back. From fiedzia at fiedzia.prv.pl Tue Aug 29 16:08:48 2006 From: fiedzia at fiedzia.prv.pl (Maciej Dziardziel) Date: Tue, 29 Aug 2006 22:08:48 +0200 Subject: python for flash drives References: <1156876019.177142.101730@e3g2000cwe.googlegroups.com> Message-ID: <20060829200848.2268.0.NOFFLE@fiedzia.homeip.net> Putty wrote: > Is there such a thing as a special version of python that I can run > more efficiently from a flash drive? google for movable python (or similar) -- Maciej "Fiedzia" Dziardziel (maciejdziardziel at poczta.wp.pl) In the land of the blind, the one eyed man is king. From mapsetah2000-maillist5 at yahoo.ca Tue Aug 29 13:37:17 2006 From: mapsetah2000-maillist5 at yahoo.ca (gmax2006) Date: 29 Aug 2006 10:37:17 -0700 Subject: sys.argv[0] doesn't always contain the full path of running script. Message-ID: <1156873037.590351.158120@i42g2000cwa.googlegroups.com> Hi, I use RedHat linux. How can I find where exactly the current python script is running? I use this code: #test.py import os,sys print sys.argv os.chdir(os.path.dirname(sys.argv[0])) It doesn't work when I run this command from the directory that test.py is located: python test.py That means sys.argv[0] doesn't always contain the full path of running script. Any help would be appreciated, Max From danielwong at berkeley.edu Thu Aug 17 15:27:46 2006 From: danielwong at berkeley.edu (danielx) Date: 17 Aug 2006 12:27:46 -0700 Subject: hide python code ! In-Reply-To: <1155813593.559451.84740@p79g2000cwp.googlegroups.com> References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155300852.497741.73230@74g2000cwt.googlegroups.com> <1155301468.870340.82920@b28g2000cwb.googlegroups.com> <1155307415.855555.124760@i3g2000cwc.googlegroups.com> <1155309563.898182.195950@p79g2000cwp.googlegroups.com> <1155313092.743230.33950@m73g2000cwd.googlegroups.com> <1155320948.142524.124990@p79g2000cwp.googlegroups.com> <1155564295.361980.279350@m73g2000cwd.googlegroups.com> <1155570126.905733.137850@m79g2000cwm.googlegroups.com> <1155657616.103285.40040@75g2000cwc.googlegroups.com> <1155760750.172859.172920@h48g2000cwc.googlegroups.com> <1155813593.559451.84740@p79g2000cwp.googlegroups.com> Message-ID: <1155842866.720030.284840@i42g2000cwa.googlegroups.com> Paul Boddie wrote: > danielx wrote: > > > > But we have only considered the economics of such a decision. Even if > > there is no market value to a work, a person has an understandable > > desire to exercise the rights of ownership over a work, given the > > amount of personal investment one makes in producing it. > > There are other motivations, too. An author might wish that their work > convey a particular message and that others should not be able to make > derived works which distort or contradict that message. However, there > are various established principles of fair use which limit the author's > control over such derived works. > > [...] > > > I think the above idea is frequently missed in discussions about > > copyrights/patents in the open source world. There, the focus seems to > > be on the marketability granted by protections (legal or physical). The > > post I am responding to illustrates this focus. Do we believe an author > > forfeits ownership of a work merely by sharing it? As a matter of > > conscience, I don't believe the answer can be imposed on anyone. Every > > person must answer this for him or herself. > > As we've mentioned above, one crucial issue is control over published > works and over the potentially related works of others. With software, > such control is mediated by the licence which is often prominent, even > unavoidable when using proprietary software; thus, people using or > distributing software should be aware of the licence which applies to > the work. In contrast, works in areas such as popular music are not While I agree with most of your post, I think the point should be made that eula's don't hold up very well in US courts: http://en.wikipedia.org/wiki/EULA#Enforceability > prominently "labelled" with licensing information if you're listening > to that music playing on the radio, television, in a public space, and > so on. This apparent "promiscuity" with such works leads people to > believe that they are freely exchangeable and that the author is not > exercising control, even if that isn't really the case due to the > framework established by the recording industry for broadcasters. > > So, people perceive an apparent lack of control as some kind of lack of > ownership, that the work has, by being shared in an apparently Extremely interesting point! This should really motivate people to answer the question I posed earlier: Does an author of software forfeit his rights to the code if he shares his program (ie, reliquishes _complete_ protection over the code)? Let's say this happens: I want to sell some software, but I'm affraid people will just copy it. So I prototype it in Python (or whatever programming language) and never release the program. Based on that, I design a chip (I know this is nearly impossible, but we are doing a mental experiment), which does exactly the same thing. First of all, the chip can be reverse engineered (of course, with MUCH greater difficulty than the equivalent code). Should I still be worried that my invention will be copied? A second point to consider: The chip is patentable (I think this is the case legally, as well as in the court of public opinion), so what about the equivalent code? > unconditional way, become part of their common culture - a sentiment or > an understanding that can presumably be traced back throughout the > history of human culture itself. At the opposite end of the spectrum of > control, when mechanisms of control are used to restrict the > distribution of derived works or the production of coincidentally > related works, is it unfair that people wish to disregard such > apparently counter-intuitive mechanisms? An interesting example in > popular culture was the legal argument about whether silence > constitutes an original work > (http://news.bbc.co.uk/1/hi/entertainment/music/2133426.stm), but > things like patents affect the ability of others to create works in a > fashion that can be much harder to predict. > > Paul From kay.schluehr at gmx.net Wed Aug 16 10:29:44 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 16 Aug 2006 07:29:44 -0700 Subject: Defining our own types? References: Message-ID: <1155738584.742828.303950@h48g2000cwc.googlegroups.com> Michael Yanowitz wrote: > Hello: > > I know this will probably turn about to be another dumb question > and I know I have asked a few really dumb ones lately on this list, > but I am hoping otherwise this time: > > suppose I type: > ip = 123.45.67.89 > (no quotes) > - is it possible (maybe by catching an exception), to have this > automatically converted to an ip address and maybe have the exception > convert this into: > ip = make_ip_address (123, 45, 67, 89) This will fail already on the parser level. The tokenizer recogizes '123.45' as a number as well as '.67' and '.89' and can't fit them together to something meaningfull. So you must adapt the tokenizer to accept '123.45.67.89' as a number and handle the corresponding NUMBER token by visiting the syntax tree later on i.e. returning either a NUMBER or a function call. I've written a framework that lets you do this [1] but be aware that you actually create a new language. Personally I don't think it's worth the effort and would define an IP object instead: ip = IP (123, 45, 67, 89) and/or ip = IP ("123.45.67.89") Regards, Kay [1] http://www.fiber-space.de/EasyExtend/doc/EE.html From bryanjugglercryptographer at yahoo.com Tue Aug 1 01:43:41 2006 From: bryanjugglercryptographer at yahoo.com (bryanjugglercryptographer at yahoo.com) Date: 31 Jul 2006 22:43:41 -0700 Subject: BCD List to HEX List In-Reply-To: <1154375956.397032.166310@p79g2000cwp.googlegroups.com> References: <5S8zg.1553$W93.658@dukeread05> <1154296114.094452.158000@p79g2000cwp.googlegroups.com> <1154298390.280625.206560@75g2000cwc.googlegroups.com> <1154299830.987261.9800@b28g2000cwb.googlegroups.com> <1154301233.360818.93450@s13g2000cwa.googlegroups.com> <0abzg.1576$W93.173@dukeread05> <1154361998.861851.157210@h48g2000cwc.googlegroups.com> <1154375956.397032.166310@p79g2000cwp.googlegroups.com> Message-ID: <1154411021.642620.255750@s13g2000cwa.googlegroups.com> John Machin wrote: > bryanjugglercryptographer at yahoo.com wrote: > > Philippe Martin wrote: > > > Yes, I came here for the "algorithm" question, not the code result. > > > > To turn BCD x to binary integer y, > > > > set y to zero > > for each nibble n of x: > > y = (((y shifted left 2) + y) shifted left 1) + n > > Yeah yeah yeah > i.e. y = y * 10 + n > he's been shown that already. > > Problem is that the OP needs an 8-decimal-digit (32-bits) answer, but > steadfastly maintains that he doesn't "have access to" long (32-bit) > arithmetic in his C compiler!!! And he doesn't need one. He might need the algorithms for shift and add. -- --Bryan From mervyn11 at gmail.com Tue Aug 15 08:48:13 2006 From: mervyn11 at gmail.com (M_M) Date: Tue, 15 Aug 2006 22:48:13 +1000 Subject: Beginner Textbook Message-ID: <12e3gkdhjngum6a@corp.supernews.com> Hi, I am looking for a simple text book to introduce 13 to 18 year olds to python programming. Suggestion? New to python. From sjmachin at lexicon.net Sun Aug 13 08:18:34 2006 From: sjmachin at lexicon.net (John Machin) Date: 13 Aug 2006 05:18:34 -0700 Subject: __LINE__ and __FILE__ functionality in Python? References: Message-ID: <1155471514.569981.237170@p79g2000cwp.googlegroups.com> Joakim Hove wrote: > Hello, > > i have simple[1] function like this: > > def log_msg(msg , file , line): > print "%s:%s %s" % (file,line,msg) > > the file and line arguments should be the filename and linenumber of > the source file where the function is called. If this were C I would > have used the __FILE__ and __LINE__ macros as: > > log_msg(msg , __FILE__ , __LINE__) > > Is there a way to emulate this behaviour in Python? > It's better in Python not to emulate that but to let the caller do the work: C:\junk>type caller_id.py import inspect def logger(msg): print "logger:", msg print "called from %s:%d" % inspect.stack()[1][1:3] print def client1(): logger("one") def client2(): logger("two") client1() client2() C:\junk>caller_id.py logger: one called from C:\junk\caller_id.py:9 logger: two called from C:\junk\caller_id.py:12 If you care to search for __LINE__ in this newsgroup, there's a slight chance you might find a thread or two or twenty-two on the topic :-) I don't usually go for one-liners, especially ugly ones like "inspect.stack()[1][1:3]" but it avoids the risk of hanging on to a reference to the frame object -- see the warning in the inspect docs. You can get the name of the calling function or method (and, indirectly, the method's class) if you want to log the whole dossier -- details left as an exercise :-) HTH, John From hadeshuang at gmail.com Fri Aug 25 20:00:18 2006 From: hadeshuang at gmail.com (Pebblestone) Date: 25 Aug 2006 17:00:18 -0700 Subject: Python and STL efficiency In-Reply-To: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> Message-ID: <1156550418.652278.210330@i42g2000cwa.googlegroups.com> Ruby is also not far away :-) Here's my code: ++++++++++++++++++++++++++++++++++++++++ require 'time' def f a = [] 1000000.times do a.push "What do you know" a.push "so long ..." a.push "chicken crosses road" a.push "fool" end b = a.uniq b.each do |x| puts x end end def f2 a = Array.new(4000000) 1000000.times do |i| a[i] = "What do you know" a[i+1] = "so long ..." a[i+2] = "chicken crosses road" a[i+3] = "fool" end b = a.uniq b.each do |x| puts x end end f_start = Time.now f f_end = Time.now f2_start = Time.now f2 f2_end = Time.now puts "f: Elapsed time: #{f_end - f_start} sec." puts "f2: Elapsed time: #{f2_end - f_start} sec." ++++++++++++++++++++++++++++++++++++++++++ And the benchmark result: What do you know so long ... chicken crosses road fool What do you know so long ... chicken crosses road fool nil f: Elapsed time: 3.600294 sec. f2: Elapsed time: 11.182927 sec. ++++++++++++++++++++++++++++++++++++++++++ I like ruby because its purity. :p Licheng Fang wrote: > Hi, I'm learning STL and I wrote some simple code to compare the > efficiency of python and STL. > > //C++ > #include > #include > #include > #include > #include > using namespace std; > > int main(){ > vector a; > for (long int i=0; i<10000 ; ++i){ > a.push_back("What do you know?"); > a.push_back("so long..."); > a.push_back("chicken crosses road"); > a.push_back("fool"); > } > set b(a.begin(), a.end()); > unique_copy(b.begin(), b.end(), ostream_iterator(cout, "\n")); > } > > #python > def f(): > a = [] > for i in range(10000): > a.append('What do you know') > a.append('so long...') > a.append('chicken crosses road') > a.append('fool') > b = set(a) > for s in b: > print s > > I was using VC++.net and IDLE, respectively. I had expected C++ to be > way faster. However, while the python code gave the result almost > instantly, the C++ code took several seconds to run! Can somebody > explain this to me? Or is there something wrong with my code? From duncan.booth at invalid.invalid Mon Aug 7 03:30:39 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 7 Aug 2006 07:30:39 GMT Subject: Proposal: [... for ... while cond(x)] References: <1154886383.696899.171490@i3g2000cwc.googlegroups.com> Message-ID: Slawomir Nowaczyk wrote: > #> No, the list comprehension lets you write an expression directly > #> avoiding a function call, and it also allows you to add in a > #> condition which can be used to filer the sequence. > > I am not sure if I understand you correctly, but... Does it? > >>>> a = [0,1,2,3,7,8,9] >>>> [x for x in takewhile(lambda x: x in a, range(10))] > [0, 1, 2, 3] >>>> [x for x in takewhile(x in a, range(10))] > Traceback (most recent call last): > File "", line 1, in ? > TypeError: 'bool' object is not callable > > Did I miss something? Yes, you missed out a lambda (so I was wrong, your suggestion would actually gain you more than 3 characters of typing) Try: >>> a = [0,1,2,3,7,8,9] >>> [x for x in takewhile(lambda x:x in a, range(10))] [0, 1, 2, 3] For this particular expression you could also write: >>> [x for x in takewhile(a.__contains__, range(10))] [0, 1, 2, 3] or with Python 2.5 we can avoid referencing __contains__ with the following variant: >>> from itertools import takewhile >>> from functools import partial >>> from operator import contains >>> a = [0,1,2,3,7,8,9] >>> [x for x in takewhile(partial(contains,a), range(10))] [0, 1, 2, 3] >>> From kay.schluehr at gmx.net Thu Aug 3 01:39:59 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 2 Aug 2006 22:39:59 -0700 Subject: Are there any AOP project in python community? In-Reply-To: <1154562487.677431.274440@i3g2000cwc.googlegroups.com> References: <1154562487.677431.274440@i3g2000cwc.googlegroups.com> Message-ID: <1154583599.141749.3730@b28g2000cwb.googlegroups.com> steve wrote: > I mean Aspect-Oriented Programming. > If any please give me some of links. > Thanks a lot. http://www.google.de/search?hl=de&q=python+%2B+AOP&btnG=Google-Suche&meta= From johnjsal at NOSPAMgmail.com Fri Aug 11 10:48:05 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 11 Aug 2006 14:48:05 GMT Subject: converting a nested try/except statement into try/except/else In-Reply-To: <1155253367.600486.176300@75g2000cwc.googlegroups.com> References: <1155154782.885182.7580@n13g2000cwa.googlegroups.com> <1155253367.600486.176300@75g2000cwc.googlegroups.com> Message-ID: Simon Forman wrote: > I'm sorry to hear that. I thought it was cleaner and more > understandable than that. May I indulge in explaining it a bit? I > can, perhaps, make it clearer. Thanks for the explanation. I find that with a little concentration, it's not that it's hard to follow the code, just that I feel like I will need to 're-concentrate' each time I come back to it, because of the different variables being used in different places. But I like the idea of making the try/except do very little, if not just one thing, so I'm going to keep studying it! :) From steve at holdenweb.com Tue Aug 15 21:51:13 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 16 Aug 2006 02:51:13 +0100 Subject: proc A def/calls proc B: variable scoping rules. In-Reply-To: <1155692329.075173.49060@p79g2000cwp.googlegroups.com> References: <1155685233.002415.184150@74g2000cwt.googlegroups.com> <1155692329.075173.49060@p79g2000cwp.googlegroups.com> Message-ID: NevilleDNZ wrote: > Steve Holden wrote: > >>Hardly surprising. This statement is an assignment to x2, which >>therefore becomes local to the function. Since no previous value has >>been assigned to this local, the exception occurs. > > > But: In this case the assignment is never reached.... eg.. Doesn't matter. It's not the *execution* of the assignment that makes the name local, it's the *existence* of the assignment, detected by static code analysis. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From claudio.grondi at freenet.de Sun Aug 27 10:16:54 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Sun, 27 Aug 2006 16:16:54 +0200 Subject: How to let a loop run for a while before checking for break condition? In-Reply-To: References: <4ldfp0F1csmpU1@uni-berlin.de> <4ldiacF1ckeeU1@uni-berlin.de> Message-ID: Fredrik Lundh wrote: > Diez B. Roggisch wrote: > >> A while loop has a condition. period. The only thing to change that is >> to introduce a uncoditioned loop, and use self-modifying code to make >> it a while-loop after that timer interrupt of yours. > > > or use a timer interrupt to interrupt the loop: > > import signal, time > > def func1(timeout): > > def callback(signum, frame): > raise EOFError # could use a custom exception instead > signal.signal(signal.SIGALRM, callback) > signal.alarm(timeout) > > count = 0 > try: > while 1: > count += 1 > except EOFError: > for i in range(10): > count += 1 > print count > > for an utterly trivial task like the one in that example, the alarm > version runs about five times faster than a polling version, on my test > machine (ymmv): > > def func2(timeout): > > gettime = time.time > t_limit = gettime() + timeout > > count = 0 > while gettime() < t_limit: > count += 1 > for i in range(10): > count += 1 > print count > > > This above is exactly what I am looking for, except it does not work in Microsoft Windows where the signal.alarm() function is not available. So now the only thing I would like to know is how to achieve the same functionality when running Python on a Microsoft Windows box. Claudio Grondi From sjmachin at lexicon.net Thu Aug 10 22:06:41 2006 From: sjmachin at lexicon.net (John Machin) Date: 10 Aug 2006 19:06:41 -0700 Subject: python/mysql/list question... In-Reply-To: References: Message-ID: <1155262001.555557.128050@p79g2000cwp.googlegroups.com> bruce wrote: > hi. > > i have the following sample code. i'm trying to figure out if there's a way > to use a 'list of lists' in a mysql execute... > > i've tried a variety of combinations but i get an error: > Error 1241: Operand should contain 1 column(s) > > the test code is: > > insertSQL = """insert into appTBL > (appName, universityID) > values(%s,%s)""" > > a = [] > b = [] > a.append('qqa') > a.append(222) > b.append(a) > a=[] > a.append('bbb') > a.append(66) > b.append(a) What's wrong with b = [['qqa', 222], ['bbb', 66]] ??? > > try: > c.execute(insertSQL, (b[0],b[1])) <<<<<<<<<<<<<<<<<<< I don't use mysqldb but here are some thoughts: (1) the v 2.0 DB API says the second arg should be a list of tuples, not a tuple of lists (2) and that usage is deprecated -- use executemany() instead. > except MySQLdb.Error, e: > print "Error %d: %s" % (e.args[0], e.args[1]) > print b > sys.exit (1) > > i've tried to use b, (b), etc... > using b[0] works for the 1st row... > > > any thoughts/comments... At first glimpse [like I said, I don't use this and have not visited the website before now], the author of mySQLdb has put a lot of effort into the docs e.g.. the executemany() example at the end of this page answers your question: http://sourceforge.net/docman/display_doc.php?docid=32071&group_id=22307#some-examples ... why don't you bother to read the docs??? From bwm at acm.org Sat Aug 19 19:14:16 2006 From: bwm at acm.org (Bernhard Mulder) Date: Sat, 19 Aug 2006 23:14:16 GMT Subject: cloning generator iterators Message-ID: I have something like the following (using Python 2.5 syntax): class adapt(object): def __init__(self): self.iterator = self.generator() self.n = 0 def generator(self): while True: while True: if (yield 1): if (yield 1): break self.n = 2 while (yield self.n): self.n += 1 def clone(self): clone = self.__class__() clone.n = self.n # This assignment does not work! clone.iterator.gi_frame.f_lasti = clone.iterator.gi_frame.f_lasti a = adapt() c = a.clone() c should be an independent clone of a, *including the program counter*. However, I have trouble adjusting the pc. The assignment above does not work since f_lasti is a readonly attribute. c1 = copy.copy(a) c1.iterator = copy.copy(a.iterator) also does not work, since a.iterator can not be copied. Question: What is the best way to implement this clone operation? Solutions I came up with: 1. Don't use generators, and program a state based approached directly, 2. Keep track of the values that where sent to the generator iterator, and feed the same values to the clone. I would like to keep the clone operation fairly independent from the generator, so that I can try out different generators (the generator above is probably not optimal). 2. is somewhat unsatisfactory, since with the clone operation become more expensive with long histories. Motivation: Abstractly speaking, I have a list of elements, and the list as a whole has property P. Now some of these elements can be deleted, and the list still has property P. The goal of the program is to delete as many elements of the list as possible without loosing property P. Now assume the following additional two conditions: 1. Testing for property P is time consuming. 2. Elements which can be deleted often come in 'clusters', that is elements at index i, i+1, i+2, i+3, ... can all be deleted without loosing property p. I am trying to address 1. and 2. by the above generator which I use to determine how many elements to delete. After two successful deletions, I delete 2, 3, 4, ... elements until the list does not show property P anymore. Now the generator helps, but it is still taking (too) long. On multi-core machines (soon coming to a desktop near you) I can reduce the elapsed time by testing three lists simultaneously: the second list is constructed under the assumption that the first list has property P, and the third list is constructed under the assumption that the first list does *not* have property P. My idea was to clone the class constructing the lists to test, which includes a clone of the adapt class sketched above. One of the two clones (for list 2 and 3) will be thrown away depending on the outcome of the test of list 1. From slawomir.nowaczyk.847 at student.lu.se Fri Aug 11 06:48:33 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Fri, 11 Aug 2006 12:48:33 +0200 Subject: Nested function scope problem In-Reply-To: <816zp2meldzw$.dlg@gelists.gmail.com> References: <20060809093215.EEDA.SLAWOMIR.NOWACZYK.847@student.lu.se> <816zp2meldzw$.dlg@gelists.gmail.com> Message-ID: <20060811110853.EFD5.SLAWOMIR.NOWACZYK.847@student.lu.se> On Wed, 09 Aug 2006 15:11:16 -0300 Gerhard Fiedler wrote: #> On 2006-08-09 07:54:21, Slawomir Nowaczyk wrote: #> #> > Nope. Equivalence table can look like this: #> > #> > Python C #> > variable: a variable: a #> > textual representation: "a" address operator: &a #> > id of object: id(a) dereference operator: *a #> > #> > Also, notice, that "id(a)" does not really "identify" a variable. It #> > only identifies *object* which is bound to this variable. Both in #> > Python and in C. #> #> Rests one question: what is the value of the variable? In Python, it would #> be the result of "a". In C, it would be the result of ...? Hmmm, well, it should be value of a, but it clearly doesn't make much sense. It seems like I got confused and was saying something else than I was thinking. So, indeed, you were right: this analogy is broken. But let me try again, please (just one more time, if this doesn't work either I am willing to admit I do not see a simple analogy between Python and C variables :-) Python C variable: a variable: a value of variable: eval("a") dereference operator: *a textual representation: "a" address operator: &a id of object: id(a) value of variable: a Thus, equivalent operations would be: Python C a = 1003 a = &three // (1) id(a) a b = 1004 b = &four a == b # False *a == *b // false id(a) == id(b) # False a == b // false b = a b = a a == b # True *a == *b // true id(a) == id(b) # True a == b // true a = 1001+1002 a = MallocNewIntFromValue( one+two ) a == b # True *a == *b // true id(a) == id(b) # False / True (2) a == b // false / true a = 1003+1004 a = MallocNewIntFromValue( three+four ) a == b # False *a == *b // false id(a) == id(b) # False a == b // false (1) one, two, three and four are constants, something like "const int one = 1". That is because there is no "literal int object" in C - the thing you would write as "1" is likely not to actually exist at runtime. And you cannot take an address of it. (2) is actually True in CPython implementation for small integers, but that's a minor detail. MallocNewIntFromValue might cache objects as well. -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) Housework can't kill you... but why take a chance? From tim.golden at viacom-outdoor.co.uk Fri Aug 4 05:03:42 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 4 Aug 2006 10:03:42 +0100 Subject: encoding of a file Message-ID: [Thomas Thomas] | how can I find the encoding to use to open a file.. I have a | file with "?" chararcter.. | is there some utility function in python that I can use | | how can I know which encoding to use [This is going to be a longer answer than you really want. The short answer is "probably iso-8859-1 but there's no way of being certain without trying it out".] The general answer to "how can I know which encoding to use for an arbitrary text file?" is that: you can't. The more helpful answer is that there are various heuristics (polite term for "good guessing algorithms") which will help you out. I believe that the latest BeautifulSoup has one: http://www.crummy.com/software/BeautifulSoup/ and I'm sure there are others. To be certain, though, you need to be told -- somehow -- what encoding was in use when the file was saved. However, that's not quite what you're asking. You say you have a file with a "?" character. But what does that mean? Ultimately, that you have some text in a file, one character of which you expect to display as a pound sign (that's a British pound sign, not the # which Americans bizarrely call a pound sign ;). Someone, somewhere, got this pound sign into a file. Maybe it was from a text editor, maybe through a database. However it happened, the application saved its data to disk using some encoding. If it was a naive tool (non-unicode-aware) then it was probably ASCII with some kind of extension above the 7-bit mark. iso-8859-1 / latin-1 (same thing) often cope with that. If the app was unicode-aware, it'll be a specific unicode encoding. Quite possibly utf-8. To experiment, pick the necessary byte/bytes out of your text stream and compare with a few encodings: import sys from unicodedata import name # # This is, for example, your original "pound sign" # bytes = "\x9c" # # This is what we're aiming for: what unicode # thinks of as a pound sign # print name (u"?") # -> POUND SIGN # # Let's try ascii # print name (bytes.decode ("ascii")) # # Whoops! # -> UnicodeDecodeError: 'ascii' codec can't decode byte 0x9c in position 0: ordinal not in range(128) # # iso-8859-1 / latin-1 # print name (bytes.decode ("iso-8859-1")) # # Still not right # -> ValueError: no such name # # Cheating, slightly... # print name (bytes.decode (sys.stdin.encoding)) # # Bingo! # -> POUND SIGN print sys.stdin.encoding # -> cp437 print sys.stdout.encoding # -> cp437 So in this case it was cp437 (since I got the bytes from typing "?" into the interpreter, something I can do on my keyboard. You might well find it was some other encoding. If this doesn't take you anwhere -- or you don't understand it -- try dumping a bit of your data into an email and posting it. If nothing else, someone will probably be able to tell you what encoding you need! TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From sjmachin at lexicon.net Mon Aug 7 18:03:41 2006 From: sjmachin at lexicon.net (John Machin) Date: 7 Aug 2006 15:03:41 -0700 Subject: Getting previous file name References: <1154983936.588478.298380@m79g2000cwm.googlegroups.com> Message-ID: <1154988221.107543.268030@n13g2000cwa.googlegroups.com> Hitesh wrote: > Hi, > > I have a small script here that goes to inside dir and sorts the file > by create date. I can return the create date but I don't know how to > find the name of that file... > I need file that is not latest but was created before the last file. > Any hints... I am newbiw python dude and still trying to figure out lot > of 'stuff'.. > > > import os, time, sys > from stat import * Lose that, and use ".st_ctime" instead of "[ST_CTIME]" below > > def walktree(path): This function name is rather misleading. The function examines only the entries in the nominated path. If any of those entries are directories, it doesn't examine their contents. > test1 = [] > for f in os.listdir(path): > filename = os.path.join(path, f) os.listdir() gives you directories etc as well as files. Import os.path, and add something like this: if not os.path.isfile(filename): print "*** Not a file:", repr(filename) continue > create_date_sces = os.stat(filename)[ST_CTIME] Do you mean "secs" rather than "sces"? > create_date = time.strftime("%Y%m%d%H%M%S", > time.localtime(create_date_sces)) > print create_date, " ....." , f > test1.append(create_date) Answer to your main question: change that to test1.append((create_date, filename)) and see what happens. > test1.sort() If there is any chance that multiple files can be created inside 1 second, you have a problem -- even turning on float results by using os.stat_float_times(True) (and changing "[ST_CTIME]" to ".st_ctime") doesn't help; the Windows result appears to be no finer than 1 second granularity. The pywin32 package may provide a solution. > print test1 > return test1[-2] > > > if __name__ == '__main__': > path = '\\\\srv12\\c$\\backup\\my_folder\\' (1) Use raw strings. (2) You don't need the '\' on the end. E.g. path = r'\\srv12\c$\backup\my_folder' > prev_file = walktree(path) > print "Previous back file is ", prev_file > > Cheers, John From frikker at gmail.com Thu Aug 24 09:17:56 2006 From: frikker at gmail.com (frikker at gmail.com) Date: 24 Aug 2006 06:17:56 -0700 Subject: Python Syntax Highlighting Module References: <1156172592.903109.172520@p79g2000cwp.googlegroups.com> <1156173569.306945.320640@m79g2000cwm.googlegroups.com> Message-ID: <1156425476.419806.90520@74g2000cwt.googlegroups.com> thank you! These will be very helpful. I'm not necessarily creating an editor from scratch, but maybe an editor that has some additional custom functionality. Thanks again, blaine gene tani wrote: > frikker at gmail.com wrote: > > Hello, > > I have an idea for a project which involves an editor that supports > > syntax highlighting. This would be for any language, particularly php, > > html, css, etc. I would like to write this program using python. It > > would only make sense to base this upon existing open source code. My > > question is there a python module or examples on how to write a code > > editor which supports modulated syntax highlighting? > > > > Thank you, > > Blaine > > just a *few* examples > > http://lfw.org/python/cedit > > http://mathieu.fenniak.net/formatting-a-simple-function-in-python/ > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/200638 > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442482 > > http://effbot.python-hosting.com/browser/stuff/sandbox/pythondoc/ > > http://qbnz.com/highlighter/index.php > http://pudge.lesscode.org/ > > also look at GNU / emacs: > > http://fly.srk.fer.hr/~hniksic/emacs/htmlize.el.html > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52298 > > http://www.danbala.com/python/lpy/lpy.py.html > http://www.gnu.org/software/src-highlite/ From linnorm at gmail.com Wed Aug 9 16:48:38 2006 From: linnorm at gmail.com (linnorm at gmail.com) Date: 9 Aug 2006 13:48:38 -0700 Subject: Python share CPU time? In-Reply-To: <1155146500.063665.282430@p79g2000cwp.googlegroups.com> References: <1155146500.063665.282430@p79g2000cwp.googlegroups.com> Message-ID: <1155156518.923797.133210@h48g2000cwc.googlegroups.com> Yannick wrote: > Hi, > > I would like to program a small game in Python, kind of like robocode > (http://robocode.sourceforge.net/). > Problem is that I would have to share the CPU between all the robots, > and thus allocate a time period to each robot. However I couldn't find > any way to start a thread (robot), and interrupt it after a given time > period. > Any suggestions on how to proceed? > Is Python just not adapted to this kind of things? > > Thanks, > Yannick You should take a look at stackless Python. It should do very nicely for what you want. There is a good tutorial on it here: http://members.verizon.net/olsongt/stackless/why_stackless.html From riko at despammed.com Wed Aug 23 08:47:47 2006 From: riko at despammed.com (Mc Osten) Date: Wed, 23 Aug 2006 14:47:47 +0200 Subject: Python and STL efficiency References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <1hkh28d.xscw4v1y4v9a6N%riko@despammed.com> <1hkh6lb.6dsnh51lj8z96N%riko@despammed.com> <1156252193.524186.107520@b28g2000cwb.googlegroups.com> <1hkhexv.18m65rl61swqyN%riko@despammed.com> <1156265848.875774.251640@i42g2000cwa.googlegroups.com> <1156290607.269119.88710@b28g2000cwb.googlegroups.com> <1hkil6j.xm4l6y1kwo13dN%riko@despammed.com> <1156317315.946762.215690@p79g2000cwp.googlegroups.com> <1hkioxy.42be4c1lg0jq5N%riko@despammed.com> <1156320792.011620.141030@m79g2000cwm.googlegroups.com> Message-ID: <1hkitqt.c17kl5o30nr4N%riko@despammed.com> Ray wrote: > Yeah, my guess would be either he used the Debug configuration or he > actually created a Managed executable instead of a pure Win32 > application. Sigh, now I can't wait to get home and try it out :) Can be. But I suppose a Managed should not get *that* slow. IronPython on Tim's machine is still faster than C++ (even though not as fast as CPython). -- blog: http://www.akropolix.net/rik0/blogs | Uccidete i filosofi, site: http://www.akropolix.net/rik0/ | tenetevi riso e forum: http://www.akropolix.net/forum/ | bacchette per voi. From paul at boddie.org.uk Fri Aug 11 11:19:23 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 11 Aug 2006 08:19:23 -0700 Subject: hide python code ! References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155300852.497741.73230@74g2000cwt.googlegroups.com> <1155301468.870340.82920@b28g2000cwb.googlegroups.com> <1155307415.855555.124760@i3g2000cwc.googlegroups.com> Message-ID: <1155309563.898182.195950@p79g2000cwp.googlegroups.com> Ben Sizer wrote: > > It's worth remembering that there is a massive amount of software that > has nothing to do with 'infrastructure', that won't need to be > maintained, or upgraded. Examples include most retail software for the > home or small office, and most entertainment software. Developers of > such software often have understandable reasons for making it > inconvenient to examine the algorithms at a high level. It may be the case that certain kinds of applications can go on working forever on whatever hardware they were intended to run, right until the point when the hardware ceases to function correctly or when the end-user gets bored of it, or envious of the neighbour's hardware, or for whatever other reason. However, I've seen plenty of evidence of "home or small office" software which arrives as a binary, employs its own proprietary format, runs on now-legacy hardware and whose users are now high-and-dry with respect to accessing their old documents. Sure, developers of such software may not want their competitors to find out how their products work - certain companies also like to file patents for that added anticompetitive edge, should their competitors even consider figuring out the not-so-magic formula - but as end-users of software ourselves, we don't have to share such an understanding of their motivations, especially when such motivations directly conflict with our own: with respect to the above evidence, our own motivations are to have a reasonable level of control over the tools to manage our own data. It may not matter if some console game or other doesn't work after 20 years, although I think it's actually something of a shame given that such artifacts, no matter how apparently trivial they are, are actually part of our culture and shouldn't be so readily discarded and forgotten, but when your own data is not easily accessible within a much shorter timeframe, the scandal is (at least to me) so much more obvious. Paul From antroy at gmail.com Mon Aug 21 02:21:41 2006 From: antroy at gmail.com (Ant) Date: 20 Aug 2006 23:21:41 -0700 Subject: trouble using "\" as a string In-Reply-To: <1156023013.462640.165970@i42g2000cwa.googlegroups.com> References: <1156023013.462640.165970@i42g2000cwa.googlegroups.com> Message-ID: <1156141301.606614.8270@75g2000cwc.googlegroups.com> > such as tempname="\"..it says that the line is single qouted. The others have addressed the escape issue I think. However it looks like you want the funtionality of the os.path module. For example: >>> import os.path as path >>> filename = "/home/ant/test.sh" >>> filename2 = r"c:\python24\scripts\test.py" >>> path.split(filename) ('/home/ant', 'test.sh') >>> path.split(filename2) ('c:\\python24\\scripts', 'test.py') From dingbat at codesmiths.com Tue Aug 1 06:31:04 2006 From: dingbat at codesmiths.com (Andy Dingley) Date: 1 Aug 2006 03:31:04 -0700 Subject: Windows vs. Linux In-Reply-To: <1154385878.713809.113060@i42g2000cwa.googlegroups.com> References: <1154301694.445639.99580@m79g2000cwm.googlegroups.com> <1154385878.713809.113060@i42g2000cwa.googlegroups.com> Message-ID: <1154428264.934787.112500@s13g2000cwa.googlegroups.com> diffuser78 at gmail.com wrote: > Python and Ubuntu rock...go fot it. That's nice. I've just burned myself a new Ubuntu f*ck-a-duck release CD intending to rebuild a flakey old Deadrat box with it. Once it's done I'd like to be running Python with some USB to Dallas one-wire hardware on it, re-plugged from an old Windows box. Nice to know I have a hope of getting somewhere. From R.Brodie at rl.ac.uk Thu Aug 17 10:56:29 2006 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Thu, 17 Aug 2006 15:56:29 +0100 Subject: List match References: <1155823451.766317.7640@74g2000cwt.googlegroups.com> Message-ID: "OriginalBrownster" wrote in message news:1155823451.766317.7640 at 74g2000cwt.googlegroups.com... > I know this probably is a very easy thing to do in python, but i wanted > to compare 2 lists and generate a new list that does not copy similar > entries. An example below > > list= ["apple", "banana", "grape"] > list2=["orange","banana", "pear"] Other people have already posted solutions but I'll add a couple of comments: 1. Avoid calling lists 'list', you will break the list built-in function. 2. You don't specify whether the lists are ordered. If there is no significance to the order of the items, it may be more appropriate to use sets throughout. Then the answer is just: set3 = set1 | set2. From http Sun Aug 27 18:06:07 2006 From: http (Paul Rubin) Date: 27 Aug 2006 15:06:07 -0700 Subject: random writing access to a file in Python References: <5a9ue2lrjh214ecmme09fsodhm3ico1ntm@4ax.com> <7xhczzqoi3.fsf@ruckus.brouhaha.com> <7xbqq7f6q7.fsf@ruckus.brouhaha.com> <7xd5anf23u.fsf@ruckus.brouhaha.com> <7xr6z2dpt0.fsf@ruckus.brouhaha.com> Message-ID: <7xpselvnow.fsf@ruckus.brouhaha.com> Claudio Grondi writes: > >>The Windows XP SP 2 '/> sort' (sorting of four Gigs of 20 byte records > >>took 12 CPU and 18 usual hours).... > Ok, I see - the misunderstanding is, that there were 4.294.967.296 > records each 20 bytes long, what makes the actual file 85.899.345.920 > bytes large (I just used 'Gigs' for telling the number of records, not > the size of the file). > Still not acceptable sorting time? I think that's not so bad, though probably still not optimal. 85 GB divided by 18 hours is 1.3 MB/sec, which means if the program is reading the file 8 times, it's getting 10 MB/sec through the Windows file system, which is fairly reasonable throughput. If you know something about the distribution of the data (e.g. the records are random 20-byte hashes) you might be able to sort it in essentially linear time (radix sorting). But even with a general purpose algorithm, if you have a few hundred MB of ram and some scratch disk space to work with, you should be able to sort that much data in much less than 18 hours. But if you only had to do it once and it's finished now, why do you still care how long it took? From psnim2000 at gmail.com Sat Aug 12 19:07:06 2006 From: psnim2000 at gmail.com (Chaos) Date: 12 Aug 2006 16:07:06 -0700 Subject: wxPython ListBook Class, Label Position w/ ImageList In-Reply-To: <44de128b$0$21149$7a628cd7@news.club-internet.fr> References: <1155383930.411326.10150@h48g2000cwc.googlegroups.com> <44de128b$0$21149$7a628cd7@news.club-internet.fr> Message-ID: <1155424026.906471.112210@p79g2000cwp.googlegroups.com> jean-michel bain-cornu wrote: > Hi, > > By default the label position of an image list is below the image. Is > > there any way to change this? > > > > If it exists, it's undocumented, and there is not a sample. > Did you ask the wx forum ? It's probably a better place to have this > kind of information. If they provide you a C sample, I could help you to > convert it in python. > Anyway, if you find out something, I'm interested... > > Regards, > jm I didnt find an answer but I simple used the TreeControl and everythime its clicked I use it to update the main frame From sjmachin at lexicon.net Fri Aug 18 18:55:45 2006 From: sjmachin at lexicon.net (John Machin) Date: 18 Aug 2006 15:55:45 -0700 Subject: Search or compai problem References: Message-ID: <1155941745.802556.299470@m73g2000cwd.googlegroups.com> Gallagher, Tim (NE) wrote: > I am new to python and I want to compare 2 strings, here is my code: > [start] > > import active_directory > import re > > lstUsers = [] Using "lst" or "l" as a variable name is bad news in any language; with many fonts they are too easily misread as "1st" or "1" respectively. > users = active_directory.root() > for user in users.search ("sn='gallagher'"): **** Insert here: print type(user.samAccountName), repr(user.samAccountName) **** that may indicate where your problem *starts* **** Then read the documentation for the active_directory module, in particular what it says about the attributes of the objects in the sequence returned by users.search. > lstUsers.append(user.samAccountName) > > print "----------------------------------------" > lstUsers.sort() > > ## Printing out what is inside of the arrar(list) What is "arrar(list)" ?? **** Here insert this code: print lstUsers **** Look at the elements in the list; do you see ..., 'None', ... or do you see ..., None, ... > x = 0 > while x < len(lstUsers): *Please* consider using a "for" statement: for item in lstUsers: do_something_with(item) > if re.compile(lstUsers[x]).match("None",0): 1. Python or not, using regular expressions to test for equality is extreme overkill. Use if lstUsers[x] == "None": 2. Python or not, it is usual to do re.compile(constant pattern).match(variable_input) not the other way around. 3. The second arg to match defaults to 0, so you can leave it out. > print "Somthing here" > > x = x + 1 > > [/end] > > When I do the: > if re.compile(lstUsers[x]).match("None",0): > print "Somthing here" > > Some of the items in lstUsers[x] are the word None. > I am not sure why I cant do this > > I want to compare lstUsers[x] to the word "None", how can I do this. You *have* compared lstUsers[x] to the word "None" -- with the re sledgehammer, but you've done it. Maybe what's in there is *not* the string "None" :-) HTH, John From paddy3118 at netscape.net Sun Aug 20 05:44:03 2006 From: paddy3118 at netscape.net (Paddy) Date: 20 Aug 2006 02:44:03 -0700 Subject: sum and strings In-Reply-To: <1156038134.216383.80960@h48g2000cwc.googlegroups.com> References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <7xr6zel2r2.fsf@ruckus.brouhaha.com> <1155971485.709068.255140@b28g2000cwb.googlegroups.com> <1156038134.216383.80960@h48g2000cwc.googlegroups.com> Message-ID: <1156067043.386056.129320@i42g2000cwa.googlegroups.com> Rhamphoryncus wrote: > > It's worthwhile to note that the use of + as the concatenation operator > is arbitrary. It could just have well been | or &, and has no > relationship with mathematically addition. The effect of the string concatenation operator is only secondary. Secondary to the use of the word sum; and what could be 'reasonably' concieved as sum's effect on non-numeric types. > > It's also worth stressing (not in response to your post, but others) > that sum([[1],[2],[3]], []) is just as bad as attempting to sum > strings, both conceptually (it's not mathematical addition) Unfortunately, the words sum and summation are linked to other words that are commonly used to describe what is happening to the numders, the lists, and the strings. Words such as accumulate, concatenate, aggregate, collect, assemble, as well as add. > and performance-wise. Don't do it. :) Amen to that. > I believe the prefered method to flatten a list of lists is this: > > shallow = [] > for i in deep: > shallow.extend(i) > > Yes, it's three lines. It's also very easy to read. reduce() and > sum() are not. I'd like to squeeze in the listcomp version, not because it is one line shorter, but because I, and maybe others prefer short listcomps such as the folowing: shallow = [] [shallow.extend(i) for i in deep] -Pad. From stargaming at gmail.com Sun Aug 13 05:06:24 2006 From: stargaming at gmail.com (Stargaming) Date: Sun, 13 Aug 2006 11:06:24 +0200 Subject: keep a list of read and unread items In-Reply-To: <1155459572.658340.242190@74g2000cwt.googlegroups.com> References: <1155456602.502808.105990@m79g2000cwm.googlegroups.com> <1155459572.658340.242190@74g2000cwt.googlegroups.com> Message-ID: Ant schrieb: > a wrote: > > >>i m building an rss reader and i want you suggestions for datastructure >>for keeping read and unread list for each use >>i m assuming it will be very sparse > > > A dictionary for each site seems to be the obvious choice, mapping the > article ID to True or False. > You could also write a class, let's say RSSEntry, with attributes like "read", "title", "author", "content", "date" and everything you need. Another class-way would be some class like RSSFeed, being a container holding entries like RSSFeed[0] RSSFeed[1] etc., each again with attributes like RSSFeed[0].author. Those class instances can be pickle'd easily, so you don't have to bother about any database or stuff. From bugnthecode at gmail.com Sun Aug 20 13:09:59 2006 From: bugnthecode at gmail.com (bugnthecode) Date: 20 Aug 2006 10:09:59 -0700 Subject: import In-Reply-To: <1156093283.529579.80600@i42g2000cwa.googlegroups.com> References: <1156093283.529579.80600@i42g2000cwa.googlegroups.com> Message-ID: <1156093799.775420.51970@m73g2000cwd.googlegroups.com> How are you trying to import it? Is it in the same directory as your other script? If not is your python path set correctly? When importing a module that you have written you exlude the .py extension. You should be using: import hello Hope that helps, Will From rogue_pedro at yahoo.com Sun Aug 13 14:28:55 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 13 Aug 2006 11:28:55 -0700 Subject: yet another noob question In-Reply-To: <1155492110.659011.196280@75g2000cwc.googlegroups.com> References: <1155492110.659011.196280@75g2000cwc.googlegroups.com> Message-ID: <1155493735.622048.305320@m73g2000cwd.googlegroups.com> mike_wilson1333 wrote: > I would like to generate every unique combination of numbers 1-5 in a 5 > digit number and follow each combo with a newline. So i'm looking at > generating combinations such as: (12345) , (12235), (55554) and so on. > What would be the best way to do this? So, basically i'm looking for a > list of all combinations of 1-5 in a 5 digit unique number. Also, when > I send the list to print there can't be any duplicates of the combos. > > > Thanks, > > Mike Hi Mike, this is one of those "Somebody must have had this problem before me" kind of situations. Google on "python combination" and you should be well rewarded. :-) Peace, ~Simon From tim at tdw.net Wed Aug 16 19:48:05 2006 From: tim at tdw.net (Tim Williams) Date: Thu, 17 Aug 2006 00:48:05 +0100 Subject: Anyone have a link handy to an RFC 821 compliant email address regex for Python? In-Reply-To: References: Message-ID: <9afea2ac0608161648s1cd70112rb32d6788dd7bd59f@mail.gmail.com> On 16 Aug 2006 15:23:06 -0700, fuzzylollipop wrote: > I want to do email address format validations, without turning to ANTLR > or pyparsing, anyone know of a regex that is COMPLIANT with RFC 821. > Most of the ones I have found from google searches are not really as > robust as I need them to be. > RFC 2821 and 2822 specify the format for email addresses. Contrary to popular belief, just about all characters are valid and this makes validating an address format very difficult. Also, just because an email address is in the correct format doesn't mean its a real or valid address. http://en.wikipedia.org/wiki/E-mail_address has a short overview >From experience, you might be better off not putting too much energy into this, and maybe instead just do a basic template validation eg: some text followed by @ followed by some text which when split by '.' gives at least 2 parts. In addition a DNS MX record lookup will tell you if the domain part is capable of receiving email, the address can't be valid (for internet transmission) without MX records. If you want to take it a step further, you can also query the server(s) pointed to in the MX records, but this takes time, and is not accurate. Some domains have catchalls, and others like yahoo don't refuse an address until after a whole email has been received. HTH :) From dpeschel at eskimo.com Sat Aug 26 03:14:56 2006 From: dpeschel at eskimo.com (Derek Peschel) Date: 26 Aug 2006 07:14:56 GMT Subject: Finding the type of indexing supported by an object? References: <1hkii5f.19t6trjthzd67N%aleax@mac.com> Message-ID: In article <1hkii5f.19t6trjthzd67N%aleax at mac.com>, Alex Martelli wrote: >Derek Peschel wrote: >> They are the same except for the expression in "for key in ...". Can they >> be combined into one function? How can I determine if the argument is > >They can easily be refactored, if that's what you mean: No, that isn't what I mean. I wanted _one_ function that works with a wide variety of objects -- anything that has a finite number of keys you can iterate over, with each key mapping to a finite number of values, and the key iteration and value lookup referentially transparent. This hypothetical function would have to do some checking of the argument type, but hopefully as little as possible. It should work with object types invented after it was written. Reading everyone's replies, especially yours and Fredrik Lundh's, I realized I've been thinking of the whole problem in Smalltalk (or possibly Ruby) terms. Smalltalk and Ruby use inheritance to describe some properties of objects. Python has many primitive types that aren't related to eaach other. I thought that testing for methods might get the properties I wanted, but you two pointed out that the method writer has too much latitude. Do you think the generic-function idea is still useful? At the moment I only need to invert dicts and lists. Is subclassing dict and list considred good style? (I see I can't add methods to dict and list directly.) >I've also performed a few other minor enhancements (never name things >dict or list because that hides the builtin types, use xrange vs range). OK, I'll remember those points. The argument names are a style I got from my Ruby code, and possibly not a good idea there either. >I have not changed the 4 lines in the if/else though I don't like them >(if not.../else is a very confusing construct -- at a minimum I'd >rephrase it as if/else swapping the bodies of the two clauses). It used if/else originally. Then I swapped the parts of the conditional to make the inversion function match another function (that takes a key, old value, and new value, and makes the change in a sequence and in its inverted form). To me the swapped version made some sense in the second function, because of the layout of the function as a whole, but you have a point that if not/else is rarely (never?) clear. >If you want to add a generic form accepting either lists or dicts you >need a try/except statement inside it, e.g.: Is that a reliable way to get the properties I wanted? RADLogic Pty. Ltd. added a two-way dict package to the Cheese Shop. It requires that the mapping be one-to-one, which won't work for me. It sub- classes dict, and requires that keys and values be hashable. -- Derek From pavlovevidence at gmail.com Thu Aug 17 12:43:52 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 17 Aug 2006 09:43:52 -0700 Subject: Curried class methods? References: <1155779616.228836.153470@p79g2000cwp.googlegroups.com> Message-ID: <1155833032.599601.228190@75g2000cwc.googlegroups.com> Scott Lamb wrote: > I'm trying to dynamically generate class methods which have access to > some state passed in at creation time. (Basically as a workaround to > twisted's trial not having a way to dynamically add stuff. Plain > unittest seems to have TestSuite, but the trial runner doesn't know > about it.) > > My first attempt might better illustrate this - > > class Foo: > def generalized(self, ctx): > print 'my ctx is %r' % ctx > > for i in ['a','b','c']: > setattr(Foo, i, lambda self: self.generalized(i)) > > foo = Foo() > foo.a() > foo.b() > foo.c() > > but this prints "my ctx is c" three times; I'd hoped for a, b, c, of > course. def build(j): setattr(Foo, j, lambda self: self.generalized(j)) for i in ["a","b","c"]: build(i) Each call of the the build function creates its own cell "j" that the lambda references. Carl Banks From Dieter_Deyke at CoCreate.com Tue Aug 8 11:39:16 2006 From: Dieter_Deyke at CoCreate.com (Dieter Deyke) Date: Tue, 08 Aug 2006 09:39:16 -0600 Subject: Accessing Yahoo Mail withtout POP References: <1155050998.864753.198990@m79g2000cwm.googlegroups.com> Message-ID: "T" writes: > Is there a way to access yahoo mail via its web interface? If so, can > someone give some pointers? This works for me: http://www.ypopsemail.com/ -- Dieter Deyke mailto:Dieter_Deyke at CoCreate.com mailto:deyke at comcast.net Vs lbh pna ernq guvf, lbh unir jnl gbb zhpu gvzr. From sjmachin at lexicon.net Wed Aug 16 18:10:22 2006 From: sjmachin at lexicon.net (John Machin) Date: 16 Aug 2006 15:10:22 -0700 Subject: PySequence_SetItem In-Reply-To: <1155764364.775366.76070@i3g2000cwc.googlegroups.com> References: <1155754847.392950.266180@h48g2000cwc.googlegroups.com> <1155755905.233229.93440@74g2000cwt.googlegroups.com> <1155761144.583994.260150@m73g2000cwd.googlegroups.com> <1155764364.775366.76070@i3g2000cwc.googlegroups.com> Message-ID: <1155766222.212302.35360@m79g2000cwm.googlegroups.com> John Machin wrote: > Jack Diederich wrote: > > > Changing the PySequence_SetItem to PyList_SetItem and dropping the > > DECREF works for me too (PyList functions steal a reference). I also > > tried setting the list to length 1, still no dice. The PySequence > > version segs under 2.4 and 2.5. It segs even when the Int is changed > > to a String. > > > > Yikes, I'll poke around some more. > > Yikes indeed. > > Not the OP's problem, but a bug in the manual: example in the chapter > that the OP was reading acts as though the 2nd arg to PyObject_SetItem > is a C int (as it is for the List and Sequence varieties) -- it is in > fact a (PyObject *), which explains the SystemError that I got. > OK, here's the story: PyList_New fills the list with NULLs. PyList_SetItem applies Py_XDECREF to the previous contents. PySequence_SetItem calls the function in the object's sq_ass_item slot. This is list_ass_item, which as the OP noted, applies Py_DECREF to the previous contents. Splat when NULL. I wonder how long it's been like that? FYI, the buggy manual section is http://docs.python.org/api/refcountDetails.html Cheers, John From micahc at gmail.com Mon Aug 28 15:07:02 2006 From: micahc at gmail.com (micahc at gmail.com) Date: 28 Aug 2006 12:07:02 -0700 Subject: How to store ASCII encoded python string? Message-ID: <1156792022.792854.90700@i42g2000cwa.googlegroups.com> I currently have a Python program that reads in emails from a POP3 server. As soon as the message is read in it is fed directly into a PostgreSQL database for storage. Later, it is broken down into it's parts and displayed to the user. My problem is that when I try to pass "\tsome text\xa7some more text\n" into the database it gives me a unicode decode error. At this point in the program I don't know what codec it is (I won't know that until I break apart the message later) and it may even be binary data so I just want to store it in the database with the escape characters, not as a decoded/encoded string. So, how do I store "\tsome text\xa7 some more text\n" as that instead of: " some text? some more text " I don't have a problem escaping it so the above would look like "\\tsome text\\xa7 some more text\\n" as long as I have a way to later unescape it when I want to actual do something with the data. From smeenehan at hmc.edu Fri Aug 4 07:59:57 2006 From: smeenehan at hmc.edu (smeenehan at hmc.edu) Date: 4 Aug 2006 04:59:57 -0700 Subject: Problem reading/writing files References: <1154661460.803694.241220@s13g2000cwa.googlegroups.com> <1154663988.871166.112930@s13g2000cwa.googlegroups.com> Message-ID: <1154692797.329732.73290@75g2000cwc.googlegroups.com> > What platform? What version of Python? Have you opened the > file in binary mode i.e. open('thefile', 'rb') ?? Show us the relevant > parts of your code, plus what caused you to conclude that read() > changed data on the fly in an undocumented fashion. Yes, I've been reading and writing everything in binary mode. I'm using version 2.4 on a Windows XP machine. Here is the code that I have been using to split up the original file: f = open('evil2.gfx','rb') i1 = open('img1.jpg','wb') i2 = open('img2.png','wb') i3 = open('img3.gif','wb') i4 = open('img4.png','wb') i5 = open('img5.jpg','wb') for i in range(0,67575,5): i1.write(f.read(1)) i2.write(f.read(1)) i3.write(f.read(1)) i4.write(f.read(1)) i5.write(f.read(1)) f.close() i1.close() i2.close() i3.close() i4.close() i5.close() I first noticed the problem by looking at the original file and img1.jpg side by side with a hex editor. Since img1 contains every 5th byte from the original file, I was able to find many places where \x00 should have been copied to img1.jpg, but instead a \x20 was copied. What caused me to suspect the read method was the following: >>> f = open('evil2.gfx','rb') >>> s = f.read() print repr(s[19:22]) '\xe0 \r' Now, I have checked many times with a hex editor that the 21st byte of the file is \x00, yet above you can see that it is reading it as a space. I've repeated this with several different nulls in the original file and the result is always the same. As I said in my original post, when I try simply writing a null to my own file and reading it (as someone mentioned earlier) everything is fine. It seems to be only this file which is causing issue. From g.brandl-nospam at gmx.net Tue Aug 8 03:11:10 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Tue, 08 Aug 2006 09:11:10 +0200 Subject: Ann: SE 2.2b In-Reply-To: References: <01d101c6b86a$fb7aa1c0$0201a8c0@mcuf7> Message-ID: Anthra Norell wrote: > If you go to http://www.python.org/pypi. you see it about in the middle of the recently updated packages. It's blue, so you can > click it and you're there. > The update page shows only the twenty most recent updates. So they drop out at the bottom rather fast. If it's gone by the > time you check, type SE into the search template in the upper right corner. Thanks, but I know how to use the Cheese Shop. Last time I looked, there was no file available for download. Now it is. Georg From aleax at mac.com Fri Aug 4 00:57:07 2006 From: aleax at mac.com (Alex Martelli) Date: Thu, 3 Aug 2006 21:57:07 -0700 Subject: Can Your Programming Language Do This? Joel on functional programming and briefly on anonymous functions! References: Message-ID: <1hjikws.n7a5lfm2v0yuN%aleax@mac.com> Jarek Zgoda wrote: > Casey Hawthorne napisa?(a): > > > Can Your Programming Language Do This? > > > > Joel on functional programming and briefly on anonymous functions! > > > > http://www.joelonsoftware.com/items/2006/08/01.html > > Ridiculos. That's how single-programming-mood people react when they > find that you can program in procedural or functional way and get your > work done. I always had a fun seeing these "all-java-kids" fighting > CRTJVAPGM or RUNJVAPGM on OS/400. ;) Uh?-( Are you calling *Joel* an "all-java kid"?! He's an old clunker, just like me!, and HIS background is primarily in C and some kind of LISP -- he makes that quite clear in some of his books. Alex From python.list at tim.thechases.com Mon Aug 14 12:43:34 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 14 Aug 2006 11:43:34 -0500 Subject: A little assistance with os.walk please. In-Reply-To: <1155571727.168983.103480@m73g2000cwd.googlegroups.com> References: <1155566679.139086.279430@h48g2000cwc.googlegroups.com> <44E09561.1030902@websafe.com> <1155571727.168983.103480@m73g2000cwd.googlegroups.com> Message-ID: <44E0A836.5070700@tim.thechases.com> > 1) there seems to be an optional topdown flag. Is that passed to > os.walk(path, topdownFlag) Yes. > 2) I only want to process files that match *.txt for example... Does > that mean I need to parse the list of files for the .txt extention or > can I pass a wildcard in the path parameter? >>> for path, dirs, files in os.walk("."): ... for f in files: ... if not f.lower().endswith(".txt"): continue ... print os.path.join(path, f) If you want to be more complex: >>> from os.path import splitext >>> allowed = ['.txt', '.sql'] >>> for path, dirs, files in os.walk("."): ... for f in files: ... if splitext(f)[1].lower() not in allowed: continue ... fn = os.path.join(path, f) ... print "do something with %s" % fn Just a few ideas, -tkc From johnjsal at NOSPAMgmail.com Tue Aug 22 14:59:40 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 22 Aug 2006 18:59:40 GMT Subject: text editor suggestion? In-Reply-To: <1156270662.954255.323330@75g2000cwc.googlegroups.com> References: <44e66724$0$2363$c3e8da3@news.astraweb.com> <1156219373.342609.71480@h48g2000cwc.googlegroups.com> <1156270662.954255.323330@75g2000cwc.googlegroups.com> Message-ID: Ravi Teja wrote: > ??? > > In the same file, near the top. > > keywordclass.python=and assert break class continue def del elif \ > else except exec finally for from global if import in is lambda None \ > not or pass print raise return try while yield > > I could add my own keywords to it. > But I don't want all my keywords to be highlighted in the same way. I have different colors for Python keywords, functions and methods, exceptions, other words like 'self', etc. and there's no way to do this without rewriting the lexer file (which is in C++) and recompiling Scite to build the changes into it. From jaysherby at gmail.com Tue Aug 8 20:18:21 2006 From: jaysherby at gmail.com (jaysherby at gmail.com) Date: 8 Aug 2006 17:18:21 -0700 Subject: newb question: file searching In-Reply-To: <1155082260.661319.240760@h48g2000cwc.googlegroups.com> References: <1155067111.892386.130610@n13g2000cwa.googlegroups.com> <1155082260.661319.240760@h48g2000cwc.googlegroups.com> Message-ID: <1155082701.041100.280180@i3g2000cwc.googlegroups.com> Something's really not reliable in my logic. I say this because if I change the extension to .png then a file in a hidden directory (one the starts with '.') shows up! The most frustrating part is that there are .jpg files in the very same directory that don't show up when it searches for jpegs. I tried os.walk('.') and it works, so I'll be using that instead. jaysherby at gmail.com wrote: > Here's my code: > > def getFileList(): > import os > imageList = [] > for dirpath, dirnames, filenames in os.walk(os.getcwd()): > for filename in filenames: > for dirname in dirnames: > if not dirname.startswith('.'): > if filename.lower().endswith('.jpg') and not > filename.startswith('.'): > imageList.append(os.path.join(dirpath, filename)) > return imageList > > I've adapted it around all the much appreciated suggestions. However, > I'm running into two very peculiar logical errors. First, I'm getting > repeated entries. That's no good. One image, one entry in the list. > The other is that if I run the script from my Desktop folder, it won't > find any files, and I make sure to have lots of jpegs in the Desktop > folder for the test. Can anyone figure this out? > > jaysherby at gmail.com wrote: > > I'm new at Python and I need a little advice. Part of the script I'm > > trying to write needs to be aware of all the files of a certain > > extension in the script's path and all sub-directories. Can someone > > set me on the right path to what modules and calls to use to do that? > > You'd think that it would be a fairly simple proposition, but I can't > > find examples anywhere. Thanks. From jaywgraves at gmail.com Thu Aug 31 16:44:44 2006 From: jaywgraves at gmail.com (jay graves) Date: 31 Aug 2006 13:44:44 -0700 Subject: re.compile() doesn't work under Windows? References: Message-ID: <1157057084.388234.89170@b28g2000cwb.googlegroups.com> ddtl wrote: > My script uses re.compile() function, and while it rans without errors > under Linux, when I ran that script under Windows I get the following > error: > Traceback (most recent call last): > File "C:\a\projects\re.py", line 4, in ? > import re > File "C:\a\projects\re.py", line 95, in ? > main() > File "C:\a\projects\re.py", line 37, in main > s_exp = re.compile(op['-s']) > AttributeError: 'module' object has no attribute 'compile' > What is the problem here? re module is installed and is on the path - > for example, the following code works and doesn't cause any errors: The traceback has the answer. It seems your file is named 're.py' so it is trying to import itself rather the the 're' python module. I don't know why it ran OK on Linux. Maybe your script is named differently on Linux or the sys.path order is different between Windows and Linux. HTH. ... jay From consuella1 at verizon.net Mon Aug 21 12:24:30 2006 From: consuella1 at verizon.net (ERNEST SMITH) Date: Mon, 21 Aug 2006 09:24:30 -0700 (PDT) Subject: Fwd: Re: Cannot remove this program from my computer Message-ID: <20060821162431.22539.qmail@web84004.mail.mud.yahoo.com> Note: forwarded message attached. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded message was scrubbed... From: Sjoerd Mullender Subject: Re: Cannot remove this program from my computer Date: Mon, 14 Aug 2006 08:47:09 +0200 Size: 3465 URL: From thattommyhall at gmail.com Fri Aug 18 16:19:02 2006 From: thattommyhall at gmail.com (thattommyhallll@gmail.com) Date: 18 Aug 2006 13:19:02 -0700 Subject: amd64 In-Reply-To: <1155926575.291233.83350@b28g2000cwb.googlegroups.com> References: <1155926575.291233.83350@b28g2000cwb.googlegroups.com> Message-ID: <1155932342.798877.111820@i3g2000cwc.googlegroups.com> if the install is 64 bit, you will hit trouble i used the guide here http://www.debian-administration.org/articles/356 on my 64 bit debian system to get 32bit apps available if they have a particular distro install, usually the package management tools for it can add most python modules you will need hope that helps, add more details if you want more help tom > Robin Becker wrote: > > Does anyone know if it's possible to run python as a 32 bit app on AMD64's? One > > of our host providers AMD Athlon 64 3000+ and we are currently using a celeron > > which is real slow. The problem is that this machine would be a backup for > > another which is 32 pentium 4. > > > > If I have to recompile/debug all the extensions etc etc for another architecture > > it might not seem so attractive. > > -not ready for 64bitly yrs- > > Robin Becker > Most 64 bit processors can run 32 bit apps natively, so the short > answer would be yes. From jaywgraves at gmail.com Fri Aug 11 07:58:46 2006 From: jaywgraves at gmail.com (jay graves) Date: 11 Aug 2006 04:58:46 -0700 Subject: Rendering Vector Graphics In-Reply-To: <1155293639.748785.316170@m73g2000cwd.googlegroups.com> References: <1155293639.748785.316170@m73g2000cwd.googlegroups.com> Message-ID: <1155297526.362566.96120@74g2000cwt.googlegroups.com> Bytter wrote: > Hi ppl, > I've already posted this message through the mailing-list, but it seems > it never arrived here. Strange... Anyway: > I need to render high-quality vector graphics with Python. I was > thinking of something like 'cairo', though I need to run under win32 > and can't find a pycairo package for it. Suggestions? AGG (Anti-Grain Geometry) is one such engine that a couple of people have interfaced to Python. http://www.antigrain.com/ ... jay graves From rogue_pedro at yahoo.com Sat Aug 5 18:27:03 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 5 Aug 2006 15:27:03 -0700 Subject: Backup GMAIL Messages with Python References: Message-ID: <1154816823.543334.242930@75g2000cwc.googlegroups.com> Gregory Pi?ero wrote: > I was wondering what methods you experts would reccomend for this task? > > Here are the options I have come up with so far: > > 1. Build something with the poblib library > (http://docs.python.org/lib/module-poplib.html) > --Any pointers on doing this? How to I get poplib to save messages in > a standard format I can > later import into Thunderbird, Outlook, etc? (mbox?) I don't do much with email, but there's an example of accessing gmail via poplib here: http://groups.google.ca/group/comp.lang.python/msg/a12263a870f5f236 And of course there's the 'email' standard library module: http://docs.python.org/lib/module-email.html HTH, ~Simon Out of curiosity, why do you want to _backup_ a gmail account? (I use my gmail account to backup files and documents I never want to lose.) I could think of some reasons, but I'm wondering what yours are. : ) From bj_666 at gmx.net Mon Aug 28 04:53:11 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 28 Aug 2006 10:53:11 +0200 Subject: A Sort Optimization Technique: decorate-sort-dedecorate References: <1156719092.603277.57390@b28g2000cwb.googlegroups.com> <1156723602.192984.49610@m79g2000cwm.googlegroups.com> Message-ID: In <1156723602.192984.49610 at m79g2000cwm.googlegroups.com>, Tom Cole wrote: > In Java, classes can implement the Comparable interface. This interface > contains only one method, a compareTo(Object o) method, and it is > defined to return a value < 0 if the Object is considered less than the > one being passed as an argument, it returns a value > 0 if considered > greater than, and 0 if they are considered equal. > > The object implementing this interface can use any of the variables > available to it (AKA address, zip code, longitude, latitude, first > name, whatever) to return this -1, 0 or 1. This is slightly different > than what you mention as we don't have to "decorate" the object. These > are all variables that already exist in the Object, and if fact make it > what it is. So, of course, there is no need to un-decorate at the end. Python has such a mechanism too, the special `__cmp__()` method has basically the same signature. The problem the decorate, sort, un-decorate pattern solves is that this object specific compare operations only use *one* criteria. Let's say you have a `Person` object with name, surname, date of birth and so on. When you have a list of such objects and want to sort them by name or by date of birth you can't use the `compareTo()` method for both. Ciao, Marc 'BlackJack' Rintsch From superflit at gmail.com Tue Aug 1 17:00:09 2006 From: superflit at gmail.com (flit) Date: 1 Aug 2006 14:00:09 -0700 Subject: Best way to read, and analyze a log file? In-Reply-To: <1154452943.852932.84960@p79g2000cwp.googlegroups.com> References: <1154440597.436863.131750@i3g2000cwc.googlegroups.com> <1154452943.852932.84960@p79g2000cwp.googlegroups.com> Message-ID: <1154466009.486784.315820@i3g2000cwc.googlegroups.com> Thanks for all input.. I think I should put all data on a mysql base.. The company will need this for reports and statistics for a year. bearophileHUGS at lycos.com wrote: > superflit at gmail.com: > > > 1- Read the data and put all variables in a list > > 2- Read the data and put all the variables in dictionary? > > the logs is in this format > > xxxxxxxxxxxxxxxxxxxxxxxxxx > > The separation is by byte size like > > xxx three bytes for code x , xxxx bytes for hour, etc.. > > I have two main objectives. > > Show all data to user. > > Analyze the data: like total sum, average,etc.. > > If you want to do all by yourself you can create a list of starting > positions, and you can add None to it, so you can use it to slice a > line with a loop. > You can also create a list of types, so you can cast the string parts > to their correct types, catching the exceptions. You can do it in a > second loop for clarity, or the first one to speed up a bit. > So you can just create a list of data for each input line, a dict may > be unnecessary because the number of fields seems fixed. > > Bye, > bearophile From slawomir.nowaczyk.847 at student.lu.se Sun Aug 6 16:54:28 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Sun, 06 Aug 2006 22:54:28 +0200 Subject: Proposal: [... for ... while cond(x)] In-Reply-To: References: <1154886383.696899.171490@i3g2000cwc.googlegroups.com> Message-ID: <20060806223616.EEB7.SLAWOMIR.NOWACZYK.847@student.lu.se> On Sun, 06 Aug 2006 18:59:39 +0000 (GMT) Duncan Booth wrote: #> >> > I suggest a new extension of the list comprehension syntax: #> >> > #> >> > [x for x in xs while cond(x)] #> >> > #> >> > which would be equivalent to #> >> > #> >> > list(itertools.takewhile(cond, xs)) #> >> #> >> What would this syntax offer that: #> >> #> >> [x for x in takewhile(cond, xs)] #> >> #> >> doesn't currently offer? #> > #> > The same thing that [f(x) for x in xs] offers that map(f, xs) doesn't, #> > and the same thing that [x for x in xs if f(x)] offers that filter(f, #> > xs) doesn't. It's more "pythonic". You can use an expression for cond #> > instead of a lambda. #> > #> No, the list comprehension lets you write an expression directly #> avoiding a function call, and it also allows you to add in a #> condition which can be used to filer the sequence. I am not sure if I understand you correctly, but... Does it? >>> a = [0,1,2,3,7,8,9] >>> [x for x in takewhile(lambda x: x in a, range(10))] [0, 1, 2, 3] >>> [x for x in takewhile(x in a, range(10))] Traceback (most recent call last): File "", line 1, in ? TypeError: 'bool' object is not callable Did I miss something? Notice that using "if" gives different result: >>> [x for x in range(10) if x in a] [0, 1, 2, 3, 7, 8, 9] #> Your proposal adds nothing. Well, I am not sure how useful the proposal really is, but it seems to add *something* if it would allow for things like: [x for x in range(10) while x in a] -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) Women who seek to be equal to men lack ambition. From pmartin at snakecard.com Sun Aug 6 19:08:52 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Sun, 06 Aug 2006 18:08:52 -0500 Subject: why did wxpython MakeActiveXclass stopped working?!?!!?!? References: <1154884250.224877.229650@p79g2000cwp.googlegroups.com> <1154888499.881410.24130@i3g2000cwc.googlegroups.com> Message-ID: jojoba wrote: > Hi Phillipe! > Thanks for the response! > > Unfortunately, i have also reinstalled pywin32, and i still get the > same error. > > Isn't this weird? > You know what else. > > I have a py2exe version of this code, that actually runs fine, using > the embedded windows media player. But Im guessing i made that py2exe > distributable with older pywin32 and older wxpython. > This makes me think that one of the newer versions of pywin32 or > wxpython is giving me that error trouble. > > Any other ideas on how to rectify this? > Thanks again, > jojoba > > > Philippe Martin wrote: >> Philippe Martin wrote: >> >> > jojoba wrote: >> > >> >> HI >> >> I wrote a little wxpython program with an embedded windows media >> >> player. >> >> It worked great. Recently, I reinstalled windows and then wxpython >> >> (most likely a newer version than i had before). Now when i run the >> >> exact same code, i get this error: >> >> >> >> File "C:\Documents and >> >> Settings\jojoba.DEMO-019591FB22\Desktop\Projects\SrAsse >> >> ts\sr.py", line 353, in __init__ >> >> self.CreateActiveXplayer() >> >> File "C:\Documents and >> >> Settings\jojoba.DEMO-019591FB22\Desktop\Projects\SrAsse >> >> ts\sr.py", line 363, in CreateActiveXplayer >> >> self.Player = PlayerActiveXClass(self, -1) >> >> File >> >> "C \Python24\Lib\site-packages\wx-2.6-msw-ansi\wx\lib\activexwrapper.py", >> >> line 108, in axw__init__ >> >> (0, 0, sz.width, sz.height), self._wnd, ID) >> >> File "C:\Python24\Lib\site-packages\pythonwin\pywin\mfc\activex.py", >> >> line 23, >> >> in CreateControl >> >> self.__dict__["_obj_"] = win32ui.CreateControl(clsid, windowTitle, >> >> style, re >> >> ct, parent, id, None, False, lic_string) >> >> win32ui: The window can not be created as it has an invalid handle >> >> >> >> >> >> Here is a snippet from my code: >> >> >> >> from wxPython.lib.activexwrapper import MakeActiveXClass >> >> import win32com >> >> from win32com import client >> >> >> >> class wxWMPlayer(wxPanel): >> >> def __init__(self, parent): >> >> wxPanel.__init__(self, parent, -1, >> >> style=wxCLIP_CHILDREN|wxNO_FULL_REPAINT_ON_RESIZE) >> >> self.MixMaster = parent >> >> self.ID3data = {} >> >> self.InitWindowProperties() >> >> self.CreateActiveXplayer() >> >> >> >> def InitWindowProperties(self): >> >> self.WindowsMediaPlayerTopSizer = wxBoxSizer(wxVERTICAL) >> >> self.SetSizer(self.WindowsMediaPlayerTopSizer) >> >> self.SetAutoLayout(1) >> >> >> >> def CreateActiveXplayer(self): >> >> PlayerModule = >> >> >> > >> win32com.client.gencache.EnsureModule('{6BF52A50-394A-11D3-B153-00C04F79FAA6}', >> >> 0,1,0) >> >> PlayerActiveXClass = >> >> MakeActiveXClass(PlayerModule.WindowsMediaPlayer, eventObj = self) >> >> self.Player = PlayerActiveXClass(self, -1) >> >> self.Player.isPlaying = 0 >> >> self.Player.uiMode = 'full' >> >> self.WindowsMediaPlayerTopSizer.Add(self.Player, 1, wxEXPAND) >> >> >> >> >> >> Any ideas anyone...i have reinstalled wxpython to no avail....Please >> >> help anyone.... >> >> thanks, >> >> jojoba >> > >> > >> > Did you reinstall pywin32 ? >> > >> > Philippe >> >> Well I'm silly: it would not import. Hi, I'd post this to wxPython-users at lists.wxwidgets.org Philippe From quentel.pierre at wanadoo.fr Tue Aug 22 15:33:15 2006 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: 22 Aug 2006 12:33:15 -0700 Subject: key not found in dictionary In-Reply-To: <1156272596.613723.219280@h48g2000cwc.googlegroups.com> References: <1156272596.613723.219280@h48g2000cwc.googlegroups.com> Message-ID: <1156275195.225742.89270@75g2000cwc.googlegroups.com> Depending on what you want to do if the key doesn't exist, you might want to use the dictionary method get() : value = some_dict.get(key,default) sets value to some_dict[key] if the key exists, and to default otherwise Regards, Pierre From ericcoetzee at gmail.com Thu Aug 10 09:54:00 2006 From: ericcoetzee at gmail.com (kingcrustybun) Date: 10 Aug 2006 06:54:00 -0700 Subject: Embedding Python in C/C++ In-Reply-To: <1155137133.180603.90150@m73g2000cwd.googlegroups.com> References: <1155137133.180603.90150@m73g2000cwd.googlegroups.com> Message-ID: <1155218040.807956.239980@m73g2000cwd.googlegroups.com> We are still struggling with this but having spent many hours looking at related code on the net, i have noticed the following sequence quite a lot globals = PyDict_New(); PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins()); Can anyone explain what this does exactly? I know what "__builtins__" is from a Python perspective but cant understand why you would want to add it to another newly created dictionary? Also, where can i find info on PyEval_GetBuiltins(). It does not appear in the Release 2.4.3 Python/C API Reference index at http://docs.python.org/api/genindex.html In fact there are a whole lot of PyEval_??? items which do not appear in this index. Are these deprecated? If so what does on use now? Any idea please? From gmt at sdf-eu.org Wed Aug 16 14:22:05 2006 From: gmt at sdf-eu.org (Max Yuzhakov) Date: Wed, 16 Aug 2006 18:22:05 +0000 (UTC) Subject: It is __del__ calling twice for some instances? Message-ID: Hello! It is correct behaviour for python to call __del__ on some identity of a class object more than once? In brief I shall describe a situation. Sorry for my english. For debugin purposes I'm put in my module global counters for counting __init__ and __del__ calls. This is a sample code for clearness: ------------------------------------------------------- init_cnt = 0 del_cnt = 0 class foo: def __init__(self): global init_cnt init_cnt += 1 def __del__(self): global del_cnt del_cnt += 1 def stat(): print "init_cnt = %d" % init_cnt print "del_cnt = %d" % del_cnt print "difference = %d" % init_cnt-del_cnt ------------------------------------------------------- And the result of a stat() call in some moment of time looks like so: init_cnt = 6233 del_cnt = 6234 difference = -1 It is __del__ called twice for some instance? Thanks in advance! -- GMT More Then ... From bearophileHUGS at lycos.com Mon Aug 14 14:23:35 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 14 Aug 2006 11:23:35 -0700 Subject: yet another noob question In-Reply-To: References: <1155492110.659011.196280@75g2000cwc.googlegroups.com> Message-ID: <1155579814.930093.99840@75g2000cwc.googlegroups.com> Jason Nordwick: > Stargaming wrote: > > Also note that reduce will be removed in Python 3000. > What will replace it? Nothing, I presume. You will have to write a function to find another way to solve problems. Bye, bearophile From joel at rosdahl.net Sat Aug 19 08:40:55 2006 From: joel at rosdahl.net (Joel Rosdahl) Date: Sat, 19 Aug 2006 14:40:55 +0200 Subject: couple more questions about sqlite In-Reply-To: <44e6ab6b$0$2359$c3e8da3@news.astraweb.com> (John Salerno's message of "Sat, 19 Aug 2006 02:12:06 -0400") References: <1155930772.591854.53910@m79g2000cwm.googlegroups.com> <1rpFg.2705$No6.52662@news.tufts.edu> <0n5de290agb0k6fvccjhrmel6jehaskcuv@4ax.com> <44e6ab6b$0$2359$c3e8da3@news.astraweb.com> Message-ID: <87hd08525k.fsf@rosdahl.net> John Salerno writes: > What is really confusing is that I did a search for 'sqlite' in my > Ubuntu repositories and it came up with entries like this: > > python2.4-pysqlite1.1 python interface to SQLite 3 > python2.4-pysqlite2 python interface to SQLite 3 > python2.4-pysqlite python interface to SQLite 2 That's python2.4-sqlite, not python2.4-pysqlite. The reason for both having pythonX.Y-foo and python-foo packages is Debian's (and therefore Ubuntu's) Python package policy. > python-pysqlite1.1 python interface to SQLite 3 > python-pysqlite2 python interface to SQLite 3 > python-sqlite python interface to SQlite 2 > > Needless to say, the numbering had me banging my head against my > desk. Sorry to hear that, and I can understand that the names are a bit confusing. Here's the story behind the mess: In the beginning (well, at least in 2003 when I found out about SQLite), SQLite was up to version 2.something and the Python module was called sqlite.py. While the Python module *project* was called pysqlite 0.something, Debian modules were generally called python-foo when providing the module foo; hence the name python-sqlite. Then, SQLite 3 was released (incompatible with SQLite 2 databases), and pysqlite 1.1 was released with the same module name (sqlite.py) and API as the old sqlite.py module but linked against SQLite 3. I decided not to package that version but instead wait for pysqlite 2, a rewritten and improved version linked against SQLite 3 and with a new Python API. pysqlite 2 was released and the Python module was called pysqlite2.dbapi2. I didn't think python-sqlite3 would be a good name for the Debian package since there were actually two different pysqlite versions (both actively maintained) linked against SQLite3, so I ended up calling the package python-pysqlite2, following the name and version of the pysqlite project instead of the module. Finally, by request of Debian users, I also packaged the other pysqlite version linked against SQLite 3 giving the package python-pysqlite1.1. Oh, and then there's python-apsw too. :-) Regards, Joel (maintainer of Debian's Python-related sqlite packages) -- Joel Rosdahl Key BB845E97; fingerprint 9F4B D780 6EF4 5700 778D 8B22 0064 F9FF BB84 5E97 From fakeaddress at nowhere.org Sun Aug 20 01:10:04 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 20 Aug 2006 05:10:04 GMT Subject: Stopping all threads from other thread In-Reply-To: <1156016004.845028.266500@74g2000cwt.googlegroups.com> References: <1156016004.845028.266500@74g2000cwt.googlegroups.com> Message-ID: amadeusz.jasak at gmail.com wrote: > Hello, > it is possible to stop all threads (application) from thread of > application: > App > |-MainThread > |-WebServer > |-CmdListener # From this I want to stop App > > The sys.exit isn't working... You can start all threads other than CmdListener as daemon threads, using threading.Thread.setDaemon(). Then when CmdListener exits, the program will exit. Python starts with one, non-daemon thread, and if that's what you are using for MainThread, you'd have to switch which thread runs what. Python deliberately does not offer a threadicide method. -- --Bryan From johan2sson at gmail.com Fri Aug 25 18:25:37 2006 From: johan2sson at gmail.com (johan2sson at gmail.com) Date: 25 Aug 2006 15:25:37 -0700 Subject: Interrupting a running python thread Message-ID: <1156544737.435103.32350@m79g2000cwm.googlegroups.com> I have embedded a python console in a plugin to a Windows application. I do not control the application, but the plugin is mine. Since the application is not thread-safe, I am push()-ing each line onto a code.InteractiveConsole on the GUI thread. This has the downside that a silly mistake that creates an infinite loop also hangs the GUI, thus preventing you from saving your work or exiting the application in any normal fashion. As a workaround, I've installed a console handler that calls thread.interrupt_main() when control-c is pressed. I should point out that this is done on a new thread. Unfortunately this doesn't work at all. Without returning from the last call to InteractiveConsole.push() or catching the KeyboardInterrupt, the interpreter explodes with a "no current thread" fatal error. I've tried the exact same code at "the real" python prompt and that happily prints: Traceback (most recent call last): File "", line 1, in ? KeyboardInterrupt >>> The code used is this infinite loop: a = 0 while a == 0: b = a + 2 What's the secret? The only use of SetConsoleCtrlHandler I could find in the CPython source didn't make me much wiser. Johan From bearophileHUGS at lycos.com Sun Aug 20 07:55:20 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 20 Aug 2006 04:55:20 -0700 Subject: convert a long string in binary In-Reply-To: References: Message-ID: <1156074920.467982.278610@p79g2000cwp.googlegroups.com> bussiere maillist: > i've got a very long string > and i wanted to convert it in binary Not much tested: _nibbles = {"0":"0000", "1":"0001", "2":"0010", "3":"0011", "4":"0100", "5":"0101", "6":"0110", "7":"0111", "8":"1000", "9":"1001", "A":"1010", "B":"1011", "C":"1100", "D":"1101", "E":"1110", "F":"1111"} def toBase2(number): if number < 16: return "0000" + _nibbles["%X" % number] else: d1, d2 = "%X" % number return _nibbles[d1] + _nibbles[d2] convbin = dict((chr(i), toBase2(i)) for i in xrange(256)) def binary(s): return "".join(convbin[c] for c in s) print binary("testing string") Surely there are ways to make it shorter (But it's fast enough). Bye, bearophile From shane at hathawaymix.org Tue Aug 1 12:13:08 2006 From: shane at hathawaymix.org (Shane Hathaway) Date: Tue, 01 Aug 2006 10:13:08 -0600 Subject: Finding the name of a class In-Reply-To: References: <44cf7538$0$29435$626a54ce@news.free.fr> Message-ID: <44CF7D94.90908@hathawaymix.org> John Salerno wrote: > >>> class Foo(object): > pass > > >>> dir(Foo) > ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', > '__hash__', '__init__', '__module__', '__new__', '__reduce__', > '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__'] > > Hmmm..... Don't forget to file a bug. Shane From johan2sson at gmail.com Sat Aug 5 20:01:47 2006 From: johan2sson at gmail.com (johan2sson at gmail.com) Date: 5 Aug 2006 17:01:47 -0700 Subject: Subtyping a non-builtin type in C/C++ Message-ID: <1154822507.152920.182940@i3g2000cwc.googlegroups.com> Hi I am trying to create a subclass of a python class, defined in python, in C++, but I am having some problems. It all boils down to a problem of finding the base class' type object and according to the PEP (253) I would also need to figure out the size of the base class instance structure, but I'm guessing that the latter can't be done in a way that would allow me to define a structure for my own type. The following code is what I've tried, which is an adaptation of http://groups.google.com/group/comp.lang.python/msg/b32952c69182d366 /* import the module that holds the base class */ PyObject *code_module = PyImport_ImportModule("code"); if (!code_module) return; /* get a pointer to the base class */ PyObject *ic_class = PyMapping_GetItemString( PyModule_GetDict(code_module), "InteractiveConsole"); if (!ic_class) return; /* assign it as base class */ // The next line is the original code, but as far as I can understand // the docs for Py_BuildValue the code used is equivalent. I find it // to be clearer as well. // EmConType.tp_bases = Py_BuildValue("(O)", ic_class); Py_INCREF(ic_class); EmConType.tp_bases = ic_class; if (PyType_Ready(&EmConType) < 0) This breaks an assertion in the function classic_mro called by PyType_Ready however, specifically that on line 1000 of typeobject.c: assert(PyClass_Check(cls)). To get there you need to fail PyType_Check as well and indeed, at least in the debug build, cls.ob_type.tp_name is "dict". ic_class appears to be a "classobj" before the call to PyType_Ready. I would of course much rather have seen that it was a "type", but I'm not sufficiently well versed in the python guts to know if this is ok or not. If anyone could please lend me a clue, I'd be terribly happy about it. Thanks, Johan From fakeaddress at nowhere.org Fri Aug 25 11:29:40 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 25 Aug 2006 15:29:40 GMT Subject: sum and strings In-Reply-To: <7xodu8j2j5.fsf@ruckus.brouhaha.com> References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <1155922208.930580.135080@m79g2000cwm.googlegroups.com> <1156365271.487489.62640@m73g2000cwd.googlegroups.com> <44ECC789.1010202@tim.thechases.com> <44EDCFDE.9060604@tim.thechases.com> <7xodu8j2j5.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Are you saying "abc"+"def" should not be concatenation? I guess > that's reasonable. No, I'm definitely not saying that, or at least I didn't mean that. > As long as + is string concatenation though, the > principle of least astonishment suggests that "sum" should > conconcatenate several strings. Absolutely. > I'm not sure what you mean by addition being symmetric or transitive; > it is not an equivalence relation. Do you mean commutative and > associative? Oops, yes, of course. Posting too late at night. -- --Bryan From sjmachin at lexicon.net Fri Aug 11 06:39:50 2006 From: sjmachin at lexicon.net (John Machin) Date: 11 Aug 2006 03:39:50 -0700 Subject: Read a file with open command References: <1155288288.954142.293000@i3g2000cwc.googlegroups.com> Message-ID: <1155292790.709061.308930@75g2000cwc.googlegroups.com> jean-jeanot wrote: > I can access to a file with the command: > file_obj = open ( " D:\My documents\Textfile.txt",'r') With a space before the drive letter? I don't think so. When asking questions, *don't* type what you thought you used, copy/paste what you actually used. > > When I now try to read a file with the following command: > > file_obj = open ("D:\My documents\File.ods",'r') it doesn't function. > The extension ods is coming from OpenOffice.org Calc. > > Why ? You haven't told us what "it doesn't function" means, so we'll have to play guessing games ...could be for at least two possible reasons: (1) .ods files are binary and you didn't specify 'rb' (2) you really typed "d:\my documents\file.ods" and the \f got interpreted as a form-feed character. You should *never* type literal Windows filenames like that. Instead, you have three choices: (a) "d:\\my documents\\file.ods" # not recommended (b) r"d:\my documents\file.ods" (c) "d:/my documents/file.ods" I'd suggest that you fix *both* of the above problems and try again. HTH, John From bearophileHUGS at lycos.com Wed Aug 23 08:24:32 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 23 Aug 2006 05:24:32 -0700 Subject: Python and STL efficiency In-Reply-To: References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <1156281418.697442.23000@i3g2000cwc.googlegroups.com> Message-ID: <1156335872.505528.137110@75g2000cwc.googlegroups.com> This thread can be useful for ShedSkin (the Python => C++ translator), because often it manages strings slower than CPython still, some suggestions from a C++ expert can surely improve things a lot. C++ is fast, but you have to use and know it well, otherwise you don't obtain much speed. Maybe this can be useful to speed up C++ hashing (now used in ShedSkin too): http://www.azillionmonkeys.com/qed/hash.html I suggest to test this code with the D language too, it has built-in dicts too (associative arrays, impleented with trees and not hashes), so the source code needed is pretty short. Bye, bearophile From __peter__ at web.de Mon Aug 21 04:17:25 2006 From: __peter__ at web.de (Peter Otten) Date: Mon, 21 Aug 2006 10:17:25 +0200 Subject: tkinter prob References: <1156140461.170856.136180@74g2000cwt.googlegroups.com> <1156143029.771346.22580@74g2000cwt.googlegroups.com> <1156147207.043042.308250@h48g2000cwc.googlegroups.com> Message-ID: JyotiC wrote: > got the error, > but there is one more prob, button is??not?coming?to?enable?again.?once > it is disabled > the error it's giving is:- > NameError: global name 'ENABLED' is not defined Try NORMAL instead of ENABLED. Peter From odperry at gmail.com Fri Aug 4 17:25:03 2006 From: odperry at gmail.com (Over G) Date: 4 Aug 2006 14:25:03 -0700 Subject: Programming Games with python, I know this subject was disccused need help In-Reply-To: <1154726144.395949.306950@m73g2000cwd.googlegroups.com> References: <1154725931.106708.180120@s13g2000cwa.googlegroups.com> <1154726144.395949.306950@m73g2000cwd.googlegroups.com> Message-ID: <1154726703.387186.31170@m73g2000cwd.googlegroups.com> Goalie_Ca wrote: > Well, with these libraries you won't need much else. > > http://www.pygame.org/news.html > and > http://sourceforge.net/projects/pyallegro/ > > > Over G wrote: > > HI > > > > I would like to start to program games, with python, where to start? > > > > What packages I need,? > > > > Thanks. Thanks ofr the very quick answer! Still can you shad more light on the second link, what is project allegro ? thanks/ From jmdeschamps at gmail.com Sun Aug 13 10:01:25 2006 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 13 Aug 2006 07:01:25 -0700 Subject: Newbie doing lengthy initialization with Tkinter gui References: Message-ID: <1155477685.072381.235320@75g2000cwc.googlegroups.com> Maric Michaud wrote: > Le dimanche 13 ao?t 2006 12:39, Pasi Oja-Nisula a ?crit : > > > The question is how (or where) can I call my loadImages function right > > after the mainloop starts? Or is there a better way to do this? > > > Seems a good use case for multi-thread, try something like this : > > In [28]: import Tix > > In [29]: main=Tix.Tk() > > In [30]: p=Tix.Meter(main) > > In [31]: p.pack() > > In [32]: def process(progress) : > ....: from time import sleep > ....: for i in range(10) : > ....: sleep(1) > ....: p.configure(value=float(p.cget('value'))+0.1) > ....: > ....: > > > In [33]: import thread > > In [34]: thread.start_new_thread(process, (p,)) and main.mainloop() > > Of course the last line is tricky, the thread should be started by the > App(Tix.Tk) mainloop. > > > > Pasi > > -- > _____________ > > Maric Michaud > _____________ > > Aristote - www.aristote.info > 3 place des tapis > 69004 Lyon > Tel: +33 426 880 097 Tkinter also has a timer-type function called *after*. Use this to call your init function just befrore the mainloop call. You gui wil show up and you can then update it to show progress as you wish No neep for thread or Tix modules...! Here's a working example: ################# from Tkinter import * # Your progress showing function def showProgress(i): # Tell the gui to show some progress here obj=c.find_withtag("job")[0] c.itemconfig(obj,text="Ok from job is up to "+str(i)) c.update() # Your app init function def doInitOne(): #Do some init work here for i in range(100): for j in range(100): for k in range(100): for m in range(100): a=1 # Once in a while update the gui showProgress(i) # your main app root=Tk() c=Canvas(root,bg="yellow",width=300,height=300) monobj=c.create_text(100,200,text="Some ",tags="job") c.pack() # this will *sleep* one millisec before calling # your doInitOne function and continue # with the rest of the code during that sleep time # in this case just the mainloop root.after(1, doInitOne) root.mainloop() From mail at microcorp.co.za Mon Aug 21 08:41:54 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 21 Aug 2006 14:41:54 +0200 Subject: Small Troll on notation of variables over time References: Message-ID: <00e801c6c524$7a3c3b20$03000080@hendrik> "Jeremy Sanders" wrote: | Hendrik van Rooyen wrote: | | > What do you guys think? | | You could get something similar using an object, such as | | class Hist(object): | | def __init__(self): | self.vals = [None] | | def __call__(self, index=-1): | return self.vals[index] | | def set(self, val): | self.vals.append(val) | | a = Hist() | | a.set(5) | print a() | | a.set('hi there') | print a() | print a(-2) | | Which prints | 5 | hi there | 5 - Sneaky! - I like this.... - Hendrik From nomail at nomail.it Thu Aug 3 16:41:12 2006 From: nomail at nomail.it (LaGuna) Date: Thu, 03 Aug 2006 22:41:12 +0200 Subject: E' possibile integrare ironpython con visual studio 2005? Message-ID: <44d25f48$0$47956$4fafbaef@reader3.news.tin.it> Se si come? Ciao by Enzo From ilias at lazaridis.com Fri Aug 25 13:18:35 2006 From: ilias at lazaridis.com (lazaridis_com) Date: 25 Aug 2006 10:18:35 -0700 Subject: CONSTRUCT - Module Attributes and Execution Environment In-Reply-To: <1156253769.369177.91870@74g2000cwt.googlegroups.com> References: <1156253227.092971.36510@74g2000cwt.googlegroups.com> <1156253769.369177.91870@74g2000cwt.googlegroups.com> Message-ID: <1156526315.599579.82170@i3g2000cwc.googlegroups.com> Fuzzyman wrote: > lazaridis_com wrote: > > I would like to change the construct: > > > > if __name__ == '__main__': > > > > to something like: > > > > if exec.isMain(): > > > > My (OO thought) is to place a class in an separate code module and to > > instantiate an singleton instance which would keep th something like > > this: > > > > class ExecutionEnv: > > def isMain(self) > > if CALLING_MODULE.__name__ == '__main__': > > return true > > else > > return false > > > > exec = ExecutionEnv() > > > > How to I get access to the CALLING_MODULE ? > > sys._getframe(1).f_globals['__name__'] very nice! This seems to do the work. Btw: I forgot to mention the use-case: http://case.lazaridis.com/browser/lang/python/talker.py?rev=44 > All the best, > > Fuzzyman > http://www.voidspace.org.uk/python/index.shtml From superflit at gmail.com Tue Aug 1 09:56:37 2006 From: superflit at gmail.com (superflit at gmail.com) Date: 1 Aug 2006 06:56:37 -0700 Subject: Best way to read, and analyze a log file? Message-ID: <1154440597.436863.131750@i3g2000cwc.googlegroups.com> Hi All, I am reading a log file, and wondering what is the best way to read and analize this. I am think in two options: 1- Read the data and put all variables in a list 2- Read the data and put all the variables in dictionary? the logs is in this format xxxxxxxxxxxxxxxxxxxxxxxxxx The separation is by byte size like xxx three bytes for code x , xxxx bytes for hour, etc.. I have two main objectives. Show all data to user. Analyze the data: like total sum, average,etc.. All advice will be great appreciated. And sorry about my bad english. From Eric_Dexter at msn.com Sun Aug 13 15:51:00 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 13 Aug 2006 12:51:00 -0700 Subject: looking for a simple way to load a program from another python program.. Message-ID: <1155498660.285772.144140@m73g2000cwd.googlegroups.com> I was looking for a simple way to load a simple python program from another python program. I tried os.system(cabel) The file name is cabel.py a csound instrument editor.. The error I am getting is Traceback (most recent call last): File "C:\Python24\Lib\site-packages\boa-constructor\test of snake\Frame1.py", line 212, in OnCabelItems0Menu os.system(cabel) NameError: global name 'cabel' is not defined Localisation of messages is disabled, using default language. time resolution is 279.365 ns This is with cabel in the current directory. I have managed to use import to run it but it will only do it once. I may be able to use the exec commands but I don't want to exit the program I am using only to run other programs and then exit. I would also perfer that cabel is in it's own directory. thanks in advance for any help http://www.stormpages.com/edexter/csound.html From gagsl-py at yahoo.com.ar Sat Aug 19 08:35:06 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 19 Aug 2006 09:35:06 -0300 Subject: Small Troll on notation of variables over time In-Reply-To: <01ee01c6c37d$6b0bc6a0$03000080@hendrik> References: <01ee01c6c37d$6b0bc6a0$03000080@hendrik> Message-ID: <7.0.1.0.0.20060819092815.03a8cac8@yahoo.com.ar> At Saturday 19/8/2006 07:49, Hendrik van Rooyen wrote: >Now how about introducing an index that works over time, >such that s{0} (the default so as to not break any existing code) >implies the current object bound to the name s, >with s{1} being the previous one, and so on... Doing that *always* for *all* names would be ridiculous - objects would never get garbage collected, by example. And 99.99999999999999999999% of programs don't need that behavior at all. So just implement that for your use case - if you have any! Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From dawodu4fun at yahoo.com Sat Aug 5 17:12:56 2006 From: dawodu4fun at yahoo.com (spiffy) Date: Sat, 05 Aug 2006 21:12:56 GMT Subject: programming is hard References: <1154609819.083694.22200@m73g2000cwd.googlegroups.com> <1154623085.994132.126620@m73g2000cwd.googlegroups.com> <1154648416.036565.224320@p79g2000cwp.googlegroups.com> <1154653325.803973.292490@p79g2000cwp.googlegroups.com> <1154665071.640304.201300@s13g2000cwa.googlegroups.com> Message-ID: On Fri, 04 Aug 2006 14:36:28 GMT, John Salerno wrote: >placid wrote: >> mensanator at aol.com wrote: >>> placid wrote: >>>> Alas, all good arguments. >>>> >>>> I rest my case. >>> After you've just been proven wrong? >>> >>> I wouldn't want you for my lawyer. >> >> Aha, lucky i wont be a lawyer. >> > >lawyering is hard too ;) hmmm... i guess that explains why there are so many lawyers. From rdiaz02 at gmail.com Tue Aug 22 06:05:20 2006 From: rdiaz02 at gmail.com (Ramon Diaz-Uriarte) Date: Tue, 22 Aug 2006 12:05:20 +0200 Subject: idutils and Python In-Reply-To: <1156226173.596437.266680@75g2000cwc.googlegroups.com> References: <1156226173.596437.266680@75g2000cwc.googlegroups.com> Message-ID: <624934630608220305k31b91a2ao9263c19cb342b662@mail.gmail.com> On 21 Aug 2006 22:56:13 -0700, sjdevnull at yahoo.com wrote: > What exactly are you trying to accomplish? If you want to index > function/class names, variables, etc then you should take a look at > "exuberant ctags" http://ctags.sourceforge.net53 --although it started > off as a C indexer, it has excellent Python support, it's free, and as > a bonus its indices are well supported from inside major editors (vim, > emacs, etc) so you can easily follow code flow, find function/class > definitions, etc. Sorry for not being clear enough. I want the following: a) have my editor go to the point where a function/whatever is defined b) see all places where a function/whatever is used. I've tried exuberant ctags and I do like it a lot. a) is done wonderfully (within emacs, the editor I use, but also in other editros, from what I've read). However, b) does not work exactly as I'd like: 1. With Emacs and tags: using "tags-search" I can visit, one by one, all places where a function is called, but I'd like to see where it is called before visting that file and know, before visiting each file in turn, whether I'll visit 1 or 20 files (or, to put it in another way, I'd like to see like a poor-mans static callgraph). 2. From what I understand, there is a deeper difference than just how results are shown: the tags file contains the places where, say, a function is defined, but finding where it is used requires running grep on every file looking for the tag. (I believe that is what "tags-search" does in emacs). In contrast, ID utils does not do any grep, but directly goes to the ID file, where all that is already pre-stored, which also means that it will be a lot faster than grepping for the tags. A tool similar to IDutils is Global http://www.gnu.no/software/global/, but it also does not incorporate Python support. (Though defining other parsers might be simple; I haven't looked at it closely). I think the wish "do not use grep, just look at the index file, and immediately display all matches" is reasonable and probably other Python coders had thought about it before. But I am wondering if I am missing something obvious, as most people seem to be very happy with exuberant ctags. Thanks, R. On 21 Aug 2006 22:56:13 -0700, sjdevnull at yahoo.com wrote: > Ramon Diaz-Uriarte wrote: > > Dear All, > > > > Has anybody tried to use ID Utils > > (http://www.gnu.org/software/idutils/4652) with Python? > > What exactly are you trying to accomplish? If you want to index > function/class names, variables, etc then you should take a look at > "exuberant ctags" http://ctags.sourceforge.net53 --although it started > off as a C indexer, it has excellent Python support, it's free, and as > a bonus its indices are well supported from inside major editors (vim, > emacs, etc) so you can easily follow code flow, find function/class > definitions, etc. > > -- > http://mail.python.org/mailman/listinfo/python-list54 > -- Ramon Diaz-Uriarte Bioinformatics Unit Spanish National Cancer Centre (CNIO) http://ligarto.org/rdiaz From bignose+hates-spam at benfinney.id.au Wed Aug 30 19:18:29 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 31 Aug 2006 09:18:29 +1000 Subject: Coding style and else statements References: <44f355d6$0$8812$88260bb3@free.teranews.com> <1156898310.795476.187030@i3g2000cwc.googlegroups.com> <1156965902.621615.314160@h48g2000cwc.googlegroups.com> Message-ID: <87wt8pizi2.fsf@benfinney.id.au> "Carl Banks" writes: > Ben Finney wrote: > > "Carl Banks" writes: > > > def foo(thing): > > > if thing: > > > return thing+1 > > > else: > > > return -1 > > > assert False > > > > To my eyes, that's less readable than, and has no benefit over, > > the following: > > > > def foo(thing): > > if thing: > > result = thing+1 > > else: > > result = -1 > > return result > > For this example, yes. Actually I'd probably never do it in this > particular case. What I mean in general is some rare times > (especially when logic is complex) I prefer to use a redundant > control statement that renders something non-reachable; then I use > assert False there. That's the readability problem I'm referring to. Why not ensure that there is one return point from the function, so the reader doesn't have to remind themselves to look for hidden return points? -- \ "Dyslexia means never having to say that you're ysror." -- | `\ Anonymous | _o__) | Ben Finney From cliff at develix.com Thu Aug 3 12:31:03 2006 From: cliff at develix.com (Cliff Wells) Date: Thu, 03 Aug 2006 09:31:03 -0700 Subject: Using Python for my web site In-Reply-To: References: <1154361480.915174.262720@b28g2000cwb.googlegroups.com> <44ce3a5c$0$18952$626a54ce@news.free.fr> <1154367359.931684.106650@m73g2000cwd.googlegroups.com> <44ce4530$0$28242$626a54ce@news.free.fr> <19zmaoel1tn3$.dlg@gelists.gmail.com> Message-ID: <1154622663.20290.346.camel@devilbox> On Thu, 2006-08-03 at 09:49 +0200, Sybren Stuvel wrote: > Cliff Wells enlightened us with: > > 1) PostgreSQL fans are perhaps a bit paranoid about claims of MySQL > > being better. There used to be a tiny bit of truth in this claim > > for certain applications (mostly relating to performance and ease of > > use). > > I even find PostgreSQL easier to use than MySQL :) These days certainly, by quite a wide margin. > Sounds like the Fox News Network to me. "Some people say...." If that > doesn't sound familiar, check out the documentary "Outfoxed". My main news source on Fox remains "The Simpsons". Cliff From me at privacy.net Mon Aug 14 21:04:26 2006 From: me at privacy.net (Dan Sommers) Date: Mon, 14 Aug 2006 21:04:26 -0400 Subject: recommended general-purpose string template packages? References: <1155523735.614470.199840@h48g2000cwc.googlegroups.com> Message-ID: On 13 Aug 2006 19:48:55 -0700, "John Machin" wrote: > In general, I'm mainly interested in a template engine for dynamic web > pages but would like a general purpose one to avoid learning yet > another package for generating e-mail messages, form letters, source > code, whatever. And don't forget Python's Template class: http://docs.python.org/lib/node109.html Regards, Dan -- Dan Sommers "I wish people would die in alphabetical order." -- My wife, the genealogist From bobrien18 at yahoo.com Tue Aug 15 15:06:26 2006 From: bobrien18 at yahoo.com (KraftDiner) Date: 15 Aug 2006 12:06:26 -0700 Subject: file object and eof In-Reply-To: <12e412ljneshoc3@corp.supernews.com> References: <1155660586.941712.114410@b28g2000cwb.googlegroups.com> <12e412ljneshoc3@corp.supernews.com> Message-ID: <1155668786.644843.192830@m79g2000cwm.googlegroups.com> Grant Edwards wrote: > On 2006-08-15, KraftDiner wrote: > > > I open a file in python by > > f = open('filename', mode='rb') > > > > how can I tell if I am at the end of file? > > I don't believe you can unless you try to read from the file. > > > f.eof() isn't implmented. > > > > How can I implement its functionallity? > > You don't, generally. > > There's probably a better, "more Pythonic" way to accomplish > your goal, but you're going to have to tell us what it is. > how about?!: def eof(fileobj): curloc = fileobj.tell() ofloc = fileobj.seek(0,2) fileobj.seek(curloc, 0) if ofloc >= curloc: return True return False From deets at nospam.web.de Fri Aug 4 05:43:53 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 04 Aug 2006 11:43:53 +0200 Subject: Which KDE IDE for Python? In-Reply-To: <1154682596.419636.70320@p79g2000cwp.googlegroups.com> References: <1154682596.419636.70320@p79g2000cwp.googlegroups.com> Message-ID: <4jgj6qF7n43lU1@uni-berlin.de> Bart Ogryczak schrieb: > Hi, > Rigth now I'm using two IDEs for Python, KDevelop and Eric. Both have > drawbacks. KDevelop is a multilanguage IDE, and doesn't really have > anything special for Python. There's no Python debugger, no PyDOC > integration, it's class browser doesn't display attributes. On the > other side there's Eric, which is made just for Python. But.. it > doesn't integrate with KDE, doesn't support remote files (fish://, > ftp:// etc.). Does anyone know a better IDE for Python, that'll > integrate nicely with KDE? I bet you can try and convince Detlev Offenbach (eric developer) to add that - he already has _some_ KDE-specific stuff in there, and I presume supporting IO-Slaves might not be too hard. Diez From sjdevnull at yahoo.com Wed Aug 30 13:26:31 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 30 Aug 2006 10:26:31 -0700 Subject: Coding style and else statements In-Reply-To: <1156924075.903340.281890@b28g2000cwb.googlegroups.com> References: <44f355d6$0$8812$88260bb3@free.teranews.com> <44f36bd2$0$16847$626a54ce@news.free.fr> <1156804096.616231.14990@74g2000cwt.googlegroups.com> <44f3768a$0$29491$626a54ce@news.free.fr> <1156886150.271268.126480@i3g2000cwc.googlegroups.com> <1156924075.903340.281890@b28g2000cwb.googlegroups.com> Message-ID: <1156958791.201041.247740@p79g2000cwp.googlegroups.com> Tal Einat wrote: > I meant to say that: > > (thing and [thing+1] or [-1])[0] > > is more readable (IMO) than: > > thing != -1 and (thing and thing+1 or -1) or 0 Neither is particularly readable, though I agree that the latter is worse since it has to have the third option ("0") on the end. But I'd go with an if statement unless I had a real reason to use something so unreadable. If you are enamored of such constructs, 2.5 will allow conditional expressions: (thing + 1) if thing else -1 From rogue_pedro at yahoo.com Thu Aug 3 15:44:04 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 3 Aug 2006 12:44:04 -0700 Subject: OS independent files In-Reply-To: <1154632873.085941.281850@75g2000cwc.googlegroups.com> References: <1154632873.085941.281850@75g2000cwc.googlegroups.com> Message-ID: <1154634244.535278.224800@s13g2000cwa.googlegroups.com> crystalattice wrote: > I'm sure this has been addressed before but it's difficult to search > through several thousand postings for exactly what I need, so I > apologize if this a redundant question. Google groups has a very good search. > I've figured out how to use os.path.join to make a file or directory > location prior to pickling something to it. But I have a question > about it. In Windows I can make a file with this: > > os.path.join("C:", "myfiles", "myfile.dat") > > If I want to make sure the file/directory is made in a user's home > directory (e.g. /home/users/path/to/file) but also compatible w/ > Windows, how would I rewrite this (if required)? Try os.path.expanduser('~') (in http://docs.python.org/lib/module-os.path.html) or you could just look up the HOME environment variable in os.environ, but I don't know if windows sets this correctly in all cases. (os.environ is documented in http://docs.python.org/lib/os-procinfo.html) Peace, ~Simon From jojoba12 at hotmail.com Wed Aug 23 12:29:40 2006 From: jojoba12 at hotmail.com (jojoba) Date: 23 Aug 2006 09:29:40 -0700 Subject: how do you get the name of a dictionary? In-Reply-To: References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> <1156264475.968894.221710@p79g2000cwp.googlegroups.com> <1156266720.205126.284050@i3g2000cwc.googlegroups.com> <1156268752.574983.123520@75g2000cwc.googlegroups.com> <1156281268.865624.302070@b28g2000cwb.googlegroups.com> <1156283135.985893.186500@m73g2000cwd.googlegroups.com> <1156284812.469380.274370@b28g2000cwb.googlegroups.com> Message-ID: <1156350580.363393.256730@74g2000cwt.googlegroups.com> Fredrik Lundh wrote: > the fact that despite all attempts to explain how things work, you're > still haven't realized that if you want the names of things, you should > pass *namespaces* to your object viewer, not individual objects. And what im saying is that isnt it silly that we need pass an entire namespace, when a much simpler notion would be to have each object know its own name(s) (even if that name doesnt exist). Now, here's where everyone tells me this isnt possible, and how my statement implies that i have no idea whatsoever of how python works.... jojoba From rogue_pedro at yahoo.com Sun Aug 6 12:19:36 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 6 Aug 2006 09:19:36 -0700 Subject: subprocesses and deadlocks In-Reply-To: <1154875161.540968.275080@b28g2000cwb.googlegroups.com> References: <1154875161.540968.275080@b28g2000cwb.googlegroups.com> Message-ID: <1154881176.660442.284410@m73g2000cwd.googlegroups.com> betatim at gmail.com wrote: > Hi, > > there are many ways of solving the problem of finite buffer sizes when > talking to a subprocess. I'd usually suggest using select() but today I > was looking for a more readable/understandable way of doing this. Back > in 1997 Guido himself posted a very nice solution, write your input to > a temporary file and then read that from your new process. His posting > can be found here: > http://groups.google.com/group/comp.lang.python/tree/browse_frm/thread/2b31d990a8613d93/17d3dea9089aad00?rnum=1&q=subprocess+deadlock&_done=%2Fgroup%2Fcomp.lang.python%2Fbrowse_frm%2Fthread%2F2b31d990a8613d93%2F63b0a786d87ba23b%3Flnk%3Dgst%26q%3Dsubprocess+deadlock%26rnum%3D6%26#doc_63b0a786d87ba23b > > Being a bit puzzled over this usage of tempfile I read its > documentation and as expected it says: > > [...] The file is created using mkstemp. It will be destroyed as soon > as it is closed (including an implicit close when the object is garbage > collected). [...] your code should not rely on a temporary file created > using this function having or not having a visible name in the file > system. > > so how was Guido planning to get the contents of the file after closing > it? Should we do a tf.flush() instead of the close to ensure everything > is written, then read from it, using subprocess.Popen(....,stdin=tf,..) > and only close it afterwards? > > Is it correct to assume that a named temporary file will be (sometimes) > accesible while it has not been closed yet? > > cheers, > tim When GvR wrote that around a decade ago, tempfile.mktemp() had not yet been deprecated. It returns "an absolute pathname of a file that did not exist at the time the call is made". It does not create a file, you have to do that yourself. You're quoting the docs for tempfile.TemporaryFile(). It returns a "file (or file-like) object", and I'd assume that you would have to pass this object around without closing it in order to use it in the manner described in GvR's post. http://docs.python.org/lib/module-tempfile.html From eugene at boardkulture.com Tue Aug 15 04:20:11 2006 From: eugene at boardkulture.com (3KWA) Date: 15 Aug 2006 01:20:11 -0700 Subject: sending mailing list with smtplib In-Reply-To: References: <1155561746.812918.128770@h48g2000cwc.googlegroups.com> Message-ID: <1155630010.956035.270580@74g2000cwt.googlegroups.com> Gabriel Genellina wrote: > > Specify "didn't work" at least... see > http://www.catb.org/~esr/faqs/smart-questions.html Ooops, didn't work explained (the worst is I bought and read ESR's book :() list.txt= email1 email2 email3 ... emailn email1 received from:xsbar.com to:email1 subject: [xsbar] alive and kicking ... message from email2 onwards it seems what happened is that the recipient list kept growing, email 2 received from:eugene at xsbar.com to:email1 to:email2 subject: ... email3 received from:eugene at xsbar.com to:email1 to:email2 to:email3 subject:... ... emailn received from:eugene at xsbar.com to:email1 to:email2 to:email3 ... to:emailn subject:... Many didn't receive the email because the header grew too big (I received 1257 failure notice ~50% of them for header too big or inappropriate recipient list). Apologize for the inaccuracy of my first post From rogue_pedro at yahoo.com Thu Aug 24 17:41:04 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 24 Aug 2006 14:41:04 -0700 Subject: When is a subclass not right? In-Reply-To: References: <1156387621.568779.191420@m73g2000cwd.googlegroups.com> <1156393371.550249.138930@75g2000cwc.googlegroups.com> <1156394781.155152.313080@i3g2000cwc.googlegroups.com> <44ede9b8$0$8925$88260bb3@free.teranews.com> Message-ID: <1156455663.871501.219440@i42g2000cwa.googlegroups.com> Chaz Ginger wrote: > I was writing some code that used someone else class as a subclass. He > wrote me to tell me that using his class as a subclass was incorrect. I > am wondering under what conditions, if ever, does a class using a > subclass not work. > > Here is an example. For instance the original class might look like: > > class A : > def __init__(self,arg) : > self.foo = arg > def bar(self) : > return self.foo > > > And I defined a class B1 which looked like: > > > class B1(A); > def __init__(self,a1,a2) : > self.c = a1 > A.__init__(self,ag) > > > He said I should use it this way: > > class B2: > def __init__(self,a1,a2): > self.c = a1 > self.t = A(a2) > > def bar(self) : > self.t.bar() > > > Other than the obvious difference of B2 having an attribute 't', I can't > see any other obvious differences. Is there something I am missing? > > TIA > Chaz When the developer *tells* you it won't work, that's a good indication. :-) You haven't missed anything: the developer was talking about his specific code, not python in general. (I'm on the Twisted list too. ;-) ) Peace, ~Simon From carsten at uniqsys.com Tue Aug 1 12:46:36 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 01 Aug 2006 12:46:36 -0400 Subject: Can't get LCHARVAR's with InformixDB In-Reply-To: <1154447228.669652.169320@75g2000cwc.googlegroups.com> References: <1154437329.471918.35150@h48g2000cwc.googlegroups.com> <1154438862.714569.9130@b28g2000cwb.googlegroups.com> <1154446906.915203.13790@m73g2000cwd.googlegroups.com> <1154447228.669652.169320@75g2000cwc.googlegroups.com> Message-ID: <1154450796.452.58.camel@dot.uniqsys.com> On Tue, 2006-08-01 at 11:47, fhurley at gmail.com wrote: > Another thing... > > > Output is: > > description is <('msg_tx', 'lvarchar', 0, 0, None, None, 1)> > > The 0's worried me, as I could see where they could be used as parms to > allocate/trim things as necessary... just a thought. That is indeed a problem. For some as of yet undetermined reason, the client thinks that msg_tx is a column of length zero, so it's no big surprise that all you get back is empty strings. Once again, I'll need the create table statement for the table you're selecting from in order to investigate what's happening. -Carsten From dieter at handshake.de Tue Aug 22 13:19:44 2006 From: dieter at handshake.de (Dieter Maurer) Date: 22 Aug 2006 19:19:44 +0200 Subject: Input from the same file as the script References: <1156096945.924216.14380@m73g2000cwd.googlegroups.com> Message-ID: Georg Brandl writes on Sun, 20 Aug 2006 20:08:38 +0200: > poggle.themammal at gmail.com wrote: > > Can the input to the python script be given from the same file as the > > script itself. e.g., when we execute a python script with the command > > 'python > When I ran the below the python interpreter gave an error. The easiest way would be: data = '''\ here comes your data ... ''' # and now you use it ... data ... # you can even wrap it into a file from StringIO import StringIO data_as_file = StringIO(data) ... data_as_file.readline() ... -- Dieter From rogue_pedro at yahoo.com Wed Aug 23 16:46:51 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 23 Aug 2006 13:46:51 -0700 Subject: Regex help...pretty please? References: <1156358822.649578.126990@74g2000cwt.googlegroups.com> Message-ID: <1156366011.056598.295310@m79g2000cwm.googlegroups.com> MooMaster wrote: > I'm trying to develop a little script that does some string > manipulation. I have some few hundred strings that currently look like > this: > > cond(a,b,c) > > and I want them to look like this: > > cond(c,a,b) > > but it gets a little more complicated because the conds themselves may > have conds within, like the following: > > cond(0,cond(c,cond(e,cond(g,h,(a > What I want to do in this case is move the last parameter to the front > and then work backwards all the way out (if you're thinking recursion > too, I'm vindicated) so that it ends up looking like this: > > cond((a<1), 0, cond((a > futhermore, the conds may be multiplied by an expression, such as the > following: > > cond(-1,1,f)*((float(e)*(2**4))+(float(d)*8)+(float(c)*4)+(float(b)*2)+float(a)) > > Here, all I want to do is switch the parameters of the conds without > touching the expression, like so: > > cond(f,-1,1)*((float(e)*(2**4))+(float(d)*8)+(float(c)*4)+(float(b)*2)+float(a)) > > So that's the gist of my problem statement. I immediately thought that > regular expressions would provide an elegant solution. I would go > through the string by conds, stripping them & the () off, until I got > to the lowest level, then move the parameters and work backwards. That > thought process became this: > -------------------------------------CODE-------------------------------------------------------- > import re > > def swap(left, middle, right): > left = left.replace("(", "") > right = right.replace(")", "") > temp = left > left = right > right = temp > temp = middle > middle = right > right = temp > whole = 'cond(' + left + ',' + middle + ',' + right + ')' > return whole > > def condReplacer(string): > #regex = re.compile(r'cond\(.*,.*,.+\)') > regex = re.compile(r'cond\(.*,.*,.+?\)') > if not regex.search(string): > print "whole string is: " + string > [left, middle, right] = string.split(',') > right = right.replace('\'', ' ') > string = swap(left.strip(), middle.strip(), right.strip()) > print "the new string is:" + string > return string > else: > more_conds = regex.search(string) > temp_string = more_conds.group() > firstParen = temp_string.find('(') > temp_string = temp_string[firstParen:] > print "there are more conditionals!" + temp_string > condReplacer(temp_string) > def lineReader(file): > for line in file: > regex = r'cond\(.*,.*,.+\)?' > if re.search(regex,line,re.DOTALL): > condReplacer(line) > > if __name__ == "__main__": > input_file = open("only_conds2.txt", 'r') > lineReader(input_file) > -------------------------------------CODE-------------------------------------------------------- > > I think my problem lies in my regular expression... If I use the one > commented out I do a greedy search and in my test case where I have a > conditional * an expression, I grab the expression too, like so: > > INPUT: > > cond(-1,1,f)*((float(e)*(2**4))+(float(d)*8)+(float(c)*4)+(float(b)*2)+float(a)) > OUTPUT: > whole string is: > (-1,1,f)*((float(e)*(2**4))+(float(d)*8)+(float(c)*4)+(float(b)*2)+float > (a)) > the new string > is:cond(f*((float(e*(2**4+(float(d*8+(float(c*4+(float(b*2+float > (a,-1,1) > > when all I really want to do is grab the part associated with the cond. > But if I do a non-greedy search I avoid that problem but stop too early > when I have an expression like this: > > INPUT: > cond(a,b,(abs(c) >= d)) > OUTPUT: > whole string is: (a,b,(abs(c) > the new string is:cond((abs(c,a,b) > > Can anyone help me with the regular expression? Is this even the best > approach to take? Anyone have any thoughts? > > Thanks for your time! You're gonna want a parser for this. pyparsing or spark would suffice. However, since it looks like your source strings are valid python you could get some traction out of the tokenize standard library module: from tokenize import generate_tokens from StringIO import StringIO s = 'cond(-1,1,f)*((float(e)*(2**4))+(float(d)*8)+(float(c)*4)+(float(b)*2)+float(a))' for t in generate_tokens(StringIO(s).readline): print t[1], Prints: cond ( - 1 , 1 , f ) * ( ( float ( e ) * ( 2 ** 4 ) ) + ( float ( d ) * 8 ) + ( float ( c ) * 4 ) + ( float ( b ) * 2 ) + float ( a ) ) Once you've got that far the rest should be easy. :) Peace, ~Simon http://pyparsing.wikispaces.com/ http://pages.cpsc.ucalgary.ca/~aycock/spark/ http://docs.python.org/lib/module-tokenize.html From bussieremaillist at gmail.com Sun Aug 20 07:35:36 2006 From: bussieremaillist at gmail.com (bussiere maillist) Date: Sun, 20 Aug 2006 13:35:36 +0200 Subject: convert a long string in binary Message-ID: <8a8f62c80608200435q362ee38fs1de5e2ca1679f4bc@mail.gmail.com> i've got a very long string and i wanted to convert it in binary like string = """Monty Python, or The Pythons, is the collective name of the creators of Monty Python's Flying Circus, a British television comedy sketch show that first aired on the BBC on October 5, 1969. A total of 45 episodes were made over four series. However, the Python phenomenon was much greater, spawning stage tours, a musical, four films, numerous albums, and several books, as well as launching the members to individual stardom. The television series, broadcast by the BBC from 1969 to 1974, was conceived, written and performed by Graham Chapman, John Cleese (1969-1973), Terry Gilliam, Eric Idle, Terry Jones and Michael Palin. Loosely structured as a sketch show, but with a highly innovative stream-of-consciousness approach (aided by Terry Gilliam's animations), it pushed the boundaries of what was then considered acceptable, both in terms of style and content. """ string = binary(string) print string // 01010101010101 i 'am searching for something like the binary function (taht doesn't exist) to convert my string directly in binary. Regards Bussiere From blue99 at interia.pl Tue Aug 8 02:50:30 2006 From: blue99 at interia.pl (Rob Wolfe) Date: 7 Aug 2006 23:50:30 -0700 Subject: import help In-Reply-To: <1155016977.405733.32170@n13g2000cwa.googlegroups.com> References: <1155016977.405733.32170@n13g2000cwa.googlegroups.com> Message-ID: <1155019830.536992.262330@n13g2000cwa.googlegroups.com> placid wrote: > Hi all, > > How do i import a module that has an hypen/dash (-) in its name ? I get > a SytaxError exception You can use function __import__. >>> print open("-test.py").read() def fun2(): return "Hello from -test !" >>> import -test File "", line 1 import -test ^ SyntaxError: invalid syntax >>> __import__("-test", globals(), locals(), []) But here is another problem: >>> -test.fun2() Traceback (most recent call last): File "", line 1, in ? NameError: name 'test' is not defined >>> import sys >>> sys.modules["-test"].fun2() 'Hello from -test !' Regards, Rob From pmartin at snakecard.com Tue Aug 15 09:47:50 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Tue, 15 Aug 2006 08:47:50 -0500 Subject: hide python code ! References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155646273.926275.41610@74g2000cwt.googlegroups.com> Message-ID: Bayazee wrote: > > Armin Steinhoff wrote: >> Bayazee wrote: >> > hi >> > can we hide a python code ? >> > if i want to write a commercial software can i hide my source code from >> > users access ? >> > we can conver it to pyc but this file can decompiled ... so ...!! >> > do you have any idea about this ...? >> >> Use Pyrex in order to build C-Modules from the critical parts of your >> software. >> >> > >> > --------------------------------------- >> > First Iranian Open Source Community : www.python.ir >> >> Interesting ... but you are not a member of this community. Right? >> >> --Armin > > > Hi > thanx for your answers . i read all of your replys carefully ... > i am an open source Programmer ! i love to distribute my sources and > use other ideas ! but asking a question is't reason of using it ! i > want to find a way to hide python source codes ! can we do it ? how ? > but i dont want to use it .... > this is a question that i must be answer to a friend ! Then the answer could be a question: can we hide any source/binary ? Hardware tokens (ex: smart cards) are used just for that purpose. So as long as you distribute a PC with your package and are certain it cannot be tempered with (the correct O/S, administrative rights, encrypted partitions .....) ... but I do not think there is such a PC out there. You might want to read this: http://www.commoncriteriaportal.org/ www.commoncriteriaportal.org/public/files/ccintroduction.pdf http://en.wikipedia.org/wiki/Common_Criteria Philippe From fabiofz at gmail.com Fri Aug 4 13:39:50 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Fri, 4 Aug 2006 14:39:50 -0300 Subject: Pydev with Eclipse on OSX Q In-Reply-To: <186128F8-803B-43BA-BC7F-40A282B7EB34@thingmajig.org> References: <186128F8-803B-43BA-BC7F-40A282B7EB34@thingmajig.org> Message-ID: On 8/4/06, Michiel Sikma wrote: > > Hey guys. I'm trying to run Pydev on Eclipse on OSX, but I've got a > problem that prevents me from making new projects in it. It seems > that I cannot add my Python interpreter to the list of interpreters > (it seems to do _something_ when I select it, but then ends up not > adding it to the list). > > Are any of you guys familiar with this? Is there something I need to > do before I can add my interpreter to that list? I'm on a G5 iMac and > have the latest version of both programs. > Have you checked your error log? (when adding an interpreter, there might be problems if you don't specify your real interpreter, but a link for it... (see bug http://sourceforge.net/tracker/index.php?func=detail&aid=1523582&group_id=85796&atid=577329for details) or have spaces in your eclipse path (see bug http://sourceforge.net/tracker/index.php?func=detail&aid=1228027&group_id=85796&atid=577329for details). Cheers, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: From pu.news.001 at gmail.com Sat Aug 12 11:36:03 2006 From: pu.news.001 at gmail.com (Patrick Useldinger) Date: Sat, 12 Aug 2006 17:36:03 +0200 Subject: [OT] why cd ripping on Linux is so slow In-Reply-To: References: Message-ID: <44ddf564@news.vo.lu> alf wrote: > Hi, > > I try to ip some music CD and later convert it into mp3 for my mp3 > player, but can not get around one problem. ripping from Linux is > extremely slow like 0.5x of CD speed. > > In contrary, on M$ Windows it takes like a few minutes to have CD ripped > and compresses into wmf yet I do not knowhow to get pure wavs... > > Hope I find someone here helping me with that .... This is really OT, and you might be better off looking in Linux forums like http://www.linuxquestions.org/. That said, it's likely that your DMA is not switched on. Ask your question in the aforementioned forums, and make sure to state which distribution you are using. -pu From jaysherby at gmail.com Tue Aug 8 17:26:28 2006 From: jaysherby at gmail.com (jaysherby at gmail.com) Date: 8 Aug 2006 14:26:28 -0700 Subject: newb question: file searching In-Reply-To: <1155071509.526393.283100@m79g2000cwm.googlegroups.com> References: <1155067111.892386.130610@n13g2000cwa.googlegroups.com> <1155067720.211789.208560@i42g2000cwa.googlegroups.com> <1155068675.101390.299110@i3g2000cwc.googlegroups.com> <1155070517.448510.149380@b28g2000cwb.googlegroups.com> <1155071433.686040.276080@m79g2000cwm.googlegroups.com> <1155071509.526393.283100@m79g2000cwm.googlegroups.com> Message-ID: <1155072388.491063.317340@i42g2000cwa.googlegroups.com> So far, so good. I just have a few more questions. Here's my code so far: import os top = '/home/USERNAME/' images = [] for files in os.walk(top, topdown=True): images += [file for file in files[2] if file.endswith('jpg')] print images I still need to know how I can dynamically get the name of the directory that my script is in. Also, how can I get it to add the full path of the file to "images" instead of just the file name. See, when I go to use a particular image name later on, it won't do me much good if I don't have the path to it. From ramasubramani.g at gmail.com Wed Aug 2 08:32:06 2006 From: ramasubramani.g at gmail.com (Rama) Date: Wed, 2 Aug 2006 18:02:06 +0530 Subject: Datetime objects In-Reply-To: <1154520968.852075.66140@m79g2000cwm.googlegroups.com> References: <1154519280.363058.224110@m73g2000cwd.googlegroups.com> <1154520968.852075.66140@m79g2000cwm.googlegroups.com> Message-ID: <3f8d3ac50608020532v1ea85ad7l9942f09ba7f6ccf2@mail.gmail.com> I am a newcomer to python - so not too sure if this method is the correct one. Noticing this, >>> dir(diff) ['__abs__', '__add__', '__class__', '__delattr__', '__div__', '__doc__', '__eq__ ', '__floordiv__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__ ', '__le__', '__lt__', '__mul__', '__ne__', '__neg__', '__new__', '__nonzero__', '__pos__', '__radd__', '__rdiv__', '__reduce__', '__reduce_ex__', '__repr__', ' __rfloordiv__', '__rmul__', '__rsub__', '__setattr__', '__str__', '__sub__', 'da ys', 'max', 'microseconds', 'min', 'resolution', 'seconds'] it seems >>> diff.seconds 52662 should give you what you want. Converting the seconds to hours, minutes, seconds should be easy. Of course, looking at help(diff), I get the impression that in the generic case you should check if diff.days == 0 to decide if you should be usingthat as well. thank, Rama On 2 Aug 2006 05:16:08 -0700, Lad wrote: > > > Sybren Stuvel wrote: > > Lad enlightened us with: > > > How can I find days and minutes difference between two datetime > > > objects? > > > For example If I have > > > b=datetime.datetime(2006, 8, 2, 8, 57, 28, 687000) > > > a=datetime.datetime(2006, 8, 1, 18, 19, 45, 765000) > > > > diff = b - a > > Ok, I tried > > >>> diff=b-a > >>> diff > datetime.timedelta(0, 52662, 922000) > >>> diff.min > datetime.timedelta(-999999999) > > > which is not good for me. > > So I tried to use toordinal like this > diff=b.toordinal()-a.toordinal() > > but I get > diff=1 > > Why? > where do I make a mistake? > Thank you for help > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bedouglas at earthlink.net Thu Aug 10 14:45:55 2006 From: bedouglas at earthlink.net (bruce) Date: Thu, 10 Aug 2006 11:45:55 -0700 Subject: seaching a list... Message-ID: <268101c6bcad$384b4960$0301a8c0@Mesa.com> hi... i'm playing with a test sample. i have somethhing like: dog = mysql_get(.....) . . . such that 'dog' will be an 'AxB' array of data from the tbls furher in the test app, i'm going to have a list, foo: foo = 'a','b','c','d' i'm trying to determine what's the fastest way of searching through the 'dog' array/list of information for the 'foo' list. should i essentially make dog into A lists, where each list is B elements, or should it somehow combine all the elements/items in 'dog' into one large list, and then search through that for the 'foo' list... also, in searching through google, i haven't come across the list.search function.. so just how do i search a list to see if it contains a sublist... my real problem involves figuring out how to reduce the number of hits to the db/tbl... thanks ps. if this is confusing, i could provide psuedo-code to make it easier to see... From cliff at develix.com Tue Aug 22 17:40:37 2006 From: cliff at develix.com (Cliff Wells) Date: Tue, 22 Aug 2006 14:40:37 -0700 Subject: What do you want in a new web framework? In-Reply-To: <4jele2pe011di99c5dnq4olclglrkieggc@4ax.com> References: <1156100331.329889.216340@p79g2000cwp.googlegroups.com> <1156156636.515678.118210@75g2000cwc.googlegroups.com> <4jele2pe011di99c5dnq4olclglrkieggc@4ax.com> Message-ID: <1156282837.6319.111.camel@devilbox> On Tue, 2006-08-22 at 08:15 +0000, Tim Roberts wrote: > Ordinarily, I think the "do it yourself" nature of Python is a great thing, > and I would never try to dissuade someone from reinventing something > themselves. However, in the case of web frameworks, I believe Marc is > fundamentally correct: the web framework proliferation in Python is > actually doing the language a huge disservice. I disagree. Even if most of the frameworks end up being nothing more than research artifacts, the fact is they embody research. Without research the Python web framework space will be forever relegated to runner-up (and probably has-been at some point). > Consider Ruby. If someone asks, "I'd like to do a web site with Ruby, what > should I use?", the answer comes back loud, clear, and unanimous: Ruby on > Rails. Or Wee. Or Nitro. Or Nemo. Or others that are surely to be written as Ruby gains acceptance and experienced users capable of writing them. > If someone asks, "I'd like to do a web site with Python, what > should I use?", she gets 25 different answers. "Look at HTMLGen, Cheetah, > WebWare, CherryPy, Karrigell, Django, Pylons, Plone, Zope, TurboGears, > etc., etc.", none of which are pre-installed in the typical Linux > distribution. To the non-programming decision maker, that kind of response > makes Python look unprofessional -- a toy. Ruby on Rails doesn't come preinstalled either. I don't think it's appropriate (and apparently most Linux distros currently agree) to install web programming frameworks by default. I will add that at least a few distros offer TurboGears, Django and Pylons as add-ons. > Now, please do not send me ugly emails accusing me of running down Python. > I've been a Python believer since 1.52. I've done web sites in at least 5 > of the frameworks, and I even wrote one of the wiki pages that compares web > frameworks. However, it is only the fact that I *AM* a true Python > believer that gave me the patience and incentive to try 5 different > frameworks. If a corporate decision maker were involved, that would never > happen. Python would simply fall off of the list of options, and the job > would get done in PHP or Ruby on Rails. Yes, because PHP has only one web framework too ;-) > I agree with Marc. PLEASE do not create "yet another Python web > framework." Let's pick one, and join together to turn it into the One, > True, Unquestioned Web Solution. Yes, and for those of us who may not like your choice, we can move to another language or write our own, so nothing will have changed. I think the entire concept that Ruby on Rails is successful because it happens to be the dominant solution on what was previously a practically unknown language is just plain ridiculous. If that's the case then why hasn't Eiffel taken over the world? Or Lua? Or Io? No, the reason Rails is successful is due to being a decent, focused product with *great* marketing (screencasts, anyone?). We've had several good Python web frameworks for some time, but practically zero marketing (except for Zope/Plone, which as it turns out, weren't such great products, at least not for the "80% solution" that Rails targets). Also the fact that Ruby doesn't suck isn't hurting Rails any either. If GvR wants to improve Python's status against Ruby, I suggest looking at what people are *really* raving about in the Ruby world (despite how they got there) and address those issues rather than getting sidetracked with this nonsense. Regards, Cliff -- From mail at microcorp.co.za Sat Aug 26 04:41:34 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 26 Aug 2006 10:41:34 +0200 Subject: Fw: Is this a good idea or a waste of time? References: <1156535105.027083.277190@74g2000cwt.googlegroups.com> Message-ID: <01d701c6c8ed$0494c1e0$03000080@hendrik> "Simon Forman" Wrote: | Hendrik van Rooyen wrote: | > "Simon Forman" wrote: | > | > 8<------------------------------------------------------------- | > | > | BTW, speaking of "strictness", "more stricter" is invalid English, | > | just "stricter" is the "correct" form. ;-) | > | > or alternatively the construct "more strict" is also acceptable - Hendrik | | It is, but technically it's not. English is more bizarrer that that.. LOL! | It depends or the number of syllables in the word: one or two, add | '-er'; three or more (or if the two-syllable-er word "sounds lame"), | use "more"... | | English, the perl of natural languages.. lol (Apparently Dutch is | pretty weird too..) | | Peace, | ~Simon *grin* my Dutch is Dangerous - its actually Afrikaans - a highly simplified variant that is poison to good Dutch... I like the rule about the syllables - would never remember it in the heat of battle though... - Hendrik From jUrner at arcor.de Tue Aug 29 09:51:56 2006 From: jUrner at arcor.de (jUrner at arcor.de) Date: 29 Aug 2006 06:51:56 -0700 Subject: absolute imports (python-2.5) Message-ID: <1156859516.781841.230140@h48g2000cwc.googlegroups.com> Hello all I just played around a bit with python 2.5 and relative imports. Bit disappointed so far. Hoped to be able to use this new feature to develop standalone libraries that can be just dropped into any project without having to adjust any imports. pkg/ pkg/__init__.py pkg/main.py pkg/string.py "main.py" does: from . import string no problem if you import the whole package from another module: import pkg but if you execute "main.py" you get an error "ValueError: Relative importpath too deep" This is looks a nightmare come true for developing modules. I read all available information regarding the "-m" switch and its limitations when it comes to relative imports. Being impatient and scarend of having to wait another (year!) for this feature to become usable I wonder if anyone has any better information on things ahead. Juergen From crystalattice at gmail.com Thu Aug 24 16:27:16 2006 From: crystalattice at gmail.com (crystalattice) Date: 24 Aug 2006 13:27:16 -0700 Subject: wxPython default radiobox choice Message-ID: <1156451235.958752.101510@i42g2000cwa.googlegroups.com> In my GUI app, I have a radio box allowing the user to pick his/her gender. When I click a button, I'd like the radio box to tell the program which choice is marked. I can get it to work when I manually pick a choice but I get an error when the choice is left at the default value, which is "Male". I have the radio box tied to an event to "see" when a choice is made, but how does it work if the person just leaves the default value? I've looked at the wxPython demo but the radio box actions only work for changing values. From nicola.musatti at gmail.com Thu Aug 3 09:06:58 2006 From: nicola.musatti at gmail.com (Nicola Musatti) Date: 3 Aug 2006 06:06:58 -0700 Subject: Grammar parsing In-Reply-To: References: Message-ID: <1154610418.217565.74890@b28g2000cwb.googlegroups.com> Paolo Pantaleo wrote: > Hi, > > How can I write a pareser for a certain gramamr? I found PyPy that > does it, is thare any other tool? Maybe something built-in the python > interpreter? Check out Dave Beazley's Ply: http://www.dabeaz.com/ply/ . Cheers, Nicola Musatti From phinsxiii at gmail.com Mon Aug 21 15:06:22 2006 From: phinsxiii at gmail.com (Bucco) Date: 21 Aug 2006 12:06:22 -0700 Subject: More List Comparison Help In-Reply-To: <1156185630.491504.145530@i3g2000cwc.googlegroups.com> References: <1156185630.491504.145530@i3g2000cwc.googlegroups.com> Message-ID: <1156187182.417425.75650@i42g2000cwa.googlegroups.com> Nevermind. I found my own error. I referenced the input values instead of the class object self. That is what I get for staring at the code too long. Thanks:) SA From rosedb0 at gmail.com Sun Aug 27 22:07:39 2006 From: rosedb0 at gmail.com (hiaips) Date: 27 Aug 2006 19:07:39 -0700 Subject: Newbie Question. Class definitions on the fly. In-Reply-To: <1156728767.854606.180190@p79g2000cwp.googlegroups.com> References: <1156728767.854606.180190@p79g2000cwp.googlegroups.com> Message-ID: <1156730858.961999.148120@h48g2000cwc.googlegroups.com> ishtar2020 wrote: > Hi everyone > > I'm sure this question is kinda stupid and has been answered a few > times before... but I need your help! > > I'm writing a small application where the user can analyze some text > based on a set of changing conditions , and right now I'm stuck on a > point where I'd like to automatically generate new classes that operate > based on those user-defined conditions. > > Is there a way in python to define a class in runtime? For instance, > can I define a class which extends another(that I have previously > defined in some module) , create some instance completely on the fly > and then add/redefine methods to it? > > If affirmative, I've thought of a problem I would maybe have to face: > as the class has been defined by direct input to the python > interpreter, I could only create instances of it on the same session I > entered the definition(because it's not on a module I can load on > future uses) but not afterwards. Is there a way to keep that code? > > Even more newbie paranoia: what would happen if I make that 'on the > fly" object persist via pickle? Where would Python find the code to > handle it once unpickled on another session (once again, i take that no > code with the definition of that instance would exist, as it was never > stored on a module). > > Hope it wasn't too ridiculous an idea. > > Thank you for your time, guys. You might check out the following link on metaclass programming: http://www-128.ibm.com/developerworks/linux/library/l-pymeta.html The author gives at least one short example of creating a class dynamically and using an instance of it. There are also links to other, related articles and topics at the bottom. --dave From deets at nospam.web.de Tue Aug 15 06:18:48 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 15 Aug 2006 12:18:48 +0200 Subject: Newbie: calling the originating class ... References: <1155625995.101230.256210@74g2000cwt.googlegroups.com> Message-ID: <4kdlcbFbkka1U1@uni-berlin.de> donkeyboy wrote: > This is probably very straightforwards to someone with experience, but > I will try to explain my predicament: > > I'm trying to code a simulation, where you have a Simulation class that > knows everything about the simulation, and in turn classes that the > Simulation calls when it wants to make new instances -- for the time > being, let's call the called classes Agents (sorry, saw the Matrix > again last night!). > > In the Simulation class, there's information about the simulation that > each Agent wants to know. As such, I wrote a method in the Simulation > class for the Agents to call, to get the said required information. > However, I can't figure out a way for the Agents to call the > Simulations methods -- is this even possible? > > The pseudo-code I'm using is as follows: > > s = Simulation() > > class Simulation: > # create a number of agents > ... > # Simulation information > important_stuff = 10 > > def showImportant(self): > return important_stuff > > class Agents: > my_stuff = s.showImportant > > ... which fails: I get errors saying the global name 's' is not > defined. Any thoughts? Is what I'm trying to do even possible, or > should I be doing something else? Besides the fact that the above can't work, as you can't instantiate a Simulation object before defining its class, you have basically two options here (while they come in many disguises): - have only one instance of Simulation and a defined way to access it - in OO-terms called a singleton. There are several ways to accomplish that: - a "real" singleton or borg-pattern, that allows you to use the Simulation constructor - a module global variable you assign it to & then use it. - classmethods - pass an instance of a Simulation to each Agent, either at construction-time or later on explicit. Depending on how the overall system is supposed to run, either ways have their benefits - if you only run one simulation, the first approach enables you to only use the simulation object where you need it, and not pass it around to other objects that maybe don't need it themselves but have other objects contained/instantiated that do so. But naturally, no parallel universe with only one simulation.... Diez From john106henry at hotmail.com Mon Aug 14 12:57:48 2006 From: john106henry at hotmail.com (John Henry) Date: 14 Aug 2006 09:57:48 -0700 Subject: Easy to use distributed system? In-Reply-To: References: Message-ID: <1155574668.787239.202300@i42g2000cwa.googlegroups.com> I've been using Pyro and it does what I needs it to do for me. I don't know if it's as fancy as other packages but the price is right. Jim Jones wrote: > I am looking for a system in Python that will easily allow me to distribute > processes across multiple systems? So, if I have a function 'foo', I'd > like to be able to call something along the lines of > > distribute(foo(x)) > > And have the system figure out which node is available for process, and then > have the results returned in some sort of callback fashion. > > Any insight is greatly appreciated. > > -- > Jim > http://www.runfatboy.net - Exercise for the rest of us. From linnorm at gmail.com Tue Aug 22 15:01:40 2006 From: linnorm at gmail.com (linnorm at gmail.com) Date: 22 Aug 2006 12:01:40 -0700 Subject: key not found in dictionary References: <1156272596.613723.219280@h48g2000cwc.googlegroups.com> Message-ID: <1156273300.781151.243040@75g2000cwc.googlegroups.com> KraftDiner wrote: > I have a dictionary and sometime the lookup fails... > it seems to raise an exception when this happens. > What should I do to fix/catch this problem? > > desc = self.numericDict[k][2] > KeyError: 589824 <---- This is the error that is being produced, > because there is no key > 589824. Given the information provided the simplest answer would be: try: desc = self.numericDict[k][2] except KeyError: desc = '' From danb_83 at yahoo.com Tue Aug 15 18:43:00 2006 From: danb_83 at yahoo.com (Dan Bishop) Date: 15 Aug 2006 15:43:00 -0700 Subject: what is the keyword "is" for? In-Reply-To: References: <1155625097.784052.31330@p79g2000cwp.googlegroups.com> Message-ID: <1155681780.830614.86950@75g2000cwc.googlegroups.com> Sybren Stuvel wrote [on the difference between is and ==]: > Obviously "a is b" implies "a == b", Not necessarily. >>> a = b = 1e1000 / 1e1000 >>> a is b True >>> a == b False From martin.hoefling at gmx.de Mon Aug 7 09:41:34 2006 From: martin.hoefling at gmx.de (=?ISO-8859-15?Q?Martin_H=F6fling?=) Date: Mon, 07 Aug 2006 15:41:34 +0200 Subject: is it possible to dividing up a class in multiple files? Message-ID: Hi there, is it possible to put the methods of a class in different files? I just want to order them and try to keep the files small. Regards Martin From bj_666 at gmx.net Fri Aug 25 12:54:15 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 25 Aug 2006 18:54:15 +0200 Subject: get a line of text from a socket... References: <1156523827.971633.321830@m79g2000cwm.googlegroups.com> Message-ID: In <1156523827.971633.321830 at m79g2000cwm.googlegroups.com>, KraftDiner wrote: > If you don't know how long your input data is going to be how can you > at least treat it a text line at a time... like looking for new line in > the data... Right now recv blocks. Yes I could do a select, but the > examples seem a bit complicated for a simple line oriented input... This is already done in the `asyncore` and `asynchat` modules of the standard library. Ciao, Marc 'BlackJack' Rintsch From rogue_pedro at yahoo.com Sun Aug 13 21:30:55 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 13 Aug 2006 18:30:55 -0700 Subject: Nested if and expected an indent block In-Reply-To: <1155517461.229483.18900@i3g2000cwc.googlegroups.com> References: <1155511725.874993.140020@b28g2000cwb.googlegroups.com> <1155512775.186869.69190@m79g2000cwm.googlegroups.com> <1155514407.728107.196600@i42g2000cwa.googlegroups.com> <1155515929.791561.5300@m79g2000cwm.googlegroups.com> <1155517461.229483.18900@i3g2000cwc.googlegroups.com> Message-ID: <1155519055.451320.111050@b28g2000cwb.googlegroups.com> kagard at gmail.com wrote: > Dustan wrote: > > > > > To see the full traceback, assuming you're using windows, you need to > > run it on the Command prompt. > > Hi Dustan: > > Here's the traceback: > > C:\docs\Python>SylloSolver.py > File "C:\docs\Python\SylloSolver.py", line > """ > ^ > IndentationError: expected an indented block > > I got rid of the triple quote string at the start of the function, and > that cleared up the problem, though I don't know why. > > Thanks > > Keith Ah, yes. The docstring for a function (or at least its first triple-quote) must be indented to the same degree as its statements. (If you're using IDLE it should have indented it for you when you hit return after the def statement.) HTH, ~Simon From phredrik at gmail.com Wed Aug 2 18:11:22 2006 From: phredrik at gmail.com (phredrik at gmail.com) Date: 2 Aug 2006 15:11:22 -0700 Subject: JOB: Python Developer in Chicago, IL Message-ID: <1154556682.882920.245760@h48g2000cwc.googlegroups.com> SUMMARY We are a mid-sized Web technology firm with deep roots in the open source community and toolsets. We are seeking an experienced Python programmer to assist us in providing the best possible Web-based applications to our existing and future clients. Join our superior multi-disciplinary team in a true collaborative environment and see your ideas and innovations come alive. We combine salary with company profit-sharing, 100% company-paid health insurance and tremendous flexibility to attract and retain the very brightest looking to make a difference. We encourage open source projects and support your involvement in the open source community. POSITION OVERVIEW * A vision for programming solutions to solve business problems. * Design, build, test, document and support complex Web applications and database systems. * Participate in the maintenance and refinement of internal development and deployment processes. * Keep abreast of current and emerging technologies. REQUIRED KNOWLEDGE, SKILLS AND ABILITIES * Experience with Python and SQL * Experience with UNIX and/or Linux OS * Familiarity working with one or more Web frameworks such as Paste, Ruby on Rails, Cherry-Py,Snakelets, TurboGears * Good communication skills DESIRED SKILLS * Python Paste * Zope Page Templates (ZPT) * Zope * PostgreSQL, MySQL * Knowledge of SQLObject or other Object Relational Mapper * Familiarity with Windows Server, IIS * PHP, Perl, Ajax, Ruby * Mailman, Discus, MnogoSearch, PayFlowPro Current Company Benefits * Health insurance, dental insurance, life insurance * Profit sharing plan * Generous personal time policy * A relaxed and fun loft environment surrounded by top experts in the field of Web development. Interested parties can send their resume with cover letter to employment at imagescape.com. From pranav.choudhary at gmail.com Mon Aug 7 10:30:41 2006 From: pranav.choudhary at gmail.com (pranav.choudhary at gmail.com) Date: 7 Aug 2006 07:30:41 -0700 Subject: need an alternative to getattr() Message-ID: <1154961041.067164.199520@i42g2000cwa.googlegroups.com> Hi, AIM: I have a config file that contains configuration under headings like this: heading1: heading2: ... ... i parse this file to get heading1, heading2, etc and then i want to call heading1.process(), heading2.process(), etc. What i am trying to do is: (this is not the exact code, it just represents what i am trying to do) import heading1 import heading2 While True: heading = get_next_heading(file_ptr) # This func will return "heading1", then "heading2"(on next call) if heading = "": break getattr(heading, "process")(file_ptr) # The problem, as you would have noticed, is that the first # argument to getattr is a string!! Is there an alternatice to getattr() that will solve my problem, or is there another way to do it. -pranav From DirkHagemann at gmail.com Tue Aug 22 03:14:50 2006 From: DirkHagemann at gmail.com (Dirk Hagemann) Date: 22 Aug 2006 00:14:50 -0700 Subject: MS SQL Server: NT Authentication. Possible? In-Reply-To: References: <1156164544.513073.242290@i3g2000cwc.googlegroups.com> <1156169675.734453.286700@74g2000cwt.googlegroups.com> Message-ID: <1156230890.526230.203290@p79g2000cwp.googlegroups.com> > You have a user named "null"? > > Off-hand, it looks very much like the CGI script is still running > with the privileges of the web-server, and /that/ is set up in a locked > down account that doesn't have connection rights. I also thought this might be the reason, but when I include username = os.environ.get('REMOTE_USER') in this script and print the username, it's my NT-username and not a webserver user. By the way - the webserver is an IIS. I once before had the problem that some code worked fine when I directly executed it, but didn't work when executed by this webserver (both again with the same user-account). May be it has something to do with the IIS. I will try to find a solution by reading these sites: http://www.google.de/search?hl=de&q=%22Login+failed+for+user+'(null)'%22+%22Not+associated+with+a+trusted+SQL+Server+connection%22&btnG=Suche&meta= Dirk From sonaldgr8 at gmail.com Wed Aug 30 05:19:00 2006 From: sonaldgr8 at gmail.com (sonald) Date: 30 Aug 2006 02:19:00 -0700 Subject: how can i change the text delimiter Message-ID: <1156929540.715287.123060@h48g2000cwc.googlegroups.com> Hi, Can anybody tell me how to change the text delimiter in FastCSV Parser ? By default the text delimiter is double quotes(") I want to change it to anything else... say a pipe (|).. can anyone please tell me how do i go about it? From tim at tdw.net Wed Aug 16 14:58:25 2006 From: tim at tdw.net (Tim Williams) Date: Wed, 16 Aug 2006 19:58:25 +0100 Subject: Adding a char inside path string In-Reply-To: References: <1155737700.290268.248250@i42g2000cwa.googlegroups.com> <1155744057.573884.111850@m73g2000cwd.googlegroups.com> Message-ID: <9afea2ac0608161158p73eb8e85gc4e70e0919b0b3e0@mail.gmail.com> On 16 Aug 2006 10:30:26 -0700, Hitesh wrote: > > Thank you all it worked!. > > Tim, > > > modRows = ['\\'+itm[0].replace(":", "$") for itm in rows] > > What are those two forward slashes for? Hi Hitesh, \ is an escape character, it can give unexpected results depending on the character following it. Try this >>> print "c:\server\test" then try >>> print "c:\\server\\test" If you need \ in a string, you should use a pair of them for safety, see http://docs.python.org/ref/strings.html and http://pyfaq.infogami.com/windows-index (the comments section) HTH :) From sjdevnull at yahoo.com Mon Aug 14 18:02:13 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 14 Aug 2006 15:02:13 -0700 Subject: Best IDE for Python In-Reply-To: References: <1155541849.350392.31190@h48g2000cwc.googlegroups.com> Message-ID: <1155592933.921122.21100@m79g2000cwm.googlegroups.com> Yu-Xi Lim wrote: > Eclipse+PyDev has the advantage over emacs when it comes to big > projects, IMO. It has features like refactoring, better project > management, code coverage Emacs and vim both have good integration of BicycleRepairMan for python refactoring. I don't know what better project management or code coverage in eclipse entail, but I've posted before that if you think vim/emacs are just syntax highlighting/indenting text editors you've got them misconfigured. The beautiful thing about vim in particular is that it uses Python as an internal scripting language, so it's very easy to extend it to add whatever you want. e.g. in vim I get * Syntax checking, if I type invalid python code it gets highlighted as an error (if I type, say, "if a=1:" and hit return, it gets highlighted since I need an == there). * Object browser, with dropdowns showing the parent and child classes of the current class, and the ability to jump to various class methods * Normal tag-jump stuff, so I can drill down into the method/function call I'm looking at and then pop back up (keeping a stack so I can drill down arbitrarily deep to follow the flow of the code) * Interactive help, so when, say, I type foo.blah( then the status line displays the first line of the docstring/python doc/preceding comment for foo.blah. E.g. if I type "cmp(" then the status line shows "cmp(x, y) Compare the two objects X and Y and return an integer according to ..." and if I hit F1 then I get the full help text * Editor control for uncaught errors--if I code I'm debugging raises an uncaught exception, the editor jumps directly to it. Even works for web development, if I hit a page in my dev server that raises an exception, it brings my editor right there. and lots more (version control integration, easy mapping of keys to restart the webserver after I make changes, etc). And there's some internal crap (e.g. we work on lots of clients who have client-specific versions of some objects; I have a client menu so that if I pick one, then I'll jump to their client-specific version of the current file (or the base generic version if there isn't a specific one), tags will follow the right client versions, etc). From stanc at al.com.au Fri Aug 18 13:34:26 2006 From: stanc at al.com.au (Astan Chee) Date: Sat, 19 Aug 2006 03:34:26 +1000 Subject: a bug in list.remove? Message-ID: <44E5FA22.7050304@al.com.au> Hi all, I have 2 lists. What Im doing is check the first list and remove all occurances of the elements in the second list from the first list, like so: >>> ps = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] >>> qs = [6,7,8,9,10,11,12,1,2] >>> for p in ps: if p in qs: ps.remove(p) The problem Im having is that when I do >>> print ps it gives me [2, 3, 4, 5, 7, 9, 11, 13, 14, 15] which is incorrect since 2,7,9,11 shouldnt be in that list. Is this a bug in .remove? or is my algorithm somewhat flawed? Thanks for your help! Cheers Astan From exarkun at divmod.com Fri Aug 25 13:32:55 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 25 Aug 2006 13:32:55 -0400 Subject: get a line of text from a socket... In-Reply-To: <1156523827.971633.321830@m79g2000cwm.googlegroups.com> Message-ID: <20060825173255.1717.724262427.divmod.quotient.31077@ohm> On 25 Aug 2006 09:37:09 -0700, KraftDiner wrote: >If you don't know how long your input data is going to be how can you >at least treat it a text line at a time... like looking for new line in >the data... Right now recv blocks. Yes I could do a select, but the >examples seem a bit complicated for a simple line oriented input... Here's a simple line-based echo implementation using Twisted: from twisted.internet import reactor, protocol from twisted.protocols import basic class LineEcho(basic.LineReceiver): def lineReceived(self, line): print 'Received line:', repr(line) factory = protocol.ServerFactory() factory.protocol = LineEcho reactor.listenTCP(12345, factory) reactor.run() Jean-Paul From ajaksu at gmail.com Fri Aug 11 22:31:45 2006 From: ajaksu at gmail.com (ajaksu) Date: 11 Aug 2006 19:31:45 -0700 Subject: long(Decimal) performance References: <1155349097.946873.279970@b28g2000cwb.googlegroups.com> Message-ID: <1155349905.052090.70190@74g2000cwt.googlegroups.com> Sorry... I'm ashamed to submit such awful code in my first post. Let me try again... from decimal import Decimal def dec2long(number): """ Convert decimal.Decimal to long """ longstring = str(number) if "e" in longstring: radix, exponent = longstring.split("e") elif "E" in longstring: radix, exponent = longstring.split("E") else: radix, exponent = [longstring, "0"] floatexp = long(len(radix.split(".")[1])) floatish = Decimal(radix) * 10L**floatexp ftol = long(floatish) longexp = long(int(exponent) - floatexp) return ftol * 10L**longexp This one should run by itself, is more readable and... still smells bad :( Sorry again. From metaperl at gmail.com Thu Aug 31 15:08:54 2006 From: metaperl at gmail.com (metaperl) Date: 31 Aug 2006 12:08:54 -0700 Subject: SQLObject or SQLAlchemy? In-Reply-To: References: Message-ID: <1157051334.463100.152170@h48g2000cwc.googlegroups.com> John Salerno wrote: > Are there any major differences between these two? It seems they can > both be used with TurboGears, and SQLAlchemy with Django. I'm just > wondering what everyone's preference is, and why, and if there are even > more choices for ORM. I just finished surfing both websites last night myself and here is what I glean -- I dont see why SQLObject could not be used with Django -- SQLAlchemy is not just an ORM. It can be used that way. I dont know why you have to explicitly tell it about related tables twice though. You do it the first time when defining table metadata: http://www.sqlalchemy.org/docs/tutorial.myt#tutorial_schemasql_table_relationships but when you have to make a call to relation as well: http://www.sqlalchemy.org/docs/tutorial.myt#tutorial_orm_relationships It would seem that one or the other is enough and having to do both is redundant... continuing with the comparison -- SQLObject makes it clear that it only has support for tables with a single-column primary key -- tha can both do self-joins -- SQLAlchemy has support for connection pooling -- ORMS get slow when you need to load a lot of records. SQLAlchemy has usage modes to load massive data sets when the job calls for it. > > Thanks. Just my 2 cents. From python.list at tim.thechases.com Thu Aug 3 21:08:27 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 03 Aug 2006 20:08:27 -0500 Subject: regex question In-Reply-To: <1983a3190608031436v536243e4u7efe0877763533e2@mail.gmail.com> References: <1983a3190608031410n71eaa4d1s2a3db7c10c519b88@mail.gmail.com> <44D26BDA.2000206@tim.thechases.com> <1983a3190608031436v536243e4u7efe0877763533e2@mail.gmail.com> Message-ID: <44D29E0B.5070904@tim.thechases.com> > That's great! Thanks for the quick response. Yeah, abcdcd should be > possible too. The below passes that test now as well as a couple others I tossed at it. I changed it from a one-line regexp to a VERBOSE regexp to make it easier to read and see what's going on. You may be able to see the pattern building there, so if you need to add additional stages/letters, it should likely follow the same pattern. -tkc import re tests = [ ('aabbbaabbcccbbbcccddd', True), ('aabcabcd', True), ('abcd', True), ('aaaaabbbbbccccaaaaadddd', False), ('aaaaaaaaaaabbbbbccc', False), ('abcdcd', True), ('abccccdaaaabbbbccccd', True), ('abccccdccccd', True), ] #regex = r'^(a+b+)+(c+(a*b+c+)*)d+$' regex = r""" ^ a+ b+(a*b+)* c+((a*b+)*c+)* d+(((a*b+)*c+)*d+)* $""" r = re.compile(regex, re.VERBOSE) for test, expected in tests: matched = (r.match(test) is not None) if matched == expected: print "PASSED: %s with %s" % (test, expected) else: print "FAILED: %s with %s" % (test, expected) From levub137 at wi.rr.com Sat Aug 19 17:21:35 2006 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Sat, 19 Aug 2006 21:21:35 GMT Subject: ratfun-2.3 Polynomials and Rational Functions In-Reply-To: <1156017508.602717.69060@74g2000cwt.googlegroups.com> References: <1156017508.602717.69060@74g2000cwt.googlegroups.com> Message-ID: Bas wrote: > Are there any differences between this module and the one already > present in numpy? > > http://www.scipy.org/doc/numpy_api_docs/numpy.lib.polynomial.html > > Cheers, > Bas > Yes, there are quite a few. This module uses a multi-precision library (clnum) to make the calculations more precise. This makes the root finder significantly more precise. There is an example in the user manual that shows the difference in performance between Numeric (essentially the same code as in numpy) and the ratfun root finder on an ill-conditioned polynomial. If you choose to use exact coefficients (integers and rationals) then all calculations except for root finding are exact. Unlike the numpy implementation, arithmetic (+-*/**) uses the standard Python operators instead of requiring you to call functions. Ray From rogue_pedro at yahoo.com Tue Aug 1 17:44:39 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 1 Aug 2006 14:44:39 -0700 Subject: cleaner way to write this try/except statement? In-Reply-To: <1154466619.481420.49140@i3g2000cwc.googlegroups.com> References: <44Pzg.2617$No6.51493@news.tufts.edu> <1154466619.481420.49140@i3g2000cwc.googlegroups.com> Message-ID: <1154468679.260453.11020@s13g2000cwa.googlegroups.com> Simon Forman wrote: > John Salerno wrote: > > John Salerno wrote: > > > The code to look at is the try statement in the NumbersValidator class, > > > just a few lines down. Is this a clean way to write it? i.e. is it okay > > > to have all those return statements? Is this a good use of try? Etc. > > > > I cleaned it up a little and did this, but of course this doesn't work. > > Is this the wrong way to create a function (not method) within a class? > > > > > > > > def Validate(self, parent): > > text_ctrl = self.GetWindow() > > text = text_ctrl.GetValue() > > > > try: > > if not text or int(text) <= 0: > > error_message() > > return False > > else: > > return True > > except ValueError: > > error_message() > > return False > > > > @staticmethod > > def error_message(): > > wx.MessageBox('Enter a valid time.', 'Invalid time entered', > > wx.OK | wx.ICON_ERROR) > > Your indentation looks off. Your error_message() function should be at > the same indentation as the rest of the body of the Validate() method > (i.e. same as the try statement, "text_ctrl = ..." statements.) > > If that's not an artifact of posting it here then you'll need to > correct that. > > Also, there's no need to declare the function a staticmethod, since it > isn't. > > Other than that it looks ok to me, but I might have missed something. Maybe I did miss something: Are you actually trying to make a static method? Say, to be able to call it elsewhere than just the Validate() method? In that case, your indentation is still (apparently) off, but the error_message() method (a staticmethod is still a method I think, but I could be wrong) should be at the same indentation level as any other method, and you have to prepend the instance object ('self.' if you're calling it from inside another method) to it when you call it. class A(object): def meth(self, arg): self.func(arg) @staticmethod def func(arg): print arg a = A() a.func("hi") a.meth("world.") # prints hi world. HTH, ~Simon From bounces at foo.org Thu Aug 31 19:48:49 2006 From: bounces at foo.org (Dan) Date: Thu, 31 Aug 2006 23:48:49 GMT Subject: Allowing ref counting to close file items bad style? In-Reply-To: References: <9U6Jg.951$Xw6.283@trndny02> Message-ID: BJ?rn Lindqvist wrote: > On 8/30/06, Dan wrote: >> Is my data safer if I explicitly close, like this?: >> fileptr = open("the.file", "w") >> foo_obj.write(fileptr) >> fileptr.close() > > Have you ever experienced a problem caused by not explicitly closing > your file handles? > No. If I had, I wouldn't have asked the question. It seems to work, but can I really count on it? I am a sample of one (In that happy place that Brooks described as quadrant 1, where a person writes programs for himself to be run on his own computer. Or perhaps to be run by a handful of co-workers.) Such a small sample isn't statistically significant; a 100% success rate doesn't mean much. I've also never had a burned CD go bad, but I know that they do. /Dan -- dedded att verizon dott net From ray_usenet at yahoo.com Wed Aug 23 04:13:12 2006 From: ray_usenet at yahoo.com (Ray) Date: 23 Aug 2006 01:13:12 -0700 Subject: Python and STL efficiency In-Reply-To: <1hkioxy.42be4c1lg0jq5N%riko@despammed.com> References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <1hkh28d.xscw4v1y4v9a6N%riko@despammed.com> <1hkh6lb.6dsnh51lj8z96N%riko@despammed.com> <1156252193.524186.107520@b28g2000cwb.googlegroups.com> <1hkhexv.18m65rl61swqyN%riko@despammed.com> <1156265848.875774.251640@i42g2000cwa.googlegroups.com> <1156290607.269119.88710@b28g2000cwb.googlegroups.com> <1hkil6j.xm4l6y1kwo13dN%riko@despammed.com> <1156317315.946762.215690@p79g2000cwp.googlegroups.com> <1hkioxy.42be4c1lg0jq5N%riko@despammed.com> Message-ID: <1156320792.011620.141030@m79g2000cwm.googlegroups.com> Mc Osten wrote: > Of course. I suppose there's something broken in OP's C++ setup (in fact > the version I compiled with VCPP 2005 also takes a lot of seconds... > something like 20-30 seconds, but of course this makes me think I > haven't understood how it is supposed to work, since my gcc gives > results comparable to yours). Yeah, my guess would be either he used the Debug configuration or he actually created a Managed executable instead of a pure Win32 application. Sigh, now I can't wait to get home and try it out :) > > -- > blog: http://www.akropolix.net/rik0/blogs | Uccidete i filosofi, > site: http://www.akropolix.net/rik0/ | tenetevi riso e > forum: http://www.akropolix.net/forum/ | bacchette per voi. From ewill at sirius.tg00suus7038.net Thu Aug 31 17:00:08 2006 From: ewill at sirius.tg00suus7038.net (The Ghost In The Machine) Date: Thu, 31 Aug 2006 21:00:08 GMT Subject: Duck typing alows true polymorfisim References: <1156532721.879808.40990@i3g2000cwc.googlegroups.com> <1156533807.630662.12330@i42g2000cwa.googlegroups.com> <12fblk87ppk7ief@corp.supernews.com> <9l9hs3-64h.ln1@sirius.tg00suus7038.net> Message-ID: <04sjs3-8c2.ln1@sirius.tg00suus7038.net> In comp.lang.java.advocacy, Tor Iver Wilhelmsen wrote on 31 Aug 2006 18:31:15 +0200 : > The Ghost In The Machine writes: > >> Also, one language is very conspicuous by its absence: C#. > > He does not date any of the updates, so it's unclear how recently it > has been updated (a lot of the web is stale, like a rotting tree in a > forest.) Aye; my webpage has a similar problem. :-) > >> AmigaBasic -- Microsoft-sponsored Amiga variant > > Well, at the time Microsoft were the makers of the de-facto BASIC > implementations - M-BASIC for CP/M, the various variants in VC-20 and > C-64 and later derivates of those, and many other home computers. > "Sponsored" should probably be "created" instead - I assume they were > paid for the job. OK, "created" then. :-) > >> Also, Java now has templates. (The implementation is pretty gross >> and has some quirks, IMO, but it's better than nothing.) C++ has a >> typing system ("type_of" or some such; I'd have to look) which >> yields little more than the mangled type name and static inheritance >> testing capabilities. Of course C++ doesn't have dynamic inheritance >> anyway. > > There's the virtual stuff, and you could conceivably implement dynamic > inheritance via the bare-bones C layer - like function pointers. The > type information in C++ (RTTI) is optional. Oh yeah, that's true. Still not all that dynamic, though, unless one recompiles. > >> Dynamic type creation. I don't know if Java has this or not. One can >> of course attempt bytecode synthesis -- I think that's what BCEL >> uses -- but that's a bit of a hack. > > Groovy could possibly be used for that; also IIRC Java 6 adds some > features for that. I seem to recall security implications being one > reason this ability wasn't included from the start. Not familiar with Groovy; I'll have to look into that. It's amazing what's out there; one of the problems with Free Open Source Software (FOSS) is that there's multiple choices for the obvious stuff. :-) > >> Dynamic method creation. Java does *not* have this. AIUI >> Smalltalk-80 does; one can take an existing class and add methods >> thereto. > > Yes, but that's because a Smalltalk program lives inside a big binary > "image" that is mutable. Woe unto you if that big binary file gets > corrupted. Indeed. I for one would want Smalltalk to have the ability to transcript certain messages but would have to look. (One might call that an edit audit trail.) > >> Dynamic method deletion. I for one might only want this in the >> context of a "sandbox" but if one can create methods, one should be >> able to delete them as well if only because of undo. > > The problem with deleting a method is whether the runtime can handle > it: Smalltalk has doesNotUnderstand:#aMessage, Java has > NoSuchMetohdError - what does C++ do? A zeroed virtual method would > cause a pure virtual method call error, which I guess C++ programmers > are trained to take into account. I'd frankly have to look. My thinking is that it's a message followed by an exit(). > Also, if class A has a method and > you delet it in subclass B, it breaks the Liskov Substitution > Principle, there B should be able to function where an A is wanted. Heh...an interesting name; I'm not familiar with that issue. Of course it's important for B to be an A in many cases, though AFAICT usually what happens is that A declares a method virtual with an implementation and B munges it. > >> Dynamic method rename. This could lead to much madness but this >> might be useful during sandboxing. > > A method's name and its "address" are distinct, but for dynamic method > dispatch, what about any other code that doesn't know the new name but > assumes the method is called the same? What indeed? Much madness. > >> Dynamic inheritance. For those languages that support inheritance >> one might liken it to changing what the language inherits or >> implements on the fly. I don't know of any language apart from >> Smalltalk that can even think about allowing dynamic inheritance, >> but it's a thought. > > If you can change a Perl class, er, module's @INC array I think that > would support it. > >> Operator overload (e.g., C++'s operator ==()). > > Or rather "dotless/prefix method invocation with the added baggage of > precedence rules". Smalltalk solves this by 1) not having those > precedence rules, 2) have dotless method invocation and 3) ...? I'll admit Smalltalk has a lot of things, but popularity isn't unfortunately one of them. :-/ > >> >> Name overload. C does not have it; C++ and Java do. I suspect Ruby >> and Python do as well. > > Are you referring to namespaces, ie. namespace isolation? Hmm...that could use clarification. The general idea is that Java and C++ allow void routine1(const char *); void routine1(int); void routine1(double); in the same module or class. I suppose a slightly better term would be "function overloading", since that's what it was called some time back. C does not have this capability, and it occasionally leads to problems if a program doesn't use proper design methods (such as declaring all methods in .h files and including them, as opposed to putting local extern signatures in the .C code -- yes, my prior employer had code that did exactly that for awhile; hopefully it's cleaned up by now since it's been almost 6 years :-) ). > >> Globals. Java has no globals as such, unless one counts class names. >> C is all globals, unless one counts statics. > > Even the fully qualified classes are only "global" in the context of a > classloader and whatever classloaders it delegates to. Good point. > >> Unnamed classes. new Runnable() { public void run() {...} } is >> Java's contribution. Can be useful. > > Well, they do end up with a name after compilation. Picky, picky. :-) In any event the name is not available to the program source; one can't expect to do things like Runnable$1 r = new Runnable() { public void run() {...} } and hope for it to work. One might be able to do something slightly silly like Class c = Class.forName("Runnable$1"); c.newInstance(); but for Java that's slightly problematic, especially if there's more than one Runnable in that class. > And you do not > want to open that can of worms since then you end up with Ruby and > Smalltalk users dragging out closures and C# and Lisp users dragging > out lambdas... :) Yes, well AFAICT a closure is some code with a little context; in Java some of the context is required to have final variables, or a method by which it can pick up its owning class's members or call its routines. > >> Nested classes. > > Generally that's just a namespace issue. In Java, a class Fie nested > inside Foo is the top-level class Foo$Fie with some compiler magic to > ensure it's used correctly, which leads to funny stuff like > > Foo.Fie object = new Foo().new Fie(); > > which gets turned into the bytecode equivalent of > > Foo$Fie object = new Foo$Fie(new Foo()); Hm. > >> Primitive types -- in other words, the int<->Integer dichotomy we >> all know and love in Java; such also exists in C++ and IINM C#. I'm >> not sure if Smalltalk has such a concept, or not; Smalltalk allows >> overrides on numbers. (In Java one might contemplate 2.toString(), >> for example!) > > In Smalltalk you ask the 1 object to count to 10 for a loop. It makes > sense there, it would not feel "right" in the C family... Or anywhere else that I know of offhand. > >> Arbitrary integer size. The only language I know having this is >> Common LISP. > > java.math.BigInteger, but the operations you can perform are limited. Hm. OK, "arbitrary number size with transparency". > >> Thread-level variable/value scoping. In Java this is done using the >> ThreadLocal class, but is not (AFAICT) supported by the language >> proper. > > Yes, and that leads to a problem where if you forget to null a > ThreadLocal you can "leak" objects. Ugh. Well, unfortunately for Java it's all too easy to leak certain objects, though the only one coming to mind are FileInputStream, FileOutputStream, FileReader, and FileWriter. Forget to close them before the variable goes out of scope and they remain open forever, as far as I can tell. (Maybe that'll be fixed in a subsequent rev. I don't know.) > >> One might even contemplate function-level scoping, but that would >> only be useful if one can create new functions on the fly and modify >> these values; otherwise, they might as well be static. > > As long as you make sure you never use a private static member > elsewhere than in that particular method, it can play the role of a > function-level method. > >> Persistability. In Java one can implement Serializable or >> Externalizable, and generate output from an object. I've always >> considered this a bit of a weird hack but it can come in handy, and >> forms one leg of the Java EJB implementation. > > Persistability is left as an excercise to libraries in most languages. True, and in that library one usually has a base class. > >> Volatile field. In Java there is a volatile keyword. I don't know >> its precise semantics but it applies to fields. > > In Java it's generally a hint to the optimizer NOT to optimize away or > make any assumptions about access to a field. > >> C#'s event handling emulates this concept to some extent using the >> += operator, though I doubt they do it all that generally -- or all >> that well. > > Well it's closer to a list of function pointers, sorry delegates; not > much more than Java's more explicit (or cumbersome if you like) event > interfaces can do. Operator overloading has two issues: it's far more convenient to write something like Matrix m1, m2; Matrix m3 = m1 * m2; instead of Matrix m3 = m1.multiplyBy(m2); or Matrix m3 = Matrix.multiply(m1, m2); but it's harder for the compiler and the user to parse. So it's a tradeoff. The main problem I have with Swing event handling is that occasionally it's not clear when I have to tell the listeners that I've done something to a class which manages a bunch of listeners. Also, ideally, one would not need to fire off the listeners in sequence -- though without explicitly spawning subthreads that would be difficult in Java. The main problem with C# event handling is that I don't know its ramifications, but I consider delegates a bit silly, mostly because of the Java++ fiasco. That was not COOL, Microsoft. :-) > >> Integrated database access (and how tightly). C++ has none at all, >> though of one can use various third-party libraries. Java has some >> base-level API -- the java.sql.* and javax.sql* library. > > Well, those are general library APIs that require native or > socket-based implementation by vendors or third parties. > > What you talk about is better represented by "inline" SQL in the form > of SQLJ or Oracle's Pro*C and related products. There's the issue of how to handle schema changes, as well; that's probably why nobody wants to tightly integrate anymore. I can't really blame 'em. > > It boils down to how much should be in the language (syntax, compiler, > runtime) and how much should be left to libraries. E.g. he has a "no" > for garbage collection in C++, but there are libraries for that sort > of thing (relying mostly on the ability to override the new, delete > and assignment operators. Even in Java you often have a choice of > garbage collector algorithms in a runtime. Hm; I'll have to research that. Apart from the aforementioned stream issues and the occasional "oops I left the thing in the global Collection" issue, though, I've not had to do much with garbage collection, though I did write a rather poorly-performing cache. I will definitely have to fiddle with WeakReference at some point, though it's probably easier just to punt to a solution like Hibernate or JBossCache (TreeCache) or even Castor/JDO. Like I said, FOSS has a lot of stuff out there; the main problem for me is finding it. :-) -- #191, ewill3 at earthlink.net Windows Vista. Because it's time to refresh your hardware. Trust us. From Sibylle.Koczian at Bibliothek.Uni-Augsburg.de Tue Aug 22 10:06:27 2006 From: Sibylle.Koczian at Bibliothek.Uni-Augsburg.de (Sibylle Koczian) Date: Tue, 22 Aug 2006 16:06:27 +0200 Subject: Modules... paths... newbie confusion In-Reply-To: References: <1156166327.327422.149470@b28g2000cwb.googlegroups.com> <4ktuo2Fdf60sU1@news.dfncis.de> <1156231390.380360.133780@i3g2000cwc.googlegroups.com> Message-ID: <4l0hb3FdtugtU1@news.dfncis.de> Steve Holden schrieb: > You won;t get MySQLdb to run without running the setup.py since IIRC > there's a compile step for a C library (and it's that compile step that > needs to be able to find the MySQL client libraries). > But MySQLdb comes with a windows installer. No need to tweak anything. Sometimes you've got to choose between a slightly older version without install worries and the newest source, but not at the moment. -- Dr. Sibylle Koczian Universitaetsbibliothek, Abt. Naturwiss. D-86135 Augsburg e-mail : Sibylle.Koczian at Bibliothek.Uni-Augsburg.DE From tim.leeuwvander at nl.unisys.com Mon Aug 21 04:50:23 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 21 Aug 2006 01:50:23 -0700 Subject: Python and STL efficiency In-Reply-To: References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <1156148654.420508.57960@p79g2000cwp.googlegroups.com> Message-ID: <1156150223.825318.210500@p79g2000cwp.googlegroups.com> Marc 'BlackJack' Rintsch wrote: > In <1156148654.420508.57960 at p79g2000cwp.googlegroups.com>, Tim N. van der > Leeuw wrote: > > > (your C++ code contains some C#-isms, such as omitting the '.h' in the > > include <> statements). > > That's no C#-ism, that's C++. The standard C++ header names don't have a > trailing '.h'. ``gcc`` prints deprecation warnings if you write the > names with '.h'. > > Ciao, > Marc 'BlackJack' Rintsch We stand corrected. --Tim From avelldiroll at yahoo.fr Thu Aug 10 08:56:01 2006 From: avelldiroll at yahoo.fr (Avell Diroll) Date: Thu, 10 Aug 2006 14:56:01 +0200 Subject: String Formatting In-Reply-To: <1155213326.679334.234880@i42g2000cwa.googlegroups.com> References: <1155213326.679334.234880@i42g2000cwa.googlegroups.com> Message-ID: <44DB2CE1.2080704@yahoo.fr> OriginalBrownster wrote: > Hi there: > > I was wondering if its at all possible to search through a string for a > specific character. > > I want to search through a string backwords and find the last > period/comma, then take everything after that period/comma > > Example > > If i had a list: bread, butter, milk > > I want to just take that last entry of milk. However the need for it > arises from something more complicated. > > Any help would be appreciated > Would that work for you ? >>> a = 'bread, butter, milk' >>> a 'bread, butter, milk' >>> b = a.split(',') >>> b ['bread', ' butter', ' milk'] >>> c = b[-1] >>> c ' milk' >>> d = c.strip() >>> d 'milk' HIH Avell From skip at pobox.com Wed Aug 23 12:42:04 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 23 Aug 2006 11:42:04 -0500 Subject: Python and STL efficiency In-Reply-To: <1156319484.165195.80540@p79g2000cwp.googlegroups.com> References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <1hkh28d.xscw4v1y4v9a6N%riko@despammed.com> <1hkh6lb.6dsnh51lj8z96N%riko@despammed.com> <1156252193.524186.107520@b28g2000cwb.googlegroups.com> <1156299389.336939.211670@i42g2000cwa.googlegroups.com> <1hkildy.73vcuzyxlsgeN%riko@despammed.com> <1156319484.165195.80540@p79g2000cwp.googlegroups.com> Message-ID: <17644.34140.491121.696937@montanaro.dyndns.org> >> Yes it is. But of course you can't sat that "Python is faster than >> C++". Harald> Of course not. Python is faster then assembler. Proofed @ Harald> EuroPython 2006 in CERN, near the LHC Beta, in the same room Harald> many Nobel laurates gave their presentations before. Harald, do you have a reference to a talk abstract or a paper? Thx, Skip From johnjsal at NOSPAMgmail.com Mon Aug 21 11:57:00 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 21 Aug 2006 15:57:00 GMT Subject: text editor suggestion? In-Reply-To: References: <44e66724$0$2363$c3e8da3@news.astraweb.com> <44e6ab26$0$12557$c3e8da3@news.astraweb.com> <44e788fd$0$12550$c3e8da3@news.astraweb.com> Message-ID: Sybren Stuvel wrote: > John Salerno enlightened us with: >> But what about customizing syntax coloring? Is this also in the same >> file? I've noticed a separate file called python.vim (in Windows, >> this file exists in a 'syntax' folder, and also another file of the >> same name in an 'indent' folder, so I'm *still* confused about which >> files are used for which settings. > > And you're also confused about what things are settings and what > aren't. No, my point was just that there are more files needed than just the .vimrc file if you want to do some extra customization. I'd like to change the syntax highlighting to specific colors for each group of keywords, and you can't do that in the settings file. I'm not even sure you can do that at all, or if you have to settle for pre-made color schemes. I haven't looked into how difficult it is to make your own color scheme. (And does vim support bold text?) From bearophileHUGS at lycos.com Fri Aug 25 08:15:04 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 25 Aug 2006 05:15:04 -0700 Subject: performance of dictionary lookup vs. object attributes In-Reply-To: References: Message-ID: <1156508104.583914.323700@b28g2000cwb.googlegroups.com> Andre Meyer: > Is the test meaningful and are you surprised by the results? > I am, actually, because I would have assumed that attribute access > with an object should be faster because lookup can be precompiled. The results seem okay. Python is a dynamic language, object attributes (and methods, etc) are kept inside a dict, where you can add and remove them when you like. So using a dict is faster. You can also take a look at __slots__ Bye, bearophile From fredrik at pythonware.com Sun Aug 20 09:31:20 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Aug 2006 15:31:20 +0200 Subject: How to get the ascii code of Chinese characters? In-Reply-To: <1qmwgpkqdo3wg.dlg@gelists.gmail.com> References: <1155986298.643983.157460@i3g2000cwc.googlegroups.com> <1155990488.395220.178810@74g2000cwt.googlegroups.com> <1155999554.486951.303480@i42g2000cwa.googlegroups.com> <1qmwgpkqdo3wg.dlg@gelists.gmail.com> Message-ID: Gerhard Fiedler wrote: >>> Actually, Unicode goes beyond 65535. >> >> you may want to look up "at least" in a dictionary. > > As a homework, try to parse "at least until" and "goes beyond" and compare > the two (a dictionary is not necessarily of help with this :) > > "range is least 0..65535" : upper_bound >= 65535 > "goes beyond 65535" : upper_bound > 65535 > > For some discussions (like how to represent code points etc) this > distinction is crucial. do you know anything about how Unicode is used in real life, or are you just squabbling ? From sjmachin at lexicon.net Tue Aug 29 04:50:37 2006 From: sjmachin at lexicon.net (John Machin) Date: 29 Aug 2006 01:50:37 -0700 Subject: The lib email parse problem... References: <1156837260.222395.305960@b28g2000cwb.googlegroups.com> Message-ID: <1156841437.692537.68200@i42g2000cwa.googlegroups.com> ???? wrote: > hi, all > > when a email body consist with multipart/alternative, i must know when > the boundary ends to parse it, > > but the email lib have not provide some function to indicate the > boundary end, how to solve it ? By reading the manual. http://docs.python.org/lib/module-email.Message.html You don't need to concern yourself with boundaries -- a high-level parser is provided. Here's a simple example: This script: msg_text = """ [snip -- message is some plain text plus an attached file] """ import email pmsg = email.message_from_string(msg_text) for part in pmsg.walk(): print part.get_content_type(), part.get_filename("<>") produced this output: multipart/mixed <> text/plain <> application/octet-stream Extract.py For a more comprehensive example, see http://docs.python.org/lib/node597.html HTH, John From sjmachin at lexicon.net Mon Aug 7 22:02:06 2006 From: sjmachin at lexicon.net (John Machin) Date: 7 Aug 2006 19:02:06 -0700 Subject: Import module with non-standard file name In-Reply-To: References: Message-ID: <1155002526.831944.240480@h48g2000cwc.googlegroups.com> Ben Finney wrote: > Howdy all, > > Question: I have Python modules named without '.py' as the extension, > and I'd like to be able to import them. How can I do that? > > Background: > > On Unix, I write programs intended to be run as commands to a file > with no extension. This allows other programs to use the command as an > interface, and I can re-write the program in some other language > without obsoleting the commandline interface. > > e.g., I might write 'frobnicate-foo' as a shell program so that other > programs can 'frobnicate-foo --bar baz'. If I later decide to > re-implement 'frobnicate-foo' in Python, I'll save the top level > module to the same file name since it implements the same command-line > interface. > > Now that I've got it written as a Python module, I'd like to write > unit tests for that module, which of course will need to import the > program module to test it. The unit test can explicitly add the > directory where the program module lives to 'sys.path' for the purpose > of importing that module. If it can do that, it can copy the MUT to some temp directory, adding .py to the end of the name of the new file, and put the temp directory in sys.path .... can't it? Cheers, John From bj_666 at gmx.net Wed Aug 23 06:13:16 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 23 Aug 2006 12:13:16 +0200 Subject: swapping numeric items in a list References: Message-ID: In , Jiang Nutao wrote: > To convert list > aa = [0x12, 0x34, 0x56, 0x78] > into > [0x34, 0x12, 0x78, 0x56] > > How to do it fast? My real list is huge. Use the `array` module and the `array.byteswap()` method. Ciao, Marc 'BlackJack' Rintsch From rrr at ronadam.com Wed Aug 9 18:04:01 2006 From: rrr at ronadam.com (Ron Adam) Date: Wed, 09 Aug 2006 17:04:01 -0500 Subject: String.digits help!!! In-Reply-To: <1155075748.927391.326310@h48g2000cwc.googlegroups.com> References: <1155058550.954997.320250@m79g2000cwm.googlegroups.com> <1155063757.284414.135630@n13g2000cwa.googlegroups.com> <1155064331.588367.136290@m73g2000cwd.googlegroups.com> <1155070685.953831.204500@m79g2000cwm.googlegroups.com> <1155075748.927391.326310@h48g2000cwc.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Simon Forman: > >> accessing it from a >> module (perhaps math.. math.infinity, math.epsilon, etc., just like >> math.pi and math.e.) > > It too looks acceptable. > > >> I look forward to hearing your thoughts an the subject. > > Thank you, but I am not expert enough on such topics to give you good > comments, so I keep the muzzle shut. > > Bye, > bearophile > I've been thinking along this lines as well, but with the more general question of when should a method or attribute be included in a type or class and when shouldn't it. I think that's an important question and having some clear guidelines for that will help me to write better programs in general. A few general rules I've found to be mostly true is.. (1) If a class method does not have a reference to 'self' or an attribute or other method of self. It probably should be a function instead. This is more common than you might think because class's are also used as containers to hold a collection of functions and/or values. I think its useful to keep these collections separate from "objects". It keeps the objects simpler, and the collection of functions and values clearer. The difficulty is when you mix the two together, that's when you begin to get a cluttered class that is difficult to understand. (2) If no method of a class has a reference to an attribute, then the attribute should probably not be part of the class or type. On the flip side, the inverse of these rules does not necessarily mean something should be in the class. But maybe... (3) If an value is not useful by other class's or functions. It probably should be an attribute of the class. These are just guide lines of course, but by keeping them in mind, I do think it has helped me to abstain from writing cluttered class's. Maybe there are other guidelines like these that are helpful? Cheers, Ron From justin.azoff at gmail.com Mon Aug 21 01:25:40 2006 From: justin.azoff at gmail.com (Justin Azoff) Date: 20 Aug 2006 22:25:40 -0700 Subject: trouble using "\" as a string In-Reply-To: <1156023013.462640.165970@i42g2000cwa.googlegroups.com> References: <1156023013.462640.165970@i42g2000cwa.googlegroups.com> Message-ID: <1156137940.462577.244710@74g2000cwt.googlegroups.com> OriginalBrownster wrote: > i want this because using python I am pulling in filenames from a > mac..thus they are "/" in the pathways..and i want to .split it at the > "/" to obtain the filename at the end...but its proving diffucult with > this obstacle in the way. sounds like you want import posixpath posixpath.basename(path) assuming you are on a windows box,otherwise the normal os.path.basename will do it. -- - Justin From nas at arctrix.com Wed Aug 30 22:25:31 2006 From: nas at arctrix.com (Neil Schemenauer) Date: Thu, 31 Aug 2006 02:25:31 GMT Subject: How ahead are you guys in the (Python) real world? References: <1156821234.820929.299740@p79g2000cwp.googlegroups.com> Message-ID: Aahz wrote: > My company uses 2.2 and 2.3; we hope to drop 2.2 Real Soon Now. This has been an interesting thread. There has been some discussion on python-dev about doing another 2.3 bugfix release. Based on the number of people still using 2.3, it looks to me like there would be interest. Neil From pavlovevidence at gmail.com Thu Aug 24 16:42:16 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 24 Aug 2006 13:42:16 -0700 Subject: When is a subclass not right? In-Reply-To: References: <1156387621.568779.191420@m73g2000cwd.googlegroups.com> <1156393371.550249.138930@75g2000cwc.googlegroups.com> <1156394781.155152.313080@i3g2000cwc.googlegroups.com> <44ede9b8$0$8925$88260bb3@free.teranews.com> Message-ID: <1156452136.196964.193620@i42g2000cwa.googlegroups.com> Chaz Ginger wrote: > I was writing some code that used someone else class as a subclass. He > wrote me to tell me that using his class as a subclass was incorrect. I > am wondering under what conditions, if ever, does a class using a > subclass not work. [snip] > He said I should use it this way: > > class B2: > def __init__(self,a1,a2): > self.c = a1 > self.t = A(a2) > > def bar(self) : > self.t.bar() > > Other than the obvious difference of B2 having an attribute 't', I can't > see any other obvious differences. Is there something I am missing? I think it's kind of a fine point. In my own code I've had cases where I've switched from subclass to attribute and back over the development, and vice versa. I think there are many cases where it's preferable to use an attribute, but not really wrong to subclass (and vice versa). The classical advice in choosing whether to subclass or or use attribute is whether its more an an "is a" or "has a" relationship. If it's more natural to say B is an A, then subclass. If it's more natural to say B has an A, then use an attribute. But that's only a rule of thumb. I personally find another question helpful. If it's reasonable that B could have more than one of A, regardless if it actually does, use an attribute. If it's unreasonable, subclass. Again, rule of thumb. Carl Banks From deets at nospam.web.de Wed Aug 2 07:56:46 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 02 Aug 2006 13:56:46 +0200 Subject: Datetime objects References: <1154519280.363058.224110@m73g2000cwd.googlegroups.com> Message-ID: <4jbi29F7b5s9U1@uni-berlin.de> Lad wrote: > How can I find days and minutes difference between two datetime > objects? > For example If I have > b=datetime.datetime(2006, 8, 2, 8, 57, 28, 687000) > a=datetime.datetime(2006, 8, 1, 18, 19, 45, 765000) a - b Lookup datetime.timedelta - all of this is neatly documented. Diez From justask at acme.com Sun Aug 13 16:00:22 2006 From: justask at acme.com (Vincent Delporte) Date: Sun, 13 Aug 2006 22:00:22 +0200 Subject: Compiling wxPython app for Windows; Single EXE Message-ID: Hi I browsed the archives, but since some messages date back a bit, I wanted to make sure that - py2exe is still the best tool in town to compile Python scripts to run on a Windows host that doesn't have Python installed, including wxWidgets/wxPython - there's no way to build a single EXE, to make deployment easier (if multiple files, I need to build an installer with eg. NSIS or InnoSetup)? Thank you. From pmartin at snakecard.com Sat Aug 19 10:04:31 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Sat, 19 Aug 2006 09:04:31 -0500 Subject: How to get the ascii code of Chinese characters? References: <1155986298.643983.157460@i3g2000cwc.googlegroups.com> Message-ID: Philippe Martin wrote: > many_years_after wrote: > >> Hi,everyone: >> >> Have you any ideas? >> >> Say whatever you know about this. >> >> >> thanks. > Hi, > > You mean unicode I assume: > http://www.rikai.com/library/kanjitables/kanji_codes.unicode.shtml > > Regards, > > Philippe Hi, I have received a personnal email on this: Kanji is indeed a Japanese subset of the Chinese Character set. I just thought it would be relevant as it includes ~47000 characters. If I hurt any feeling, sorry. Regards, Philippe From michiel at thingmajig.org Mon Aug 14 04:53:35 2006 From: michiel at thingmajig.org (Michiel Sikma) Date: Mon, 14 Aug 2006 10:53:35 +0200 Subject: Best IDE for Python In-Reply-To: <1155541849.350392.31190@h48g2000cwc.googlegroups.com> References: <1155541849.350392.31190@h48g2000cwc.googlegroups.com> Message-ID: <171873D4-8F7F-41D0-8984-771F8301D373@thingmajig.org> By FOS, do you mean FOSS (Free and Open Source Software)? I've never seen the acronym FOS used. I personally use Eclipse with PyDev. http://www.eclipse.org/ http://pydev.sourceforge.net/ Michiel Op 14-aug-2006, om 9:50 heeft stylecomputers at gmail.com het volgende geschreven: > Hi All, What do you find the best IDE for creating web applications in > Python is? Preferably FOS IDE. > > Cheers > > -- > http://mail.python.org/mailman/listinfo/python-list From gagsl-py at yahoo.com.ar Tue Aug 8 13:09:24 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 08 Aug 2006 14:09:24 -0300 Subject: Accessing Yahoo Mail withtout POP In-Reply-To: References: <1155050998.864753.198990@m79g2000cwm.googlegroups.com> Message-ID: <7.0.1.0.0.20060808140605.03ddc3c8@yahoo.com.ar> At Tuesday 8/8/2006 12:39, Dieter Deyke wrote: > > Is there a way to access yahoo mail via its web interface? If so, can > > someone give some pointers? www.freepops.org Very generic almost-anything-to-pop3, but it's not written in Python, uses LUA instead. Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From mail at microcorp.co.za Fri Aug 4 05:04:24 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Fri, 4 Aug 2006 11:04:24 +0200 Subject: Is there an obvious way to do this in python? References: <44d128e5$0$13484$636a55ce@news.free.fr> <1154602887.279222.37980@75g2000cwc.googlegroups.com> Message-ID: <006601c6b7b7$63914200$03000080@hendrik> From: "Bryan Olson" | H J van Rooyen wrote: | [...] | > This is broadly what I had in mind, yes - but sort of down to | a transaction | > level - this user does invoicing, this one enters cheques, | this one does credit | > notes, and their supervisor can do all three, and in a | different department its | > different because the jobs are different, but the invoicing | GUI module is the | > same for wherever its used... | | Pretty much any business has to deal with those things. You are | right about the need for transactions and authorization, and | that you don't want to have to manually update all the clients | whenever your modify the applications. Everyone has those | problems, and consequently there's a large body of experience | and conventional best practice. The highly redundant advice | you've been getting is recommending that you to do those things | that way most successful modern systems do them. | | No question what you describe calls for a DBMS. Further, this | sounds like a job for a "three tier" architecture, what Dennis | L. Bieber explained as [db-server] <-> [app-server] <-> [client]. | In the old days a three-tier system called for a large | data-processing staff; today one guy can set up a simple one in | an afternoon. | | In a three-tier system, either the database, the server | application can enforce authorization policy. In order for the | database to enforce authorization, the application creates one | database connection for each client user, and logs in as the | user. That works well for most accounting-type systems, where | all the users are known in advance. In systems such as web | shopping carts, the application typically has its own user ID, | and creates all database connections as itself. The app, not the | database, is then responsible for keeping users from reading and | altering each other's data. | | Trying to enforce authorization at the client is generally a | mistake. The user has too much control over his local machine. | He is not limited to running just the code you provide. | | | Don't get too hung up on choice of DBMS, but stick with portable | standard SQL. I bet you'll find your potential customers want it | to run against the database they already have. The particular | tables your system needs will become part of their larger | schema. | | | -- | --Bryan Thank you - this is a sane summary of the general business case, and I particularly like the bit about keeping the SQL portable - its something I did not even consider... The conventional best practice advice is swamping my original query of how to do something in Python... Just a note: If conventional best practice is followed all the time, without question - how is it ever made better? but that is probably a question for a separate thread - please ignore it here... - it has nothing to do with the Python language. - Hendrik From tim.golden at viacom-outdoor.co.uk Thu Aug 31 04:01:19 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 31 Aug 2006 09:01:19 +0100 Subject: How to avoid a warning message box when sending email via Outlook Message-ID: [Dermot Doran] | I'm very new to using win32com! I just want to send an email | message via Outlook. However, I keep getting an annoying | message box (generated by Outlook) indicating that my program | could be a virus. Does anybody know how to get around this? As far as I've ever been able to tell, you're stuck with it. Obviously, in a sense, since otherwise any would-be virus / zombie program would simply turn the option off before using Outlook to send out its emails! TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From bj_666 at gmx.net Thu Aug 3 08:53:25 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 03 Aug 2006 14:53:25 +0200 Subject: Datetime question References: <1154607991.404201.23400@p79g2000cwp.googlegroups.com> Message-ID: In <1154607991.404201.23400 at p79g2000cwp.googlegroups.com>, Lad wrote: > In a datetime object I would like to change days and hours. > Or in other words, I would like to copy this datetime object but > increase days and hours. > Is it possible? > For example:If I have a datetime object like this > datetime.datetime(2006, 8, 3, 14, 13, 56, 609000) > > I would like to make a new ,for example like this > > datetime.datetime(2006, 8, 12, 10, 13, 56, 609000) > > is it possible to do so? Yes it is, just add a `timedelta` object: In [18]: a = datetime.datetime(2006, 8, 3, 14, 13, 56, 609000) In [19]: a + datetime.timedelta(days=8, hours=20) Out[19]: datetime.datetime(2006, 8, 12, 10, 13, 56, 609000) Ciao, Marc 'BlackJack' Rintsch From fredrik at pythonware.com Fri Aug 25 06:50:11 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Aug 2006 12:50:11 +0200 Subject: M$ windows python libs installed in arbitrary directories forcustomized python distributions References: Message-ID: "alf" wrote: > It turned out it is quite simple - I just install the python from > python.org and all the libs needed. Then I take python2n.dll from > c:\win*\system32 and move directly to PYTHONDIR. Then I can just tar/zip > the PYTHON dir and distribute around so users do not have to deal with > dozen of libs and packages. > > Small difficulty is a maintenance of such "distribution". Namely when I > want install a new lib M$ installer just can not find my python > installations probably due to missing registry entries. > > Is there any way to force the actual python site-lib for M$ installers???? it's spelled "Windows installers", and code to do the necessary registry updates can be found here: http://effbot.org/zone/python-register.htm From sulsa at gazeta.pl Mon Aug 14 23:07:33 2006 From: sulsa at gazeta.pl (Sulsa) Date: Tue, 15 Aug 2006 05:07:33 +0200 Subject: How to fill a form References: <20060815034051.89ef7e18.sulsa@gazeta.pl> Message-ID: <20060815050733.10e14112.sulsa@gazeta.pl> On Tue, 15 Aug 2006 03:22:40 +0100 Steve Holden wrote: > I'd recommend you take a look at mechanize, see > > http://wwwsearch.sourceforge.net/mechanize/ > > and specifically at ClientForm, see > > http://wwwsearch.sourceforge.net/ClientForm/ > > These make it easy to perform browser-like accesses to forms-based > web applications. > I want to fill only one smiple form so i would like not to use any non standard libraries. From ilias at lazaridis.com Sun Aug 27 07:31:00 2006 From: ilias at lazaridis.com (lazaridis_com) Date: 27 Aug 2006 04:31:00 -0700 Subject: CONSTRUCT - Module Attributes and Execution Environment In-Reply-To: <1156253227.092971.36510@74g2000cwt.googlegroups.com> References: <1156253227.092971.36510@74g2000cwt.googlegroups.com> Message-ID: <1156678260.710723.76890@i3g2000cwc.googlegroups.com> lazaridis_com wrote: > I would like to change the construct: > > if __name__ == '__main__': ... Is there a standard way / naming to wrap "__name__" and other similar attributes to an encapsulating class? Something like e.g.: if mod.name ... or if gbl.name ... - "gbl.newAttribute = value" would create __newAttribute__ This should become available whereever such ____ occour. (I assume this should be implementable with e.g. metaclasses) From fredrik at pythonware.com Wed Aug 23 01:11:45 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Aug 2006 07:11:45 +0200 Subject: key not found in dictionary In-Reply-To: <87hd04xnzl.fsf@benfinney.id.au> References: <1156272596.613723.219280@h48g2000cwc.googlegroups.com> <87hd04xnzl.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > In the specific use case of wanting a default value when a dictionary > doesn't have a particular key, you can also use this: > > >>> foo = {0: "spam", 1: "eggs", 7: "beans"} > >>> for key in [1, 2, 7]: > ... desc = foo.get(key, None) usually spelled desc = foo.get(key) # returns None if not present or desc = foo.get(key, default) if you want something other than None. From searyan at gmail.com Tue Aug 1 09:46:30 2006 From: searyan at gmail.com (Sean Ryan) Date: Tue, 1 Aug 2006 14:46:30 +0100 Subject: Python Embedding Questions Message-ID: <357b87b40608010646kad09a3bn2ff64e1674d481b0@mail.gmail.com> Hi Guys, I have a couple of questions (and some concerns) about embedded python within my application. The application is a multi-threaded relatively complex c++ middleware Solaris 9 based application. A decision was made some time ago to provide some scripting capabilities and python was selected as the scripting language. As such, an interpreter was embedded within the application and threading was managed using PyEval_SaveThread, PyEval_RestoreThread and friends. The application switches between python and c++ many, many times during the execution of one business request - typically the flow will be c++ -> python -> c++ -> python -> c++ -> python etc (roughly 60 - 40 split in terms of coverage) Originally python2.2.1 was embedded within the application - we now have a business case (performance being a primary driver) to move to python2.4(.2). We are having some stability issues (random core dumps), and in an attempt to track down the root cause I executed some stress tests under a purify environment and noticed the following : Python2.4.2 trips quite a few ABR (array bounds read) and FMR (free memory read) violations - python2.2.1 less so. purify notes the following as the innermost frames for a FMR. frame_dealloc [frameobject.c:76] PyEval_EvalCodeEx [ceval.c:2596] fast_function [ceval.c:3161] Is this a known issue with embedded python? I can trigger a similar crash with python 2.2.1 in a stress test environment. At this stage, I am getting very concerned about our implementation of embedded python and wondered : 1. Is our use of python as an embedded language commonplace? 2. Does anyone have names of commerical applications that use python in this way 3. Are we switching between python and c++ code too frequently (as many as 40 times in the execution of 1 request) 4. Are there any consultants / contractors that we could engage to aid debugging our application / implementation. 5. Are the warnings that purify is raising related to loss of stability in the application 6. Is python the correct choice for an embedded application (I am aware of the GIL issue) We need to make a concise decision very quickly regarding our use of python, and as such would appreciate the community's honest opinion. Best regards, Sean -------------- next part -------------- An HTML attachment was scrubbed... URL: From st at tobiah.org Wed Aug 30 18:04:02 2006 From: st at tobiah.org (tobiah) Date: Wed, 30 Aug 2006 15:04:02 -0700 Subject: csv module strangeness. In-Reply-To: References: <44f5e870$0$8814$88260bb3@free.teranews.com> <44f5f347$0$8846$88260bb3@free.teranews.com> Message-ID: <44f5fe32$0$8835$88260bb3@free.teranews.com> >>>> for row in csv.reader(instream, delimiter="\t"): Awesome. Thanks. -- Posted via a free Usenet account from http://www.teranews.com From blue99 at interia.pl Tue Aug 29 06:47:16 2006 From: blue99 at interia.pl (Rob Wolfe) Date: 29 Aug 2006 03:47:16 -0700 Subject: NEED HELP In-Reply-To: <1156818170.279428.312250@h48g2000cwc.googlegroups.com> References: <1156818170.279428.312250@h48g2000cwc.googlegroups.com> Message-ID: <1156848436.486206.80120@m79g2000cwm.googlegroups.com> mailme.grover at gmail.com wrote: > Below is my code, which is kind of virtual and with its help ill use it > in my main project. > Now what i am looking for is can anybody write all the code inside a > class...so that I can reuse it. I am kind of novice...n kind of stuc > with that. > > from Tkinter import * > > root = Tk() > > w = Label(root, text="Right-click to display menu", width=40, > height=20) > w.pack() > > # create a menu > popup = Menu(root, tearoff=0) > popup.add_radiobutton(label="SourceIP", command= hello) # , > command=next) etc... > popup.add_radiobutton(label="DestIP", command= hello) > popup.add_radiobutton(label="Reporter'sIP", command= hello) > popup.add_radiobutton(label="Observer'sIP", command= hello) > popup.add_separator() > popup.add_radiobutton(label="Home") > > def do_popup(event): > # display the popup menu > try: > popup.post(event.x_root, event.y_root) > finally: > # make sure to release the grab (Tk 8.0a1 only) > popup.grab_release() > def hello(event= None): > print "hello" > > w.bind("", do_popup) > > b = Button(root, text="Quit", command=root.destroy) > b.pack() > > mainloop() Here's a great tutorial: http://www.effbot.org/tkinterbook/tkinter-hello-again.htm HTH, Rob From 3wheels at gmail.com Mon Aug 14 18:04:41 2006 From: 3wheels at gmail.com (Tryker) Date: 14 Aug 2006 15:04:41 -0700 Subject: Best IDE for Python In-Reply-To: <1155541849.350392.31190@h48g2000cwc.googlegroups.com> References: <1155541849.350392.31190@h48g2000cwc.googlegroups.com> Message-ID: <1155593080.976094.33460@m79g2000cwm.googlegroups.com> Gotta love PyScripter. Light, easy to use, free. http://mmm-experts.com/Products.aspx?ProductID=4 stylecomputers at gmail.com wrote: > Hi All, What do you find the best IDE for creating web applications in > Python is? Preferably FOS IDE. > > Cheers From g.brandl at gmx.net Sun Aug 27 12:30:10 2006 From: g.brandl at gmx.net (Georg Brandl) Date: Sun, 27 Aug 2006 18:30:10 +0200 Subject: Weekly Python Patch/Bug Summary In-Reply-To: References: <200608270327.k7R3RNcT027925@bayview.thirdcreek.com> Message-ID: Fredrik Lundh wrote: > Kurt B. Kaiser wrote: > >> Patch / Bug Summary >> ___________________ >> >> Patches : 407 open ( +3) / 3393 closed (+17) / 3800 total (+20) >> Bugs : 888 open (+28) / 6145 closed (+14) / 7033 total (+42) >> RFE : 232 open ( +3) / 236 closed ( +1) / 468 total ( +4) > > could this script perhaps be modified to filter out Python 3000 stuff, > at least for the edition sent to python-dev ? Good idea, but I'd wait until we have the new tracker running. Georg From h112211 at gmail.com Sun Aug 20 04:52:15 2006 From: h112211 at gmail.com (h112211 at gmail.com) Date: 20 Aug 2006 01:52:15 -0700 Subject: PIL problem: IOError: cannot identify image file Message-ID: <1156063935.533140.18950@p79g2000cwp.googlegroups.com> Hi, I installed the newest available PIL (1.1.5 for Python 2.4) from their site, but cannot seem to open any files. The following from PIL import Image i = Image.open(file('c:\\image2.png')) results in File "C:\Program Files\Python24\lib\site-packages\PIL\Image.py", line 1745, in open raise IOError("cannot identify image file") IOError: cannot identify image file for any graphics file I've tried. Anyone know what's wrong? From sdistefano at gmail.com Sat Aug 26 23:01:40 2006 From: sdistefano at gmail.com (sdistefano at gmail.com) Date: 26 Aug 2006 20:01:40 -0700 Subject: about daemons and IPC Message-ID: <1156647700.097018.67040@m73g2000cwd.googlegroups.com> Hey people! For the first time I'm doing a client/server application, and I'm really confused with IPC stuff. I read the fastest method is shared memory, but I tryed mmap and found it tedious for the amount of data I'm handling (which is 30K at most, but mmap seems to get tedious for anything bigger than a boolean... am I missing something?) Then I found many solutions for forked processes (like posh), but that's not what I need right now. Any suggestions? From tom at nextstate.net Mon Aug 14 23:57:54 2006 From: tom at nextstate.net (Tom Brown) Date: Mon, 14 Aug 2006 20:57:54 -0700 Subject: How to fill a form In-Reply-To: <20060815054343.1c31f3f7.sulsa@gazeta.pl> References: <20060815034051.89ef7e18.sulsa@gazeta.pl> <12e2gau4jouhmcf@corp.supernews.com> <20060815054343.1c31f3f7.sulsa@gazeta.pl> Message-ID: <200608142057.55100.tom@nextstate.net> On Monday 14 August 2006 20:43, Sulsa wrote: > On Tue, 15 Aug 2006 03:37:02 -0000 > > Grant Edwards wrote: > > On 2006-08-15, Sulsa wrote: > > > I want to fill only one smiple form so i would like not to use > > > any non standard libraries. > > > > Then just send the HTTP "POST" request containing the fields > > and data you want to submit. > > but i don't know how to post these data if i knew there there would > be no topic. When I need to learn the POST method for a form, I use wireshark (www.wireshark.org) to capture the POST I do manually the first time. However, I think I'm going to look into mechanize/clientform now that I know about it. Hope this helps, Tom From esj at harvee.org Mon Aug 21 16:57:37 2006 From: esj at harvee.org (Eric S. Johansson) Date: Mon, 21 Aug 2006 16:57:37 -0400 Subject: What do you want in a new web framework? In-Reply-To: <1156183574.781794.11340@p79g2000cwp.googlegroups.com> References: <1156100331.329889.216340@p79g2000cwp.googlegroups.com> <1156156636.515678.118210@75g2000cwc.googlegroups.com> <1156173509.767030.255710@b28g2000cwb.googlegroups.com> <1156183574.781794.11340@p79g2000cwp.googlegroups.com> Message-ID: <44EA1E41.6000002@harvee.org> UrsusMaximus at gmail.com wrote: > hardemr wrote: > >> I've just read all of the answers. Most of yours said that there are >> many web frameworks ,so it is nonsense to make a new web framework in >> python. > > Hardemr, I like Ajacksu's answer, with a twist. Please concnentrate on > writing a Visual Studio-like gui designer, and make it possible to add > your Visual Studio like gui designer to Django (and TurboGears, et al). it only make sense if you are disabled (visual or upper limb). most if not all web frameworks are "no cripples need apply". why? mixed caps, mixed modes (i.e. html+python), crappy editors to start. these few items have such a *huge* impact that it can mean the difference between being able to do the job or not. if you want to make a diff, make an IDE that works for the blind and the mobility impaired. the work has been started but it needs labor (see voicecoder project). second place to make a difference is to build a bridge between windows and gnome at-spi so one can speak (NaturallySpeaking on windows) then have the effect show up on linux. but in the context of web frameworks, my hp friendly framework shows how easy it is to make apps HP friendly. the framework is rtg except for packaging (and some docs). (I'm having problems trying to understand and speak the setup file at the same time.) If you want specific examples handicap barriers, I'll tell you after my new mic arrives and my hands stop hurting so much. my cost: this message means 30-40 min timeout for the nerves to cool off. --- eric From http Tue Aug 15 16:22:57 2006 From: http (Paul Rubin) Date: 15 Aug 2006 13:22:57 -0700 Subject: X windows and Python? References: <7xy7tpyhbf.fsf_-_@ruckus.brouhaha.com> <1155667686.196587.94250@p79g2000cwp.googlegroups.com> <1155668046.277321.27570@i3g2000cwc.googlegroups.com> Message-ID: <7xac65ycim.fsf@ruckus.brouhaha.com> "David Boddie" writes: > The usual follow-up to "fix" Google's "formatting". Maybe this does > what you need: > > http://python-xlib.sourceforge.net/ Thanks, wow, a complete xlib implementation in Python, so I'd get to do low-level X programming and implement the stuff Grant Edwards described. I hope I can avoid that. What I'm doing right now is writing the stuff out to a file and loading it into OpenOffice, then selecting the contents there and copying it the cut buffer. Blecccch. From metaperl at gmail.com Thu Aug 24 19:01:23 2006 From: metaperl at gmail.com (metaperl) Date: 24 Aug 2006 16:01:23 -0700 Subject: OS X and Python - what is your install strategy? Message-ID: <1156460483.616400.120160@i3g2000cwc.googlegroups.com> I'm about to get a new OS X box on which I will rewrite a bunch of data munging scripts from Perl to Python. I know that there are several port services for OS X (fink, darwin ports, opendarwin). So I am not sure whether to use their port of Python or whether to build from scratch or use the Python image file. Also ActivePython is something of a choice but for some reason not a front-running one for me. I tend to like Gentoo-style compile from source over pre-bundled all-in-one solutions like ActivePython. I'm not going to do much other than maybe install Plone and do some XML and CSV processing. Most everything I need is in the Python stdlib. Maybe down the road some graphics and web stuff (I like Clever Harold or Pylons for that... but I still ahve not examined the 900 other web app options in Python :) From outstretchedarm at hotmail.com Fri Aug 11 10:04:54 2006 From: outstretchedarm at hotmail.com (Omar) Date: 11 Aug 2006 07:04:54 -0700 Subject: some n00b question Message-ID: <1155305094.295652.218220@i3g2000cwc.googlegroups.com> I'm learning how to program python. a few questions a) I'm mostly interested in creating exe's that have to do with music -- things to help me keep track of chord progressions, transpositions, etc. can anyone point me in the direction of resources on this? b) I'm also interested in created GUI's sooner rather than later. Can anyone point me to a fast track to doing GUI's on python? thanks From tim.golden at viacom-outdoor.co.uk Fri Aug 11 04:23:01 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 11 Aug 2006 09:23:01 +0100 Subject: sys.platform documentation? Message-ID: [Michiel Sikma] | So if you run this script: | -- | import platform | platform.platform() | platform.uname() | -- | You will get all the information that is necessary. And then | you just | need to provide it with a human-determined name of the operating | system you're using. If you're interested: >>> platform.platform() 'Windows-XP-5.1.2600-SP2' >>> platform.uname() ('Windows', 'VOGBP350', 'XP', '5.1.2600', '', '') >>> TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From spam at me.please Wed Aug 30 11:58:40 2006 From: spam at me.please (Skink) Date: Wed, 30 Aug 2006 17:58:40 +0200 Subject: models & editors in PyQt4 In-Reply-To: <1156952123.240684.35350@i3g2000cwc.googlegroups.com> References: <1156952123.240684.35350@i3g2000cwc.googlegroups.com> Message-ID: David Boddie wrote: > > It should be OK - it shouldn't crash, anyway. It depends on the view > doing the right thing when it finds that it hasn't received an editor > widget. > > You could create an empty placeholder widget in the createEditor() > method, call QColorDialog.getColor() with the existing color from the > model in setEditorData(), record the color returned by the dialog in > some internal instance variable, and finally set the data in the model > when setModelData() is called: > > class ColorProperty(Property): > ... > def createEditor(self, parent, option, index): > return QtGui.QWidget(parent) > def setEditorData(self, editor, index): > self.color = QtGui.QColorDialog.getColor( > index.model().getObjectData(self.name())) > def setModelData(self, editor, model, index): > if self.color.isValid(): > index.model().setObjectData(self.name(), self.color) thanks for tip, i'll check it how it works. > ... > > I find it strange that you have to triple-click to edit any of the > items in your example. Do you see the same behaviour? oh, this is default Qt behavoiur: first click selects row, second select editor (for ColorProperty, IntProperty & StringProperty you can now change the value) but third click is required only for properties w/ QCombobox editor (EnumProperty & BooleanProperty) ... skink > > David > From rafal at ewipo.pl Sat Aug 19 06:47:46 2006 From: rafal at ewipo.pl (=?ISO-8859-2?Q?=22Rafa=B3_Janas=22?=) Date: Sat, 19 Aug 2006 12:47:46 +0200 Subject: sending values over classes Message-ID: <204988311944e6ec52e031c5.57296123.Active.mail@poczta.nazwa.pl> Hi, How to read/write value over different classes (in different files) Something like global values? Thanks Rafa? From anthra.norell at tiscalinet.ch Tue Aug 22 05:57:47 2006 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Tue, 22 Aug 2006 11:57:47 +0200 Subject: Regular Expression question References: <1156153916.849933.178790@75g2000cwc.googlegroups.com> <1156196158.321416.244700@b28g2000cwb.googlegroups.com> Message-ID: <008b01c6c5d1$6d1b9a00$0201a8c0@mcuf7> Steve, I thought Fredrik Lundh's proposal was perfect. Are you now saying it doesn't solve your problem because your description of the problem was incomplete? If so, could you post a worst case piece of htm, one that contains all possible complications, or a collection of different cases all of which you need to handle? Frederic ----- Original Message ----- From: Newsgroups: comp.lang.python To: Sent: Monday, August 21, 2006 11:35 PM Subject: Re: Regular Expression question > Hi, thanks everyone for the information! Still going through it :) > > The reason I did not match on tag2 in my original expression (and I > apologize because I should have mentioned this before) is that other > tags could also have an attribute with the value of "adj__" and the > attribute name may not be the same for the other tags. The only thing I > can be sure of is that the value will begin with "adj__". > > I need to match the "adj__" value with the closest preceding tag1 > irrespective of what tag the "adj__" is in, or what the attribute > holding it is called, or the order of the attributes (there may be > others). This data will be inside an html page and so there will be > plenty of html tags in the middle all of which I need to ignore. > > Thanks very much! > Steve > > -- > http://mail.python.org/mailman/listinfo/python-list From hadeshuang at gmail.com Fri Aug 25 15:22:48 2006 From: hadeshuang at gmail.com (Pebblestone) Date: 25 Aug 2006 12:22:48 -0700 Subject: Python and STL efficiency References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> Message-ID: <1156533768.283454.48570@m73g2000cwd.googlegroups.com> I tested in Common Lisp and compared the result with python. My PC is: 3.6GH Pentium4 My OS is: Ubuntu 6.06 i386 My lisp implementation is SBCL 0.9.8 for i386 My python's version is: V2.4.3 Both implementations were installed via apt-get install. Here's my Lisp program: ++++++++++++++++++++++++++++++++++++++++++++++++++ ;;; from slow to fast implementation (proclaim '(optimize (speed 3) (debug 0) (safety 0) (space 0))) (defun test1 () (let ((a (make-array 0 :adjustable t :fill-pointer 0)) (b nil)) (dotimes (i 1000000) (progn (vector-push-extend "What do you know" a) (vector-push-extend "so long ..." a) (vector-push-extend "chicken crosses road" a) (vector-push-extend "fool" a))) (setf b (remove-duplicates a :test #'string-equal)) (map 'vector #'print b))) (defun test2 () (let ((a (make-array 0 :adjustable t :fill-pointer 0)) (b nil)) (dotimes (i 1000000) (progn (vector-push-extend "What do you know" a) (vector-push-extend "so long ..." a) (vector-push-extend "chicken crosses road" a) (vector-push-extend "fool" a))) (setf b (remove-duplicates a :test #'eq)) (map 'vector #'print b))) (defun test3 () (let ((a (make-array 4000000 :element-type 'string :adjustable nil :fill-pointer 0)) (b nil)) (dotimes (i 1000000) (progn (vector-push "What do you know" a) (vector-push "so long ..." a) (vector-push "chicken crosses road" a) (vector-push "fool" a))) (setf b (remove-duplicates a)) (map 'vector #'print b))) (defun test4 () (let ((a (make-array 4000000 :element-type 'string :adjustable nil)) (b nil)) (dotimes (i 1000000) (progn (let ((j (1- (* 4 i)))) (setf (aref a (incf j)) "What do you know") (setf (aref a (incf j)) "so long ...") (setf (aref a (incf j)) "chicken crosses road") (setf (aref a (incf j)) "fool")))) (setf b (remove-duplicates a)) (map 'vector #'print b))) +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1. When using string equal comparator (test #1), the speed slows down dramatically. 1.93 -> 9.35 2. It seems that append(vector-push) in lisp costs much more than direct access via index. Here's my benchmark result: +++++++++++++++++++++++++++++++++++++++++++++++++++++++ #1 (time (test1)) "What do you know" "so long ..." "chicken crosses road" "fool" Evaluation took: 9.346 seconds of real time 9.020564 seconds of user run time 0.328021 seconds of system run time 0 page faults and 457,565,688 bytes consed. #2 (time (test2)) "What do you know" "so long ..." "chicken crosses road" "fool" Evaluation took: 1.931 seconds of real time 1.884118 seconds of user run time 0.048003 seconds of system run time 0 page faults and 49,561,312 bytes consed. #3 (time (test3)) "What do you know" "so long ..." "chicken crosses road" "fool" Evaluation took: 1.721 seconds of real time 1.704107 seconds of user run time 0.016001 seconds of system run time 0 page faults and 32,012,040 bytes consed. #4 (time (test4)) "What do you know" "so long ..." "chicken crosses road" "fool" Evaluation took: 0.843 seconds of real time 0.824051 seconds of user run time 0.020001 seconds of system run time 0 page faults and 32,012,040 bytes consed. +++++++++++++++++++++++++++++++++++++++++++++++++++ Here's my python's code: ef f(): a = [] for i in range(1000000): a.append('What do you know') a.append('so long...') a.append('chicken crosses road') a.append('fool') b = set(a) for s in b: print s import time from time import clock f_start = clock() f() f_end = clock() print "Elapsed: %f seconds" % (f_end - f_start) And benchmark result: python -O test.py so long... What do you know fool chicken crosses road Elapsed: 1.260000 seconds Oops, Python beat native-compiled lisp code. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Any way, MY CONCLUSION is: C++ is not the right model for symbolic computation. From rogue_pedro at yahoo.com Mon Aug 28 00:29:14 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 27 Aug 2006 21:29:14 -0700 Subject: Newbie Question. Class definitions on the fly. References: <1156728767.854606.180190@p79g2000cwp.googlegroups.com> Message-ID: <1156739354.099172.158310@m73g2000cwd.googlegroups.com> ishtar2020 wrote: > Hi everyone > > I'm sure this question is kinda stupid and has been answered a few > times before... but I need your help! > > I'm writing a small application where the user can analyze some text > based on a set of changing conditions , and right now I'm stuck on a > point where I'd like to automatically generate new classes that operate > based on those user-defined conditions. > > Is there a way in python to define a class in runtime? For instance, > can I define a class which extends another(that I have previously > defined in some module) , create some instance completely on the fly > and then add/redefine methods to it? > > If affirmative, I've thought of a problem I would maybe have to face: > as the class has been defined by direct input to the python > interpreter, I could only create instances of it on the same session I > entered the definition(because it's not on a module I can load on > future uses) but not afterwards. Is there a way to keep that code? > > Even more newbie paranoia: what would happen if I make that 'on the > fly" object persist via pickle? Where would Python find the code to > handle it once unpickled on another session (once again, i take that no > code with the definition of that instance would exist, as it was never > stored on a module). > > Hope it wasn't too ridiculous an idea. > > Thank you for your time, guys. It's not ridiculous at all. The easiest way to do what you want would be to build a string containing your new class and then run it with the exec statement: |>> s = 'class foo: pass' |>> exec s |>> foo If you want to keep your new class around between runs of your script (and if you want to make it pickle-able) then you should write your strings to a .py file (be sure to include an import statement to import the classes you're subclassing) and import that file. If you do that and are going to modify the class(es) during a single session, be sure to call reload() on your new (modified) file (rather than just importing it again) otherwise you won't get the changes. See http://docs.python.org/ref/exec.html for the exec statement and http://docs.python.org/lib/built-in-funcs.html#l2h-59 for the reload() function. Peace, ~Simon From tjreedy at udel.edu Tue Aug 15 10:37:46 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 15 Aug 2006 10:37:46 -0400 Subject: Reference Variables In Python Like Those In PHP References: <1155651471.605912.46640@m73g2000cwd.googlegroups.com> Message-ID: "Chaos" wrote in message news:1155651471.605912.46640 at m73g2000cwd.googlegroups.com... > Is It possible to have reference variables like in PHP > $x = 1; > $y =& $x; > $y += 1; > echo $x; > echo "\n" > echo $y; > ?> > > This would show > 2 > 2 > Is this available in python? No, in the literal meaning of your question. But.. 1. The concept 'reference variable' pertains to PHP's object model, which is different from Python's. 2. They are means, not ends. So a possibly more useful question would be along the lines of "In PHP, I do this with a reference variable. How can I accomplish the same goal in Python?" Terry Jan Reedy From tim.leslie at gmail.com Wed Aug 16 03:47:04 2006 From: tim.leslie at gmail.com (Tim Leslie) Date: Wed, 16 Aug 2006 17:47:04 +1000 Subject: round not rounding to 0 places In-Reply-To: <1155712764.516132.251800@m73g2000cwd.googlegroups.com> References: <1155712764.516132.251800@m73g2000cwd.googlegroups.com> Message-ID: On 16 Aug 2006 00:19:24 -0700, Fuzzydave wrote: > I have been using a round command in a few places to round > a value to zero decimal places using the following format, > > round('+value+', 0) > > but this consistantly returns the rounded result of the value > to one decimal place with a zero > > EG: > > 4.97 is returned as 5.0 when i want it returned as 5, does > anyone know why this is and if i can get the round to make > the value 5? round returns a float. You probably want to convert it to an int. >>> int(round(4.97)) 5 Cheers, Tim > > David P > > -- > http://mail.python.org/mailman/listinfo/python-list > From bj_666 at gmx.net Wed Aug 2 13:50:36 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 02 Aug 2006 19:50:36 +0200 Subject: Pickle vs XML for file I/O References: <1154391849.335723.94480@s13g2000cwa.googlegroups.com> <1154392539.551356.70870@i3g2000cwc.googlegroups.com> <1154451307.232785.282080@m79g2000cwm.googlegroups.com> <1154539264.728714.247000@h48g2000cwc.googlegroups.com> Message-ID: In <1154539264.728714.247000 at h48g2000cwc.googlegroups.com>, crystalattice wrote: > One other question though (hope it doesn't sound silly/stupid). Your > suggestion to "pickle a party" using a list has me thinking: can a > list store class instances? Yes of course you can store class instances in lists. > For example, if I wanted to store a party of characters, rather than > pickling each person separately could I put each character instance in > a list then pickle the list? Like this: > > char1 = Character() > char2 = Character() > char3 = Character() > party = [char1, char2, char3] > file = open("partyfile.dat", "w") > pickle.dump(party, file) Yes that would work. Ciao, Marc 'BlackJack' Rintsch From slawomir.nowaczyk.847 at student.lu.se Sun Aug 6 05:41:20 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Sun, 06 Aug 2006 11:41:20 +0200 Subject: regex question In-Reply-To: <1154728534.277367.157560@p79g2000cwp.googlegroups.com> References: <1154728534.277367.157560@p79g2000cwp.googlegroups.com> Message-ID: <20060806111742.EEAD.SLAWOMIR.NOWACZYK.847@student.lu.se> On Fri, 04 Aug 2006 14:55:34 -0700 John Machin wrote: #> > def test(data): #> > format, index = 'abcd', 0 #> > for c in data: #> > i = format.index(c) #> > if i > index+1: #> > return False #> > index = i #> > return index==format.index('d') #> > #> > Could be made faster if format was made a dictionary or if one wanted #> > to compare characters directly. Writing (and profiling) left as an #> > exercise for a reader. #> #> Premature optimisation .... #> #> #>>> test('bcd') #> True #> #>>> Oooops... You are right. Should be format, index = 'abcd', -1 of course. Thanks. -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) I believe that math illiteracy affects 7 out of every 5 people. From snmishra at XXXhotYYYpop.com Fri Aug 4 21:19:26 2006 From: snmishra at XXXhotYYYpop.com (Satya) Date: Fri, 04 Aug 2006 19:19:26 -0600 Subject: MVC for wxWidgets or Tkinter? References: <1154735585.120218.243640@i3g2000cwc.googlegroups.com> Message-ID: <44d3e4e7$0$14009$88260bb3@free.teranews.com> samuraisam wrote: > Are there any MVC-framework-like libraries for wxWidgets or Tkinter for > Python? If so, any experiences with using them? I need to develop a > desktop application *fast* and experiences with the likes of Turbogears > have taught me that you can indeed develop very fast with a framework > and the MVC structure seems to work very well. I haven't used it personally, but Envisage from Enthought is supposed to be one. Satya -- Posted via a free Usenet account from http://www.teranews.com From pmartin at snakecard.com Tue Aug 22 15:14:05 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Tue, 22 Aug 2006 14:14:05 -0500 Subject: key not found in dictionary References: <1156272596.613723.219280@h48g2000cwc.googlegroups.com> Message-ID: KraftDiner wrote: > I have a dictionary and sometime the lookup fails... > it seems to raise an exception when this happens. > What should I do to fix/catch this problem? > > desc = self.numericDict[k][2] > KeyError: 589824 <---- This is the error that is being produced, > because there is no key > 589824. If you agree that the key is not there, then just catch the exception (try ... except) Philippe From rxrx at yamama.com Sun Aug 13 15:53:12 2006 From: rxrx at yamama.com (Butternut Squash) Date: Sun, 13 Aug 2006 19:53:12 GMT Subject: open() and Arabic language References: <1155492625.573013.78440@74g2000cwt.googlegroups.com> Message-ID: MaaSTaaR wrote: > Hello ... > > firstly , sorry for my bad English . > > i have problem with open() function when i use it with file which name > in Arabic , the open() will not find the file , and i am sure the file > is exist . > > > so how i can solve this problem ? probably a unicode problem. Good luck. From shane at hathawaymix.org Thu Aug 3 12:39:19 2006 From: shane at hathawaymix.org (Shane Hathaway) Date: Thu, 03 Aug 2006 10:39:19 -0600 Subject: Finding the name of a class In-Reply-To: References: <44cf7538$0$29435$626a54ce@news.free.fr> Message-ID: <44D226B7.2050905@hathawaymix.org> John Salerno wrote: > Shane Hathaway wrote: > >> Don't forget to file a bug. > > I'm reluctant to call it a bug just yet. Here's more stuff below. > There's obviously a difference between old- and new-style classes. It > seems that as far as new-style is concerned, __name__ is an attribute of > __class__ (along with a bunch of other stuff), but not of Foo itself. I'm not sure what you're saying. The class of a class is the 'type' builtin, unless metaclasses are involved. So your expression "dir(Foo.__class__)" is equivalent to "dir(type)", and the 'type' builtin happens to have a __name__ attribute that dir() notices. Take a look: >>> class Foo(object): ... pass ... >>> Foo.__class__ is type True >>> Foo.__name__ 'Foo' >>> Foo.__class__.__name__ 'type' The bug is that the expression "dir(someclass)", where the class is a user-defined class of either new or old style, never reveals to the user that the class object has a __name__ attribute. I tested this with Python versions 2.3 through 2.5b1. This is an education issue; since that important attribute is not in the list, newcomers are not likely to discover it, and may instead use strange incantations to get the name of a class. Do you want me to file the bug? Shane From alfargnoli at yahoo.com Tue Aug 1 11:04:02 2006 From: alfargnoli at yahoo.com (Al in Dallas) Date: 1 Aug 2006 08:04:02 -0700 Subject: Working with Widget after Instance loses the reference References: <1154369736.280787.260900@i3g2000cwc.googlegroups.com> Message-ID: <1154444642.138493.237600@75g2000cwc.googlegroups.com> John McMonagle wrote: > On Mon, 2006-07-31 at 11:15 -0700, Al in Dallas wrote: [example of "losing" a widget] > Consider the following code run in the python shell: > > >>> from Tkinter import * > >>> r = Tk() > >>> b1 = Button(r, text='test') > >>> b1.pack() > >>> b2 = Button(r, text='test2') > >>> b2.pack() > >>> r.children > {'-1210160564': , '-1210225748': > } > >>> r.slaves() > [, 0xb7de6a4c>] > >>> b1 = 'xxx' > >>> b1.destroy() > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'str' object has no attribute 'destroy' > >>> b1 = r.slaves()[0] > >>> b1.destroy() > >>> > > > So, as long as you know what your widget instance is in root.slaves() or > root.children you can assign it to a new name. Since I've been leaving my shell open, I jumped in and tried: recoveredlabel = root.slaves()[6] And after I verified I could manipulate the widget with that name, I executed: = recoveredlabel Now the only difference between where I was (before I screwed up) and where I am is that I've got this extra variable named "recoveredlabel." Thanks. Now, do you have any advice on learning the syntax for dealing with Tix megawidgets in Python? I guess my alternative is to learn how to use Elmer or SWIG so I can hide all the Python I've inherited "under the hood" and write my GUI in Tcl/Tk. From tod at uchicago.edu Wed Aug 9 07:44:50 2006 From: tod at uchicago.edu (Tod Olson) Date: Wed, 09 Aug 2006 06:44:50 -0500 Subject: import logging fails on MacPython 2.4.3 In-Reply-To: <4jtijgF9g8m2U1@uni-berlin.de> References: <4jtijgF9g8m2U1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Tod Olson schrieb: >> Anyone have advice for importing the logging module using MacPython >> 2.4.3? >> >> MacPython installs the logging module in: >> >> /Library/Frameworks/Python.framework/Versions/2.4/lib/logging/ > > On my machine, that is > /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/logging That's good to hear, as it agrees with the other Python installations I've examined. That locations makes much more sense than where it landed on my machine. >> There's an __init__.py there and everything, but this directory is not >> in sys.path. I add it to sys.path as follows: >> >> >>> sys.path.append(os.path.join(sys.prefix, 'lib', 'logging')) >> >>> print sys.path[-1] >> /Library/Frameworks/Python.framework/Versions/2.4/lib/logging > > > Which is wrong - you'd have to add the path without the logging part! Great, thanks! -Tod From outstretchedarm at hotmail.com Fri Aug 11 11:18:51 2006 From: outstretchedarm at hotmail.com (Omar) Date: 11 Aug 2006 08:18:51 -0700 Subject: some n00b question In-Reply-To: References: <1155305094.295652.218220@i3g2000cwc.googlegroups.com> Message-ID: <1155309531.616503.9360@i3g2000cwc.googlegroups.com> John Salerno wrote: > Omar wrote: > > > b) I'm also interested in created GUI's sooner rather than later. Can > > anyone point me to a fast track to doing GUI's on python? > > I recommend reading wxPython in Action. It's a great starter and > reference to the wxPython GUI toolkit. Tkinter is usually considered > easier and simpler, but I find it lacking in functionality, and wxPython > is actually fairly easy to learn. thanks, John anyone on the music side? From fuzzyman at gmail.com Tue Aug 29 05:17:06 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 29 Aug 2006 02:17:06 -0700 Subject: How ahead are you guys in the (Python) real world? In-Reply-To: <1156821234.820929.299740@p79g2000cwp.googlegroups.com> References: <1156821234.820929.299740@p79g2000cwp.googlegroups.com> Message-ID: <1156843026.272988.78410@75g2000cwc.googlegroups.com> Ray wrote: > Since I haven't used Python at work, I am using Python 2.5 right now. > However I wonder, how fast are you guys moving from version to version > at work? As an illustration my ex-company just moved to Java 5, which > was released around... what, 2-3 years ago? (While I am running Java 6 > at home) > > Is it the same in the Python world? What version of Python is used in, > say, Google? Is it even 2.4 yet? I'm lucky in that the company I work for are developing with IronPython. That means I get to use Python 2.4. I'm appreciating the joy of sets and decorators. :-) I doubt we will move to 2.5 until that is the standard stable version of IronPython. For most of my own projects I try to maintain compatibility with 2.3, as it is still very common. For CGI stuff I try to remain 2.2 compatible, because that is the default version of Python on many web-hosts (and Linux distros). Fuzzyman http://www.voidspace.org.uk/python/index.shtml From david_wahler at bic.ky Sun Aug 20 01:21:43 2006 From: david_wahler at bic.ky (david_wahler at bic.ky) Date: 20 Aug 2006 00:21:43 -0500 Subject: =?utf-8?Q?Re:_[ANN]_ratfun=2D2.3__Polynomials_and_Rational_Functions?= Message-ID: <20060820052143.11159.qmail@BICSRV1011.bic.ky> I'll be out of the office until approximately August 20th. If you have any questions, please email support at bic.ky. -- David Wahler From claudio.grondi at freenet.de Mon Aug 28 11:38:24 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Mon, 28 Aug 2006 17:38:24 +0200 Subject: time.clock() going backwards?? In-Reply-To: References: Message-ID: Rob Williscroft wrote: > Claudio Grondi wrote in news:ecu546$sn9$1 at newsreader2.netcologne.de in > gmane.comp.python.general: > > >>Tim Roberts wrote: >> >>>"Tim Peters" wrote: > > >>>It is much simpler than that. With a multiprocessor HAL, including >>>on a dual-core or hyperthreaded system, QueryPerformanceCounter >>>returns the raw cycle counter (RDTSC). However, on Windows XP, the >>>operating system does not synchronize the cycle counters on multiple >>>processors, and they can be actually be millions of cycles apart. >>> >>>This was a change from previous systems. On NT4 and Win2000, the >>>operating actually rewrote the cycle counters on the second (and >>>beyond) processors to align them to the first processor, so the delta >>>was usually only a dozen or two cycles. XP does not appear to do >>>that. I think that is a huge mistake, since it renders >>>QueryPerformanceCounter non-monotonic. >> >>How does it come, that processors on same mainboard run at different >>speeds? Do they have separate clock-pulse generators? > > > I don't see any claim above that they run at different speeds, only > that the counters are several million cycles apart, IOW running at the > same speed but with different initial values, or more likely starting > at different times. > > For processors that run at (say) 2GHz, several million (say 10 million) > represents a difference of 10e6/2e9 = 0.005 seconds between when the > processors were sufficiently powered up to start counting cycles. > > Rob. If it were so, than why can't the delta of time between the processors be set to exact zero? I assume, that it is known how many cycles adjusting the value will take, so it could be done exactly ... hmmm ... Claudio Grondi From johnjsal at NOSPAMgmail.com Wed Aug 2 10:07:43 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 02 Aug 2006 14:07:43 GMT Subject: Windows vs. Linux In-Reply-To: References: <1154301694.445639.99580@m79g2000cwm.googlegroups.com> <44cddfb3$0$7761$7a628cd7@news.club-internet.fr> Message-ID: Gerhard Fiedler wrote: > A design choice is not necessarily a > bad choice just because it turns out that some 30 years later there is a > similar common product whose creators made a different choice, and now > programmers have to cater to both. To be fair, this isn't the reason he gave for it being a bad design choice. His reason was that MS chose to use the escape character as their path separator. But of course I still agree with you that in either case it's not a judgment you can fairly make 30 years after the fact. From neokosmos at gmail.com Thu Aug 10 09:56:05 2006 From: neokosmos at gmail.com (neokosmos at gmail.com) Date: 10 Aug 2006 06:56:05 -0700 Subject: Password authentication systems Message-ID: <1155218165.193546.136090@h48g2000cwc.googlegroups.com> This may only be tangentially related to Python, but since I am coding a password authentication system in Python, I thought I would ask here. In Linux (and presumably other *NIX systems that support it), when shadow passwords are enabled, the actual password is not stored. Instead an encrypted version is stored. Then, to authenticate the password, the system re-encrypts the user's input to see if it matches the stored, encrypted version. Presumably, this is done using the crypt() system call (and, fortunuately, Python has a builtin crypt module!). Presumably, as well, this is at least somewhat secure, assuming a source of cryptographic randomness to use to choose the salt. Are SHA1 and MD5 suitable for this sort of thing as well, or would I need to move to something more "industrial strength" from, say, the pyCrypto module if I wanted to avoid a dependency on the crypt module? From exarkun at divmod.com Tue Aug 8 11:37:59 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 8 Aug 2006 11:37:59 -0400 Subject: Info on continuations? In-Reply-To: <1155049622.601867.90340@75g2000cwc.googlegroups.com> Message-ID: <20060808153759.1717.501358120.divmod.quotient.17521@ohm> On 8 Aug 2006 08:07:02 -0700, olsongt at verizon.net wrote: > >vasudevram wrote: >> Hi, >> >> I am Googling and will do more, found some stuff, but interested to get >> viewpoints of list members on: >> >> Continuations in Python. >> >> Saw a few URLs which had some info, some of which I understood. But >> like I said, personal viewpoints are good to have. >> >> Thanks >> Vasudev > >Could you be a little more specific on what you're looking for? >Continuations are a big can of worms. > >In general, some of the historical uses of continuations are better >represented as classes in python. Generators provide some limited >functionality as well, and will be able to send info both ways in >python 2.5 to enable limited co-routines. Stackless python allows you Coroutines can switch out of stacks deeper than one frame. Generators cannot, even in Python 2.5. You seem to be partially aware of this, given your comments below, but have suffered some of the confusion PEP 342's naming seems intended to generate. Python doesn't have continuations or coroutines at all. It has generators, and calling them anything else (even "limited coroutines" - depending on what "limited" means (which no one really knows), Python 2.4 already had these - the ability to pass information into a generator is not new, only the syntax by which to do it is) can't help but lead to misunderstandings. >to *really* suspend the stack at a given time and do a bunch of crazy >stuff, but doesn't currently support 'full continuations'. > Jean-Paul From tim.leeuwvander at nl.unisys.com Mon Aug 21 04:24:14 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 21 Aug 2006 01:24:14 -0700 Subject: Python and STL efficiency In-Reply-To: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> Message-ID: <1156148654.420508.57960@p79g2000cwp.googlegroups.com> Licheng Fang wrote: > Hi, I'm learning STL and I wrote some simple code to compare the > efficiency of python and STL. > > > I was using VC++.net and IDLE, respectively. I had expected C++ to be > way faster. However, while the python code gave the result almost > instantly, the C++ code took several seconds to run! Can somebody > explain this to me? Or is there something wrong with my code? Hi, I'm no C++ guru so cannot comment on the C++ code itself, however I do wonder if you tested your C++ code with other STL implementation such as gcc (gcc is available on windows as well, in various versions). What could be is that expanding the list in C++ is done in very small increments, leading to many re-allocations. Is it possible to pre-allocate the vector<> with sufficient entries? Also, your Python code as quoted, doesn't actually call your function f(). If you say that you get results instantly, I assume that you mean all 4 strings are actually printed to console? (I'm surprised that the console prints things that fast). btw, using range() in Python isn't very efficient, I think... Better to use xrange(). Asked a C++ collegue of mine to comment, and he strongly suspects that you're actually running it in the .Net runtime (your C++ code contains some C#-isms, such as omitting the '.h' in the include <> statements). Luck, --Tim From rpdooling at gmail.com Thu Aug 3 12:38:06 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 3 Aug 2006 09:38:06 -0700 Subject: programming is hard In-Reply-To: References: <1154609819.083694.22200@m73g2000cwd.googlegroups.com> Message-ID: <1154623085.994132.126620@m73g2000cwd.googlegroups.com> Tim Chase wrote: > it may also be that "programmingishard...unless you use python" ;) > > -tkc Or if somebody made a site called programmingisfun.com, then you might find some Python snippets there. rd From duncan.booth at invalid.invalid Thu Aug 10 04:24:12 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Aug 2006 08:24:12 GMT Subject: def __init__(self, link, *arg, **key): References: <1155196761.085198.140530@i3g2000cwc.googlegroups.com> Message-ID: flogic wrote: > Hi > i m a newbie to python .. > jus started to learn ...am quite confused about variable arguments used > in python functions and in init. > > i dont where to use **keys , **kwds,*args ...etc... > > if anyone culd give some explanation with examples or clear detailed > web link, it wuld be helpful to me > Have you read sections 4.7.2-4.7.4 of the Tutorial? http://docs.python.org/tut/node6.html#SECTION006720000000000000000 From deets at nospam.web.de Wed Aug 30 17:33:18 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 30 Aug 2006 23:33:18 +0200 Subject: inet_aton and struct issue In-Reply-To: <11944606.TXfyH4Zyga@teancum> References: <11944606.TXfyH4Zyga@teancum> Message-ID: <4lmeguF2lmldU1@uni-berlin.de> David Bear schrieb: > I found this simple recipe for converting a dotted quad ip address to a > string of a long int. > > struct.unpack('L',socket.inet_aton(ip))[0] > > trouble is when I use this, I get > > struct.error: unpack str size does not match format > > I thought ip addresses were unsigned 32 bit integers. > > Is there a better way to take a dotted quad and convert it to a string > representation of an long int? Works for me: >>> import socket >>> import struct >>> ip = "127.0.0.1" >>> struct.unpack('L',socket.inet_aton(ip))[0] 2130706433L Diez From claudio.grondi at freenet.de Mon Aug 28 15:30:17 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Mon, 28 Aug 2006 21:30:17 +0200 Subject: How to let a loop run for a while before checking for break condition? In-Reply-To: References: Message-ID: Sorin Schwimmer wrote: > I am thinking on something in the following form: > > > import time > import thread > > delay=True > > def fn() > global delay > time.sleep() > delay=False > > thread.start_new_thread(fn,()) > > while delay: > > > ... > > while : > > > ... > > > Or, if you need to use "break", the second loop may be > something like: > > > while True: > > > ... > if : break > > ... > > > The two while loops have the same content, but the > first is terminated after a pre-determined amount of > time, while the second by another condition. Usually > the content of the too loops, being the same, is a > call to a function that does the actual work. In your > case, as time seems to be critical, you don't want to > spend it in function-call overheads, so you repeat > (cut'n'paste) the relevant code. > > Of course, the price to be paid is in maintenance > headache: you'll have to make all the changes in both > loops, to keep consistency. > > I hope this helps. It doesn't. Claudio From steve at REMOVEME.cybersource.com.au Wed Aug 16 00:51:27 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 16 Aug 2006 14:51:27 +1000 Subject: hide python code ! References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155300852.497741.73230@74g2000cwt.googlegroups.com> <1155301468.870340.82920@b28g2000cwb.googlegroups.com> <1155307415.855555.124760@i3g2000cwc.googlegroups.com> <1155309563.898182.195950@p79g2000cwp.googlegroups.com> <1155313092.743230.33950@m73g2000cwd.googlegroups.com> <1155320948.142524.124990@p79g2000cwp.googlegroups.com> <1155564295.361980.279350@m73g2000cwd.googlegroups.com> <1155570126.905733.137850@m79g2000cwm.googlegroups.com> <1155657616.103285.40040@75g2000cwc.googlegroups.com> Message-ID: On Tue, 15 Aug 2006 09:00:16 -0700, Ben Sizer wrote: > Yes, in much the same way that there is no point ever locking your > doors or installing burglar alarms, as a determined thief will > eventually steal your belongings. That's an utterly pointless and foolish analogy. (1) If a thief breaks into your house and steals your TV, you no longer have a TV. If a developer sees your code, you still have your code, *even if they subsequently copy it*. You haven't lost your code, it is just no longer secret. Since secrecy is rarely valuable in and of itself, you've lost nothing. Yes, I've heard all the stories about "valuable algorithms" and the like. Some of them might even be true. But for 99+% of code, spending even one cent to keep it secret is just wasting money. (2) Compiling code to machine language isn't like locking your door. Compiling code doesn't prevent me from seeing your code or your algorithm, it just means I see it written in machine language instead of C. If I know how to read machine code, or if I have a decompiler, then I can read it, no problems at all. Would you argue that Python source code hides your algorithm because it is inscrutable to people who can't read and understand Python? Surely not. So why do you argue that compiled code is hidden merely because it is inscrutable to people who don't know how to download a decompiler off the Internet? (3) Compiling code is certainly not like installing a burglar alarm. When I decompile your code, no alarms ring and you are not notified. > I find it strange that people (at least on c.l.py) often equate > 'imperfect protection' with 'pointless protection'. Nonsense. Can I remind you that the Original Poster *explicitly* rejected using Python's imperfect code-hiding technique (distribute only the compiled .pyc files) because they can be disassembled, but failed to realise that EXACTLY the same argument holds for compiled C code? Let me make it clear with a better analogy than your locked door one: the O.P. says "I don't want people to look through the windows of my Python house. I thought about hanging curtains, but people with thermal imaging equipment can see right through the walls. Can I hang vertical blinds in Python like my C programmer friends?" The answers are: (1) No, Python uses curtains. If you want vertical blinds, use another language. (2) Even if you hang vertical blinds, it isn't going to stop people with thermal imaging equipment from seeing into your house and copying your algorithm, just like they can with Python. > The all-or-nothing > attitude makes no sense. If you can halve the number of people who can > deduce your algorithm, that helps. If you can double the time it takes > for those people to deduce it, that also helps. If it took you months > of R&D, the value of even imperfect protection rises. Fine. But you haven't demonstrated how to do that. You're just plucking figures out of the air. Anyone can do that: I claim that going to the trouble of hiding code with (say) py2exe reduces the number of people who can deduce your algorithm by 0.1%, and increases the time it takes them by 0.01%. Who is to say that my figures are not as good or better than yours? Do you really think that (say) Microsoft has got neither decompilers nor people who can operate them? -- Steven D'Aprano From mail at microcorp.co.za Fri Aug 4 06:27:30 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Fri, 4 Aug 2006 12:27:30 +0200 Subject: Enhanced Listbox References: <1154645765.984577.122710@b28g2000cwb.googlegroups.com> Message-ID: <006901c6b7b7$65b9a040$03000080@hendrik> "drodrig" | My apologies if this question has been asked an answered. | | I am looking for a tkinter grid control or enhanced listbox that can | act as a "receipt" for a cash register program. I would like the widget | to contain a visible grid of columns and rows. I've tried binding | multiple listboxes to a scrollbar. This works OK, but I am missing the | vertical lines dividing each row and I can't seem to figure out how to | set the height (or vertical margin) of each row in the listbox(es). If | I could do these things my current implementation might be OK. Or, I | could just use a pre-packaged solution, if I coud find one. | | Any help is appreciated. | - you could try making your columns different background colours if this is acceptable... - Hendrik From mzhou at cs.hku.hk Sun Aug 13 09:08:31 2006 From: mzhou at cs.hku.hk (Angelo Zhou) Date: Sun, 13 Aug 2006 21:08:31 +0800 Subject: Installed correctly In-Reply-To: References: Message-ID: Ray wrote: > > I've just installed Python 2.4.3 on windows 2000. On the download page > it says that if python is installed the version number will be > displayed if you enter "python" in a command line window, but that > does not happen - it just says "unrecognized command". Rebooting does > not help. > > So is it correctly installed? I installed it under "program > files/python" instead of the default location C:\python, since I don-t > like to have the root of C: cluttered with stuff, are there any > problems with this? > > Do you know how to set up the %PATH% variable in win2k? Add the path of the bin directory of your python installation to the %PATH% From inigoserna at gmail.com Thu Aug 17 06:19:00 2006 From: inigoserna at gmail.com (=?ISO-8859-1?Q?I=F1igo_Serna?=) Date: Thu, 17 Aug 2006 12:19:00 +0200 Subject: Looking For mp3 ID Tag Module In-Reply-To: References: Message-ID: <65a1d6f80608170319r67d31e7cp88dc2b21d51004a1@mail.gmail.com> Hi Tim, try mutagen. http://www.sacredchao.net/quodlibet/wiki/Development/Mutagen Regards, I?igo On 8/17/06, Tim Daneliuk wrote: > I have DAGS and generally nosed around the net but cannot quite find what > I need. I am looking for a platform-independent Python module that would > permit me to write mp3 ID tags conformant to the latest spects. I am > currently calling 'mp3info' from my Python script, but that program is limited > to the older ID tags that are severely limited in length and thus truncate > the description strings I am providing. > > Ideas anyone? > -- > ---------------------------------------------------------------------------- > Tim Daneliuk tundra at tundraware.com > PGP Key: http://www.tundraware.com/PGP/ > -- > http://mail.python.org/mailman/listinfo/python-list From mail at microcorp.co.za Thu Aug 3 05:07:31 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Thu, 3 Aug 2006 11:07:31 +0200 Subject: How to force a thread to stop References: <1153831188.646392.185770@i42g2000cwa.googlegroups.com><1153880729.687711.227570@h48g2000cwc.googlegroups.com><1153942270.301732.99880@h48g2000cwc.googlegroups.com><7xslkoum88.fsf@ruckus.brouhaha.com> <44C7E7EC.4020301@mvista.com><1lwn8bs8qhg4c.dlg@gelists.gmail.com><3sphc25or7ir5keeithpvb1k3vog39botu@4ax.com><7xwt9y8916.fsf@ruckus.brouhaha.com><7xvephg7yq.fsf@ruckus.brouhaha.com> <1hjgrs7.w01xtjt192o1N%aleax@mac.com> Message-ID: <00ae01c6b6e5$9996ca00$03000080@hendrik> "Alex Martelli" Wrote: | H J van Rooyen wrote: | | > "Paul Rubin" Writes: | > | > | "H J van Rooyen" writes: | > | > *grin* - Yes of course - if the WDT was enabled - its something that | > | > I have not seen on PC's yet... | > | | > | They are available for PC's, as plug-in cards, at least for the ISA | > | bus in the old days, and almost certainly for the PCI bus today. | > | > That is cool, I was not aware of this - added to a long running server it will | > help to make the system more stable - a hardware solution to hard to find bugs | > in Software - (or even stuff like soft errors in hardware - speak to the | > Avionics boys about Neutrons) do you know who sells them and what they are | > called? - | | When you're talking about a bunch of (multiprocessing) machines on a | LAN, you can have a "watchdog machine" (or more than one, for | redundancy) periodically checking all others for signs of health -- and, | if needed, rebooting the sick machines via ssh (assuming the sickness is | in userland, of course -- to come back from a kernel panic _would_ | require HW support)... so (in this setting) you _could_ do it in SW, and | save the $100+ per box that you'd have to spend at some shop such as | or the like... | | | Alex Thanks - will check it out - seems a lot of money for 555 functionality though.... Especially if like I, you have to pay for it with Rand - I have started to call the local currency Runt... (Typical South African Knee Jerk Reaction - everything is too expensive here... :- ) ) - Hendrik From bobrien18 at yahoo.com Tue Aug 15 16:44:28 2006 From: bobrien18 at yahoo.com (KraftDiner) Date: 15 Aug 2006 13:44:28 -0700 Subject: include a python class in another python script. Message-ID: <1155674668.549905.60550@75g2000cwc.googlegroups.com> I have a class that is defined in a file called MyClass.py How do I use that class in another python script.. import MyClass ? (Does it need to be in a specific location?) From caoshouhong at gmail.com Mon Aug 28 13:36:57 2006 From: caoshouhong at gmail.com (fegge) Date: 28 Aug 2006 10:36:57 -0700 Subject: class problem Message-ID: <1156786617.162744.128870@h48g2000cwc.googlegroups.com> when i declare a class, is there difference between the below: class myClass(): class myClass(threading.Thread) From izuzak at gmail.com Wed Aug 30 15:59:34 2006 From: izuzak at gmail.com (Ivan Zuzak) Date: 30 Aug 2006 12:59:34 -0700 Subject: sys.argv[0] doesn't always contain the full path of running script. In-Reply-To: <1156873037.590351.158120@i42g2000cwa.googlegroups.com> References: <1156873037.590351.158120@i42g2000cwa.googlegroups.com> Message-ID: <1156967974.600841.148460@p79g2000cwp.googlegroups.com> gmax2006 wrote: > Hi, > > I use RedHat linux. > > How can I find where exactly the current python script is running? Hi, Doesnt __file__ attribute of each module contain the full filepath of the module? So, try this: filepath = __file__ print filepath Works for me :) Cheers, i. zuzak From nicolasg at gmail.com Wed Aug 30 06:25:17 2006 From: nicolasg at gmail.com (NicolasG) Date: 30 Aug 2006 03:25:17 -0700 Subject: Python web service ... In-Reply-To: References: <7d2580610608281645u65941eabwf4a8e74802b84976@mail.gmail.co m> <1156590455.555359.247410@h48g2000cwc.googlegroups.com> <32822fe60608281459i56784c8bo20b3cacba0852423@mail.gmail.com> <7d2580610608281645u65941eabwf4a8e74802b84976@mail.gmail.com> Message-ID: <1156933517.659327.184080@i3g2000cwc.googlegroups.com> You mean to use only python HTTP socket library ? I never had use sockets before, it has a big learning curve ? Gabriel Genellina wrote: > At Monday 28/8/2006 20:45, Nicolas G wrote: > > >If I want to run my program as a web service I need to setup a > >webserver , am I right ? > >Whars that difference ? can a webservice be run without a webserver ? > > Well, a webservice uses HTTP as its transport protocol, so you need > an HTTP server, but you don't have to use a full-blown web server to > implement it. SimpleHTTPServer > > in the standard library may be enough. > > > > Gabriel Genellina > Softlab SRL > > > > > > __________________________________________________ > Pregunt?. Respond?. Descubr?. > Todo lo que quer?as saber, y lo que ni imaginabas, > est? en Yahoo! Respuestas (Beta). > ?Probalo ya! > http://www.yahoo.com.ar/respuestas From bobrien18 at yahoo.com Tue Aug 15 22:35:11 2006 From: bobrien18 at yahoo.com (KraftDiner) Date: 15 Aug 2006 19:35:11 -0700 Subject: inheritance? Message-ID: <1155695711.057312.8020@p79g2000cwp.googlegroups.com> I have two classes: class implicitClass: def __init__(self): def isIVR(self): #This is a class private method. def fromfile(self, fileObj, byteOrder): def getVR(self): def getGroup(self): def getElement(self): def getSize(self): def getData(self): class explicitClass: def __init__(self): def fromfile(self, fileObj): def getVR(self): def getGroup(self): def getElement(self): def getSize(self): def getData(self): As you can see the interface is almost identical. How can I define a base class that will abstract the type such that I don't know if its really and inplicit or explicit object? From futurelogix at gmail.com Thu Aug 10 03:59:21 2006 From: futurelogix at gmail.com (flogic) Date: 10 Aug 2006 00:59:21 -0700 Subject: def __init__(self, link, *arg, **key): Message-ID: <1155196761.085198.140530@i3g2000cwc.googlegroups.com> Hi i m a newbie to python .. jus started to learn ...am quite confused about variable arguments used in python functions and in init. i dont where to use **keys , **kwds,*args ...etc... if anyone culd give some explanation with examples or clear detailed web link, it wuld be helpful to me thanks in advance i have a python code like shown below examples: def __init__(self, link, *arg, **key): blah blah def setTransponderDefaultConfiguration(self, *arg, **kwds): blah blah From chris at kateandchris.net Wed Aug 9 11:04:32 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Wed, 9 Aug 2006 11:04:32 -0400 Subject: Eval (was Re: Question about using python as a scripting language) In-Reply-To: <73BFFFC6-760D-4794-9B5C-AA749287B78A@carnegielearning.com> References: <73BFFFC6-760D-4794-9B5C-AA749287B78A@carnegielearning.com> Message-ID: <20060809150432.GA15121@kateandchris.net> How is your data stored? (site was not loading for me). test = 'blah = [1,2,3,4,5]' >>> var,val = test.split('=') >>> print var,val blah [1,2,3,4,5] >>> val = val.strip('[] ') >>> print val 1,2,3,4,5 >>> vals = [int(x) for x in val.split(',')] >>> print vals [1, 2, 3, 4, 5] More sophisiticated situations (like nested lists) may require something like pyparsing. from pyparsing import Suppress, Regex, delimitedList, Forward, QuotedString stringValue = QuotedString('"', '\\', multiline=True) intValue = Regex(r'[+-]?0|([1-9][0-9]*)') intValue.setParseAction(lambda s,l,toks: int(toks[0])) floatValue = Regex(r'[+-]?[0-9]+\.[0-9]+([eE][+-]?[0-9]+)?') floatValue.setParseAction(lambda s,l,toks: ('real', float(toks[0]))) constantValue = stringValue ^ intValue ^ floatValue arrayInitializer = Forward() arrayInitializer << (Suppress("[") + delimitedList(constantValue ^ arrayInitializer) \ + Suppress("]")) arrayInitializer.setParseAction(lambda s,l,toks: toks.asList()) test_data = '["a", 1, 5.6, ["b","c",6, 10.0e-19]]' print arrayInitializer.parseString(test_data) results in: ['a', 1, ('real', 5.5999999999999996), 'b', 'c', 6, ('real', 1.0000000000000001e-18)] -Chris On Wed, Aug 09, 2006 at 10:23:49AM -0400, Brendon Towle wrote: > Slawomir Nowaczyk noted: > > #> Heck, whenever *is* it OK to use eval() then? > eval is like optimisation. There are two rules: > Rule 1: Do not use it. > Rule 2 (for experts only): Do not use it (yet). > > So, that brings up a question I have. I have some code that goes out to a > website, grabs stock data, and sends out some reports based on the data. > Turns out that the website in question stores its data in the format of a > Python list ([1]http://quotes.nasdaq.com/quote.dll?page=nasdaq100, search > the source for "var table_body"). So, the part of my code that extracts > the data looks something like this: > START_MARKER = 'var table_body = ' > END_MARKER = '];' > def extractStockData(data): > pos1 = data.find(START_MARKER) > pos2 = data.find(END_MARKER, pos1) > return eval(data[pos1+len(START_MARKER):END_MARKER]) > (I may have an off-by-one error in there somewhere -- this is from memory, > and the code actually works.) > My question is: what's the safe way to do this? > B. > -- > Brendon Towle, PhD > Cognitive Scientist > +1-412-690-2442x127 > Carnegie Learning, Inc. > The Cognitive Tutor Company ? > Helping over 375,000 students in 1000 school districts succeed in math. > > References > > Visible links > 1. http://quotes.nasdaq.com/quote.dll?page=nasdaq100 > -- > http://mail.python.org/mailman/listinfo/python-list From alfargnoli at yahoo.com Thu Aug 3 17:56:02 2006 From: alfargnoli at yahoo.com (Al in Dallas) Date: 3 Aug 2006 14:56:02 -0700 Subject: Megawidget Syntax (Tix) References: <1154369455.631993.318760@s13g2000cwa.googlegroups.com> Message-ID: <1154642161.917100.144730@75g2000cwc.googlegroups.com> Al in Dallas wrote: > I'm new to Python*. I am having trouble with the Tix NoteBook > megawidget. When I use a simpler megawidget, such as a ButtonBox, I can > add buttons by invoking > > .add ('button3', text='Retry') > > Unfortunately, with the Notebook, I need access to a subwidget, and all > my attempts have led to error messages. When I try to look up the > megawidget documentation, I can only find example in Tcl, so I'm > confident that if someone explains the syntax of the TixNoteBook > megawidget to me, I should be able to figure it out for all the other > megawidgets on my own. Here's an attempt to add something to the hlist > subwidget: > > >>> lnotebook.hlist.add ('wrongsyntax') > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python24\lib\lib-tk\Tix.py", line 863, in add > return self.tk.call(self._w, 'add', entry, *self._options(cnf, kw)) > _tkinter.TclError: invalid command name > ".12204992.pane.p1.shlist.f1.hlist" > > *I evaluated it many years ago (1996) when the only other choices > seemed to be Perl, Tcl, and VB. Unfortunately, my various employers > chose which scripting language would be used, and none of them ever > chose Python. Oddly, I ended up using all of the others. Well, I've found a partial answer for a slightly less complicated megawidget: >>> nbpage1 = notebook.add ('first',label="First") >>> nbpage2 = notebook.add ('second',label="Second") >>> notebook.pages() [, ] >>> notebook.subwidget_list {'nbframe': , 'second': , 'first': } >>> nblab = Tix.Label(nbpage1,text="Test First Tab") >>> nblab.pack() >>> nbbtn = Tix.Button(nbpage2,text="Test Second Tab") >>> nbbtn.pack() >>> nbbbox = Tix.ButtonBox(nbpage1) >>> nbbbox.add ('nbbxb1',text='Yeah!') '.12236560.nbframe.first.12237760.nbbxb1' >>> nbbbox.pack() >>> nbbbox.add ('nbbxb2',text='Nah...') '.12236560.nbframe.first.12237760.nbbxb2' >>> nbp2lab1 = Tix.Label(nbpage2,text='This is the second most\ncomplicated widg et that has been mastered\nCome over some day maybe play poker') >>> >>> nbp2lab1.pack() I still don't have ListNoteBook widgets sussed, but I'm on the road. From hitesh287 at gmail.com Wed Aug 16 13:30:26 2006 From: hitesh287 at gmail.com (Hitesh) Date: 16 Aug 2006 10:30:26 -0700 Subject: Adding a char inside path string In-Reply-To: References: <1155737700.290268.248250@i42g2000cwa.googlegroups.com> <1155744057.573884.111850@m73g2000cwd.googlegroups.com> Message-ID: <1155749426.592821.38770@b28g2000cwb.googlegroups.com> Thank you all it worked!. Tim, > modRows = ['\\'+itm[0].replace(":", "$") for itm in rows] What are those two forward slashes for? I had to remove them otherwise I was getting output like '\\\\\\' inside list or if I print I was getting like \\\ Thanks, hj Tim Williams wrote: > On 16/08/06, Dennis Lee Bieber wrote: > > On 16 Aug 2006 09:00:57 -0700, "Hitesh" declaimed > > the following in comp.lang.python: > > > > > > > > Thank you Fredrik. That works for a string. > > > But I am getting list of tuples from DB. > > > > > > rows = [('\\serverName\C:\FolderName1\FolderName2\example.exe',), > > > ('\\serverName\C:\FolderName1\FolderName2\example2.exe',), > > > ('\\serverName\C:\FolderName1\FolderName2\example3.exe',), > > > ('\\serverName\C:\FolderName1\FolderName2\example4.exe',)] > > > > > > I tried this: > > > for i in rows: > > > row = str(i) > > > path = row.replace("C:" , "c$") > > > print path > > > > > > I am getting path something like > > > > > > ('\\serverName\c$:\FolderName1\FolderName2\example.exe',) > > > > > > How on the earth I can remove those paranthesis? > > > > > By accessing the contents of the tuple, not the tuple itself > > > > >>> rows = [('\\serverName\C:\FolderName1\FolderName2\example.exe',), > > .... ('\\serverName\C:\FolderName1\FolderName2\example2.exe',), > > .... ('\\serverName\C:\FolderName1\FolderName2\example3.exe',), > > .... ('\\serverName\C:\FolderName1\FolderName2\example4.exe',)] > > >>> rows > > [('\\serverName\\C:\\FolderName1\\FolderName2\\example.exe',), > > ('\\serverName\\C:\\FolderName1\\FolderName2\\example2.exe',), > > ('\\serverName\\C:\\FolderName1\\FolderName2\\example3.exe',), > > ('\\serverName\\C:\\FolderName1\\FolderName2\\example4.exe',)] > > >>> modRows = [itm[0].replace("C:", "C$") for itm in rows] > > >>> modRows > > ['\\serverName\\C$\\FolderName1\\FolderName2\\example.exe', > > '\\serverName\\C$\\FolderName1\\FolderName2\\example2.exe', > > '\\serverName\\C$\\FolderName1\\FolderName2\\example3.exe', > > '\\serverName\\C$\\FolderName1\\FolderName2\\example4.exe'] > > >>> > > Try > > modRows = ['\\'+itm[0].replace(":", "$") for itm in rows] > > It will work with any drive letter and makes an allowance for the > first escape character. > > >>> modRows > ['\\\\serverName\\C$\\FolderName1\\FolderName2\\example.exe', > '\\\\serverName\\C$\\FolderName1\\FolderName2\\example2.exe', > ....etc > > for r in modRows: > print r > > \\serverName\C$\FolderName1\FolderName2\example.exe > \\serverName\C$\FolderName1\FolderName2\example2.exe > ......etc > > > :) From blue99 at interia.pl Wed Aug 9 10:33:41 2006 From: blue99 at interia.pl (Rob Wolfe) Date: 9 Aug 2006 07:33:41 -0700 Subject: do people really complain about significant whitespace? In-Reply-To: References: <1154991523.887791.9640@i42g2000cwa.googlegroups.com> <1154994477.450666.226550@b28g2000cwb.googlegroups.com> Message-ID: <1155134021.169710.24540@75g2000cwc.googlegroups.com> Slawomir Nowaczyk wrote: > Really, typing brace after function/if/etc should add newlines and > indent code as required -- automatically. Actually, for me, it is even > *less* typing in C and similar languages... I probably should teach my > Emacs to automatically add newline after colon in Python, just as it > does after a brace in C... As soon as I figure out how to deal with > dictionary literals. Hmmm. Are you sure? My Emacs already know how to do it with the help of python-mode and magic function py-newline-and-indent. emacs-version "21.3.1" py-version "$Revision: 4.63 $" Regards, Rob From zxo102 at gmail.com Tue Aug 8 10:30:35 2006 From: zxo102 at gmail.com (zxo102) Date: 8 Aug 2006 07:30:35 -0700 Subject: how to make python socket server work with the app.MainLoop() in wxpython? In-Reply-To: <6b1vc25d90bo9atdqt6l58o6o5p48s5qrr@4ax.com> References: <1154269116.890584.215040@i3g2000cwc.googlegroups.com> <1154419818.825540.327500@i3g2000cwc.googlegroups.com> <6b1vc25d90bo9atdqt6l58o6o5p48s5qrr@4ax.com> Message-ID: <1155047435.643439.177840@m79g2000cwm.googlegroups.com> Dennis: Thanks for your message. Let me try the double-buffer-operation. Ouyang Dennis Lee Bieber wrote: > On 1 Aug 2006 01:10:18 -0700, "zxo102" declaimed the > following in comp.lang.python: > > > > > I just wrote the code following the example you provided. The image > > location can be controlled with the data from socket client. But only > > one thing confuse me. When the image keeps moving to a new location, > > the image at a "old" location is not deleted and is left behind in the > > frame. Do you know what is going on with it? The location of image is > > processed in "def OnResult(self,event):" and is initialized in "def > > __init__(self, parent, id):" of "class MainFrame" ( See the code > > attached). > > > Off hand, it is doing just what the code says it should. > > Each time you update position, you are COPYING a SMALL rectangle > (the "moved" image) into the larger frame... Only the pixels > corresponding to the small rectangle are changed -- anything that was > already in the frame stays there. > > You might want to double-buffer the operations... > > For each move: > clear an unseen "frame-sized" buffer > compute the new location of the "moved" image > blit the "moved" image into the unseen buffer > blit the full unseen buffer to the viewed frame (not to a > portion of the frame, but replace the entire frame contents) > > The double-buffer is to avoid annoying the viewer with the "flash" > of clearing out the view frame before drawing the new image > > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com wulfraed at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-asst at bestiaria.com) > HTTP://www.bestiaria.com/ From paddy3118 at netscape.net Wed Aug 9 01:06:54 2006 From: paddy3118 at netscape.net (Paddy) Date: 8 Aug 2006 22:06:54 -0700 Subject: singleton decorator In-Reply-To: References: Message-ID: <1155100014.081933.160710@b28g2000cwb.googlegroups.com> Andre Meyer wrote: > Am I missing something here? What is the preferred pythonic way of > implementing singleton elegantly? > > Thanks for your help > Andr? Hi Andre, You might also google for python borg pattern As a discussion on the 'borg' design pattern might be informative. - Pad. From justask at acme.com Tue Aug 15 06:33:25 2006 From: justask at acme.com (Vincent Delporte) Date: Tue, 15 Aug 2006 12:33:25 +0200 Subject: Compiling wxPython app for Windows; Single EXE References: Message-ID: <1n83e2tg0vqpsrrjfnc18ph5mb5oor1047@4ax.com> On Mon, 14 Aug 2006 17:46:11 -0500, Philippe Martin wrote: >Yes there is a way to make one .exe/.msi for everything ... but it does >require purchasing a tool such as VC++. > >I have python + wxWindows + my stuff + many other libraries in one installer >(takes 120 Megs (sigh)) I know. An empty frame with wxPython runs at ... 12MB :-/ From jgodoy at gmail.com Sun Aug 20 09:35:31 2006 From: jgodoy at gmail.com (Jorge Godoy) Date: Sun, 20 Aug 2006 10:35:31 -0300 Subject: Permission Denied References: <1156038847.616137.61800@m79g2000cwm.googlegroups.com> Message-ID: <87lkpjv8bg.fsf@gmail.com> Stargaming writes: > In the most cases, PATH is preconfigured to include "." (. is the current > directory as .. is the parent one). You can use ./yourpythonscript in this > case. I most cases on Unix boxes it isn't configured to include ".". This is so for safety reasons (somebody might replace some command with a tampered binary or a script and capture information that they shouldn't have access to...). The solution of creating a directory and adding it to PATH is the best one, IMHO. Having a "~/bin" is also common for Linux and some distributions of it already ship with it in /etc/skel and in the PATH, so just put a link there or copy your scripts there. > The most "advanced" way would be expanding PATH with > /home/youraccount/python/learning (use PATH=$PATH:/path/here..). Yes. This is the best. > Choose the one you're most comfortable with. :-) ;-) And think about security as well. -- Jorge Godoy From andos561 at gmail.com Mon Aug 7 11:34:27 2006 From: andos561 at gmail.com (=?ISO-8859-1?Q?Anders_=D6sterholm?=) Date: Mon, 7 Aug 2006 17:34:27 +0200 Subject: PyMorphic Project Message-ID: As a part of my Master Thesis in Cognitive Science at the University of Link?ping in Sweden i have created a Squeak-like system in Python called PyMorphic. Project homepage is http://pymorphic.sourceforge.net/ I am about to make a new release with minor changes. There is a tutorial for you in the Toolbar of the main screen. The major technical focus lies on the auto-reloading of classes. This means that instances can be updated with new class definitions. The code that is used for the autoreloading can be found at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164 Any comments on this project are welcome. /Anders ?sterholm -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Wed Aug 30 02:56:38 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 30 Aug 2006 07:56:38 +0100 Subject: NumPy 1.0b4 now available In-Reply-To: <1156899603.642334.163550@p79g2000cwp.googlegroups.com> References: <1156892631.086347.274840@b28g2000cwb.googlegroups.com> <1156899603.642334.163550@p79g2000cwp.googlegroups.com> Message-ID: mensanator at aol.com wrote: > Robert Kern wrote: >>mensanator at aol.com wrote: [...] >>>>The full C-API of Numeric is supported as is the C-API >>>>of Numarray. >>>> >>>>More information is available at http://numpy.scipy.org >>> >>>Like the statement >>> >>>"There is a module called convertcode.py in NumPy that >>>can make the transition to NumPy easier (it will automatically >>>perform the search-and-replace style changes that need to >>>be made to python code that uses Numeric to make it work >>>with NumPy)." >>> >>>Which is a lie, there is no such module included in numpy. >>>Is alter_code1.py supposed to take its place? If so why hasn't >>>the Home Page been updated to reflect this? >> >>Are you volunteering to maintain the site? > > Sure. [...] Good for you! The open source world *needs* to encourage more involvement from (forgive me, but you imply the same yourself) "clueless" users. That way, the software will become more widely available, as it won't speak only to experienced developers. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From wcampagner at hotmail.com Mon Aug 21 10:17:30 2006 From: wcampagner at hotmail.com (Wagner Garcia Campagner) Date: Mon, 21 Aug 2006 11:17:30 -0300 Subject: Dynamic RadioButton creation with Python + Qt Message-ID: Hello, I'm trying to create dynamic RadioButton as follows: for i in out.keys(): msg = "radioButton_" + str(i) msg2 = 20 * x msg = QRadioButton(self.buttonGroup_interfaces, msg) msg.setGeometry(QRect(30,msg2,121,23)) msg.setTect(i) x += 1 The problem is that Python is creating all RadioButton as "msg" and not the value of "msg" so i can't access the RadioButton after the creation. Is there a way i can create the RadioButton with diferent names?? Thanks in advance, Wagner. From rhamph at gmail.com Sat Aug 19 21:42:14 2006 From: rhamph at gmail.com (Rhamphoryncus) Date: 19 Aug 2006 18:42:14 -0700 Subject: sum and strings In-Reply-To: <1155971485.709068.255140@b28g2000cwb.googlegroups.com> References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <7xr6zel2r2.fsf@ruckus.brouhaha.com> <1155971485.709068.255140@b28g2000cwb.googlegroups.com> Message-ID: <1156038134.216383.80960@h48g2000cwc.googlegroups.com> Bill Pursell wrote: > Georg Brandl wrote: > > Paul Rubin wrote: > > > Sybren Stuvel writes: > > >> Because of "there should only be one way to do it, and that way should > > >> be obvious". There are already the str.join and unicode.join methods, > > > > > > Those are obvious??? > > > > Why would you try to sum up strings? Besides, the ''.join idiom is quite > > common in Python. > > One could extend this argument to dissallow the following: > >>> "foo" + "bar" It's worthwhile to note that the use of + as the concatenation operator is arbitrary. It could just have well been | or &, and has no relationship with mathematically addition. Were history different perhaps Guido would have gone with | or & instead, and we wouldn't be having this conversation. It's also worth stressing (not in response to your post, but others) that sum([[1],[2],[3]], []) is just as bad as attempting to sum strings, both conceptually (it's not mathematical addition), and performance-wise. Don't do it. :) I believe the prefered method to flatten a list of lists is this: shallow = [] for i in deep: shallow.extend(i) Yes, it's three lines. It's also very easy to read. reduce() and sum() are not. From tim.peters at gmail.com Tue Aug 8 19:59:33 2006 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 8 Aug 2006 19:59:33 -0400 Subject: threading.Event usage causing intermitent exception In-Reply-To: <1155072235.904227.303090@m73g2000cwd.googlegroups.com> References: <1155072235.904227.303090@m73g2000cwd.googlegroups.com> Message-ID: <1f7befae0608081659u77477eb7p3ccd644cff753c69@mail.gmail.com> [akameswaran at gmail.com] > Admittedly this problem causes no actual functional issues aside from > an occasional error message when the program exits. The error is: > > Unhandled exception in thread started by > Error in sys.excepthook: > Original exception was: > > Yes all that info is blank. That's typical when the interpreter has torn so much of itself down that there's not enough left in the `sys` module even to print exception info gracefully. The easiest way to stop that is to stop /trying/ to run Python code while the interpreter is tearing itself down. > The application is a console application that is waiting for some > condition on the machine to happen. However, I leave open the > possiblitiy to cancel by a single key press at which > point the program terminates. Suffice it to say, I cannot perform both > checks without invoking threads as the key press gets "missed" > sometimes. Below is a simplification of the code > > canceled = False > myEvent = threading.Event() > > def watchForCancel() > global canceled > # turn of terminal buffering and capture key presses here > canceled = True > myEvent.set() Presumably this is some kind of poll-and-sleep loop? If so, add a check to get out of the loop if myEvent.isSet(). Or if not, make it some kind of poll-and-sleep loop ;-) > def watchForCondition() > # do a bunch of stuff checking the system > myEvent.set() Ditto. > cancelThread = threading.Thread(target = watchForCancel) > cancelThread.setDaemon(True) # so I can exit the program when I want to And get rid of that. The comment doesn't make sense to me, and forcing a thread to be a daemon is exactly what /allows/ the thread to keep running while the interpreter is tearing itself down. That's why "daemonism" isn't the default: it's at best delicate. I don't see a real reason for wanting this here. > cancelThread.start() > conditionThread = threading.Thread(target = watchForCondition) > conditionThread.setDaemon(True) Ditto. > conditionThread.start() > > myEvent.wait() > > if cancelled: > sys.exit(2) > > # do more stuff if the condition returned instead of cancel and then > I'm done > > > I've left out most of the active code, just cuz I think it muddies the > water. Now about 9 out of 10 times this works just fine. However, > every once in a while I get the exceptions mentioned above, but only > when I cancel out of the operation. I think the conditionThread is in > the process of shutting down and gets hosed up somehow and spits out an > exception, but the interpreter no longer has access to the info since > it is shutting down. At this point it's likely that even sys.stdout and sys.stderr no longer exist. The "Unhandled exception" message is printed directly to the C-level `stderr` instead. > ... > I suppose I could make the threads aware of each other, but that just > seems stupid. Any suggestions on how to eliminate this intermittent > error? Stop forcing them to be daemon threads. The interpreter won't start to tear itself down then before both threads terminate on their own. To arrange for that, it's not necessary for the threads to become aware of each other, but it is necessary for the threads to become aware of another (shared) reason /for/ exiting. The most natural way to do that, given what you said above, is to make both threads aware that their shared myEvent event may get set "externally", and to stop when they find it has been set. From ksreddy25 at gmail.com Mon Aug 14 08:17:23 2006 From: ksreddy25 at gmail.com (NRI Events) Date: 14 Aug 2006 05:17:23 -0700 Subject: NRIEvents - Independence Day Contest : Message-ID: <1155557843.760582.297130@m73g2000cwd.googlegroups.com> Hello Friend, Kindly spare 2 minutes to celebrate INDIA's Independence Day with us. Host INDIA'S tri-color flag at your desk-top to show your love & support to INDIA. Its specially designed for you. (Home page) Participate in the event & win a gift for your brother or friend in INDIA. Click: http://www.nrievents.com Thanks for taking time in participating the event. Regards, NRIEVENTS Team From ells.david at gmail.com Fri Aug 25 15:12:34 2006 From: ells.david at gmail.com (David Ells) Date: 25 Aug 2006 12:12:34 -0700 Subject: When is a subclass not right? In-Reply-To: <1156452136.196964.193620@i42g2000cwa.googlegroups.com> References: <1156387621.568779.191420@m73g2000cwd.googlegroups.com> <1156393371.550249.138930@75g2000cwc.googlegroups.com> <1156394781.155152.313080@i3g2000cwc.googlegroups.com> <44ede9b8$0$8925$88260bb3@free.teranews.com> <1156452136.196964.193620@i42g2000cwa.googlegroups.com> Message-ID: <1156533153.847764.311990@75g2000cwc.googlegroups.com> Carl Banks wrote: > > I think it's kind of a fine point. In my own code I've had cases where > I've switched from subclass to attribute and back over the development, > and vice versa. I think there are many cases where it's preferable to > use an attribute, but not really wrong to subclass (and vice versa). > > The classical advice in choosing whether to subclass or or use > attribute is whether its more an an "is a" or "has a" relationship. If > it's more natural to say B is an A, then subclass. If it's more > natural to say B has an A, then use an attribute. But that's only a > rule of thumb. > > I personally find another question helpful. If it's reasonable that B > could have more than one of A, regardless if it actually does, use an > attribute. If it's unreasonable, subclass. Again, rule of thumb. > > > Carl Banks This is not always the defining line between when to use inheritance vs. when to use composition. It is of course the way to decide among the two in the situation of 'has a' vs. 'is a', i.e. a car with an engine instance ( a car has an engine) vs. a ford mustang engine which is an engine. But even in the second case, you may not automatically want to use the built in language inheritance, like class B1(A). Instead, you may want to use a private instance of the super class and delegate calls from the subclass to it, in order to preserve the abstraction barrier that the interface of the super class has put up. Then a ford mustang engine, which is still an engine, is simply a class with a private engine instance that delegates the appropriate calls to that instance. The rule of 'has a' and 'is a' still holds, but there is also more than one way to do inheritance (language-facilitated vs. composition), and while this would normally be a peripheral point, this is basically what the O.P. was asking about (i.e. the difference between classes B1 and B2, and how they go about subclassing A). From email at christoph-haas.de Thu Aug 3 13:22:12 2006 From: email at christoph-haas.de (Christoph Haas) Date: Thu, 3 Aug 2006 19:22:12 +0200 Subject: Running queries on large data structure In-Reply-To: <1154619947.900116.88780@i3g2000cwc.googlegroups.com> References: <200608022224.00925.email@christoph-haas.de> <1154619947.900116.88780@i3g2000cwc.googlegroups.com> Message-ID: <200608031922.12769.email@christoph-haas.de> On Thursday 03 August 2006 17:45, hiaips wrote: > Christoph, > > Several possibilities come to mind... > > From your description, maybe something like Postgres, MySql, or sqlite > would not be the best option. (However, I'm wondering what your query > requirements are Imagine this example firewall rule: | Source | Destination | Service | Action | | 10.0.0.1 | 192.168.51.9 | tcp/22 | allow | | group_internal | | tcp/23 | | | 10.2.0.0/16 | | | | | 10.4.0.0-10.4.9.255 | | | | Where e.g. group_internal is a group consisting of several IPs. And '10.4.0.0-10.4.9.255' is a range of IP addresses. SQL doesn't really know such criteria (although a network match is possible with PostgreSQL's "inet" data type). So I would probably need to read the rule from the database and for each type (IP, network, group, IP range) run some subroutine to determine whether a searched for IP address is part of it. > -- for example, if you really need the power of SQL, > maybe you should just bite the bullet and map to an RDBMS schema, as > painful as that may be. That's how I do it now (in the old Perl program). I don't allow IP ranges and expand the groups (like "group_internal") to all the members contained within. Here the optimization lies in the database but it's just doing the easy parts and not supporting the hard parts (e.g. IP ranges). > A couple of other possibilities: > 1. What about storing your data in XML and using XQuery to facilitate > queries? If your data is deeply nested, as you say, this may be a good > match. I assume that XQuery can't to weird queries like IP ranges, or can it? > 2. What about storing your data in the same syntax as a Python > dictionary? Is that possibile? (If it is, then your data *is* your > code, and you don't have to worry about parsing it.) Oh, yes, that's perfect. Perhaps a bit slower because I do the query code myself. But I would like that. Just how do I keep the dictionary somewhere on disk so that another process can use it? Thanks for the ideas. Christoph From tim.peters at gmail.com Tue Aug 29 18:17:14 2006 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 29 Aug 2006 18:17:14 -0400 Subject: A Sort Optimization Technique: decorate-sort-dedecorate In-Reply-To: <44F49BCD.6000903@durchholz.org> References: <1156719092.603277.57390@b28g2000cwb.googlegroups.com> <1156723602.192984.49610@m79g2000cwm.googlegroups.com> <280820061150081729%jgibson@mail.arc.nasa.gov> <7.0.1.0.0.20060829132302.05c9e758@yahoo.com.ar> <44F480EF.9080202@durchholz.org> <1f7befae0608291225o12985c18u95137d9b6ba928e2@mail.gmail.com> <44F49BCD.6000903@durchholz.org> Message-ID: <1f7befae0608291517h7a412533v90a129f746205f36@mail.gmail.com> [Joachim Durchholz] >>>>> Wikipedia says it's going from 2NlogN to N. If a sort is massively >>>>> dominated by the comparison, that could give a speedup of up to 100% >>>>> (approximately - dropping the logN factor is almost irrelevant, what >>>>> counts is losing that factor of 2). [Gabriel Genellina] >>>> In fact it's the other way - losing a factor of 2 is irrelevant, >>>> O(2N)=O(N). The logN factor is crucial here. [Joachim Durchholz] >>> That's just a question of what you're interested in. >>> >>> If it's asymptotic behavior, then the O(logN) factor is a difference. >>> >>> If it's practical speed, a constant factor of 2 is far more relevant >>> than any O(logN) factor. [Tim Peters] >> Nope. Even if you're thinking of base 10 logarithms, log(N, 10) > 2 >> for every N > 100. Base 2 logarithms are actually most appropriate >> here, and log(N, 2) > 2 for every N > 4. So even if the "2" made >> sense here (it doesn't -- see next paragraph), the log(N) term >> dominates it for even relatively tiny values of N. [Joachim Durchholz] > Whether this argument is relevant depends on the constant factors > associated with each term. I'm afraid you're still missing the point in this example: it's not just that Python's (& Perl's) current sorts do O(N*log(N)) worst-case comparisons, it's that they /do/ N*log(N, 2) worst-case comparisons. O() notation isn't being used, and there is no "constant factor" here: the count of worst-case comparisons made is close to exactly N*log(N, 2), not to some mystery-constant times N*log(N, 2). For example, sorting a randomly permuted array with a million distinct elements will require nearly 1000000*log(1000000, 2) ~= 1000000 * 20 = 20 million comparisons, and DSU will save about 19 million key computations in this case. O() arguments are irrelevant to this, and the Wikipedia page you started from wasn't making an O() argument either: http://en.wikipedia.org/wiki/Schwartzian_transform For an efficient ordinary sort function, the number of invocations of the transform function goes from an average of 2nlogn to n; No O() in sight, and no O() was intended there either. You do exactly N key computations when using DSU, while the hypothetical "efficient ordinary sort function" the author had in mind does about 2*N*log(N, 2) key computations when not using DSU. That's overly pessimistic for Python's & Perl's current sort functions, where no more than N*log(N, 2) key computations are done when not using DSU. The /factor/ of key computations saved is thus as large as N*log(N, 2) / N = log(N, 2). O() behavior has nothing to do with this result, and the factor of log(N, 2) is as real as it gets. If key extraction is at all expensive, and N isn't trivially small, saving a factor of log(N, 2) key extractions is /enormously/ helpful. If this is sinking in now, reread the rest of my last reply that got snipped hre. > Roughly speaking, if the constant factor on the O(N) term is 100 and the > constant factor on the O(logN) term is 1, then it's still irrelevant. As above, it's talking about O() that's actually irrelevant in this specific case. > My point actually is this: big-Oh measures are fine for comparing > algorithms in general, but when it comes to optimizing concrete > implementations, its value greatly diminishes: you still have to > investigate the constant factors and all the details that the big-Oh > notation abstracts away. That's true, although the argument here wasn't actually abstracting away anything. You've been adding abstraction to an argument that didn't have any ;-) > From that point of view, it's irrelevant whether some part of the > algorithm contributes an O(1) or an O(logN) factor: the decision where > to optimize is almost entirely dominated by the constant factors. While true in some cases, it's irrelevant to this specific case. More, in practice a factor of O(log(N)) is almost always more important "for real" than a factor of O(1) anyway -- theoretical algorithms hiding gigantic constant factors in O() notion are very rarely used in real life. For example, the best-known algorithm for finding the number of primes <= x has O(sqrt(x)) time complexity, but AFAIK has /never/ been implemented because the constant factor is believed to be gigantic indeed. Theoretical CompSci is full of results like that, but they have little bearing on practical programming. From neoedmund at gmail.com Wed Aug 30 22:17:33 2006 From: neoedmund at gmail.com (neoedmund) Date: 30 Aug 2006 19:17:33 -0700 Subject: The lib email parse problem... In-Reply-To: <1156920257.020916.268490@m73g2000cwd.googlegroups.com> References: <1156837260.222395.305960@b28g2000cwb.googlegroups.com> <1156841437.692537.68200@i42g2000cwa.googlegroups.com> <1156841950.866776.66400@b28g2000cwb.googlegroups.com> <1156842395.855885.183330@p79g2000cwp.googlegroups.com> <1156844520.044398.7900@h48g2000cwc.googlegroups.com> <1156919044.575120.195580@i42g2000cwa.googlegroups.com> <1156920257.020916.268490@m73g2000cwd.googlegroups.com> Message-ID: <1156990652.746754.233150@p79g2000cwp.googlegroups.com> myself wrote a multipart parser in java(i customise it because i need get information of "upload progress"). and i think it's also easy to implement in python, i've not have time done it, or i'll post it. but if you're no other special needs, just use email lib, it's quick to program and if you really not need some part, just drop it. there's anything wrong with email lib? ???? wrote: > yes, the special is i must choose exactly one section to destruct, > instead of processing all subparts. > > > John Machin ??? > > > Tim Roberts wrote: > > > "????" wrote: > > > > > > >i know how to use email module lib. > > > > > > > >the question is about how to handle the rfc 1521 mime > > > >mulitpart/alternitave part . > > > > > > > >i know emai can handle mulitpart , but the subpart alternative is > > > >special . > > > > > > No, it's not. A multipart/alternative section is constructed exactly the > > > same as any other multipart section. It just so happens that it will have > > > exactly two subsections, one text/plain and one text/html. > > > > I was under the impression that it was a little more general than that > > ... see e.g. http://www.freesoft.org/CIE/RFC/1521/18.htm > > > > My guess is that the OP meant special in the sense that the reader > > needs to choose one subpart, instead of processing all subparts. > > > > Cheers, > > John > > > > > > > > > > > -- > > > - Tim Roberts, timr at probo.com > > > Providenza & Boekelheide, Inc. From andy.terrel at gmail.com Fri Aug 18 18:30:52 2006 From: andy.terrel at gmail.com (Andy Terrel) Date: 18 Aug 2006 15:30:52 -0700 Subject: how do you get the name of a dictionary? In-Reply-To: References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <1155936774.578249.259290@74g2000cwt.googlegroups.com> Message-ID: <1155940252.189880.191910@i42g2000cwa.googlegroups.com> Georg Brandl wrote: > Andy Terrel wrote: > > Why bang your head? > > Because there's no chance that the original request is sane. > > If you want your objects to know their name, give them a name as an attribute. > This is true but sometimes it is just fun to hack around. From rrs at researchut.com Wed Aug 2 14:00:22 2006 From: rrs at researchut.com (Ritesh Raj Sarraf) Date: Wed, 02 Aug 2006 23:30:22 +0530 Subject: Thread Question References: <1153998422.670828.148360@m79g2000cwm.googlegroups.com> <1154019801.999805.150000@m73g2000cwd.googlegroups.com> Message-ID: Hi, I have this following situation: #INFO: Thread Support # Will require more design thoughts from Queue import Queue from threading import Thread, currentThread NUMTHREADS = variables.options.num_of_threads def run(request, response, func=download_from_web): '''Get items from the request Queue, process them ? ? with func(), put the results along with the ? ? Thread's name into the response Queue. ? ? Stop running once an item is None.''' name = currentThread().getName() while 1: item = request.get() (sUrl, sFile, download_size, checksum) = stripper(item) if item is None: break response.put((name, func(sUrl, sFile, sSourceDir, None))) My download_from_web() returns True or False depending upon whether the download was successful or failed. How can I check that in the above code ? One other question I had, If my user passes the --zip option, download_from_web() internally (when the download is successful) zips the downloaded data to a zip file. Since in case of threading there'll be multiple threads, and say if one of the thread completes 2 seconds before others and is doing the zipping work: What will the other thread, at that moment do, if it completes while the previous thread is doing the zipping work ? Thanks, Ritesh Justin Azoff on Thursday 27 Jul 2006 22:33 wrote: > Ritesh Raj Sarraf wrote: > [snip] >> for item in list_items: >> download_from_web(item) >> >> This way, one items is downloaded at a time. >> >> I'm planning to implement threads in my application so that multiple >> items can be downloaded concurrently. I want the thread option to be >> user-defined. > [snip] > > See my post about the iterthreader module I wrote... > http://groups.google.com/group/comp.lang.python/browse_frm/thread/2ef29fae28cf44c1/ > > for url, result in Threader(download_from_web, list_items): > print url, result > #... > -- Ritesh Raj Sarraf RESEARCHUT - http://www.researchut.com "Necessity is the mother of invention." "Stealing logic from one person is plagiarism, stealing from many is research." "The great are those who achieve the impossible, the petty are those who cannot - rrs" From gagsl-py at yahoo.com.ar Fri Aug 25 02:43:45 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 25 Aug 2006 03:43:45 -0300 Subject: pickling and endianess In-Reply-To: References: <1f7befae0608242304p3ad8cffdh123f3577daa78dca@mail.gmail.com> <7.0.1.0.0.20060825032417.044cfe50@yahoo.com.ar> Message-ID: <7.0.1.0.0.20060825034213.0409fc50@yahoo.com.ar> At Friday 25/8/2006 03:37, Chandrashekhar Kaushik wrote: >I dont think i really need that much . Just need to be able to send >data across the network and then retrieve it properly independent of >the architecture at the remote end :) What about old ASCII? Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From steve at holdenweb.com Wed Aug 30 03:51:56 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 30 Aug 2006 08:51:56 +0100 Subject: What do you want in a new web framework? In-Reply-To: <1156923758.526608.251530@b28g2000cwb.googlegroups.com> References: <1156100330.768482.326760@h48g2000cwc.googlegroups.com> <1156923758.526608.251530@b28g2000cwb.googlegroups.com> Message-ID: Maxim Sloyko wrote: > Laurent Pointal wrote: > >>Look at http://wiki.python.org/moin/WebFrameworks >> >>Do you *really* need to develop a *new* framework (maybe a scholl >>exercise - it that case, KISS)? > > > Isn't the main reason why there are so many of them is that all of them > suck badly? > Absolutely not. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From max at alcyone.com Wed Aug 9 16:54:06 2006 From: max at alcyone.com (Erik Max Francis) Date: Wed, 09 Aug 2006 13:54:06 -0700 Subject: #!/usr/bin/python or #!/usr/bin/env python? In-Reply-To: <1155154976.016662.284460@i42g2000cwa.googlegroups.com> References: <1155154976.016662.284460@i42g2000cwa.googlegroups.com> Message-ID: <-JCdnYkrHfrz1kfZnZ2dnUVZ_uudnZ2d@speakeasy.net> olsongt at verizon.net wrote: > Basically, someone could inject an arbirtrary script called 'python' > into your path that does whatever (rm -fr /) under your user context > when you run the script. But the same thing would happen if you run > 'python test.py' instead of '/usr/local/bin/python test.py' to run a > script that doesn't have a she-bang or hasn't been flagged as > executable. Some admins will use a fully-qualified path for every > command to guard against this; I think that can be overkill. The primary guard for this is not having publicly-writable things in your PATH. In other words, this is the argument for not putting things like /tmp or . (because you might cd to somewhere publicly writable like /tmp) in your PATH, not really for avoiding /usr/bin/env in hash bangs. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis We must all hang together, or, most assuredly, we will all hang separately. -- John Hancock From ajaksu at gmail.com Mon Aug 14 17:31:23 2006 From: ajaksu at gmail.com (ajaksu) Date: 14 Aug 2006 14:31:23 -0700 Subject: Mega Newbie Questions: Probably FAQs In-Reply-To: References: Message-ID: <1155591083.461286.75380@i3g2000cwc.googlegroups.com> Zeph wrote: > 1) I want to write high-level apps that are db connected, networkable > and cross-platform: Linux, Mac OSX, Windows. I know there are apps that > can convert to Linux or Windows as stand-alone executables, is there > also one that will permit me to convert to MacOSX? Yes, py2app (http://undefined.org/python/py2app.html). > 1b) Are these executable completely free from the need of the average > user needing to install Python. Basically, I want to write and sell > "compiled" apps. Yes. However, you can have downloads of a dozen MBs for something that could be 100KB for someone with the right pre-requisites already installed. And I'd research a bit about decompiling those executables, might be easier (or harder, in my case) than you thought :) > 2) I want a real and native GUI. wxPython or PyQT? My concerns are about > cross-platform and responsiveness of GUI. I suspect that this will be > one of the gravest issues for the long run. wxPython. Even if PyQT is "the best tool for the job", it'll cost you to find that out (if you're planning to sell your software). So try wxPython first. Actually, play with Dabo (http://dabodev.com/ -> wxPython + DBs). > 3) Can someone recommend a good framework that will enable me to keep > things well sorted out, and easy to maintain as my apps grow? (I'm > considering MVC, but have no idea how to apply it until I've gone beyond > "Hello World"). Framework... MVC... not my area, sorry. However, try a look at Envisage (http://code.enthought.com/envisage/, also http://code.enthought.com/traits/ seems relevant) PEAK (http://peak.telecommunity.com/), PlugBoard (http://plugboard.berlios.de/) and Dabo again. All of which pass miles above my head, so if you figure them out please share the wisdom :) > 4) There are a lot of books and tutorials out there, but they are of the > proof-of-concept type. Specifically, a tutorial might teach me Hello > World, but not really care about the framework, because it's a very > simple item, and the point is simply to get me coding. I'd like to start > off with an established, tested and reputable system whose habits I can > ingrain from day one, rather than figure it out later. Can someone > recommend a good book, or your favourite tutorials? Perhaps even one > that assumes MVC as the framework? IMHO, you'd benefit from "wxPython in action" (http://www.manning.com/rappin/). But see below. > 5) Following the above, is there a framework that assumes tcp/ip udp > networking, database connectivity? My first app will be in large part a > networkable database type app where two or more users can share the same > file concurrently. Sure, tons of frameworks somewhat like that. Web-based, mostly. And targeting the sane approach of a DB server talking to clients. Share the same file? What kind of file would that be? :) > 6) Since I've been a web-developer for a long time (over 10 years), I > never properly learned OOP. Recommended tutorials? http://diveintopython.org/object_oriented_framework/index.html -> I love this one http://www.voidspace.org.uk/python/articles/OOP.shtml -> gentle http://www.ibiblio.org/g2swap/byteofpython/read/oops.html -> gentle http://www.brpreiss.com/books/opus7/html/book.html -> not so gentle :) And search this group for "Book" to get much better recommendations ;) > 7) I'm developing on WinXP and for the IDE, I'm considering > theKompany.com's BlackAdder, Komodo or Eclipse. Any very strong > negatives in regards to either of these? Only one: PyScripter is better (http://mmm-experts.com/Products.aspx?ProductId=4). And SPE is very good too (http://stani.be/python/spe). Two negatives, PyScripter and SPE. Also, Eclipse is so heavy and bloated that I wonder what it eclipses :) > 8) Can anyone speak to the point, or point out a useful comparison > between Python and RealBasic? Perhaps http://discuss.joelonsoftware.com/default.asp?design.4.70287.9 And a general recommendation: go for something easier as your very first target. As you're a web-developer, writing simple and useful tools (run tidy on files, simple pre-processors, bare-bones templating, CSS inliner, etc.) first would be IMHO both rewarding and a great learning opportunity. Hoping this helps more than confuses, Daniel From ewill at sirius.tg00suus7038.net Wed Aug 30 17:00:02 2006 From: ewill at sirius.tg00suus7038.net (The Ghost In The Machine) Date: Wed, 30 Aug 2006 21:00:02 GMT Subject: Duck typing alows true polymorfisim References: <1156532721.879808.40990@i3g2000cwc.googlegroups.com> <1156533807.630662.12330@i42g2000cwa.googlegroups.com> <12fblk87ppk7ief@corp.supernews.com> Message-ID: <9l9hs3-64h.ln1@sirius.tg00suus7038.net> In comp.lang.java.advocacy, Jeroen Wenting wrote on Wed, 30 Aug 2006 20:18:52 +0200 <12fblk87ppk7ief at corp.supernews.com>: > > "Simon Forman" wrote in message > news:1156533807.630662.12330 at i42g2000cwa.googlegroups.com... >> atbusbook at aol.com wrote: >>> lets say you want a generic numerical algorithom like sum >>> > >> What's your question? (Or, if no question, point?) :-) >> > Reads like the weekly "Ruby is better than Java because XXXXX" post. > Well, FWIW one could throw this into the pot and watch it explode: http://www.approximity.com/ruby/Comparison_rb_st_m_java.html :-) This table needs some work. The leftmost column is unidentified, for example ("Capability" or "Feature" suggests itself here) and each of these capabilities or features should probably have a link to a short description of the capability or feature, preferably with an example. Also, one language is very conspicuous by its absence: C#. One could also add C, Basic, and ISO Pascal; the first is widely used but lacks polymorphism, inheritance, dynamic casting, etc., and the last is probably not used anywhere in its form (though dialects are plenty), since one can't do anything *with* it, really -- though IIRC someone has told me it can at least open an arbitrary file now, as opposed to having the user pass one down in the program identifier list. :-) As for the middle one: which dialect? Was it ever standardized? Visual Basic is a very object-oriented language in spots, but it's not the only variant; I used to use at least 4 other variants off and on: GWBasic -- old IBM PCs ABasic -- Amiga variant AmigaBasic -- Microsoft-sponsored Amiga variant HP Basic (?) -- load tape into very old HP 21xx-series computer and one had a multitasking Basic which could do the simpler stuff, but its error diagnostics were pure numeric: ERROR 67 IN LINE 20. Fortunately, we had plenty of pamphlets detailing the errors. Also, Java now has templates. (The implementation is pretty gross and has some quirks, IMO, but it's better than nothing.) C++ has a typing system ("type_of" or some such; I'd have to look) which yields little more than the mangled type name and static inheritance testing capabilities. Of course C++ doesn't have dynamic inheritance anyway. One could include additional capabilities: Dynamic type creation. I don't know if Java has this or not. One can of course attempt bytecode synthesis -- I think that's what BCEL uses -- but that's a bit of a hack. Dynamic method creation. Java does *not* have this. AIUI Smalltalk-80 does; one can take an existing class and add methods thereto. Dynamic method override. This may be an artificial distinction but in some languages -- Smalltalk-80 again, presumably -- one can take an existing method implementation and override it in the same class, but without allowing the creation of new methods. How this would be enforced without additional keywords and/or a full-fledged ACL method/metadata system, I for one do not know. Dynamic method deletion. I for one might only want this in the context of a "sandbox" but if one can create methods, one should be able to delete them as well if only because of undo. Dynamic method rename. This could lead to much madness but this might be useful during sandboxing. Dynamic method signature changing. Eclipse has a reasonable way of doing it using source but I'll admit to wondering whether it makes sense given a Method descriptor whether one should be able to edit (as opposed to viewing or invoking) that descriptor, and when. One might implement this as a new method, followed by a delete of the old one. Dynamic other method deletion. If one can delete one's own methods in an edit session, should it be possible to delete others' methods too? An interesting question. Dynamic inheritance. For those languages that support inheritance one might liken it to changing what the language inherits or implements on the fly. I don't know of any language apart from Smalltalk that can even think about allowing dynamic inheritance, but it's a thought. Operator overload (e.g., C++'s operator ==()). Name overload. C does not have it; C++ and Java do. I suspect Ruby and Python do as well. Globals. Java has no globals as such, unless one counts class names. C is all globals, unless one counts statics. Unnamed classes. new Runnable() { public void run() {...} } is Java's contribution. Can be useful. Nested classes. Primitive types -- in other words, the int<->Integer dichotomy we all know and love in Java; such also exists in C++ and IINM C#. I'm not sure if Smalltalk has such a concept, or not; Smalltalk allows overrides on numbers. (In Java one might contemplate 2.toString(), for example!) Arbitrary integer size. The only language I know having this is Common LISP. Explicit module-level identifier scoping. In C++ this might be implemented during link using the -E flag on ld, for example (there is the Microsoft concept of exporting in their DLLs, which is vaguely similar as well). An identifier could be "global" in the module but inaccessible to those outside of the module. Modules can include other modules in C++, which makes life even more interesting. (This might be more of an environmental versus a language issue.) Thread-level variable/value scoping. In Java this is done using the ThreadLocal class, but is not (AFAICT) supported by the language proper. This of course differs from call-level (stack), global-level, and class-level scoping. One might even contemplate function-level scoping, but that would only be useful if one can create new functions on the fly and modify these values; otherwise, they might as well be static. Persistability. In Java one can implement Serializable or Externalizable, and generate output from an object. I've always considered this a bit of a weird hack but it can come in handy, and forms one leg of the Java EJB implementation. Transient field. In Java a capability exists to mark a field as transient, which is a hint during serialization that this field in a class not be persisted. (One can check for this using the Modifier.TRANSIENT bit.) Volatile field. In Java there is a volatile keyword. I don't know its precise semantics but it applies to fields. Virtuals. In C++ one must explicitly declare a function virtual; C has none at all, and in Java one must explicitly declare a function final (disallowing overrides) and cannot really disable a non-method's "virtuality" at all. Pure/abstract virtuals. C++ has the "=0" construct; Java has the abstract keyword. Static virtuals. Delegates. This Microsoftish concept is a bit hard for me to pin down (it feels a lot like a C++ method pointer -- or even a C function pointer) but is occasionally touted as an advantage for such languages as C++ and the ill-fated Java++, which had them as part of the language. First-level object functions. AIUI, this is a high-level concept which would allow for constructs in a hypothetical language such as k = (f @ g)(s1,s2,s3); if f has arguments (int v) and g has arguments (string s1, string s2, string s3). It would also allow for constructs such as h = f @ g; where h is a "function variable" of some sort -- and it would have the same signature as g. (The '@' is used in lieu of 'o', although one might use character U+2218 (ring operator) in a theoretical language where everyone understands Unicode.) C#'s event handling emulates this concept to some extent using the += operator, though I doubt they do it all that generally -- or all that well. Function-function operators. Under certain conditions the construct f + g makes sense, if they have compatible signatures; one might even write int (f + g)(int a) { return f(a) + g(a) } Ditto for f - g, f * g, and even f += g if f returns a reference. One can also contemplate unary operators such as '-f' . Set/collection union/intersection/subtraction/element of support. This is probably most useful for hard-core mathematicians and database junkies. :-) In Java one might declare a Union class easily enough, which takes two collections and tries to do something intelligent with them during a scan with the iterator, and of course the .contains() method is good enough for now. Integrated database access (and how tightly). C++ has none at all, though of one can use various third-party libraries. Java has some base-level API -- the java.sql.* and javax.sql* library. I suspect C#'s access is similar; I don't know regarding Ruby. A variant of COBOL was able to access the database -- DEC's DBMS product, which was a CODASIL affair -- by using statements in the language itself. Nowadays, apparently, such are considered slightly problematic, mostly because DB defs change a little too often. Arbitrary iterator positioning. In C++ some collections can position an iterator in an arbitrary location within the collection -- the only obvious one would be arrays. The closest one might get in current Java is to do a head(), tail(), or subset() and iterate over that. GUI support -- this is primarily API/library but might be put in the language if it makes sense -- perhaps when combined with collections and sets (e.g., is a point within a rectangle?), though there are some issues such as whether one would want to enumerate all the elements in a collection (points in a rectangle). There's probably a number I've missed but there are some interesting and somewhat unexplored directions in Java. Whether it makes sense to explore them is not clear to me. -- #191, ewill3 at earthlink.net Windows Vista. Because it's time to refresh your hardware. Trust us. From psnim2000 at gmail.com Tue Aug 15 10:17:51 2006 From: psnim2000 at gmail.com (Chaos) Date: 15 Aug 2006 07:17:51 -0700 Subject: Reference Variables In Python Like Those In PHP Message-ID: <1155651471.605912.46640@m73g2000cwd.googlegroups.com> Is It possible to have reference variables like in PHP ex. This would show 2 2 Is this available in python? From bounces at foo.org Tue Aug 29 23:59:43 2006 From: bounces at foo.org (Dan) Date: Wed, 30 Aug 2006 03:59:43 GMT Subject: Allowing ref counting to close file items bad style? In-Reply-To: <7x4pvvylrh.fsf@ruckus.brouhaha.com> References: <9U6Jg.951$Xw6.283@trndny02> <7x4pvvylrh.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Dan writes: >> Is this discouraged?: >> >> for line in open(filename): >> > > Yes. Well, not what I wanted to hear, but what I expected. Thanks, Dan -- dedded att verizon dott net From steve at holdenweb.com Wed Aug 23 22:12:40 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 24 Aug 2006 03:12:40 +0100 Subject: Accessing application data portably In-Reply-To: <20060823162056.GA4698@weber> References: <20060823162056.GA4698@weber> Message-ID: <44ED0B18.4080200@holdenweb.com> Tom E H wrote: > My Python application includes some data files that need to be accessed by > modules I distribute with it. > > Where can I put them, and how should I arrange my code, so that it works > across platforms? > > On Linux, I could install the data to "/usr/lib/myprogram/datafile", and > on Windows to "datafile" relative to where the executable (made by > py2exe) is installed. Then I could detect the operating system, and choose > appropriately. > > To be that explicit seems undesirable. Any cleverer ideas? > > Tom > > (Please CC me on replies: I'm not subscribed. The From address is munged) > If you aren't ubscribed then the only person who is going to copy you on email is someone complaining about your presumptuousness in assuming they'd happily want to spend time trimming your email address just so you won't be bothered by the spam plagie. Sorry, the question seems to have completely gone out of my head ... regards Steeve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From sjmachin at lexicon.net Tue Aug 15 20:19:50 2006 From: sjmachin at lexicon.net (John Machin) Date: 15 Aug 2006 17:19:50 -0700 Subject: Clean way to not get object back from instantiation attempt gone bad In-Reply-To: <44E25CD4.40103@tobiah.org> References: <44e245c0$0$20991$88260bb3@free.teranews.com> <44E25CD4.40103@tobiah.org> Message-ID: <1155687590.741871.75050@i42g2000cwa.googlegroups.com> tobiah wrote: > I should have made it more clear that Foo is a class: > > > class Foo: > > def __init__(self, *args): > > for arg in args: > if is_fruit(arg): > del(self) > > > > tobiah wrote: > > Suppose I do: > > > > -*> > myfoo = Foo('grapes', 'oranges') > > > > And in the __init__() of Foo, there is > > a real problem with the consumption of fruit. > > Is there a clean way to ensure that myfoo > > will be None after the call? Would the > > __init__() just do del(self), or is there > > a better way to think about this? > > Yes. Raise an exception, with details of what the problem is -- which arg? what (out of multiple possible problems) is wrong with it? if self.is_fruit(arg): raise FooError("I don't eat fruit: %r" % arg) if self.some_other_problem(arg): raise FooError("Some other problem: %r" % arg) HTH, John From gagsl-py at yahoo.com.ar Fri Aug 25 00:49:37 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 25 Aug 2006 01:49:37 -0300 Subject: lazy arithmetic In-Reply-To: <1156476992.102203.304450@p79g2000cwp.googlegroups.com> References: <1156476992.102203.304450@p79g2000cwp.googlegroups.com> Message-ID: <7.0.1.0.0.20060825012220.03df1280@yahoo.com.ar> At Friday 25/8/2006 00:36, pianomaestro at gmail.com wrote: ># This is what I have in mind: > >class Item(object): > def __add__(self, other): > return Add(self, other) And this works fine... why make thinks complicated? ># Now, I am going absolutely crazy with this idea ># and using it in a big way. So I'm looking at ># automating the process. As a first step, ># I thought maybe this would work: > >class Item(object): > pass > >class Add(Item): > def __init__(self, a, b=None): > print self, a, b > self.a = a > self.b = b > >Item.__add__ = Add This doesn't make sense... __add__ should be a method, not a class... >x = Item() >y = Item() > >print x, y > >c = x+y > ># This time, the Add constructor gets only the first two arguments: >"self" and "y". ># So, what happened to "x" ? Is this some kind of property voodoo going >on ? x+y get translated to x.__add__(y) x.__add__ is Add (the class), so Python calls Add, which means using it as a constructor with y as the (only) argument. So you see in the __init__ method: self=a new instance of Add, a=y, b=None (default, as only one argument was provided). If you really want to "inject" __add__ into the Item class, you could use a factory: def AddFactory(a,b): return Add(a,b) Item.__add__ = AddFactory (but as you've said yourself, that's a bit crazy...) Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From you at cogeco.ca Thu Aug 10 21:05:14 2006 From: you at cogeco.ca (AlbaClause) Date: Thu, 10 Aug 2006 21:05:14 -0400 Subject: reading from sockets References: <1155227695.625250.17920@m73g2000cwd.googlegroups.com> Message-ID: AndrewTK wrote: > Hello, > > I'm trying to read data from a socket and I'm not seeing what I'm > expecting.... it seems to skip the first line of data. I am new to > Python and just trying to test what I can do with it... and it's not > looking pretty. > > > I have some Python code: > [------------------------------ > #! /usr/bin/python > > import socket > > s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) > s.connect( ("localhost",54321) ); > s.send("hello") > data = s.recv(1024) > while len(data) > 0: > print repr(data) # the first print of data always seems to "ignore" > the first line of data... > data = s.recv(1024) > ------------------------------] I'm new to Python too, but I'd have to agree with Simon on this: There's probably something screwy in your java code. I'm assuming that your server waits to receive the word 'hello' before replying with the three strings (first, second, and third)? So once your script sends the word 'hello', there's nothing for it to do but wait for a response. And that's exactly what your script does. From neokosmos at gmail.com Thu Aug 10 10:46:24 2006 From: neokosmos at gmail.com (neokosmos at gmail.com) Date: 10 Aug 2006 07:46:24 -0700 Subject: Password authentication systems In-Reply-To: <7xk65g3cis.fsf@ruckus.brouhaha.com> References: <1155218165.193546.136090@h48g2000cwc.googlegroups.com> <7xk65g3cis.fsf@ruckus.brouhaha.com> Message-ID: <1155221184.665002.95160@i42g2000cwa.googlegroups.com> First, I'd just like to say, wow, and thanks to both you and Sybren for your fast responses. :) Twenty minutes is less time than it takes to get an answer from some companies paid tech support. ;) Paul Rubin wrote: > There are two main issues: > > 1) Unix password hashing uses several different algorithms depending > on version and configuration. Do you need to interoperate, or are you > just trying to do something similar? > > 2) Even with salting, computers are fast enough thse days to run > dictionary searches against unkeyed hashed passwords, so Unix now uses > a non-publicly-readable shadow password file. You're best off hashing > with an actual secret key, if you have a way to maintain one. I'd > suggest using the hmac module: To answer your questions, 1. there's no need for any sort of interoperability. Otherwise, the obvious thing to do is to look up the particular system(s) I needed to interoperate with and find out what algorithm(s) are used there. This is a password authentication system intended for a game server (a MUD/MMOG, in fact). The real limiting factor here is that I want to keep the server accessible via pure telnet protocol. Otherwise, using SSH would make sense. For my particular use case, simply using crypt() or MD5 or SHA1 would certainly be adequate, as I don't intend to charge money for people to play on my particular server. But, there is always the possibility that someone might want to do so, and, when money is involved, it always pays to be extra careful. (Of course I do realize that it would make sense to have any credit-card verification system isolated on a separate server entirely, not accessible to the internet, simply so that if the game server is compromised, it's much harder to get credit card details. But, I digress.) I had considered the hmac module. The thing that bugs me about it is that I'd have to keep this secret key around someplace accessible to the server. Most likely, this means storing it in a file. I'd guess that if someone could steal a file containing all my users' passwords, then they could also access this (since the server itself would need access.) Essentially, I guess it's an issue with maintaining the secret key that I haven't fully considered yet. From figo_wei01 at 126.com Sun Aug 20 13:55:50 2006 From: figo_wei01 at 126.com (01) Date: 20 Aug 2006 10:55:50 -0700 Subject: import In-Reply-To: References: <1156093283.529579.80600@i42g2000cwa.googlegroups.com> <1156093799.775420.51970@m73g2000cwd.googlegroups.com> <1156094307.576025.3430@i3g2000cwc.googlegroups.com> Message-ID: <1156096550.873958.289300@m79g2000cwm.googlegroups.com> Georg Brandl wrote: > figo_wei01 at 126.com wrote: > > bugnthecode ??? > > > >> How are you trying to import it? Is it in the same directory as your > >> other script? If not is your python path set correctly? > >> > >> When importing a module that you have written you exlude the .py > >> extension. You should be using: > >> import hello > >> > >> Hope that helps, > >> Will > > > > i am on a windows platform. i have written scrip named 123.py. it can > > be run. ok i save it to C:\Python24 ,exactly the same dir where python > > works. but " import 123" doesnt work. > > You can't import modules whose names have non-identifier names with > plain "import". Or would you like "123" to refer to a module? > > If you have to do this (and I have a strong feeling that you haven't) > use the built-in function __import__(). > you have to name your program with the name mymodule,or something like that when you use "import". does python have a clear declaration on how to name a module? From bignose+hates-spam at benfinney.id.au Fri Aug 11 20:29:57 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 12 Aug 2006 10:29:57 +1000 Subject: hide python code ! References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155300852.497741.73230@74g2000cwt.googlegroups.com> <1155301468.870340.82920@b28g2000cwb.googlegroups.com> <1155302025.090055.237230@i3g2000cwc.googlegroups.com> Message-ID: <87mzaax0ca.fsf@benfinney.id.au> "Fuzzyman" writes: > Paul Boddie wrote: > > Well, given the pace of technological development and the > > disregard in some environments for perpetual backward > > compatibility, how much of your infrastructure would you implement > > in vendor-supplied binaries, especially when the vendor is a one > > man plus dog operation? > > The question keeps getting asked because a lot of new programmers are > looking to create programs that they will sell. "Sell the software" is in no way dependent on "hide the source code": businesses across the globe sell software that doesn't have the source code hidden, often *with* source code. Indeed, as Paul Boddie points out, hiding the source code from one's customers, and refusing them permission to take the software to someone else to improve it, is increasingly becoming a way to *reduce* the willingness of people to buy one's software. All this seems worth pointing out to any new programmers whom you posit are looking to create programs that they will sell. -- \ "I always wanted to be somebody. I see now that I should have | `\ been more specific." -- Lily Tomlin | _o__) | Ben Finney From bdesth.quelquechose at free.quelquepart.fr Mon Aug 28 18:30:37 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 29 Aug 2006 00:30:37 +0200 Subject: Coding style and else statements In-Reply-To: <44f355d6$0$8812$88260bb3@free.teranews.com> References: <44f355d6$0$8812$88260bb3@free.teranews.com> Message-ID: <44f36bd2$0$16847$626a54ce@news.free.fr> tobiah a ?crit : > def foo(thing): > > if thing: > return thing + 1 > else: > return -1 > > def foo(thing): > > if thing: > return thing + 1 > return -1 > > Obviously both do the same thing. The first is > possibly clearer, while the second is more concise. > > Comments? > What about: def foo(thing): if thing: result = thing + 1 else: result = -1 return result and: foo = lambda thing: thing and thing + 1 or -1 From metaperl at gmail.com Mon Aug 14 10:03:15 2006 From: metaperl at gmail.com (metaperl) Date: 14 Aug 2006 07:03:15 -0700 Subject: recommended general-purpose string template packages? In-Reply-To: <1155523735.614470.199840@h48g2000cwc.googlegroups.com> References: <1155523735.614470.199840@h48g2000cwc.googlegroups.com> Message-ID: <1155564195.844302.165510@p79g2000cwp.googlegroups.com> John Machin wrote: > Hi, > > In general, I'm mainly interested in a template engine for dynamic web > pages but would like a general purpose one to avoid learning yet > another package for generating e-mail messages, form letters, source > code, whatever. HTMLTemplate and texttemplate offer a somewhat uniform approach to text versus HTML... it attempts to raise string processing up to the level of tree/HTML processing. That stringtemplate module seems to be aiming for the lowest common denominator. Interesting contrast in approaches: http://freespace.virgin.net/hamish.sanderson/index.html From steve at holdenweb.com Wed Aug 30 06:46:26 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 30 Aug 2006 11:46:26 +0100 Subject: Python web service ... In-Reply-To: <1156933517.659327.184080@i3g2000cwc.googlegroups.com> References: <7d2580610608281645u65941eabwf4a8e74802b84976@mail.gmail.co m> <1156590455.555359.247410@h48g2000cwc.googlegroups.com> <32822fe60608281459i56784c8bo20b3cacba0852423@mail.gmail.com> <7d2580610608281645u65941eabwf4a8e74802b84976@mail.gmail.com> <1156933517.659327.184080@i3g2000cwc.googlegroups.com> Message-ID: NicolasG wrote (top-posting, which is very naughty ...): >>At Monday 28/8/2006 20:45, Nicolas G wrote: >> >> >>>If I want to run my program as a web service I need to setup a >>>webserver , am I right ? >>>Whars that difference ? can a webservice be run without a webserver ? >> >>Well, a webservice uses HTTP as its transport protocol, so you need >>an HTTP server, but you don't have to use a full-blown web server to >>implement it. SimpleHTTPServer >> >> in the standard library may be enough. >> > You mean to use only python HTTP socket library ? > I never had use sockets before, it has a big learning curve ? > Gabriel Genellina wrote: > He's actually suggesting you use the SimpleHTTPServer library, which itself uses the socket library. All you really need to do is subclass the main clas defining your own (?) handle_request() (?) method. This server is not design for industrial-strength networking but it's fine if you need either a low-volume server or something to experiment with. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From steve at holdenweb.com Tue Aug 29 05:19:59 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 29 Aug 2006 10:19:59 +0100 Subject: Is this a good idea or a waste of time? In-Reply-To: References: <1156449402.022781.292840@p79g2000cwp.googlegroups.com> <1156485945.967160.238790@m73g2000cwd.googlegroups.com> <44f322cd$1@nntp0.pdx.net> <1156802762.331853.80000@75g2000cwc.googlegroups.com> Message-ID: Antoon Pardon wrote: > On 2006-08-29, Gabriel Genellina wrote: > >>At Tuesday 29/8/2006 02:45, Antoon Pardon wrote: >> >> >>>>>That may be true. But one may wonder if this is a failing of the >>>>>programmer or a failing of the language that doesn't support >>>>>such things. >>>> >>>>In any case, I don't see how this supports the original claim that >>>>strict type checking input params is good practice. >>> >>>I'm not defending that claim. I'm just putting question marks >>>with the claim that strict type checking input parameters is >>>bad practice. >> >>I think others have shown enough examples of good things that can be >>done by *not* enforcing a specific type... > > > That doesn't contradict that in other situations good things can be > done by enforcing specific type or at least limiting to a subset > of specific types. > Indeed it doesn't, but perhaps in future we could leave others to work out the glaringly obvious for themselves rather than having to explicitly provide the counterargument to each single response to a posting? crabbi-ly y'rs - steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From pavlovevidence at gmail.com Tue Aug 29 20:38:30 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 29 Aug 2006 17:38:30 -0700 Subject: Coding style and else statements In-Reply-To: <44f355d6$0$8812$88260bb3@free.teranews.com> References: <44f355d6$0$8812$88260bb3@free.teranews.com> Message-ID: <1156898310.795476.187030@i3g2000cwc.googlegroups.com> tobiah wrote: > def foo(thing): > if thing: > return thing + 1 > else: > return -1 > > def foo(thing): > if thing: > return thing + 1 > return -1 > > Obviously both do the same thing. The first is > possibly clearer, while the second is more concise. I almost always go with #2. The else clause is redundant and potentially misleading in the first one. (A casual programmer might not notice that it always returns and so add code beneath it, or a casual code checker might not notice that the end is unreachable, and flag the function as both returning a value and returning the default.) However, I have rare cases where I do choose to use the else (ususally in the midst of a complicated piece of logic, where it's be more distracting than concise). In that case, I'd do something like this: def foo(thing): if thing: return thing+1 else: return -1 assert False Carl Banks From johnjsal at NOSPAMgmail.com Wed Aug 23 15:53:00 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 23 Aug 2006 19:53:00 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Aug 23) In-Reply-To: References: Message-ID: Jack Diederich wrote: > David Wahler is no longer out of the office. > http://groups.google.com/groups/search?q=David+Wahler+out+of+office LOL. That's the best part this week! :) From aries.shuaib at gmail.com Tue Aug 8 12:00:42 2006 From: aries.shuaib at gmail.com (Shuaib) Date: 8 Aug 2006 09:00:42 -0700 Subject: Tkinter module not found References: <1155049496.292471.37020@h48g2000cwc.googlegroups.com> Message-ID: <1155052842.806353.18120@i3g2000cwc.googlegroups.com> Hey again, I am using the latest python available on my system (2.4). So I don't think that's the problem. Any more ideas? Do I need to install Tkinter as a seperate module/package? As I said, I've already installed Tcl/Tk, though. Thanks for your time. Tim Chase wrote: > > The cause of this is usually that you are using a different > > version of Python than the one you installed Tkinter into, but > > being a Linux newbie I have yet to discover how to redirect > > the 'python' command to invoke the newer version of Python. > > > The OS looks for the first 'python' it finds in its path. > > In Linux (or other *nix OSes), you can use > > bash> which python > > and it will reply with which python it's pointing to. You can > then change into that directory (usually "/usr/bin") and get back > a listing of various pythons. On my Debian linux distro at home, > I get something back that looks like > > bash> which python > /usr/bin/python > bash> cd /usr/bin > bash> ls -lsF python* | grep -o "python.*" > python -> python2.3* > python2.3* > python2.4* > > You *should* be able to just relink the "python" link to the new > version of python: > > bash> ln -sf /usr/bin/python2.4 /usr/bin/python > > I don't know if this will cause other problems down the line for > packages that expect the system default. > > Alternatively, at least on my system, you can force your choice > by explicity running "python2.3" or "python2.4" instead of just > "python". > > You can determine your path via > > bash> echo $PATH > > along which your shell will search for an executable. > > Win32 has a similar executable search path > > c:\> echo %PATH% > > but doesn't have something as handy as the "which" command to do > the hunting for you. > > HTH, > > -tkc From simon at brunningonline.net Thu Aug 3 09:46:54 2006 From: simon at brunningonline.net (Simon Brunning) Date: Thu, 3 Aug 2006 14:46:54 +0100 Subject: opposite of import In-Reply-To: References: <1154605835.465468.97550@m79g2000cwm.googlegroups.com> <8c7f10c60608030517i1e68433bn569150d379648087@mail.gmail.com> <8c7f10c60608030526u59e97c79m1032d62d1d639fb@mail.gmail.com> Message-ID: <8c7f10c60608030646o470dbaa6jccbcbac1085fe76b@mail.gmail.com> On 8/3/06, Gerhard Fiedler wrote: > Is that guaranteed, or is that just until the garbage collector has removed > the module (at some arbitrary point)? I *think* it's guaranteed. It's not a matter for the garbage collector. GC only exists to remove cyclic references. Ordinary reference counting *would* remove the module as soon as you de referenced it, but for the fact that Python stashes a reference to the module in (IIRC) sys.__modules__. And you mess with *that* at your peril. ;-) -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From rogue_pedro at yahoo.com Wed Aug 2 13:58:15 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 2 Aug 2006 10:58:15 -0700 Subject: Is there an obvious way to do this in python? References: Message-ID: <1154541495.486057.316740@i3g2000cwc.googlegroups.com> H J van Rooyen wrote: > Hi, > > I want to write a small system that is transaction based. > > I want to split the GUI front end data entry away from the file handling and > record keeping. > > Now it seems almost trivially easy using the sockets module to communicate > between machines on the same LAN, so that I want to do the record keeping on one > machine. > > I want to keep the "server" machine as simple as possible - just doing record > keeping on a stimulus response basis - I would prefer it to do one thing at a > time to completion because this style of operation, though limited in > performance, keeps a lot of hassles out of life - a transaction has either > completed, or it has not - recovery scenarios are relatively easy... > > Up to this point, I don't have a problem - my toy system can create a dummy > transaction, and I can echo it from the "server" machine, with more than one > "user" machine running - so I think it is feasible to have several tens of "data > entry terminal" systems running, served by one not very strong machine. > > Now what I would really like to do is to differentiate between the 'User" > machines, so that some can do a full range of transactions, and others a limited > range. > > And I would like to make this flexible, so that it becomes easy to introduce new > transactions, without having to run around updating the code in all the user > machines, with the concomitant version number hassles. > > And I would like to do the whole thing in python - so my question is this - is > it possible to do the equivalent of dynamic linking? - i.e. if I keep a list of > what a user is allowed to do - can I somehow send him just the bits he needs to > do the job, without having to change the static code on his machine? - it seems > to me that the eval() thingy could possibly do this for me, by sending it data > that makes it do import statements followed by calls to whatever... - will this > work, or is there a better way? > > Or has all this been done already? - and no I don't want a web server and php > and browsers and Java and html or xml... - I want to write something that works > simply and reliably - its just short message accounting type data... > > - Hendrik Don't reinvent the wheel. Use a database... You probably don't want to hear this, but what you just described is a GUI client front-end with a database backend. The time it takes to download, install, and learn to use, say, postgres will be similar to the time you'd spend implementing what you've described above, but with at least 10 to 100 times the payoff. As for updating the client on the fly, one strategy would be to keep the "dynamic" code in it's own module and have the clients reload() that module when you upload a new version of it to the client machines. Peace, ~Simon From st at tobiah.org Thu Aug 31 14:21:59 2006 From: st at tobiah.org (tobiah) Date: Thu, 31 Aug 2006 11:21:59 -0700 Subject: csv module strangeness. In-Reply-To: References: <44f5e870$0$8814$88260bb3@free.teranews.com> <44f5f347$0$8846$88260bb3@free.teranews.com> Message-ID: <44F728C7.7090009@tobiah.org> >> The docs clearly state what the defaults are, but they are not >> in the code. It seems so clumsy to have to specify every one of >> these, just to change the delimiter from comma to tab. >> >> http://docs.python.org/lib/csv-fmt-params.html : > > The "it defaults to" clauses should probably be seen in the context of > the two "the programmer can" sentences in the first paragraph on that > page; the default is what's used if you don't do that. > > I agree that the first paragraph could need some work. Any volunteers? > > > I agree with Henryk's evaluation, but if Dialect is to remain, why not just fix all of the 'None' assignments in the class definition to match the sensible defaults that are already in the docs? -- Posted via a free Usenet account from http://www.teranews.com From boris.dusek at gmail.com Mon Aug 28 12:17:04 2006 From: boris.dusek at gmail.com (=?iso-8859-1?B?Qm9yaXMgRHWaZWs=?=) Date: 28 Aug 2006 09:17:04 -0700 Subject: Truly platform-independent DB access in Python? In-Reply-To: <44f310e3$0$26022$636a55ce@news.free.fr> References: <1156748466.739709.117850@h48g2000cwc.googlegroups.com> <44f2bade$0$13039$626a54ce@news.free.fr> <1156778705.807852.140510@75g2000cwc.googlegroups.com> <44f310e3$0$26022$636a55ce@news.free.fr> Message-ID: <1156781824.501010.257890@p79g2000cwp.googlegroups.com> Bruno Desthuilliers wrote: > > but what if the OS with server accessing the site that is on > > shared area changes? > > And what if Python is not installed on it ?-) > > Seriously, do you think that hosting companies swap OS very often ? No, I don't. But I was trying to find the best solution. :-) From zeph_zhang at yahoo.co.uk Mon Aug 14 15:25:48 2006 From: zeph_zhang at yahoo.co.uk (Zeph) Date: Mon, 14 Aug 2006 15:25:48 -0400 Subject: Mega Newbie Questions: Probably FAQs Message-ID: I'm pretty well of a mind to pick up Python. I like it because it seems to have a fair degree of functionality and is accessible to someone without a PhD in computer sciences. This is my second day of investigation, and I'm astounded by the huge ecosystem that surrounds it. I have a number of questions that probably should be on a FAQ, but I haven't found them. I'll explain my goals and needs, perhaps someone here will have some recommendations 1) I want to write high-level apps that are db connected, networkable and cross-platform: Linux, Mac OSX, Windows. I know there are apps that can convert to Linux or Windows as stand-alone executables, is there also one that will permit me to convert to MacOSX? 1b) Are these executable completely free from the need of the average user needing to install Python. Basically, I want to write and sell "compiled" apps. 2) I want a real and native GUI. wxPython or PyQT? My concerns are about cross-platform and responsiveness of GUI. I suspect that this will be one of the gravest issues for the long run. 3) Can someone recommend a good framework that will enable me to keep things well sorted out, and easy to maintain as my apps grow? (I'm considering MVC, but have no idea how to apply it until I've gone beyond "Hello World"). 4) There are a lot of books and tutorials out there, but they are of the proof-of-concept type. Specifically, a tutorial might teach me Hello World, but not really care about the framework, because it's a very simple item, and the point is simply to get me coding. I'd like to start off with an established, tested and reputable system whose habits I can ingrain from day one, rather than figure it out later. Can someone recommend a good book, or your favourite tutorials? Perhaps even one that assumes MVC as the framework? 5) Following the above, is there a framework that assumes tcp/ip udp networking, database connectivity? My first app will be in large part a networkable database type app where two or more users can share the same file concurrently. 6) Since I've been a web-developer for a long time (over 10 years), I never properly learned OOP. Recommended tutorials? 7) I'm developing on WinXP and for the IDE, I'm considering theKompany.com's BlackAdder, Komodo or Eclipse. Any very strong negatives in regards to either of these? 8) Can anyone speak to the point, or point out a useful comparison between Python and RealBasic? Thanks. From davidworley at gmail.com Wed Aug 9 14:55:49 2006 From: davidworley at gmail.com (Dave) Date: 9 Aug 2006 11:55:49 -0700 Subject: Announcing Switch, the CSS Preprocessor! Message-ID: <1155149749.559985.177250@b28g2000cwb.googlegroups.com> Powered by Mod_Python, Switch CSS is a full featured, production ready CSS preprocessor. Some of the features include: - variables - constants - selector prepending: #selector { .class { property: value; } } outputs: #selector { } #selector .class { property: value; } With unlimited levels of nesting, this makes CSS easy to read and fast to write. - selector copying: #selector { width: 200px; } #other_selector { @copy #selector; } outputs: #selector { width: 200px; } #other_selector { width: 200px; } - selector inheritance: #selector { width: 200px; } #other_selector { @inherit #selector; } outputs: #other_selector, #selector { width: 200px; } #other_selector { } There are other features, also. I think that's enough to get people excited. Switch was designed as a production-ready tool to solve the problem of front-end design with CSS based-layouts and large CSS files. As we realized we had 40,000 lines of CSS written and no means of abstracting or managing the code easily, we decided to write a preprocessor that was easy to use and had all the bells and whistles a CSS designer could ever want. We originally approached the program using PHP. When it took the PHP version 30 seconds to process one CSS file, we knew PHP wasn't going to cut it. By re-implementing the appication in Python - using a literal, 1-1 translation of the PHP version, under mod_python, Switch was able to process the same file in under 1/4 of a second. YAY! PYTHON! The sourceforge project link follows. We could really use some tire kickers... This group was invaluable in the early development process, so we're announcing it officially here, and on mod_python first. https://sourceforge.net/projects/switchcss/ Thanks, Dave Worley From fivenastydisco at hotmail.com Tue Aug 8 12:26:51 2006 From: fivenastydisco at hotmail.com (donkeyboy) Date: 8 Aug 2006 09:26:51 -0700 Subject: Newbie question: what's with "self"? Message-ID: <1155054411.511813.203270@i42g2000cwa.googlegroups.com> This is probably a really basic question, but anyway ... I'm new to both Python and OO programming. From looking at a number of code examples, the word "self" is used a lot when referring to classes. As such, what does "self" mean and/or do? I've read things that say it's a naming convention, but no-one has really spelt it out (in idiot form!) in a way I can understand. Any help you can provide would be great: at the moment, when code doesn't work as expected, I'm randomly sprinkling "self"s in all over the place to see if that helps, but without much of an idea of what it really achieves. Thanks in advance!! From python.leojay at gmail.com Sat Aug 19 12:22:44 2006 From: python.leojay at gmail.com (Leo Jay) Date: Sun, 20 Aug 2006 00:22:44 +0800 Subject: how to use python com server in c++? Message-ID: <4e307e0f0608190922u51aa43f7g9b48444e7904e47e@mail.gmail.com> dear all, i have a python com server like this: import win32com.server.register class HelloWorld: _reg_clsid_ = "{B0EB5AAB-0465-4D54-9CF9-04ADF7F73E4E}" _reg_desc_ = 'Python test com server' _reg_progid_ = "Leojay.ComServer" _public_methods_ = ['Add', 'Mul'] def Add(self, a, b): return a+b def Mul(self, a, b): return a*b if __name__ == '__main__': win32com.server.register.UseCommandLine(HelloWorld) after registering the com server, i can use it in visual basic .net: Dim a As Integer = 5 Dim b As Integer = 8 Dim h As Object = CreateObject("Leojay.ComServer") MsgBox(h.Add(a, b).ToString() + " " + h.Mul(a, b).ToString()) but i don't know how to use it in visual c++. who has any idea about using this com server in viusal c++? a detailed sample of early binding would be better, thanks. -- Best Regards, Leo Jay From jack at psynchronous.com Wed Aug 16 19:54:24 2006 From: jack at psynchronous.com (Jack Diederich) Date: Wed, 16 Aug 2006 19:54:24 -0400 Subject: PySequence_SetItem In-Reply-To: <1155767139.084992.133200@i42g2000cwa.googlegroups.com> References: <1155754847.392950.266180@h48g2000cwc.googlegroups.com> <1155755905.233229.93440@74g2000cwt.googlegroups.com> <1155761144.583994.260150@m73g2000cwd.googlegroups.com> <1155764364.775366.76070@i3g2000cwc.googlegroups.com> <1155767139.084992.133200@i42g2000cwa.googlegroups.com> Message-ID: <20060816235424.GE5772@performancedrivers.com> On Wed, Aug 16, 2006 at 03:25:39PM -0700, John Machin wrote: > > Jack Diederich wrote: > > On Wed, Aug 16, 2006 at 02:39:24PM -0700, John Machin wrote: > > > > > > Jack Diederich wrote: > > > > > > > Changing the PySequence_SetItem to PyList_SetItem and dropping the > > > > DECREF works for me too (PyList functions steal a reference). I also > > > > tried setting the list to length 1, still no dice. The PySequence > > > > version segs under 2.4 and 2.5. It segs even when the Int is changed > > > > to a String. > > > > > > > > Yikes, I'll poke around some more. > > > > > > Yikes indeed. > > > > > > Not the OP's problem, but a bug in the manual: example in the chapter > > > that the OP was reading acts as though the 2nd arg to PyObject_SetItem > > > is a C int (as it is for the List and Sequence varieties) -- it is in > > > fact a (PyObject *), which explains the SystemError that I got. > > > > The good news is that this is a documentation problem. > > Cop-out alert! I disagree. Elsewhere Python goes to great lengths to > check for nasties instead of just segfaulting. > > > When working at the C level you use the concrete API when you can > > (PyList_*) and at the abstract level (PySequence_*) only when someone > > passes you something and you don't know what it is, you only know it > > supports the Sequence API. > > > > The exmample should use the PyList API to construct the list. The > > Sequence API requires valid objects to work. Here the object is only half > > constructed and list_ass_item tries to DECREF the zeroth member which > > is NULL because the list isn't constructed yet. PyList_SetItem does > > an XDECREF (decrement only if the pointer isn't null) because it expects > > to be used that way. > > PyList_SetItem is not sentient. It expects nothing. Now tell us what > the developer was thinking -- certainly not consistency with the > documantation. If the Sequence API requires valid objects to work, > then in this case it should raise an error. > > In fact that manual section calls using the PySequence_SetItem the > recommended approach!!! > > Are you suggesting a rework of the manual instead of inserting a X in > the offending py_DECREF? > > Sheesh all round ... It takes a big man to admit when he's wrong so I'll blame low blood sugar. Since this had been the same going all the way back to 2.2 I assumed it was common. It isn't, simlar functions in other objects guard against the possibility. I'll check in the change assuming no one else has already (and assuming the trunk isn't currently frozen, I'll have to check). -Jack From khemkaamit at gmail.com Wed Aug 30 05:28:39 2006 From: khemkaamit at gmail.com (Amit Khemka) Date: Wed, 30 Aug 2006 14:58:39 +0530 Subject: how can i change the text delimiter In-Reply-To: <1156929540.715287.123060@h48g2000cwc.googlegroups.com> References: <1156929540.715287.123060@h48g2000cwc.googlegroups.com> Message-ID: <1360b7230608300228w2f9e00f8ta066ab1a43fd9038@mail.gmail.com> sonald wrote: > Hi, > Can anybody tell me how to change the text delimiter in FastCSV Parser > ? > By default the text delimiter is double quotes(") > I want to change it to anything else... say a pipe (|).. > can anyone please tell me how do i go about it? You can use the parser constructor to specify the field seperator: Python >>> parser(ms_double_quote = 1, field_sep = ',', auto_clear = 1) cheers, amit. -- ---- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. From mail at microcorp.co.za Fri Aug 4 01:47:42 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Fri, 4 Aug 2006 07:47:42 +0200 Subject: Running queries on large data structure References: <200608022224.00925.email@christoph-haas.de> <200608031639.30477.email@christoph-haas.de> Message-ID: <00d401c6b79d$fa01ac80$03000080@hendrik> "Christoph Haas" wrote" | On Wednesday 02 August 2006 22:24, Christoph Haas wrote: | > I have written an application in Perl some time ago (I was young and | > needed the money) that parses multiple large text files containing | > nested data structures and allows the user to run quick queries on the | > data. [...] | | I suppose my former posting was too long and concrete. So allow me to try | it in a different way. :) | | The situation is that I have input data that take ~1 minute to parse while | the users need to run queries on that within seconds. I can think of two | ways: | | (1) Database | (very quick, but the input data is deeply nested and it would be | ugly to convert it into some relational shape for the database) | (2) cPickle | (Read the data every now and then, parse it, write the nested Python | data structure into a pickled file. The let the other application | that does the queries unpickle the variable and use it time and | again.) | | So the question is: would you rather force the data into a relational | database and write object-relational wrappers around it? Or would you | pickle it and load it later and work on the data? The latter application | is currently a CGI. I'm open to whatever. :) | | Thanks for any enlightenment. | | Christoph Not sure if this is of any use - but I have noticed that dict lookups in Python is blindingly fast - but it seems to me to use them would be as much trouble to you as converting the data into a shape for the database in third normal form... Unless of course your parser is already doing something like that... There are also some fancy packages for tree structures around, but I don't know anything useful about them. - Hendrik From yxing at ucla.edu Mon Aug 14 18:07:32 2006 From: yxing at ucla.edu (Yi Xing) Date: Mon, 14 Aug 2006 15:07:32 -0700 Subject: Memory problem In-Reply-To: <1155590938.397801.302110@h48g2000cwc.googlegroups.com> References: <1155590938.397801.302110@h48g2000cwc.googlegroups.com> Message-ID: <6fe51ad185fd67a94a66ed8198120aa2@ucla.edu> Is there a way that I can define a two-dimensional array in array.array()? Thanks. On Aug 14, 2006, at 2:28 PM, John Machin wrote: > Yi Xing wrote: >> I tried the following code: >> >>>>> i=0 >>>>> n=2600*2600*30 >>>>> a=array.array("f") >>>>> while (i<=n): >> .. i=i+1 >> .. a.append(float(i)) > > Not a good idea. The array has to be resized, which may mean that a > realloc won't work because of fragmentation, you're out of luck because > plan B is to malloc another chunk, but that's likely to fail as well. >> .. >> Traceback (most recent call last): >> File "", line 3, in ? >> MemoryError >> >> to see the size of the array at the time of memory error: >>>>> len(a) >> 8539248. > > Incredible. That's only 34 MB. What is the size of your paging file? > What memory guzzlers were you running at the same time? What was the > Task Manager "Performance" pane showing while your test was running? > What version of Python? > > FWIW I got up to len(a) == 122998164 (that's 14 times what you got) on > a machine with only 1GB of memory and a 1523MB paging file, with > Firefox & ZoneAlarm running (the pagefile was showing approx 300MB in > use at the start of the test). > >> I use Windows XP x64 with 4GB RAM. > > Maybe there's a memory allocation problem with the 64-bit version. > Maybe MS just dropped in the old Win95 memory allocator that the timbot > used to fulminate about :-( > > Cheers, > John > > -- > http://mail.python.org/mailman/listinfo/python-list > From theller at python.net Tue Aug 8 12:09:35 2006 From: theller at python.net (Thomas Heller) Date: Tue, 08 Aug 2006 18:09:35 +0200 Subject: Tkinter module not found In-Reply-To: References: <1155049496.292471.37020@h48g2000cwc.googlegroups.com> Message-ID: John Salerno schrieb: > Tim Chase wrote: >>> The cause of this is usually that you are using a different >>> version of Python than the one you installed Tkinter into, but >>> being a Linux newbie I have yet to discover how to redirect >>> the 'python' command to invoke the newer version of Python. >> >> >> The OS looks for the first 'python' it finds in its path. >> >> In Linux (or other *nix OSes), you can use >> >> bash> which python > > A very helpful command to know! I'll have to wait til I get home to play > on Linux though. Then I can try these things you suggested. > > I'm suddenly very bored here at work using Windows. :) Well, we have python, haven't we? Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. c:\>which python c:\util\python.EXE c:\>which which c:\util\which.PY c:\>type \util\which.py import os, string, sys PATH = os.environ["PATH"] PATHEXT = os.environ["PATHEXT"] all = 0 if sys.argv[1] == "-a": del sys.argv[1] all = 1 arg = sys.argv[1] base, ext = os.path.splitext (arg) for path in string.split (PATH, ';'): if not ext: for extension in string.split(PATHEXT, ';'): if os.path.isfile(path + '\\' + arg + extension): print path + '\\' + arg + extension if not all: sys.exit (0) else: if os.path.isfile (path + '\\' + arg): print path + '\\' + arg if not all: sys.exit (0) c:\> There may be better variants of which out there... Thomas From dylanhughes at gmail.com Thu Aug 24 22:40:10 2006 From: dylanhughes at gmail.com (DH) Date: 24 Aug 2006 19:40:10 -0700 Subject: Taking data from a text file to parse html page In-Reply-To: References: <1156378275.662140.214650@h48g2000cwc.googlegroups.com> <1156441308.372327.319400@b28g2000cwb.googlegroups.com> Message-ID: <1156473610.654066.323410@p79g2000cwp.googlegroups.com> SE looks very helpful... I'm having a hell of a time installing it though: ----------------------------------------------------------------------------------------- foo at foo:~/Desktop/SE-2.2$ sudo python SETUP.PY install running install running build running build_py file SEL.py (for module SEL) not found file SE.py (for module SE) not found file SEL.py (for module SEL) not found file SE.py (for module SE) not found ------------------------------------------------------------------------------------------ Anthra Norell wrote: > You may also want to look at this stream editor: > > http://cheeseshop.python.org/pypi/SE/2.2%20beta > > It allows multiple replacements in a definition format of utmost simplicity: > > >>> your_example = ''' >

"Python has been an important part of Google since the > beginning, and remains so as the system grows and evolves. > "

>

-- Peter Norvig, ''' > >>> import SE > >>> Tag_Stripper = SE.SE (''' > "~<(.|\n)*?>~=" # This pattern finds all tags and deletes them (replaces with nothing) > "~~=" # This pattern deletes comments entirely even if they nest tags > ''') > >>> print Tag_Stripper (your_example) > > "Python has been an important part of Google since the > beginning, and remains so as the system grows and evolves. > " > -- Peter Norvig, > Now you see a tag fragment. So you add another deletion to the Tag_Stripper (***): > > Tag_Stripper = SE.SE (''' > "~<(.|\n)*?>~=" # This pattern finds all tags and deletes them (replaces with nothing) > "~~=" # This pattern deletes commentsentirely even if they nest tags > " # "-- Peter Norvig, ''') > >>> print Tag_Stripper (your_example) > > "Python has been an important part of Google since the > beginning, and remains so as the system grows and evolves. > " > -- Peter Norvig, > > " you can either translate or delete: > > Tag_Stripper = SE.SE (''' > "~<(.|\n)*?>~=" # This pattern finds all tags and deletes them (replaces with nothing) > "~~=" # This pattern deletes commentsentirely even if they nest tags > " # "-- Peter Norvig, htm2iso.se # This is a file (contained in the SE package that translates all ampersand codes. > # Naming the file is all you need to do to include the replacements which it defines. > ''') > > >>> print Tag_Stripper (your_example) > > 'Python has been an important part of Google since the > beginning, and remains so as the system grows and evolves. > ' > -- Peter Norvig, > > If instead of "htm2iso.se" you write ""=" you delete it and your output will be: > > Python has been an important part of Google since the > beginning, and remains so as the system grows and evolves. > > -- Peter Norvig, > > Your Tag_Stripper also does files: > > >>> print Tag_Stripper ('my_file.htm', 'my_file_without_tags') > 'my_file_without_tags' > > > A stream editor is not a substitute for a parser. It does handle more economically simple translation jobs like this one where a > parser does a lot of work which you don't need. > > Regards > > Frederic > > > ----- Original Message ----- > From: "DH" > Newsgroups: comp.lang.python > To: > Sent: Thursday, August 24, 2006 7:41 PM > Subject: Re: Taking data from a text file to parse html page > > > > I found this > > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/d1bda6ebcfb060f9/ad0ac6b1ac8cff51?lnk=gst&q=replace+text+file&r > num=8#ad0ac6b1ac8cff51 > > > > Credit Jeremy Moles > > ----------------------------------------------- > > > > finds = ("{", "}", "(", ")") > > lines = file("foo.txt", "r").readlines() > > > > for line in lines: > > for find in finds: > > if find in line: > > line.replace(find, "") > > > > print lines > > > > ----------------------------------------------- > > > > I want something like > > ----------------------------------------------- > > > > finds = file("replace.txt") > > lines = file("foo.txt", "r").readlines() > > > > for line in lines: > > for find in finds: > > if find in line: > > line.replace(find, "") > > > > print lines > > > > ----------------------------------------------- > > > > > > > > Fredrik Lundh wrote: > > > DH wrote: > > > > > > > I have a plain text file containing the html and words that I want > > > > removed(keywords) from the html file, after processing the html file it > > > > would save it as a plain text file. > > > > > > > > So the program would import the keywords, remove them from the html > > > > file and save the html file as something.txt. > > > > > > > > I would post the data but it's secret. I can post an example: > > > > > > > > index.html (html page) > > > > > > > > " > > > >

"Python has been an important part of Google since the > > > > beginning, and remains so as the system grows and evolves. > > > > "

> > > >

-- Peter Norvig, > > > " > > > > > > > > replace.txt (keywords) > > > > " > > > >

> > > > > > > >

" > > > > > > > > "

> > > > > > > >

-- Peter Norvig, > > > > > > > " > > > > > > > > something.txt(file after editing) > > > > > > > > " > > > > > > > > Python has been an important part of Google since the beginning, and > > > > remains so as the system grows and evolves. > > > > " > > > > > > reading and writing files is described in the tutorial; see > > > > > > http://pytut.infogami.com/node9.html > > > > > > (scroll down to "Reading and Writing Files") > > > > > > to do the replacement, you can use repeated calls to the "replace" method > > > > > > http://pyref.infogami.com/str.replace > > > > > > but that may cause problems if the replacement text contains things that > > > should be replaced. for an efficient way to do a "parallel" replace, see: > > > > > > http://effbot.org/zone/python-replace.htm#multiple > > > > > > > > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list From originalbrownster at gmail.com Sun Aug 20 21:03:53 2006 From: originalbrownster at gmail.com (OriginalBrownster) Date: 20 Aug 2006 18:03:53 -0700 Subject: string validation/ form validation Message-ID: <1156122233.814935.144940@h48g2000cwc.googlegroups.com> Hi there: I just had a quick thought of something that might be useful to me when creating my web app and I wanted some help on the idea; since this group has been helpful in the past. in my app I have a few html forms that require the user to enter in data, in string form is it possible to validate if the string is in a valid form..such as check if its a list An example ask the user to enter in a list seperated by commas so i want something like "apple,banana,grapes" is there a way to validate that it was entered that way? Any help would be appreciated From mattheww at chiark.greenend.org.uk Wed Aug 30 18:45:04 2006 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 30 Aug 2006 23:45:04 +0100 (BST) Subject: Name of the file associated with sys.std* References: Message-ID: Henryk Modzelewski wrote: >It might be a trivial question, but I seem to be lost. > >Is there a way to get names of the files associated with stdin/out/ >err if those are redirected to the files at the shell command-line? I doubt there is a portable way. On most linux-based systems, os.readlink("/proc/self/fd/1") and os.readlink("/proc/self/fd/2") will work. -M- From aahz at pythoncraft.com Wed Aug 9 14:00:22 2006 From: aahz at pythoncraft.com (Aahz) Date: 9 Aug 2006 11:00:22 -0700 Subject: #!/usr/bin/python or #!/usr/bin/env python? References: Message-ID: In article , John Salerno wrote: > >I understand the difference, but I'm just curious if anyone has any >strong feelings toward using one over the other? I was reading that a >disadvantage to the more general usage (i.e. env) is that it finds the >first python on the path, and that might not be the proper one to use. I >don't know if that's a real issue most of the time, but it's at least >something to consider. The main argument against the env method is that I've seen a fair number of sysadmins claim that it's less secure. I'm not competent to judget that claim myself, but I prefer to play safe and stay away from env. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." --Brian W. Kernighan From ray_usenet at yahoo.com Mon Aug 28 23:13:54 2006 From: ray_usenet at yahoo.com (Ray) Date: 28 Aug 2006 20:13:54 -0700 Subject: How ahead are you guys in the (Python) real world? Message-ID: <1156821234.820929.299740@p79g2000cwp.googlegroups.com> Since I haven't used Python at work, I am using Python 2.5 right now. However I wonder, how fast are you guys moving from version to version at work? As an illustration my ex-company just moved to Java 5, which was released around... what, 2-3 years ago? (While I am running Java 6 at home) Is it the same in the Python world? What version of Python is used in, say, Google? Is it even 2.4 yet? From david_wahler at bic.ky Tue Aug 1 10:07:58 2006 From: david_wahler at bic.ky (david_wahler at bic.ky) Date: 1 Aug 2006 09:07:58 -0500 Subject: Release: DirectPython 0.5 Message-ID: <20060801140758.8092.qmail@BICSRV1011.bic.ky> I'll be out of the office until approximately August 20th. If you have any questions, please email support at bic.ky. -- David Wahler From michiel at thingmajig.org Thu Aug 24 08:26:01 2006 From: michiel at thingmajig.org (Michiel Sikma) Date: Thu, 24 Aug 2006 14:26:01 +0200 Subject: python In-Reply-To: <1156422128.657393.68870@m73g2000cwd.googlegroups.com> References: <1156420101_143@dscnews2.dcccd.edu> <1156422128.657393.68870@m73g2000cwd.googlegroups.com> Message-ID: Op 24-aug-2006, om 14:22 heeft utabintarbo het volgende geschreven: > > laura.biding at ntlworld.com wrote: >> Regards, >> laura.biding at ntlworld.com > > Thanks! > > ???? You're welcome. Signed, Anonymous From python.list at tim.thechases.com Thu Aug 31 10:39:48 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 31 Aug 2006 09:39:48 -0500 Subject: simultaneous copy to multiple media In-Reply-To: <1157031319.315438.4950@b28g2000cwb.googlegroups.com> References: <1157031319.315438.4950@b28g2000cwb.googlegroups.com> Message-ID: <44F6F4B4.8010101@tim.thechases.com> > I need a program that simultaneously can copy a single file (1 > GB) from my pc to multiple USB-harddrives. Sounds like a pretty simple simple python script: ------------------------------------------------------- #!/bin/env python def spew(source_file_name, output_file_names, block_size = 8*1024): source = file(source_file_name, "rb") output_files = [file(s, "wb") for s in output_file_names] s = source.read(block_size) while s: for outfile in output_files: outfile.write(s) s = source.read(block_size) for outfile in output_files: outfile.close() source.close() if __name__ == '__main__': from sys import argv if len(argv) > 2: spew(argv[1], argv[2:]) else: #print some usage/help print "%s source_file dest_file1 [dest_file2 [dest_file3 [...]]]" % argv[0] ------------------------------------------------------- Just call it with bash> cd /mnt bash> python spew.py file1.txt usb1/file1.txt usb2/file2.txt for as many destinations as you want. Adjust the blocksize as you see fit: spew(argv[1], argv[2:], 1024*1024) or whatever your favorite blocksize is. It's not terribly graceful about error-checking, or prompting if any of the files exist previously, or if it can't write to any of the output files because for any reason (full disk, write-protected disk, destination path doesn't exist, etc). Thus, if there's a problem, you'll get a pretty backtrace that will allow you to solve all your problems ;) -tkc From fredrik at pythonware.com Tue Aug 29 12:51:38 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 29 Aug 2006 18:51:38 +0200 Subject: How to let a loop run for a while before checking for break condition? In-Reply-To: <20060828185707.61402.qmail@web56004.mail.re3.yahoo.com> References: <20060828185707.61402.qmail@web56004.mail.re3.yahoo.com> Message-ID: Sorin Schwimmer wrote: > I am thinking on something in the following form: > > > import time > import thread > > delay=True > > def fn() > global delay > time.sleep() > delay=False > > thread.start_new_thread(fn,()) > > while delay: > > > ... if the loop calls out to python functions at least occasionally, you can eliminate the flag by abusing the interpreter's stack check mechanism: import time, thread, sys def alarm(): time.sleep(1.234) sys.setrecursionlimit(1) thread.start_new_thread(alarm, ()) def do_some_work(): pass t0 = time.time() try: while 1: do_some_work() except RuntimeError: pass print time.time() - t0 From fakeaddress at nowhere.org Sun Aug 27 11:00:10 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 27 Aug 2006 15:00:10 GMT Subject: avoiding file corruption In-Reply-To: <1156684454.673072.157900@75g2000cwc.googlegroups.com> References: <1156664673.325201.271140@i42g2000cwa.googlegroups.com> <1156684454.673072.157900@75g2000cwc.googlegroups.com> Message-ID: <_riIg.3480$yO7.2171@newssvr14.news.prodigy.com> Paddy wrote: > I've never done this in anger so feel free to mock (a little :-). > > I'd have a fixed field at the beginning of the field that can hold the > hostname process number, and access time of a writing process, togeher > with a sentinal value that means "no process has access to the file". > > A program would: > 1. wait a random time. > 2. open for update the file > 3. read the locking data > 4. If it is already being used by another process then goto 1. > 5. write the process's locking data and time into the lock field. > 6 Modify the files other fields. > 7 write the sentinal value to the locking field. > 8. Close and flush the file to disk. That doesn't really work; you have still have a race condition. Locking the file is the good solution, but operating systems vary in how it works. Other reasonable solutions are to re-name the file, work with the renamed version, then change it back after closing; and to use "lock files", which Wikipedia explains near the bottom of the "File locking" article. -- --Bryan From thunderfoot at gmail.com Thu Aug 17 09:39:05 2006 From: thunderfoot at gmail.com (thunderfoot at gmail.com) Date: 17 Aug 2006 06:39:05 -0700 Subject: PythonCard question In-Reply-To: <44e46b3f@127.0.0.1> References: <44e46b3f@127.0.0.1> Message-ID: <1155821945.765280.194480@m79g2000cwm.googlegroups.com> DarkBlue wrote: > Is it possible to create pythoncard textField components > dynamically during run time ? > > Something on the lines of > > pseudo code : > > def make_textfield(length,topleftposx,topleftposy): > doit > > self.make_textfield(120,20,20) > > > Thanks for any ideas. The noresource.py sample that ships with PythonCard shows how to add components at runtime. HTH From __peter__ at web.de Wed Aug 30 18:13:47 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 31 Aug 2006 00:13:47 +0200 Subject: unit testing failure makes no sense References: Message-ID: listservs at mac.com wrote: > I have some unit testing code in one of my modules that appears to > run without an error, but the unit test fails anyhow. Have a look at > the output below -- the TestResult seems to have no errors and no > failures, yet I get a system exit. sys.exit(0) is just a normal way to exit a program, and it is implemented as 'raise SystemExit'. You seem to be running your test from within ipython which probably catches SystemExit exceptions to prevent you from losing state. Try running your test from the shell and all should be OK. Peter From ilias at lazaridis.com Fri Aug 25 13:56:24 2006 From: ilias at lazaridis.com (lazaridis_com) Date: 25 Aug 2006 10:56:24 -0700 Subject: CONSTRUCT - Module Attributes and Execution Environment In-Reply-To: References: <1156253227.092971.36510@74g2000cwt.googlegroups.com> Message-ID: <1156528584.439709.134790@m73g2000cwd.googlegroups.com> Larry Bates wrote: > lazaridis_com wrote: > > I would like to change the construct: > > > > if __name__ == '__main__': > > > > to something like: > > > > if exec.isMain(): > > > > My (OO thought) is to place a class in an separate code module and to > > instantiate an singleton instance which would keep th something like > > this: > > > > class ExecutionEnv: > > def isMain(self) > > if CALLING_MODULE.__name__ == '__main__': > > return true > > else > > return false > > > > exec = ExecutionEnv() > > > > How to I get access to the CALLING_MODULE ? > > > > - > > > > Are ther alternative constructs/mechanism available, which could be > > used to add this functionality possiby directly to a code-module? > > > Two thoughts: > > 1) Don't call a class instance exec, it will mask the built-in > exec statement. ok, I understand. > 2) IMHO all the suggestions are way more complicated than > if __name__ == "__main__" and are not SOP for most pythoneers. > I know what the former construct means/does. I have to > decipher your class to figure our what the latter does and it > doesn't really save you any code or provide a performance > enhancement. "Clarity for Pythoneers" is not a main requirement of the project. The main requirements (The network of requirements is not yet fully documented): http://case.lazaridis.com/wiki/Code The related issue: http://case.lazaridis.com/ticket/5 > -Larry From paolopantaleo at gmail.com Sun Aug 27 05:29:20 2006 From: paolopantaleo at gmail.com (Paolo Pantaleo) Date: Sun, 27 Aug 2006 11:29:20 +0200 Subject: Python daemon process In-Reply-To: References: Message-ID: <83e8215e0608270229j6fd8b5e3qe60d3902dc54fee@mail.gmail.com> 2006/8/26, Thomas Dybdahl Ahle : > Hi, I'm writing a program, using popen4(gnuchess), > The problem is, that gnuchess keeps running after program exit. > > I know about the atexit module, but in java, you could make a process a > daemon process, and it would only run as long as the real processes ran. I > think this is a better way to stop gnuchess, as you are 100% sure, that > it'll stop. > > Can you do this with popen? > > -- > Thomas > -- > http://mail.python.org/mailman/listinfo/python-list > You could send the quit (or close or wahtever) command to gnuchess when you want it to terminate. Supposing that gnuchess needs to do some stuff on exit, this is a better solution. PAolo -- if you have a minute to spend please visit my photogrphy site: http://mypic.co.nr From irmen.NOSPAM at xs4all.nl Tue Aug 29 13:36:40 2006 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Tue, 29 Aug 2006 19:36:40 +0200 Subject: about daemons and IPC In-Reply-To: <1156647700.097018.67040@m73g2000cwd.googlegroups.com> References: <1156647700.097018.67040@m73g2000cwd.googlegroups.com> Message-ID: <44f47b32$0$4528$e4fe514c@news.xs4all.nl> sdistefano at gmail.com wrote: > Hey people! > For the first time I'm doing a client/server application, and I'm > really confused with IPC stuff. [...] > Any suggestions? http://pyro.sourceforge.net depending on your needs.... --Irmen From david_wahler at bic.ky Tue Aug 1 10:07:48 2006 From: david_wahler at bic.ky (david_wahler at bic.ky) Date: 1 Aug 2006 09:07:48 -0500 Subject: =?utf-8?Q?Re:_[ANN]_LibYAML=2D0.0.1:_The_initial_release?= Message-ID: <20060801140748.8058.qmail@BICSRV1011.bic.ky> I'll be out of the office until approximately August 20th. If you have any questions, please email support at bic.ky. -- David Wahler From aahz at pythoncraft.com Thu Aug 3 00:41:04 2006 From: aahz at pythoncraft.com (Aahz) Date: 2 Aug 2006 21:41:04 -0700 Subject: Programming newbie coming from Ruby: a few Python questions References: <1154458926.738922.156910@h48g2000cwc.googlegroups.com> <1154460978.604511.209260@75g2000cwc.googlegroups.com> Message-ID: In article <1154460978.604511.209260 at 75g2000cwc.googlegroups.com>, crystalattice wrote: > >The best book I've found for "teaching" you the language is from Deitel >and Deitel: Python, How to Program. It's outdated in that is uses >Python 2.2 but the vast majority of concepts still apply; it does >mention when certain features are deprecated so you shouldn't have a >problem. The main problem with the Deitel book is that it does not, in fact, teach you how to program in Python. Instead, it teaches you how to program in Java using Python. (That's a little bit of an overstatement, admittedly, but not much of one.) There is also lots of incorrect information. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." --Brian W. Kernighan From jspeis at gmail.com Tue Aug 8 10:46:20 2006 From: jspeis at gmail.com (Jon) Date: 8 Aug 2006 07:46:20 -0700 Subject: variable creation In-Reply-To: References: Message-ID: <1155048380.724969.266870@m79g2000cwm.googlegroups.com> Hi, I'm not sure if this is exactly what you had in mind but what about something like this: elements = [] Els = "" pt = {'H': 1.00794, 'He': 4.002602, 'Li': 6.941, 'Be': 9.012182, 'B':10.811} while Els != 'No': Els = raw_input("""Are there any further elements you would like to include? if so type the element, eg, Pd. If not type No:""") if pt.has_key(Els): elements.append({Els:pt[Els]}) print elements Alistair King wrote: > Hei all, > > im trying to create a list of variables for further use: > > > Els = raw_input("Are there any further elements you would like to > include? if so type the element, eg, Pd. If not type No: ") > > if Els != 'No': > el = Els in pt > while el == 1 and Els != 'Next': > elements = [] > elements.insert(-1, Els) > > Els = raw_input("Which further element would you like to > include, eg, Pd, if not type Next: ") > el = Els in pt > > while el == 0 and Els != 'Next': > Els = raw_input("This is not an element in the periodic > table, please try again, eg Pd, If you dont wish to include any more, > type Next: ") > if el == 1: > elements.insert(-1, Els) > > while el == 0: > Els = raw_input("This is not an element in the periodic > table, please try again, eg Pd. If you dont wish to include any more, > type Next: ") > > print elements > > > this works to a certain extent but gets stuck on some loop. Im a > beginner and am not sure where im going wrong. > > here is a portion of the dictionary containing typical elements: > > pt = {'H': 1.00794, 'He': 4.002602, 'Li': 6.941, 'Be': 9.012182, 'B': > 10.811} > > > Ali > > > -- > Dr. Alistair King > Research Chemist, > Laboratory of Organic Chemistry, > Department of Chemistry, > Faculty of Science > P.O. Box 55 (A.I. Virtasen aukio 1) > FIN-00014 University of Helsinki > Tel. +358 9 191 50429, Mobile +358 (0)50 5279446 > Fax +358 9 191 50366 From guotie.9 at gmail.com Wed Aug 30 02:44:17 2006 From: guotie.9 at gmail.com (=?utf-8?B?5Y+u5Y+u5b2T5b2T?=) Date: 29 Aug 2006 23:44:17 -0700 Subject: The lib email parse problem... In-Reply-To: <1156919044.575120.195580@i42g2000cwa.googlegroups.com> References: <1156837260.222395.305960@b28g2000cwb.googlegroups.com> <1156841437.692537.68200@i42g2000cwa.googlegroups.com> <1156841950.866776.66400@b28g2000cwb.googlegroups.com> <1156842395.855885.183330@p79g2000cwp.googlegroups.com> <1156844520.044398.7900@h48g2000cwc.googlegroups.com> <1156919044.575120.195580@i42g2000cwa.googlegroups.com> Message-ID: <1156920257.020916.268490@m73g2000cwd.googlegroups.com> yes, the special is i must choose exactly one section to destruct, instead of processing all subparts. John Machin ??? > Tim Roberts wrote: > > "????" wrote: > > > > >i know how to use email module lib. > > > > > >the question is about how to handle the rfc 1521 mime > > >mulitpart/alternitave part . > > > > > >i know emai can handle mulitpart , but the subpart alternative is > > >special . > > > > No, it's not. A multipart/alternative section is constructed exactly the > > same as any other multipart section. It just so happens that it will have > > exactly two subsections, one text/plain and one text/html. > > I was under the impression that it was a little more general than that > ... see e.g. http://www.freesoft.org/CIE/RFC/1521/18.htm > > My guess is that the OP meant special in the sense that the reader > needs to choose one subpart, instead of processing all subparts. > > Cheers, > John > > > > > > -- > > - Tim Roberts, timr at probo.com > > Providenza & Boekelheide, Inc. From martin at v.loewis.de Wed Aug 2 17:40:19 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 02 Aug 2006 23:40:19 +0200 Subject: VisualStudio2005 supported in distutils In-Reply-To: References: Message-ID: <44D11BC3.40802@v.loewis.de> mg schrieb: > Unfortunately, distutils does not support VisualStudio2005. I tried to > modify the file msvccompiler.py without success (this case requires to > support some changes of the Visual Studio 8 register for both Win32 and > Win64). So, I wonder if the integration of VisualStudio2005 in distutils > is scheduled in the Python developments or better, if someone has > experiences or patch to support VisualStudio2005 in distutils. You shouldn't attempt to do that. Even if you manage to convince distutils to use VS 2005 to compile your extension, the resulting code may crash Python because of obscure incompatibilities between the compiler that was used to compile Python (VS 2003) and the compiler that was used to compile the extension (VS 2005). Whether or not it will actually crash depends on obscure details of the API that the extension uses. Regards, Martin From dppdoran at gmail.com Thu Aug 31 10:24:56 2006 From: dppdoran at gmail.com (Dermot Doran) Date: Thu, 31 Aug 2006 16:24:56 +0200 Subject: How to avoid a warning message box when sending email via Outlook In-Reply-To: References: Message-ID: Thanks Tim! We have smtp bolted to the floor :-( On 31/08/06, Tim Golden wrote: > > [Dermot Doran] > > | looks like I might be back to the drawing board :-( Thanks > | for letting me know what your experiences have been. > > Just to elaborate slightly on that experience, if all I want > to do is to send an email (ie not look up addresses on Contacts > or do any fancy Outlook-related thing) then I just use an SMTP > server. Here at work the admins have Exchange set up as an > SMTP server, which may or may not be the case for you. At home > or from websites etc. I simply use whichever SMTP server I'd > normally send mail through. > > Obviously this won't do anything like keeping a copy in your > Sent Mail box etc. but it will at least work, and with a bit > more effort you may be able to do things like that manually. > > TJG > > BTW, people in this group will tend to frown on top-posting, > even though we Outlook users have to work around Outlook's > tendency to offer it a [Reply] ;) > > ________________________________________________________________________ > This e-mail has been scanned for all viruses by Star. The > service is powered by MessageLabs. For more information on a proactive > anti-virus service working around the clock, around the globe, visit: > http://www.star.net.uk > ________________________________________________________________________ > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jackson at hotmail.com Mon Aug 14 03:33:42 2006 From: jackson at hotmail.com (Jackson) Date: Mon, 14 Aug 2006 00:33:42 -0700 Subject: selecting base class from user input In-Reply-To: <1155523781.860117.203140@h48g2000cwc.googlegroups.com> References: <1155523781.860117.203140@h48g2000cwc.googlegroups.com> Message-ID: Thanks for the reply. danielx wrote the following on 2006-08-13 19:49: > Is your declaration of ABC supposed to have some_super as one of the > base classes? Your constructor has some_super as a parameter. What is > this supposed to mean in light of the declaration for ABC? Indeed, my goal is to have the base class of ABC determined dynamically via a parameter passed into the constructor. > > If you are trying to customize the base class of ABC by passing an > argument to the constructor of ABC, you should probably reconsider. If > constructing one instance of ABC can change ABC (the class) itself, > then the behavior of other instances will be affected as well. No > programmer can stay sane if he creates instances of a class that could > suddenly change its behavior (due to someone else's code). Fortunately, the ABC class is not very useful. In fact, it was mostly just to be used to store particular examples of the user-specified base class. So all method calls would be from the base class only. > > What you could do instead is to create a function which constructs > classes based on the arguments it recieves. Then, you'll be able to > create instances of the generated classes (all this meta-thinking is > huring my brain ;). I am talking about something like this: > > def createClass(name, base): > exec "class %s(%s): pass" % (name, base) > return eval( "name" ) In fact, this is exactly what I ended up doing. def example(base): if base == SomeClass: # call SomeClass.__init__(self) # build example as it would look in SomeClass elif base == SomeOtherClass: # call SomeOtherClass.__init__(self) # build example as it would in SomeOtherClass > Can you please tell us why you are doing this? My curiosity is killing > me! > So here is a good example: I have 4 classes: Lion(Animal): Ant(Animal): Bee(Animal): Human(Animal): which are all subclasses of some superclass called Animal. Now I want to define an occupation. For example, Worker. A worker can exist as any of the 4 classes above. Their constructors are different and I might want to add certain features. My first thought was to create a class called "Worker" and have the base class determined by a variable which is passed into the constructor. Most of the method calls will come from the Animal superclass anyway, but some method calls might come from the Lion class, for example. Now I realize this would drive a programmer crazy...because a Lion might have a roar() method whereas a Human might have a holler() method. But so long as the user knew which argument they passed in, it shouldn't be too difficult to keep track of it. So for example (again, I know what I am typing doesn't actually work)... Worker(some_animal): def __init__(self,some_animal): # change the base class to some_animal if some_animal == Lion: # give the lion a big mane if some_animal == Ant: # make the ant dumb if some_animal == Bee: # make the bee know how to dance if some_animal == Human # give the human a hardhat def work(self, hours): # tell the animal to work for the specified number of hours if some_animal == Lion: self.cat_nap(hours) if some_animal == Ant: self.walk_back_and_forth(hours) if some_animal == Bee: self.buzz_and_dance(hours) if some_animal == Human: self.use_hammer_on_coworker(hours) # notice, a Human does not have a cat_nap method def take_lunch(location): .... and so on. So the thought is that a Worker can exist in many different forms: as a lion, as an ant, as a bee, and as a human. And I might want a single worker class that represents them all. Hopefully this makes sense. > Another meta-thought: Hopefully I've beaten everyone else to the punch > about that question. Is it just me, or will a reply with such a > question always tell the original poster that what he wants to do MUST > be flawed? I hope I have been gentler than this. > :-) There is no need to be too gentle. We are all here to learn (or help). So I am fairly happy with the def solution...any comments on this? But a Worker is an noun, and it seems like the proper way to do this is to make the Worker into a class...so that I can define methods like "work", "take_lunch", etc. However, I have no idea how I should do this. Perhaps someone can recommend a procedure. thanks. From g.brandl-nospam at gmx.net Fri Aug 25 05:13:14 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Fri, 25 Aug 2006 11:13:14 +0200 Subject: List problem In-Reply-To: <1156458544.544455.192330@m73g2000cwd.googlegroups.com> References: <1156458544.544455.192330@m73g2000cwd.googlegroups.com> Message-ID: kevndcks at aol.com wrote: > For example i write the following code in the Python command line; > >>>>list = ['One,Two,Three,Four'] > > Then enter this command, which will then return the following; > > ['One,Two,Three,Four'] This is already wrong. Assignments do not return anything. Georg From fhurley at gmail.com Tue Aug 1 09:02:09 2006 From: fhurley at gmail.com (fhurley at gmail.com) Date: 1 Aug 2006 06:02:09 -0700 Subject: Can't get LCHARVAR's with InformixDB Message-ID: <1154437329.471918.35150@h48g2000cwc.googlegroups.com> I'm using the InformixDB package, which has been a real lifesaver, but I'm finding I can't get any data from the Informix LCHARVAR types. They're coming in as empty strings. The cursor._description for the field in question is: ('msg_text', 'lvarchar', 0, 0, None, None, 1) Appreciate any help... thanks. From ajaksu at gmail.com Thu Aug 17 09:41:47 2006 From: ajaksu at gmail.com (ajaksu) Date: 17 Aug 2006 06:41:47 -0700 Subject: wxPython Grid Question In-Reply-To: <1155788722.147173.58730@m73g2000cwd.googlegroups.com> References: <1155788722.147173.58730@m73g2000cwd.googlegroups.com> Message-ID: <1155822107.651813.192860@74g2000cwt.googlegroups.com> Jordan wrote: > Hey Peoples, > I'm wonderg if there is a way to make a subclass of wx.grid.Grid in > which the coloumn labels for the grid appear on the bottom of the grid > instead of the top. Hi Jordan :) Not quite what you want, but I'm about to try faking labels in a grid. The reason is that I want more control regarding rendering the labels (using simple checkboxes and other features). So I'll try to get the first row to display as "headers". If that works, would it help you? And would you append rows frequently? Just FWIW, I recall reading that a grid is composed of some base elements (scrolled window and something else), so you might try to follow that lead. But jean-michel has two good points: it could be easier to use 2 grids and http://wxpython.org/maillist.php would give you better answers :) Cheers, Daniel From http Thu Aug 3 19:13:00 2006 From: http (Paul Rubin) Date: 03 Aug 2006 16:13:00 -0700 Subject: Running queries on large data structure References: <200608022224.00925.email@christoph-haas.de> Message-ID: <7xac6l4dmr.fsf@ruckus.brouhaha.com> Christoph Haas writes: > So the question is: would you rather force the data into a relational > database and write object-relational wrappers around it? Or would you > pickle it and load it later and work on the data? The latter application > is currently a CGI. I'm open to whatever. :) The obvious solution is don't use a CGI. Use a continuously-running server process that keeps the structure in memory. Write update records out to disk as they arrive, and reload them if you need to restart the server. From justin.azoff at gmail.com Tue Aug 8 21:34:02 2006 From: justin.azoff at gmail.com (Justin Azoff) Date: 8 Aug 2006 18:34:02 -0700 Subject: newb question: file searching References: <1155067111.892386.130610@n13g2000cwa.googlegroups.com> <1155084224.829101.63940@i42g2000cwa.googlegroups.com> Message-ID: <1155087242.679420.128830@m73g2000cwd.googlegroups.com> jaysherby at gmail.com wrote: > I've narrowed down the problem. All the problems start when I try to > eliminate the hidden files and directories. Is there a better way to > do this? > Well you almost have it, but your problem is that you are trying to do too many things in one function. (I bet I am starting to sound like a broken record :-)) The four distinct things you are doing are: * getting a list of all files in a tree * combining a files directory with its name to give the full path * ignoring hidden directories * matching files based on their extension If you split up each of those things into their own function you will end up with smaller easier to test pieces, and separate, reusable functions. The core function would be basically what you already have: def get_files(directory, include_hidden=False): """Return an expanded list of files for a directory tree optionally not ignoring hidden directories""" for path, dirs, files in os.walk(directory): for fn in files: full = os.path.join(path, fn) yield full if not include_hidden: remove_hidden(dirs) and remove_hidden is a short, but tricky function since the directory list needs to be edited in place: def remove_hidden(dirlist): """For a list containing directory names, remove any that start with a dot""" dirlist[:] = [d for d in dirlist if not d.startswith('.')] at this point, you can play with get_files on it's own, and test whether or not the include_hidden parameter works as expected. For the final step, I'd use an approach that pulls out the extension itself, and checks to see if it is in a list(or better, a set) of allowed filenames. globbing (*.foo) works as well, but if you are only ever matching on the extension, I believe this will work better. def get_files_by_ext(directory, ext_list, include_hidden=False): """Return an expanded list of files for a directory tree where the file ends with one of the extensions in ext_list""" ext_list = set(ext_list) for fn in get_files(directory, include_hidden): _, ext = os.path.splitext(fn) ext=ext[1:] #remove dot if ext.lower() in ext_list: yield fn notice at this point we still haven't said anything about images! The task of finding files by extension is pretty generic, so it shouldn't be concerned about the actual extensions. once that works, you can simply do def get_images(directory, include_hidden=False): image_exts = ('jpg','jpeg','gif','png','bmp') return get_files_by_ext(directory, image_exts, include_hidden) Hope this helps :-) -- - Justin From bdesth.quelquechose at free.quelquepart.fr Wed Aug 2 18:21:53 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 03 Aug 2006 00:21:53 +0200 Subject: Programming newbie coming from Ruby: a few Python questions In-Reply-To: <1154539223.873418.286830@i42g2000cwa.googlegroups.com> References: <1154494954.082706.283750@b28g2000cwb.googlegroups.com> <44d06f9f$0$19127$626a54ce@news.free.fr> <1154539223.873418.286830@i42g2000cwa.googlegroups.com> Message-ID: <44d12385$0$1322$626a54ce@news.free.fr> simonharrison at fastmail.co.uk a ?crit : > thanks very much for all the comments, links to articles and other > help.The Ruby crowd says you guys are no where near as friendly as > them! Yes. Python bashing sadly appears to be the national sport amongst Rubyists. Looks like a puberty crisis to me, and I guess (or at least hope) this will calm down when Ruby will start to mature. FWIW, c.l.py is still one of the more helpful and friendly place on usenet. This doesn't mean there's no RTFMs, but at least they are usually gently followed by a link to the relevant section !-) > I was half expecting a nervous breakdown after writing my first > post here. Sorry if you're disappointed. But you can take a chance on c.l.lisp if you really want a newsgroup that's nowhere as friendly as this one !-) > Cheers again Welcome on board - hope you'll enjoy the trip. From w_a_x_man at yahoo.com Mon Aug 28 04:28:40 2006 From: w_a_x_man at yahoo.com (William James) Date: 28 Aug 2006 01:28:40 -0700 Subject: A Sort Optimization Technique: decorate-sort-dedecorate References: <1156719092.603277.57390@b28g2000cwb.googlegroups.com> Message-ID: <1156753720.712245.172690@m79g2000cwm.googlegroups.com> xahlee at gmail.com wrote: > I would be interested in comments about how Common Lisp, Scheme, and > Haskell deal with the decorate-sort-dedecorate technique. %w(FORTRAN LISP COBOL).sort_by{|s| s.reverse} ==>["COBOL", "FORTRAN", "LISP"] -- Common Lisp did kill Lisp. Period. ... It is to Lisp what C++ is to C. A monstrosity that totally ignores the basics of language design, simplicity, and orthogonality to begin with. --- Bernard Lang From martin at v.loewis.de Wed Aug 2 15:23:59 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 02 Aug 2006 21:23:59 +0200 Subject: ElementTree and Unicode In-Reply-To: <1154532671.351968.142890@b28g2000cwb.googlegroups.com> References: <1154530195.741884.34350@h48g2000cwc.googlegroups.com> <1154532671.351968.142890@b28g2000cwb.googlegroups.com> Message-ID: <44D0FBCF.1040805@v.loewis.de> S?bastien Boisg?rault schrieb: > I am trying to embed an *arbitrary* (unicode) strings inside > an XML document. Of course I'd like to be able to reconstruct > it later from the xml document ... If the naive way to do it does > not work, can anyone suggest a way to do it ? XML does not support arbitrary Unicode characters; a few control characters are excluded. See the definiton of Char in http://www.w3.org/TR/2004/REC-xml-20040204 [2] Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] Now, one might thing you could use a character reference (e.g. �) to refer to the "missing" characters, but this is not so: [66] CharRef ::= '&#' [0-9]+ ';' | '&#x' [0-9a-fA-F]+ '; Well-formedness constraint: Legal Character Characters referred to using character references must match the production for Char. As others have explained, if you want to transmit arbitrary characters, you need to encode it as text in some way. One obvious solution would be to encode the Unicode data as UTF-8 first, and then encode the UTF-8 bytes using base64. The receiver of the XML document then must do the reverse. Regards, Martin From sjmachin at lexicon.net Wed Aug 30 21:32:28 2006 From: sjmachin at lexicon.net (John Machin) Date: 30 Aug 2006 18:32:28 -0700 Subject: python equivalent for fputc In-Reply-To: <1156986879.533017.241450@b28g2000cwb.googlegroups.com> References: <1156986879.533017.241450@b28g2000cwb.googlegroups.com> Message-ID: <1156987948.093037.93420@m79g2000cwm.googlegroups.com> Putty wrote: > I'm porting a program a friend wrote in C over to Python and I've run > into a little hang-up. The C program writes characters out to a file. > I'm 99% sure that a conversion is going on here as well. I know for a > fact that it's taking a number and turning it into a character. C is a low-level language -- a character *is* a number :-) > > So what kind of call can I make to do it in Python? *Guessing* that you mean e.g. fputc(97, f) writes the character 'a' to the file whose handle is f ... In Python the more-or-less literal translation (ignoring the fputc return value) would be f.write(chr(97)) Note: |>>> ord('a') 97 |>>> chr(97) 'a' HTH -- if not, show us (relevant parts of) the actual source that you are porting. Cheers, John From mturillo at gmail.com Sun Aug 20 17:32:08 2006 From: mturillo at gmail.com (Perseo) Date: 20 Aug 2006 14:32:08 -0700 Subject: Python Expert Message-ID: <1156109528.138808.179610@i42g2000cwa.googlegroups.com> Hi guys, we are looking for a python developer for a European project. This project is multilangual and free it is called EuroCv and it need a module for exporting data in PDF. As web developer I try to create this module but It's too complicate for me. Check out the service www.eurocv.eu for more details. Contact us by Skype chat system our nick is eurocv. Thanks From johnjsal at NOSPAMgmail.com Fri Aug 18 21:20:47 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 18 Aug 2006 21:20:47 -0400 Subject: text editor suggestion? Message-ID: <44e66724$0$2363$c3e8da3@news.astraweb.com> Ok, I know it's been asked a million times, but I have a more specific question so hopefully this won't be just the same old post. I've tried a few different editors, and I really like UltraEdit, but it's Windows-only and I'm working more on Linux nowadays. Here are my criteria: 1. syntax highlighting (highly customizable) 2. auto/smart indenting 3. ability to run script 4. light-weight text editor, not an IDE 5. cross-platform (not really necessary, but nice) That's pretty much all I need. It's nice when you can customize a bunch of other stuff too, but those are the most important. I've tried vim, but I really don't feel like taking the time to learn how to use it, given that I just like to casually program (not to mention that I prefer to use the mouse when navigating a document sometimes). I also just started using Scite, and I really like it, except I find its syntax highlighting to be very inflexible. You aren't able to define your own groups of words -- you have to use what's given, basically. One thing I like about UltraEdit is that you simply define as many groups of keywords as you want and then assign a style to each one. Scite has a very strange and rigid method of highlighting. So hopefully some of you might have some suggestions. My requirements are minimal, but I'm still not happy with the syntax highlighting I'm seeing in a lot of editors out there. From rogue_pedro at yahoo.com Wed Aug 16 04:07:22 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 16 Aug 2006 01:07:22 -0700 Subject: how to deepcopy a slice object? In-Reply-To: <1155714158.106027.213490@i3g2000cwc.googlegroups.com> References: <1155629155.207232.50400@m79g2000cwm.googlegroups.com> <1155633086.985976.59960@m79g2000cwm.googlegroups.com> <1155635860.046177.109830@74g2000cwt.googlegroups.com> <1155677862.630671.122950@m79g2000cwm.googlegroups.com> <1155714158.106027.213490@i3g2000cwc.googlegroups.com> Message-ID: <1155715642.317634.185530@i42g2000cwa.googlegroups.com> Alexandre Guimond wrote: > thx for all the help simon. good ideas i can work with. > > thx again. > > alex. > You're very welcome, a pleasure. ;-) ~Simon From eightyx at gmail.com Tue Aug 8 16:57:47 2006 From: eightyx at gmail.com (Eighty) Date: 8 Aug 2006 13:57:47 -0700 Subject: Proposal: [... for ... while cond(x)] In-Reply-To: References: <1154879331.903490.106020@m73g2000cwd.googlegroups.com> <1155064682.499991.246170@h48g2000cwc.googlegroups.com> Message-ID: <1155070666.951023.161280@b28g2000cwb.googlegroups.com> Terry Reedy wrote: > whereas the analogous expansion of your proposal > > for x in xs: > while cond(x): > yield e(x) > > is an infinite loop and not at all what you mean. You're right. The syntax is ambiguous. I agree it's not a good idea, now. :) > x for x in xs while cond(x) if blah(x) > x for x in xs if blah(x) while cond(x) > x*y for x in xs while cond(x) for y in ys These wouldn't be a problem. "... for x in xs while cond(x) ..." would be transformed into "... for x in takewhile(cond, xs) ..." which could be applied to an if thingy if you first transform "... for x in xs if cond(x) ..." into "... for x in filter(cond, xs) ...". From mensanator at aol.com Thu Aug 3 21:02:05 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 3 Aug 2006 18:02:05 -0700 Subject: programming is hard In-Reply-To: <1154648416.036565.224320@p79g2000cwp.googlegroups.com> References: <1154609819.083694.22200@m73g2000cwd.googlegroups.com> <1154623085.994132.126620@m73g2000cwd.googlegroups.com> <1154648416.036565.224320@p79g2000cwp.googlegroups.com> Message-ID: <1154653325.803973.292490@p79g2000cwp.googlegroups.com> placid wrote: > Alas, all good arguments. > > I rest my case. After you've just been proven wrong? I wouldn't want you for my lawyer. > > :( > > > Cheers From paul at boddie.org.uk Thu Aug 24 17:50:42 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 24 Aug 2006 14:50:42 -0700 Subject: Python & chess References: <83e8215e0608240358l4126bb83la93a4c61e4aa4499@mail.gmail.com> <44ee0a53$0$1390$da0feed9@news.zen.co.uk> Message-ID: <1156456242.421791.236000@h48g2000cwc.googlegroups.com> Will McGugan wrote: > > I have written a chess module that may be of use to you. > > http://www.willmcgugan.com/2006/06/18/chesspy/ See also ChessBoard - a nice implementation of chess using pygame: http://www.pygame.org/projects/9/282/ Paul From mailer at forums.com Wed Aug 9 00:06:17 2006 From: mailer at forums.com (Dean Card) Date: Tue, 8 Aug 2006 21:06:17 -0700 Subject: PIL Image transform Message-ID: Okay, so here is the situation. I have need to do some on-the-fly image creation. I have everything working great except for the last part of it, applying a perspective type transform to the image. The transform will take a rectangular 2D image and transform it to a 3D representation in 2D. Please see the link to see what I am trying to do: http://seanberry.com/transform.png I have PIL v1.15 installed which has a PERSPECTIVE transform, but it does not appear to do what I want - or I can't figure out how to use it correctly because it is using a transform matrix's coefficients. Here is the only info I could find on the usage: http://mail.python.org/pipermail/image-sig/2005-February/003198.html This is for the creation of images to be used in Flash. Originally I was doing the image processing in Flash because Flash 8 has a BitmapData class which does the basics of images, copy, transform, etc. To accomplish the transform I was using an algorithm that approximated triangles to fill and worked really well, but I need the image processing to be server side, not client. So, here I am. Anyone have any idea how to accomplish my goal here? Is there a way to fill a triangle with a bitmap using PIL? What about better docs on the PERSPECTIVE transform? Thanks for any and all help on this. From sxn02 at yahoo.com Mon Aug 28 13:29:23 2006 From: sxn02 at yahoo.com (Sorin Schwimmer) Date: Mon, 28 Aug 2006 10:29:23 -0700 (PDT) Subject: How to let a loop run for a while before checking for break condition? Message-ID: <20060828172923.62400.qmail@web56011.mail.re3.yahoo.com> to Fredrik Lundh I'm afraid Claudio Grondi can't use your solution, as he needs it hosted on Windows, which lacks signal.alarm. to Claudio Grondi How about splitting your loop in two? The first loop would check for your boolean, which is changed by your timer, the second loop will check for your "normal" exit condition? Sorin __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From bryanjugglercryptographer at yahoo.com Tue Aug 1 03:22:16 2006 From: bryanjugglercryptographer at yahoo.com (bryanjugglercryptographer at yahoo.com) Date: 1 Aug 2006 00:22:16 -0700 Subject: Using Python for my web site In-Reply-To: <1154361480.915174.262720@b28g2000cwb.googlegroups.com> References: <1154361480.915174.262720@b28g2000cwb.googlegroups.com> Message-ID: <1154416936.743642.50900@i42g2000cwa.googlegroups.com> northband wrote: > Hi, I am interested in re-writing my website in Python vs PHP but have > a few questions. Here are my specs, please advise as to which > configuration would be best: > > 1.Dell Poweredge Server, w/IIS, currently Windows but considering > FreeBSD > 2. Site consists of result pages for auctions and items for sale (100 > per page) > 3. MySQL (Dell Poweredge w/AMD) database server connected to my web > server > 4. Traffic, 30 million page loads/month > > I am trying to have the fastest page loads, averaging 100 items per > result page. I have read about using Apache's mod_python so I could > use PSP. Any help or tips are appreciated. So if I'm reading this correctly: you have a system that's working, and the main purpose of the re-write is faster page responses to users. Do I have that right? Have you determined where the time is spent? For some web apps, speed is all about the database, and if that's true of your system then changing scripting language isn't going to provide the performance boost you seek. Another interesting question is how response time changes with increasing load. Of course with the real website, those 30 million page loads per month are not uniformly distributed. What is your peak rate? Is rush-hour speed mostly what motivates the project? -- --Bryan From fredrik at pythonware.com Wed Aug 30 23:45:42 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 31 Aug 2006 05:45:42 +0200 Subject: python equivalent for fputc References: <1156986879.533017.241450@b28g2000cwb.googlegroups.com> Message-ID: Putty wrote: > I'm porting a program a friend wrote in C over to Python and I've run > into a little hang-up. The C program writes characters out to a file. > I'm 99% sure that a conversion is going on here as well. I know for a > fact that it's taking a number and turning it into a character. that's what fputc does, of course -- it takes an integer and writes it as a character to the given stream. f = fopen(filename, "w"); fputc(c, f); fclose(f) becomes f = open(filename, "w") f.write(chr(value)) f.close() From tom-2006 at jaguarpaw.get-rid-of-this-bit.co.uk Wed Aug 23 17:40:20 2006 From: tom-2006 at jaguarpaw.get-rid-of-this-bit.co.uk (Tom E H) Date: Wed, 23 Aug 2006 22:40:20 +0100 Subject: Accessing application data portably References: <44ECBEE1.6040106@websafe.com> Message-ID: Larry Bates wrote: > Tom E H wrote: >> My Python application includes some data files that need to be accessed >> by modules I distribute with it. >> >> Where can I put them, and how should I arrange my code, so that it works >> across platforms? >> > I almost always send along an application.ini file and put the location > of where my data is to be stored in that file instead of imbedding (or > worse, hard-coding) it in the application program itself. > Something like: > > [init] > debug=0 > quiet=0 > datafilepath=/usr/lib/myprogram/datafile Well that's great, but how do you access the ini file portably? Tom From yuxi at ece.gatech.edu Mon Aug 14 13:01:09 2006 From: yuxi at ece.gatech.edu (Yu-Xi Lim) Date: Mon, 14 Aug 2006 13:01:09 -0400 Subject: outputting a command to the terminal? In-Reply-To: References: <44df99f7$0$25025$c3e8da3@news.astraweb.com> <44dfc1cb$0$2397$c3e8da3@news.astraweb.com> Message-ID: Dennis Lee Bieber wrote: > Well, I don't do shell scripts either, but... looking at the > sample... "$@" is likely the shell equivalent of Python's sys.argv -- or > *sys.argv if passed down Yeah, kinda equivalent to *sys.argv[1:]. From blue99 at interia.pl Thu Aug 10 06:45:15 2006 From: blue99 at interia.pl (Rob Wolfe) Date: 10 Aug 2006 03:45:15 -0700 Subject: sys.platform documentation? In-Reply-To: References: <4A36E990-C1F6-47B2-99A7-CCBCFC344540@thingmajig.org> <20060810095026.GA24421@unrealtower.org> Message-ID: <1155206715.371369.3370@b28g2000cwb.googlegroups.com> Michiel Sikma wrote: > So here's the question of the day: what does your sys.platform tell > you? :-) uname -srv HP-UX B.11.00 D python -c "import sys; print sys.platform" hp-ux11 Regards, Rob From johnjsal at NOSPAMgmail.com Wed Aug 2 10:23:48 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 02 Aug 2006 14:23:48 GMT Subject: cleaner way to write this try/except statement? In-Reply-To: References: Message-ID: John Salerno wrote: > The code to look at is the try statement in the NumbersValidator class, > just a few lines down. Is this a clean way to write it? i.e. is it okay > to have all those return statements? Is this a good use of try? Etc. Ok, I came up with this. It looks much nicer, I think, though I'm still unsure if it's good to have three separate return statements: def Validate(self, parent): text = self.GetWindow().GetValue() try: if int(text) != 0: return True else: self.error_message() return False except ValueError: self.error_message() return False But instead of a pop-up box for the error, I've decided to take Peter's advice and change the status text instead (plus color the input box). But here's an ultra OO newbie question: how do I refer to my frame's children from within the validator class? :) From NOXwebmasterX at XmbstevensX.com Thu Aug 24 01:14:38 2006 From: NOXwebmasterX at XmbstevensX.com (mbstevens) Date: Thu, 24 Aug 2006 05:14:38 GMT Subject: all ip addresses of machines in the local network References: <1156387621.568779.191420@m73g2000cwd.googlegroups.com> <1156393371.550249.138930@75g2000cwc.googlegroups.com> <1156394781.155152.313080@i3g2000cwc.googlegroups.com> Message-ID: On Wed, 23 Aug 2006 21:46:21 -0700, damacy wrote: > hi, sandra. > > no, it's not as complicated as that. all i want to do is to load a > database onto different machines residing in the same network. i hope > there is a way doing it. or perhaps i have a poor understanding of how > networks work. It would not be 'as complicated as that' if we knew the kind of network you are on -- NFS, Samba, Windows, some hybred network, SSH, FTP, telnet, remote X, remote desktops? Every service has its own way of doing things. From fredrik at pythonware.com Wed Aug 23 02:56:54 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Aug 2006 08:56:54 +0200 Subject: how do you get the name of a dictionary? In-Reply-To: References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> <1156264475.968894.221710@p79g2000cwp.googlegroups.com> <1156266720.205126.284050@i3g2000cwc.googlegroups.com> Message-ID: Steven D'Aprano wrote: > But an upside is that it would enable more useful error messages, at least > sometimes. Here's some trivial pseudo-code: > > def foo(a): > assert len(a) > 10, "%s is too short" % a.__name__ > > y = "hello" > foo(y) > > would display "AssertionError: y is too short". why not "a is too short" ? or for that matter, "x is to short" ? From stk at mevis.de Wed Aug 9 02:02:03 2006 From: stk at mevis.de (Stephan Kuhagen) Date: Wed, 09 Aug 2006 08:02:03 +0200 Subject: #!/usr/bin/python or #!/usr/bin/env python? References: Message-ID: > Always prefer to use env over a hardcoded path, because that hardcoded > path will invariably be wrong. (Yes, for those about to nitpick, it's > conceivable that env might be somewhere other than /usr/bin. However, > that is very rare and results in a no-win situations regardless of the > issue of where Python is installed.) Don't yell at me for bringing in another language, but I really like the trick, Tcl does: > #!/bin/sh > # The next line starts Tcl \ > exec tclsh "$0" "$@" This works by the somewhat weird feature of Tcl, that allows comments to be continued in the next line with "\" at the end of the comment-line. It looks unfamiliar, but has several advantages, I think. First it's really VERY unlikely, that there is no /bin/sh (while I found systems with different places for env), and you can add some other features at or before the actual call of the interpreter, i.e. finding the right or preferred version... - This way I coded a complete software-installer, that runs either as a Tcl/Tk-Script with GUI, or as bash-script, when no Tcl is available. - I really would like to have something like that for python, but I did not find a way to achieve that, yet. Regards Stephan From RentInGhent at gmail.com Sun Aug 13 19:28:45 2006 From: RentInGhent at gmail.com (kagard@gmail.com) Date: 13 Aug 2006 16:28:45 -0700 Subject: Nested if and expected an indent block Message-ID: <1155511725.874993.140020@b28g2000cwb.googlegroups.com> Greetings: I'm brand new to Python and decided to write a syllogism solver for a class I'm taking. At the start of the program, I define a function that classifies the type of each statement in the syllogism. Python tells me that it is expecting an indented block at the s in "some". I can see what I'm doing wrong. Here's the code: def class_stmt(q,c): """ This function classifies a statement according to the rules of categorical syllogisms and returns A, E, I, O to identify the statement type. """ if q.lower() == "all": if "not" in c: stmt_type = "E" else: stmt_type = "A" elif q.lower() == "some" # s in some is highlighted if "not" in c: stmt_type = "O" else: stmt_type = "I" elif q.lower() == "no": if "not" in c: stmt_type = "A" else: stmt_type = "E" else: if "not" in c: stmt_type = "E" else: stmt_type = "A" return stmt_type Any ideas? Thanks in advance. Keith From maciej at localhost.localnet Mon Aug 21 05:17:07 2006 From: maciej at localhost.localnet (=?iso-8859-2?q?Maciej_Blizi=F1ski?=) Date: Mon, 21 Aug 2006 11:17:07 +0200 Subject: Detect current virtual desktop Message-ID: Hello Pythonists, I'd like to write for myself a tiny program that counts time spent on each virtual desktop (in GNOME). In order to do that, I need my program to detect the current virtual desktop. I've googled for it for about one hour and couldn't find any solution. The closest thing I found is set of tutorials: http://www.pygtk.org/articles.html Unfortunately, none of them answers my questions: How to detect current virtual desktop in GNOME? How to detect a virtual desktop change? -- http://automatthias.wordpress.com From bignose+hates-spam at benfinney.id.au Mon Aug 7 22:34:12 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 08 Aug 2006 12:34:12 +1000 Subject: Import module with non-standard file name References: <1155002526.831944.240480@h48g2000cwc.googlegroups.com> Message-ID: <87zmegx8ez.fsf@benfinney.id.au> "John Machin" writes: > Ben Finney wrote: > > Now that I've got it written as a Python module, I'd like to write > > unit tests for that module, which of course will need to import > > the program module to test it. The unit test can explicitly add > > the directory where the program module lives to 'sys.path' for the > > purpose of importing that module. > > If it can do that, it can copy the MUT to some temp directory, > adding .py to the end of the name of the new file, and put the temp > directory in sys.path .... can't it? Sounds like a nasty hack (not that fiddling sys.path isn't a hack, but at least that one's addressed in Python 2.5 with relative and absolute imports). The problem with importing the program module from a file in a different directory is that the program won't be able to find its own relative modules. That leads to either *more* sys.path hackery, or importing from a temporary file in the *same* directory. Besides which, that's still two file names for the same module code. The whole point of testing is to know that I'm testing the same module; with a two-file shim, that's one step further away from that ideal. What you describe is possible, but leads to very smelly hacks. I'd like to see what other options there are. -- \ "It's not what you pay a man, but what he costs you that | `\ counts." -- Will Rogers | _o__) | Ben Finney From Eric_Dexter at msn.com Tue Aug 29 19:51:45 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 29 Aug 2006 16:51:45 -0700 Subject: newbe question about removing items from one file to another file In-Reply-To: References: <1156714534.318183.326220@i3g2000cwc.googlegroups.com> <1156754881.496114.62170@b28g2000cwb.googlegroups.com> Message-ID: <1156895504.960976.226950@i3g2000cwc.googlegroups.com> Anthra Norell wrote: > Dexter, > > I looked at the format specification. It contains an example: > > ----------------------------------------------- > > ; > ; test.csd - a Csound structured data file > > > -W -d -o tone.wav > > > ;optional section > Before 4.10 ;these two statements check for > After 4.08 ; Csound version 4.09 > > > > ; originally tone.orc > sr = 44100 > kr = 4410 > ksmps = 10 > nchnls = 1 > instr 1 > a1 oscil p4, p5, 1 ; simple oscillator > out a1 > endin > > > > ; originally tone.sco > f1 0 8192 10 1 > i1 0 1 20000 1000 ;play one second of one kHz tone > e > > > > > ------------------------------------- > > If I understand correctly you want to write the instruments block to a file (from to )? Right? Or > each block to its own file in case there are several?. You want your code to generate the file names? Can you confirm this or > explain it differently? > > Regards > > Frederic > > > ----- Original Message ----- > From: > Newsgroups: comp.lang.python > To: > Sent: Monday, August 28, 2006 10:48 AM > Subject: Re: newbe question about removing items from one file to another file > > > > > > Anthra Norell wrote: > > > Eric, > > > Having played around with problems of this kind for quite some time I find them challenging even if I don't really have time > to > > > get sidetracked. Your description of the problem makes it all the more challenging, because its 'expressionist' quality adds the > > > challenge of guessing what you mean. > > > I'd like to take a look at your data, if you would post a segment on which to operate, the same data the way it should look > in > > > the end. In most cases this is pretty self-explanatory. Explain the points that might not be obvious to a reader who knows > nothing > > > about your mission. > > > > > > Frederic > > > > > > ----- Original Message ----- > > > From: > > > Newsgroups: comp.lang.python > > > To: > > > Sent: Sunday, August 27, 2006 11:35 PM > > > Subject: newbe question about removing items from one file to another file > > > > > > > > > > def simplecsdtoorc(filename): > > > > file = open(filename,"r") > > > > alllines = file.read_until("") > > > > pattern1 = re.compile(" > > > orcfilename = filename[-3:] + "orc" > > > > for line in alllines: > > > > if not pattern1 > > > > print >>orcfilename, line > > > > > > > > I am pretty sure my code isn't close to what I want. I need to be able > > > > to skip html like commands from to and to key on > > > > another word in adition to to end the routine > > > > > > > > I was also looking at se 2.2 beta but didn't see any easy way to use it > > > > for this or for that matter search and replace where I could just add > > > > it as a menu item and not worry about it. > > > > > > > > thanks for any help in advance > > > > > > > > -- > > > > http://mail.python.org/mailman/listinfo/python-list > > > > sorry about that this is a link to a discription of the format > > http://kevindumpscore.com/docs/csound-manual/commandunifile.html > > It is possible to have more than one instr defined in an .csd file so I > > would need to look for that string also if I want to seperate the > > instruments out. > > > > http://www.dexrow.com > > > > -- > > http://mail.python.org/mailman/listinfo/python-list I need to take it between the blocks only I also need to make sure I only take one instrument defined in this example with the code instr 1 I also need the code > ; originally tone.orc > sr = 44100 > kr = 4410 > ksmps = 10 > nchnls = 1 regardless of what instrument I take. The function would have to except the instrument number as an argument http://www.dexrow.com From wildemar at freakmail.de Wed Aug 9 10:29:09 2006 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Wed, 09 Aug 2006 16:29:09 +0200 Subject: ALLAH In-Reply-To: References: <1155117922.061942.100370@n13g2000cwa.googlegroups.com> Message-ID: <44D9F135.3030805@freakmail.de> Sybren Stuvel wrote: > faruk.nur at mynet.com enlightened us with: >> Kader; >> >> soru:madem,her?ey bir kader defterinde yaz?l? ve her?ey ona g?re >> oluyor.o halde insanlar ni?in cehenneme gidiyor? >> cevap:evet her?ey bir kader defterinde yaz?l? ve her?ey ona g?re >> oluyor.ama,defterde yaz?l? oldu?u i?in o ?ey olmuyor. > > You might want to try in English. > > Sybren Although the subject sort of makes me suspect that this text has little if anything to do with programming. Programming computers, that is. wildemar From __peter__ at web.de Sun Aug 27 12:31:09 2006 From: __peter__ at web.de (Peter Otten) Date: Sun, 27 Aug 2006 18:31:09 +0200 Subject: Defining constant strings References: <44f1bc61$0$26543$3a628fcd@textreader.nntp.hccnet.nl> Message-ID: Hans wrote: > I want to define a couple of constant strings, like in C: > #define mystring "This is my string" > or using a const char construction. > > Is this really not possible in Python? No, this is not really not possible in Python: $ ls preprocess.pyp $ cat preprocess.pyp #define MYSTRING "Hello, world" def f(): print "Goodbye, " MYOTHERSTRING print MYSTRING f() $ gcc -DMYOTHERSTRING="'sanity'" -xc -E preprocess.pyp -o preprocess.py $ python preprocess.py Hello, world Goodbye, sanity $ :-) Peter From djoefish at gmail.com Wed Aug 30 12:22:47 2006 From: djoefish at gmail.com (djoefish) Date: 30 Aug 2006 09:22:47 -0700 Subject: windows pagfile utilization In-Reply-To: References: <1156950270.045140.44950@p79g2000cwp.googlegroups.com> Message-ID: <1156954967.932556.319050@e3g2000cwe.googlegroups.com> I guess that means that I shouldn't waste my money bumping my RAM up from 1g to 2g? What about Linux? Are there constraints there too? djoefish From zcamster at gmail.com Wed Aug 9 07:41:25 2006 From: zcamster at gmail.com (_max) Date: 9 Aug 2006 04:41:25 -0700 Subject: Session implementation for Python In-Reply-To: References: Message-ID: <1155123685.495253.300500@n13g2000cwa.googlegroups.com> Flup does sessions, in the form of a WSGI middleware: http://www.saddi.com/software/flup/ Vlad Dogaru wrote: > Hello, > > is there any PHP-like implementation for sessions in Python? I fear > that writing my own would be seriously insecure, besides I could > actually learn a lot by inspecting the code. > > The reason I am asking is that I would like to implement simple scripts > which require login with CGI (no mod_python or Django -- I want to > learn CGI first). > > Thanks in advance, > Vlad > > -- > There is nothing more dangerous than an idea when it is the only one > you have. From saint.infidel at gmail.com Tue Aug 8 10:34:17 2006 From: saint.infidel at gmail.com (infidel) Date: 8 Aug 2006 07:34:17 -0700 Subject: do people really complain about significant whitespace? In-Reply-To: <1154989853.962779.301510@m73g2000cwd.googlegroups.com> References: <1154986984.740638.241130@m79g2000cwm.googlegroups.com> <1154989853.962779.301510@m73g2000cwd.googlegroups.com> Message-ID: <1155047657.446924.134390@n13g2000cwa.googlegroups.com> > All societies demonise outsiders to some extent. It's an unfortunate > human (and animal) trait. Which is why I questioned it. > So just block your ears when the propaganda vans with the loud-speakers > on top drive past your dwelling :-) Funny how using python makes me feel like a member of some kind of rebellion against the empire. Where I work it's all VB, VB.NET, and ASP.NET. I've been the lone voice in the wilderness for so long that I've become an inside joke. I actually have a certificate that says "Most likely to re-write the system in Python". *sigh* From http Sat Aug 26 02:58:56 2006 From: http (Paul Rubin) Date: 25 Aug 2006 23:58:56 -0700 Subject: Problem with List of List References: <1156569535.500196.7920@i3g2000cwc.googlegroups.com> <1156573379.951900.199030@m79g2000cwm.googlegroups.com> <1156574043.891794.266390@75g2000cwc.googlegroups.com> Message-ID: <7xodu8ugnj.fsf@ruckus.brouhaha.com> "Kirt" writes: > Actually here in my code ['1', 'a', '6'], ['1', 'b', '6'], ['1', 'c', > '6'] means: > 1==> Directory name; > a,b,c,d=== Filename > 6 ==> modified time > > So i want the out put like: > Directory name: 1 > Filename:a > modified time:6 Try writing the code in a style with fewer side effects. I like using itertools.groupby for this type of thing (not exactly tested): from itertools import groupby List=[['1', 'a', '6'], ['1', 'b', '6'], ['1', 'c', '6'], ['1', 'd', '6'],['2', 'a','6'], ['2', 'b', '6'], ['2', 'c', '6'], ['2', 'd', '6'], ['3', 'a', '6'], ['3','b', '6'], ['4', 'a', '6'], ['4', 'b', '6']] # retrieve directory name from one of those tuples def directory_name(t): return t[0] for dirname,dir_contents in groupby(sorted(List), directory_name): print 'Directory name:, dirname for dname2,filename,modtime in dir_contents: print 'Filename:%s\nmodified time:%s'% (filename, modtime) The output is: >>> ## working on region in file /usr/tmp/python-9013z7X... Directory name: 1 Filename:a modified time:6 Filename:b modified time:6 Filename:c modified time:6 Filename:d modified time:6 Directory name: 2 Filename:a modified time:6 Filename:b modified time:6 Filename:c modified time:6 Filename:d modified time:6 Directory name: 3 Filename:a modified time:6 Filename:b modified time:6 Directory name: 4 Filename:a modified time:6 Filename:b modified time:6 >>> Is that what you wanted? From faulkner612 at comcast.net Sun Aug 20 02:23:56 2006 From: faulkner612 at comcast.net (faulkner) Date: 19 Aug 2006 23:23:56 -0700 Subject: [NEWB]: List with random numbers In-Reply-To: <1156054456.520655.49040@b28g2000cwb.googlegroups.com> References: <1156054456.520655.49040@b28g2000cwb.googlegroups.com> Message-ID: <1156055036.361464.145420@i42g2000cwa.googlegroups.com> what you want is impossible. step back a second. you want 7 distinct ints all between 0 and 5 inclusive. of course you'll loop forever. once you get all 6 numbers, no matter what you get will already be in your list. if you want floats between 0 and 6, say '6 * random.random()'. random.randrange is equivalent to random.choice(range(*arguments)), which only deals with whole numbers. eltower wrote: > Hey all, > > I'm trying to write a program in Python for learning purposes which is > meant to: > > Generate a random number from 0 to 6 > Insert this random number to the end of a list unless the number is > already there > finish with a len(list) = 7 > > so far, I have this: > > import random > > random_list = [] > > while len(random_list) < 8: > j = random.randrange(6) > if (j in random_list): > continue > else: > random_list.append(j) > continue > > print random_list > > > however, I get stuck in an infinite loop. > > Any suggestions? > > Thank you in advance, > > Adri From anthra.norell at tiscalinet.ch Wed Aug 30 05:41:20 2006 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Wed, 30 Aug 2006 11:41:20 +0200 Subject: newbe question about removing items from one file to another file References: <1156714534.318183.326220@i3g2000cwc.googlegroups.com><1156754881.496114.62170@b28g2000cwb.googlegroups.com> <1156895504.960976.226950@i3g2000cwc.googlegroups.com> Message-ID: <00e601c6cc18$745ef760$0201a8c0@mcuf7> Dexter, Here's a function that screens out all instrument blocks and puts them into a dictionary keyed on the instrument number: -------------------------------------------- def get_instruments (file_name): INSIDE = 1 OUTSIDE = 0 f = file (file_name, 'ra') state = OUTSIDE instruments = {} instrument_segment = '' for line in f: if state == OUTSIDE: if line.startswith ('>> Instrument_Segment_Filter = SE.SE (' "~(?i)(.|\n)*?~==\n\n" ') >>> instrument_segments= Instrument_Segment_Filter ('file_name', '') >>> print instrument_segments (... see all instrument segments ...) >>> Instrument_Number = SE.SE (' ~instr.*~==\n') >>> instruments ={} >>> for segment in instrument_segments.split ('\n\n'): if segment: instr_line = Instrument_Number (segment) instrument_number = instr_line.split ()[1] instruments [instrument_number] = segment -------------------------------------------------- (If you're on Windows and the CRs bother you, take them out with an additional definition when you make your Instrument_Block_Filter: (13)= or "\r=") Regards Frederic ----- Original Message ----- From: Newsgroups: comp.lang.python To: Sent: Wednesday, August 30, 2006 1:51 AM Subject: Re: newbe question about removing items from one file to another file > > Anthra Norell wrote: > > Dexter, > > > > I looked at the format specification. It contains an example: > > > > ----------------------------------------------- > > > > ; > > ; test.csd - a Csound structured data file > > > > > > -W -d -o tone.wav > > > > ... etc. From seyeRMReyes at gmail.com Fri Aug 18 14:59:12 2006 From: seyeRMReyes at gmail.com (seyeRMReyes at gmail.com) Date: 18 Aug 2006 11:59:12 -0700 Subject: Text to MP3 using pyTTS - Non-programmer question In-Reply-To: References: <1155904799.935486.105460@i3g2000cwc.googlegroups.com> Message-ID: <1155927552.548657.234930@i42g2000cwa.googlegroups.com> Thanks for the script. Are there any online python intrepreters? I'd like to play around with the script. I don't have access to my home PC. From zcamster at gmail.com Wed Aug 23 11:20:14 2006 From: zcamster at gmail.com (Max Penet) Date: 23 Aug 2006 08:20:14 -0700 Subject: How to download a web page just like a web browser do ? References: <1156343685.281636.285100@p79g2000cwp.googlegroups.com> Message-ID: <1156346414.384352.298520@b28g2000cwb.googlegroups.com> You can also try HarvestMan: http://harvestman.freezope.org/ Bo Yang wrote: > Hi , > It is about one month passed since I post to this list > last time . Yes , I use python , I used it in every day normal > work , whenever I need to do some scripts or other little-scale > works , python is the first one I took consideration in . I must > say it is a powerful tool for me , and what is more important > is there is a friendly and flourish community here . > Oh , I must stop appriciation and go to my question now . > > Everyday , I receive a newsletter from NYTimes , but I > didn't want to read the news in evening the time the letter > came in . So , I am about to download the web page > contains the news and read them next morning ! I decide to > use python to write a tool , which should be feeded with a > URL , and then download the page to my disk . This > function just like the Browser's "save as..." function . I > know what shoud I do to accomplish that , I need to parse > the web page , and download all pages in the page , and > modify all the links to conrespond local disk links and ... > > So , is there any similar function any one have impelment? > Does anyone can share some code with me ? I really don't > want to some confusing code to process such as text findings > and substitutions . > > Thanks in advance ! > > > Bo From slawomir.nowaczyk.847 at student.lu.se Sun Aug 6 05:41:27 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Sun, 06 Aug 2006 11:41:27 +0200 Subject: Nested function scope problem In-Reply-To: <1qcs7qgdceml6.dlg@gelists.gmail.com> References: <1qcs7qgdceml6.dlg@gelists.gmail.com> Message-ID: <20060806111234.EEA8.SLAWOMIR.NOWACZYK.847@student.lu.se> On Fri, 04 Aug 2006 13:42:59 -0300 Gerhard Fiedler wrote: #> On 2006-08-04 12:12:44, Antoon Pardon wrote: #> #> >>> You can hardly claim that what gets printed is the "id" of the variable c. #> >>> (Well, you can claim, but few C programmers would follow you.) #> >> #> >> That's possible. I wouldn't expect too many C programmers to have any #> >> notion of "id of a variable". I, for example, never thought about such #> >> thing before this thread. #> > #> > But even in Python we don't speak of "id of a variable". It is not the #> > variable that has an id. It is the object that is currently attached to #> > the variable that has an id. Yes we can use "id of a variable" as a #> > shortcut for the correct formulation as long as you keep in mind that it #> > is not the variable itself that has an id. #> #> This sounds a bit like saying "yes we can use the term 'variable' as a #> shortcut for the correct formulation (object associated to a name) as long #> as we keep in mind that it is not actually a variable" :) No it doesn't. Anyway, where did the idea that "id(a)" is an "id of a variable a" come from, anyway? Since Python doesn't (supposedly) have variables, it couldn't have come from Python. Since C doesn't have id(), it couldn't have come from C... So? Obviously, if we use pythonic terminology of "binding", a statement would be that id(a) "is an id of a binding", which doesn't make much sense. Antoon is right, id(a) is an identifier _of an object bound to a_. Which translates into C++ as "an object pointed to by a", IMHO. -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) If at first you do succeed, try not to look astonished. From tim.peters at gmail.com Tue Aug 29 15:25:18 2006 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 29 Aug 2006 15:25:18 -0400 Subject: A Sort Optimization Technique: decorate-sort-dedecorate In-Reply-To: <44F480EF.9080202@durchholz.org> References: <1156719092.603277.57390@b28g2000cwb.googlegroups.com> <1156723602.192984.49610@m79g2000cwm.googlegroups.com> <280820061150081729%jgibson@mail.arc.nasa.gov> <7.0.1.0.0.20060829132302.05c9e758@yahoo.com.ar> <44F480EF.9080202@durchholz.org> Message-ID: <1f7befae0608291225o12985c18u95137d9b6ba928e2@mail.gmail.com> [Joachim Durchholz] >>> Wikipedia says it's going from 2NlogN to N. If a sort is massively >>> dominated by the comparison, that could give a speedup of up to 100% >>> (approximately - dropping the logN factor is almost irrelevant, what >>> counts is losing that factor of 2). [Gabriel Genellina] >> In fact it's the other way - losing a factor of 2 is irrelevant, >> O(2N)=O(N). The logN factor is crucial here. [Joachim Durchholz] > That's just a question of what you're interested in. > > If it's asymptotic behavior, then the O(logN) factor is a difference. > > If it's practical speed, a constant factor of 2 is far more relevant > than any O(logN) factor. Nope. Even if you're thinking of base 10 logarithms, log(N, 10) > 2 for every N > 100. Base 2 logarithms are actually most appropriate here, and log(N, 2) > 2 for every N > 4. So even if the "2" made sense here (it doesn't -- see next paragraph), the log(N) term dominates it for even relatively tiny values of N. Now it so happens that current versions of Python (and Perl) use merge sorts, where the worst-case number of comparisons is roughly N*log(N, 2), not Wikipedia's 2*N*log(N, 2) (BTW, the Wikipedia article neglected to specify the base of its logarithms, but it's clearly intended to be 2). So that factor of 2 doesn't even exist in current reality: the factor of log(N, 2) is the /whole/ worst-case story here, and, e.g., is near 10 when N is near 1000. A factor of 10 is nothing to sneeze at. OTOH, current versions of Python (and Perl) also happen to use "adaptive" merge sorts, which can do as few as N-1 comparisons in the best case (the input is already sorted, or reverse-sorted). Now I'm not sure why anyone would sort a list already known to be sorted, but if you do, DSU is a waste of time. In any other case, it probably wins, and usually wins big, and solely by saving a factor of (up to) log(N, 2) key computations. > (I'm not on the list, so I won't see responses unless specifically CC'd.) Done. From paddy3118 at netscape.net Sat Aug 5 15:47:03 2006 From: paddy3118 at netscape.net (Paddy) Date: 5 Aug 2006 12:47:03 -0700 Subject: More int and float attributes In-Reply-To: <1154780600.348169.158150@i42g2000cwa.googlegroups.com> References: <1154780600.348169.158150@i42g2000cwa.googlegroups.com> Message-ID: <1154807223.104418.230270@i3g2000cwc.googlegroups.com> bearophileHUGS at lycos.com wrote: > sys.maxint gives the largest positive integer supported by Python's > regular integer type. But maybe such attribute, with few others (they > can be called min and max) can be given to int type itself. > D is a very nice language, that I hope to see more used. It is copying > lot of things from Python. D Floating point values have some > proprieties: > > http://www.digitalmars.com/d/property.html > > Properties for Floating Point Types: > .init initializer (NaN) > .infinity infinity value > .nan NaN value > .dig number of decimal digits of precision > .epsilon smallest increment > .mant_dig number of bits in mantissa > .max_10_exp maximum exponent as power of 10 > .max_exp maximum exponent as power of 2 > .min_10_exp minimum exponent as power of 10 > .min_exp minimum exponent as power of 2 > .max largest representable value that's not infinity > .min smallest representable value that's not 0 > .re real part > .im imaginary part > > I think such attributes may be useful to be added to Python float > type/values too. > > Bye, > bearophile The thing about float is that people expect it to be 'fast'. Most CPU's have two or one representationfor floats that is supported by hardware and lightning fast compared to a pure software implementation. The decimal module provides for the 'bean counters' out their who can't afford to round off a penny, but I must say that this is the first request I have seen for a flexible float where you would not have hardware support (when hardware float support is available). Or do you mean the ability to choose between hardware supported float s? e.g. float and double precision? Or to be able to just interrogate the float implementation so your prog can adjust to whatever implementation it is running under? Something like: assert float.mant_dig > 20 - Paddy. From sjdevnull at yahoo.com Tue Aug 22 04:13:25 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 22 Aug 2006 01:13:25 -0700 Subject: text editor suggestion? In-Reply-To: <44e78a2b$0$12550$c3e8da3@news.astraweb.com> References: <44e66724$0$2363$c3e8da3@news.astraweb.com> <1155995807.052337.272990@i42g2000cwa.googlegroups.com> <44e78a2b$0$12550$c3e8da3@news.astraweb.com> Message-ID: <1156234405.513945.69290@b28g2000cwb.googlegroups.com> John Salerno wrote: > > The thing I liked about UltraEdit is that you can define your own groups > of words and put whatever words you want in there, so my file had a > group called '__builtins__' and it listed all the Python built-in > methods, and those would be highlighted. Most editors I see don't seem > to allow this...they just figure out what a function or method is on > their own somehow. In vim, you can just put "let python_highlight_builtins=1" in your .vimrc for this particular example (other python syntax settings include python_highlight_numbers, python_highlight_space_errors, python_highlight_exceptions). Use python_highlight_all to turn them all on. To do it by hand and have it automatically come on in all .py buffers, you could do: au BufEnter *.py syntax keyword pythonFunction abs apply basestring bool au BufEnter *.py syntax keyword pythonFunction buffer callable chr etc. Put as many as you want on one line. Use other syntax groups if you want them highlighted as something other than functions. Or, with vim's builtin python interpreter you could grab the list of builtins directly, for instance have this in your vimrc: pyf ~/.vim/vimrc.py And have this in ~/.vim/vimrc.py: import vim # Might want to trim out exceptions/leading underscores/etc from this... builtins = ' '.join( [ b for b in dir(__builtins__)] ) vim.command('au BufEnter *.py syn keyword pythonFunction '+builtins) From barberomarcelo at gmail.com Wed Aug 23 08:05:08 2006 From: barberomarcelo at gmail.com (barberomarcelo at gmail.com) Date: 23 Aug 2006 05:05:08 -0700 Subject: Can I do this with list comprehension? In-Reply-To: References: <1156306056.165984.37820@h48g2000cwc.googlegroups.com> Message-ID: <1156334708.087227.24730@h48g2000cwc.googlegroups.com> Thanks a lot to everybody. Marcelo From onurb at xiludom.gro Tue Aug 8 13:59:47 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 08 Aug 2006 19:59:47 +0200 Subject: Newbie - How to iterate list or scalar ? In-Reply-To: <1155054334.863073.243560@75g2000cwc.googlegroups.com> References: <1155030787.666942.277610@m79g2000cwm.googlegroups.com> <44d86c6c$0$21149$7a628cd7@news.club-internet.fr> <1155054334.863073.243560@75g2000cwc.googlegroups.com> Message-ID: <44d8d114$0$21145$7a628cd7@news.club-internet.fr> Andy Dingley wrote: > Bruno Desthuilliers wrote: > >> there's really no reason to >> assume it should be a list - any iterable could - and IMHO should - be >> accepted... expect of course for strings (royal PITA case, duh). > > >> 2/ test for pluginVersionsNeeded.__iter__ (an attribute of most >> iterables except strings...): > > strings don't have __iter__ ?!?! No. Should they ?-) > I'm never going to get my head round this language 8-( Hmmm.... While simple to get started with, Python is *not* a 'simple' language. There's a price to pay for it's flexibility, and this price is named "complexity". While one doesn't necessary needs to deal with it, this complexity shows as soon as you start to dig deeper into "advanced" features. FWIW, if I judge on source code I've seen so far, the canonical way to distinguish a string from another sequence type or iterable is still to use isinstance(obj, basestring), and I don't know if I should have mentionned the hasattr(obj, '__iter__') hack at all. > I can understand strings and tuples being iterable, if you take a > sufficiently first-class view of things, but why shouldn't everything > "that is iterable" support the function that makes iteration work? Actually, __iter__ is not needed to allow for loops on an object if the object defines __getitem__ so that it supports numeric indexing: class MySequence(object): def __init__(self): self._data = range(3) def __getitem__(self, key): return self._data[key] >>> m = MySequence() >>> for x in m: print x ... 0 1 2 FWIW, the iterator protocol appeared with Python 2.2. Before this version, the above solution was the only one that allowed iteration over a container type. Now if you wonder why string, unicode and buffer don't have __iter__ while other sequence types have it, ask your favourite Python guru (and please keep me informed !-). Fact is that Python is not exactly a newborn language (first release was around 1990 IIRC), and it has greatly evolved over the year. The BDFL being very conservative, great cares have been taken to ensure compatibility with older versions - with the side effect that there are lots of stuff that now looks like warts or inconsistencies. The 3K release is supposed to be the big cleanup, but until then, we'll have to live with all the compat stuff. HTH From kay.schluehr at gmx.net Wed Aug 30 06:35:11 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 30 Aug 2006 03:35:11 -0700 Subject: What do you want in a new web framework? References: <1156100331.329889.216340@p79g2000cwp.googlegroups.com> <1156156636.515678.118210@75g2000cwc.googlegroups.com> <4jele2pe011di99c5dnq4olclglrkieggc@4ax.com> <1156325280.062278.244990@m79g2000cwm.googlegroups.com> Message-ID: <1156934111.301823.190280@b28g2000cwb.googlegroups.com> Cliff Wells wrote: > My single wishlist item (which will probably never happen) is actually > the *removal* of a single "feature": the distinction between statements > and expressions. Forget list comprehensions, ternary operators, etc. > You get them with no additional syntax in expression-based languages. I > played with Logix a bit (but sadly the project appears dead) and the > expression-based Python syntax it provides gives me goose-bumps. Ironically I would prefer to turn Logix block expressions of the kind var = expression: SUITE into statements to avoid deep and awkward nestings: passing the side-effect created by SUITE to var but preserving the distinction between expressions and block statements nevertheless. I'm not yet sure if the Python 2.5 with-stmt cannot be used for exactly this purpose? Note that I'm not completely against blurring the distinction between expressions and statements in Python. The Python grammar itself contains a basic distinction between statements namely simple_stmt and compound_stmt nodes. Simple statements are defined by: simple_stmt: small_stmt ( ";" small_stmt)* [";"] NEWLINE where small_stmt nodes are nodes for assert, print, raise, return, assignment etc. It took me an evening using EasyExtend to define an enhanced lambda that enables expressions like: lambda lst: s = sum(lst); return float(s)/len(lst) or lambda x: print x; x+1 which are other Logix examples. From omg at yahoo.com Sun Aug 20 10:06:46 2006 From: omg at yahoo.com (OleMacGeezer) Date: Mon, 21 Aug 2006 00:06:46 +1000 Subject: time.localtime() Format Question Message-ID: <210820060006469660%omg@yahoo.com> Hello Everyone, I am a brand new Python programmer with barely a month of experience under my belt. Here are my specs: Mac OSX Panther 10.3.9 Jython 2.1 implementation with Hermes BBS python module installed And now the problem... Right now I am having a small problem figuring out how to properly format the "User Last Log-On" date for the new external/door that I am writing for our Hermes BBS. Initially, I was using the following in my user initialization function near the top of the code: user.data.usrUndrLast = time.localtime() "user.data.usrUndrLast" is a user data object that I created to display the last time that a person used the external. As you can see, I an setting the value of the object to "time.localtime()". The problem is that the above code gave me a long string like this: (2006, 8, 19, 23, 39, 15, 5, 231, 0) Well, that obviously was not what I wanted or needed. I don't need seconds, or whatever that is that follows after seconds...And that isn't the format I wanted either. So I scrounged around in the example code for another external I have here, as well as in the hermes.py, (module which contains some of the BBS's proprietary functions), the jython-2.1 folder, (Python implementation I am using with the BBS), and even in my OSX Python installation, and then also on the web, looking for a clue regarding how to get it to do what I want it to do. I figured out that adding [:3] like this: user.data.usrUndrLast = time.localtime()[:3] ...would reduce it to just "(2006, 8, 19)", but that is still not what I want it to do. The format is wrong. I found a lot of interesting stuff inside of "rfc822.py" concerning date and time formats, but I am still not grasping quite how to do this. Right now, I am getting a TypeError, I guess because time.localtime only deals with integers, and I am trying to throw strings at it as well, like this: user.data.usrUndrLast = time.localtime('%a, %d %b %Y') I was hoping that the above code would produce something like this: Sun 20 Aug 2006 ...but what I am getting is a TypeError which states: "TypeError: localtime(): 1st arg can't be coerced to double" So at this point, I am pretty stumped. In the list of players, I just want it to show when they were last logged into the external, preferably in one of the following formats: Sun 20 Aug 2006 Sun Aug 20 2006 Aug 20 2006 08-20-06 08-20-2006 08/20/2006 08/20/06 Once the above code, (user.data.usrUndrLast = time.localtime), initializes their last log-on date, I am using the results in a user list by appending the data to the user list like this: for u in external.users.values(): usrList.append({ 'name': u.data.usrUndrName, 'levl': u.data.usrUndrLevl, 'scor': u.data.usrUndrScor, 'last': u.data.usrUndrLast, # The one we're dealing with }) The above list code queries the external for the values that it has stored for each user. When it gets to the "last" item in the list, the external is supposed to send it the value for "u.data.usrUndrLast", (which it does), which is filled in with the value of "time.localtime()" Once the list is made, the "last" code will be displayed in the user list using this piece of code: print Style(fgLtGreen)('%(last)-10s' % markUsr) For the record, I do have "import time" at the top of my code. I looked all over the place for a module called "time.py", but couldn't find one. So I didn't quite understand where "time.py" was being imported from. I finally figured that it must just be a function which is being imported from one of the jython modules that I was looking at...although I never found an exact function called "time()" or "time.localtime(). So if anyone can lend me a hand with this, I'd really appreciate it. I am really working hard, and doing the best I can to learn Python, (my very first programming language), but I still require some guidance. If anyone here can tell me how to get the results that I want, I would really appreciate if you would write to me directly at: webmaster at endtimeprophecy.net Thanks so much. From riko at despammed.com Wed Aug 23 03:59:13 2006 From: riko at despammed.com (Mc Osten) Date: Wed, 23 Aug 2006 09:59:13 +0200 Subject: Python and STL efficiency References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <1hkh28d.xscw4v1y4v9a6N%riko@despammed.com> <1hkh6lb.6dsnh51lj8z96N%riko@despammed.com> <1156252193.524186.107520@b28g2000cwb.googlegroups.com> <1hkhexv.18m65rl61swqyN%riko@despammed.com> <1156265848.875774.251640@i42g2000cwa.googlegroups.com> <1156290607.269119.88710@b28g2000cwb.googlegroups.com> <1hkil6j.xm4l6y1kwo13dN%riko@despammed.com> <1156317315.946762.215690@p79g2000cwp.googlegroups.com> Message-ID: <1hkioxy.42be4c1lg0jq5N%riko@despammed.com> Ray wrote: > Certainly--I was not comparing 1000000 against 10000. Referring to the > OP's statement: "However, while the python code gave the result almost > instantly, the C++ code took several seconds to run!" 30ms sounds like > a definite improvement over several seconds! Of course. I suppose there's something broken in OP's C++ setup (in fact the version I compiled with VCPP 2005 also takes a lot of seconds... something like 20-30 seconds, but of course this makes me think I haven't understood how it is supposed to work, since my gcc gives results comparable to yours). -- blog: http://www.akropolix.net/rik0/blogs | Uccidete i filosofi, site: http://www.akropolix.net/rik0/ | tenetevi riso e forum: http://www.akropolix.net/forum/ | bacchette per voi. From xah at xahlee.org Thu Aug 17 09:42:55 2006 From: xah at xahlee.org (Xah Lee) Date: 17 Aug 2006 06:42:55 -0700 Subject: The Semicolon Wars as a software industry and human condition Message-ID: <1155822175.534005.100490@75g2000cwc.googlegroups.com> Of interest: ? The Semicolon Wars, by Brian Hayes. 2006. http://www.americanscientist.org/template/AssetDetail/assetid/51982 in conjunction to this article, i recommend: ? Software Needs Philosophers, by Steve Yegge, 2006 http://xahlee.org/Periodic_dosage_dir/_p/software_phil.html ? What Languages to Hate, Xah Lee, 2002 http://xahlee.org/UnixResource_dir/writ/language_to_hate.html Xah xah at xahlee.org ? http://xahlee.org/ From sjdevnull at yahoo.com Tue Aug 15 12:34:19 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 15 Aug 2006 09:34:19 -0700 Subject: Best IDE for Python In-Reply-To: References: <1155541849.350392.31190@h48g2000cwc.googlegroups.com> <1155592933.921122.21100@m79g2000cwm.googlegroups.com> Message-ID: <1155659659.431415.24410@b28g2000cwb.googlegroups.com> Bruce Who wrote: > Hi, sjdevnull > > I'm a vimmer too, and I wonder what plugins you are using. What you > said sounds interesting. Could you tell us more about the plugins? > "Object browser" is what I need most, but so far I've no idea what > plugin can do this for me, :-( It's like a 15 minute job to write something basic. Mine's a little more complicated since I deal with ugly things like finding the parent class in cases like: import generic.base.klass ... BaseKlass = generic.base.klass.someKlass ... class newKlass(BaseKlass): and similar constructs. I use the following in my vimrc: "you might need to add directories to sys.path before the following line "probably also wand to bracket parts of it in 'if have("gui_running")' python import vimrc au GUIEnter * py vimrc.tags.fakeTagsMenu() au BufEnter *.py aunmenu Tags au BufEnter *.py py vimrc.tags.buildMenu() au BufLeave *.py menu disable Ta&gs au BufEnter * py vimrc.tags.fakeTagsMenu() And then I have a vimrc.py with, among other things: -------------------------- import tags import os import vim def cur_x(): return vim.current.window.cursor[1] def cur_y(): return vim.current.window.cursor[0] def relativePath(absolutePath): cwd = os.getcwd() if absolutePath.startswith(cwd): absolutePath = absolutePath[len(cwd):] while absolutePath[0] == '/': absolutePath = absolutePath[1:] return absolutePath return absolutePath ---------------------- And a tags.py: ---------------------- #!/usr/bin/python try: import vim import vimrc except: pass def findParentClass(currLoc = None, showMenu=0, allLines=None): if not allLines: allLines = vim.current.buffer if currLoc == None: currLoc = vimrc.cur_y() lines = [ line for line in allLines[:currLoc] if line.startswith("class ") ] if len(lines) == 0: lines = [ line for line in allLines[currLoc:] if line.startswith("class ") ] else: lines.reverse() if len(lines) == 0: return None try: klass = lines[0].split("(", 1)[1].split(")")[0] except: return None currKlass = lines[0].split(" ", 1)[1] currKlass = currKlass.split(":")[0] try: currKlass = currKlass.split("(")[0] except: pass renameLines = [] for i in range(len(allLines)): line = allLines[i] while line.endswith("\\"): line = line[:-1] + allLines[i+1] i=i+1 if line.endswith(" as %s" % klass) or line.startswith("%s ="%klass) or line.startswith("%s="%klass): renameLines.append(line) if len(renameLines)>0: parseLine = renameLines[-1] if parseLine.endswith("as %s"%klass): klass = parseLine.split(" ")[-3] else: klass = parseLine.split(".")[-1] if "." in klass: klass = klass.split(".")[-1] if showMenu: if klass == currKlass: generic = "generic" else: generic = "none" vim.command('502menu Ta&gs.Parent:%s :call FindTag("%s", "%s")' %(klass, klass, generic)) try: klass = klass.split(".")[-1] except: pass return klass def YankLine(): try: word = vim.current.line word = word.split(" ")[-1] except: return try: vim.command("silent tag %s"%word) except: return stuff = vim.current.line vim.command("normal ^T") print stuff def buildChildEntries(): rv = 0 for line in vim.current.buffer: if line.startswith("class "): klass = line.split(" ", 1)[1] try: klass = klass.split("(")[0] except: pass try: klass = klass.split(":")[0] except: pass klass = klass.strip() fileName = vimrc.relativePath(vim.current.buffer.name) lines = [ line.strip() for line in open("oobr", "r").readlines() if line.startswith("%s:"%klass)] for line in lines: rv = 1 splitline = line.split(":") child = splitline[1] childBase = childFile.split("/")[-1] childBase = childBase.split(".")[0] if "_" in childBase and not fileName.startswith(childBase) and not fileName.startswith("generic") and not fileName.startswith("libs"): continue vim.command('502menu Ta&gs.Child:%s :call FindTag("%s","%s")' % (childBase, child, childFile)) vim.command('502menu Ta&gs.-children- :') return rv def editObject(): vim.command(":e object.py") vim.command(":set buftype=nowrite") vim.command(":set bufhidden=delete") vim.command(":set noswapfile") def buildParentEntries(): foundSome = 0 for i in range(len(vim.current.buffer)): if vim.current.buffer[i].startswith("class"): if findParentClass(i, showMenu=1): foundSome = 1 return foundSome def fakeTagsMenu(force=0): ft = vim.eval("&filetype") if ft == "python" and force==0: return try: vim.command("502menu Ta&gs.-Sep- :") vim.command("502menu disable Ta&gs") except: pass def showMenus(fileDict): files = fileDict.keys() files.sort() files = [vimrc.relativePath(vim.current.buffer.name)] foundSome = buildParentEntries() foundSome = buildChildEntries() or foundSome for k in files: kName = k.strip().split(".")[0] #vim.command("502menu Tags.%s :q" % kName) try: classList = fileDict[k]["class"].keys() except: if not foundSome: fakeTagsMenu(1) return classList.sort() for c in classList: c = c.strip() tagList = fileDict[k]["class"][c].keys() tagList.sort() for t in tagList: vim.command("502menu Ta&gs.%s:%s :tag %szz" % (c, t, t)) fdList = None def rebuildTags(): global fdList tagFiles=vim.eval("&tags") tagFiles = tagFiles.split(",") fd = {} for t in tagFiles: try: fd = parseTagsFile(t, fd) except: pass fdList = fd def buildMenu(): global fdList if not fdList: rebuildTags() fd = fdList showMenus(fd) def parseTagsFile(file, files = None): if not files: files = dict() for i in open(file).readlines(): i = i.strip() try: (tagName, fileName, exCmd, extensions) = i.split("\t", 3) except: continue extensions = extensions.split("\t") className = "" if not files.has_key(fileName): files[fileName] = {"class":{}, "method":{}} hadClass=0 for e in extensions: if e.startswith("class:"): hadClass=1 className = e.split(":", 1)[1] if not files[fileName]["class"].has_key(className): files[fileName]["class"][className] = {} files[fileName]["class"][className][tagName] = 1 if not hadClass: if extensions[0] == "c": if not files[fileName]["class"].has_key(tagName): files[fileName]["class"][tagName] = {} else: files[fileName]["method"][tagName] = tagName return files From bryanjugglercryptographer at yahoo.com Wed Aug 2 11:06:00 2006 From: bryanjugglercryptographer at yahoo.com (bryanjugglercryptographer at yahoo.com) Date: 2 Aug 2006 08:06:00 -0700 Subject: Windows vs. Linux In-Reply-To: References: <1154301694.445639.99580@m79g2000cwm.googlegroups.com> <44cddfb3$0$7761$7a628cd7@news.club-internet.fr> Message-ID: <1154531160.066733.71210@s13g2000cwa.googlegroups.com> Sybren Stuvel wrote: > John Salerno enlightened us with: > > But of course I still agree with you that in either case it's not a > > judgment you can fairly make 30 years after the fact. > > I don't see Microsoft changing it the next 30 years either... Apple > moved from \r to \n as EOL character. I'm sure the folks at mickeysoft > are smart enough to change from \ to /. They dis-allow '/' in filenames, and many Microsoft products now respect '/' as an alternate to '\'. >From a WinXP command prompt: C:\> C:\>cd /windows/system32 C:\WINDOWS\system32> For a "Windows vs. Linux" thread, this one has been remarkably rant-free. -- --Bryan From reply.in.the.newsgroup at my.address.is.invalid Sun Aug 13 14:37:46 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sun, 13 Aug 2006 20:37:46 +0200 Subject: yet another noob question References: <1155492110.659011.196280@75g2000cwc.googlegroups.com> Message-ID: Stargaming: >Generally, it is range(11111, 55555) Minus all numbers whose decimal string representation matches [0-9]*[06-9][0-9]* Briljant! -- Ren? Pijlman From nick at craig-wood.com Fri Aug 25 07:30:12 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Fri, 25 Aug 2006 06:30:12 -0500 Subject: Best Practices for Python Script Development? References: <1156471481.265329.291360@m79g2000cwm.googlegroups.com> Message-ID: metaperl wrote: > high-quality scripts. I know about object-oriented programming and > application configuration and have spent 6 years doing professional > Perl but have decided that Python is the new choice of serious agile > developers. I was where you are a couple of years ago! > Books > ===== > I think these 4 will carry me a long way, but any other suggestions ar > welcome: > * `Dive into Python `_ This is an excellent book to bootstrap your way into Python. It is very good for experienced programmers. > * `Text Processing in Python `_ I liked this book. However by the time I read it I'd already read quite a few Python books so I perhaps didn't get as much out of it as I should. > * Python Cookbook Cookbooks don't really lend themselves to general reading, but saying that I did read this one from cover to cover (the previous edition). There is lots of interesting stuff in there and you'll learn plenty of tricks, though Python doesn't have nearly as many tricks as Perl to learn. If you are looking for something in particular there are many more recipes in the online cookbook. > * Programming Python The second edition is a thorough introduction to python 2.1. (Amazon says there is a 3rd edition due out very soon though covering python 2.5.) The 2nd edition is missing newer features of the language, but otherwise it is a solid book with lots of good stuff in. The section on programming with TK is very good too - I keep coming back to that section. ... I'd recommend the first and the last from your list to start with, "Dive into Python" and "Programming Python". -- Nick Craig-Wood -- http://www.craig-wood.com/nick From bearophileHUGS at lycos.com Fri Aug 18 12:02:58 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 18 Aug 2006 09:02:58 -0700 Subject: sum and strings In-Reply-To: <7xr6zel2r2.fsf@ruckus.brouhaha.com> References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <7xr6zel2r2.fsf@ruckus.brouhaha.com> Message-ID: <1155916977.972148.37190@b28g2000cwb.googlegroups.com> Paul Rubin: > Sybren Stuvel: > > Because of "there should only be one way to do it, and that way should > > be obvious". There are already the str.join and unicode.join methods, > > Those are obvious??? They aren't fully obvious (because they are methods of the separator string), but after reading some documentation about string methods, and after some tests done on the Python shell, you too can probably use then without much problems. Bye, bearophile From gagsl-py at yahoo.com.ar Sat Aug 19 07:58:56 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 19 Aug 2006 08:58:56 -0300 Subject: Documenting a package with Pydoc In-Reply-To: <1155912351.433504.265020@h48g2000cwc.googlegroups.com> References: <1155912351.433504.265020@h48g2000cwc.googlegroups.com> Message-ID: <7.0.1.0.0.20060819080623.05b0bd50@yahoo.com.ar> At Friday 18/8/2006 11:45, Rob Cowie wrote: >Pydoc seems to be capable of writing documentation for all modules >within a package by simply pointing it to the package on the command >line... > >pydoc -w > >Certainly, the method writedocs() appears to descend into a directory >and create docs for each importable object. > >Perhaps I'm doing something wrong but when I do this, pydoc reports >that no Python documentation can be found for each of the contents of >the package. Of course, if I point pydoc directly to the modules, it >succeeds. > >Am I doing something wrong? That appears to be a bug. In pydoc.writedocs, when iterating over the package directory contents, it uses inspect.getmodulename(path). That returns the bare filename (without path nor extension) (is it ok???), and later the resolve() function can't load the module because it lacks package information. For simple cases this patch may work: In writedocs, add the following line at the beginning: if pkgpath=='' and ispackage(dir): pkgpath = os.path.basename(dir) + '.' This works for top level packages located at sys.path, but not for packages located elsewhere. By example, I can generate now the docs for pychart: python c:\apps\python\lib\pydoc.py -w c:\apps\python\lib\site-packages\pychart Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From siona at chiark.greenend.org.uk Thu Aug 10 12:49:32 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 10 Aug 2006 17:49:32 +0100 (BST) Subject: Two Classes In Two Files References: <1155151480.848276.52650@75g2000cwc.googlegroups.com> <44DA3937.5040901@mxm.dk> <1155152148.014855.166690@p79g2000cwp.googlegroups.com> Message-ID: Pedro Werneck wrote: >"dhable at gmail.com" wrote: >> Wasn't so much a worry, just trying to figure out how to think the >> python way. >Seems like you're thinking the Java way... if you don't want to do it, >put both classes in the same file. OP: think of a .py file as being more akin to Java package than a .java file. Don't worry about the resulting files getting too large -- Python is a lot more compact than Java. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From jgodoy at gmail.com Thu Aug 31 23:57:33 2006 From: jgodoy at gmail.com (Jorge Godoy) Date: Fri, 01 Sep 2006 00:57:33 -0300 Subject: SQLObject or SQLAlchemy? References: Message-ID: <8764g81bo2.fsf@gmail.com> "Jorge Vargas" writes: > for example SA wins at using an existing db > but SO wins at not worring about the db structure That's not entirely true. Some things are impossible with SQL Object alone. You have to, at least, make use of sqlbuilder. And these aren't hard things, mind you: performing joins, filtering data accordingly to N:N relationships, etc. > SO demands tables to have a primary single col int key which is manage > by the API, while SA lets you mess with it a bit more. SQL Objects allows for an str primary key as well. You're not tied to integers only. > so you could say that SO takes care about many things so you don't > have to worry about them, or other may say SO is too intrusive. As has been said, it's approach to mapping the database is a subset from SQL Alchemy. This makes it better in some cases -- simpler, at least -- and worse in other cases -- inefficient, impossible to use, etc. > In my experience SO is great for new projects and if you don't want to > mess/optimize with the actual SQL queries (which is great for an ORM because > IMO that is the main goal of ORMing) It is good for simple projects. If you need more performance then you'll have lots of troubles optimizing things with SQL Object in mind. Also it will force you to work directly on the database more often than SQL Alchemy to squeeze more performance from it. I'm converting an application from SQL Object -- that's what I've been using for a while -- to SQL Alchemy -- this will be my first production application with it -- and I'm liking the possibilities and extendability of SQL Alchemy. A lot of things that I did in the database are possible with my declarations in SQL Alchemy, so I have a map that's more "real" with regards to what's in the database. > Now if you need to mess a lot with the db (either a existing one or > need optimized queries) then SA is worth the extra effort, since > making those things on SO is going uphill. It isn't too hard to use SA for simple things. I dare to say that with ActiveMapper it is just a bit more verbose than SQL Object, but not too much. -- Jorge Godoy From kschutte at csail.mit.edu Tue Aug 15 09:40:58 2006 From: kschutte at csail.mit.edu (Ken Schutte) Date: Tue, 15 Aug 2006 09:40:58 -0400 Subject: modifying __new__ of list subclass In-Reply-To: References: Message-ID: <44E1CEEA.90403@csail.mit.edu> Steven Bethard wrote: > > The __new__ method is for immutable types. So things like str and int > do their initialization in __new__. But for regular mutable types, you > should do your initialization in __init__:: > I see... So, is there a use for __new__ in mutable types? From my list-derirved class, it was obviously being called, but it's return value is totally ignored? Thanks for the reply. From james at uh-hosting.co.uk Mon Aug 21 15:50:53 2006 From: james at uh-hosting.co.uk (jamesuh) Date: 21 Aug 2006 12:50:53 -0700 Subject: Problem installing Python 2.4.3 on FreeBSD 5.3-RELEASE-p31 In-Reply-To: <44E8A5B8.703@v.loewis.de> References: <1155845217.325852.170320@m73g2000cwd.googlegroups.com> <44E8A5B8.703@v.loewis.de> Message-ID: <1156189853.305452.13080@i42g2000cwa.googlegroups.com> Martin v. L?wis wrote: > james at uh-hosting.co.uk schrieb: > > I assume this is related to the configure warning... ? Same error with > > just a standard "./configure" and "make". > > > > Any help would be great :) > > If you don't need the curses module, go on with the installation. > It's a known bug in FreeBSD's curses header file. > > Regards, > Martin But I cannot continue because it seg faults and does not continue the make - Forgive my ignorance, but how do I prevent the curses module from being included? From bobrien18 at yahoo.com Thu Aug 17 11:35:41 2006 From: bobrien18 at yahoo.com (KraftDiner) Date: 17 Aug 2006 08:35:41 -0700 Subject: modify element of a list. Message-ID: <1155828941.317153.238310@74g2000cwt.googlegroups.com> Hi I have a list of Ojbects... I want to change one of the objects in the list for a new object.... How do I replace an existing object with a new one and maintain the list order.. This is what I have... def setAttribute(self, desc, value): n = anObject(desc, value) for o in self.Objects: if o.getDescription() == desc: self.Objects.replace(o, n) #Replace o with n? return self.Objects.append(n) It's the replace in place that I don't know how to do... From __peter__ at web.de Sat Aug 12 05:54:29 2006 From: __peter__ at web.de (Peter Otten) Date: Sat, 12 Aug 2006 11:54:29 +0200 Subject: unbound methods References: <1155374957.203786.73840@74g2000cwt.googlegroups.com> Message-ID: brent.chambers at gmail.com wrote: > I wrote a small class today at work playing with sockets in command > line windows. When attempting to call the handle function, I get a > TypeError. "Unbound method handle() must be called with connection > instance as first argument (got nothing instead). Any suggestions > would be greatly appreciated. Thanks! That happens if you call a (normal) method on the class instead of on an instance. >>> class A: ... def method(self, *args): print args ... This works: >>> A().method(42) (42,) while this doesn't: >>> A.method(42) Traceback (most recent call last): File "", line 1, in ? TypeError: unbound method method() must be called with A instance as first argument (got int instance instead) For details you need to post some code illustrating the problem. Peter From jojoba12 at hotmail.com Tue Aug 22 17:45:36 2006 From: jojoba12 at hotmail.com (jojoba) Date: 22 Aug 2006 14:45:36 -0700 Subject: how do you get the name of a dictionary? References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> <1156264475.968894.221710@p79g2000cwp.googlegroups.com> <1156266720.205126.284050@i3g2000cwc.googlegroups.com> <1156268752.574983.123520@75g2000cwc.googlegroups.com> <1156281268.865624.302070@b28g2000cwb.googlegroups.com> Message-ID: <1156283135.985893.186500@m73g2000cwd.googlegroups.com> > > I know i must be driving python purists to their limits... > no, you're just wasting a lot of bandwidth making it clear that you just > cannot be bothered to learn how things actually work. Wow Fredrick! Are you serious? Hey man, come on.I got lambasted on this topic from the beginning. Everyone keeps saying i dont know what im talking about, but no one actually gives me a reason why. Every counter argument i gave was either shrugged off or followed up with a "no, that's wrong" statement. Also, why are my PYTHON QUESTIONS wasting bandwidth, while yours and others RIDICULING STATEMENTS not? > do you behave this way in real life too, or is it just something you're > doing on the internet ? You sure you wanna go there. I have great respect for you and all you have done for python. I use your modules often (thank you!). But im not sure why my persistence on a this topic means i refuse to learn how python really works. If you dont agree with me, fine, PROVE your answer....forget about links. Tell me what you know or dont know, but please dont mock me. What is this grade school? As a community, we can choose to share or not. We should not bicker, or chide the ignorant (such as myself on this matter). Of course i try to learn how python works, just as i am sure you do to. We all have different levels of expertise (or lack of). Im just trying to learn man. Im not asking for a spoon feeding either. Im just trying to get CLEAR information from people about this "issue" but that has actually been quite difficult. And yes, i do inquire about things i dont understand in real life. And in fact, if i dont get a reasonable, sufficient answer, i will press the other side until a CLEAR argument sways me one way or the other (sorry if that bothers you) Thats one of my strong suits. In fact, its what led me to study and pursue science. But i digress. Please be nice to me, thats all im asking. I will try to be more concise and do "more" research before bothering others with apparent inadequecies. Thanks, jojoba From listserver at tdw.net Mon Aug 7 17:59:10 2006 From: listserver at tdw.net (Tim Williams) Date: Mon, 7 Aug 2006 22:59:10 +0100 Subject: Getting previous file name In-Reply-To: References: Message-ID: <9afea2ac0608071459v62bfa295j1a84f6c4ec6bf89@mail.gmail.com> On 7 Aug 2006 13:52:16 -0700, Hitesh wrote: > > I have a small script here that goes to inside dir and sorts the file > by create date. I can return the create date but I don't know how to > find the name of that file... > I need file that is not latest but was created before the last file. I notice that your path is UNC & windows, if you are running this on a windows platform only you could let the windows DIR do the work for you. >>> import os >>> i,o,e = os.popen3('dir /O-D /A-D /B') >>> o.readlines()[1].strip() 'dnscheck.html' I would put a try:except around the o.readlines().... bit in case there is only 0 or 1 file in the directory. Hints: c:\> dir /? (enter) >>> i,o,e = os.popen3('dir /O-D /A-D /B) >>>o.readlines() ['recover.tbl\n', 'dnscheck.html\n', 'v3changes.txt\n', 'V3todo.txt\n', 'fupdates.pyc\n', 'Auth_db.pyc\n'] HTH :) From sjmaster at gmail.com Tue Aug 8 17:32:07 2006 From: sjmaster at gmail.com (Steve M) Date: 8 Aug 2006 14:32:07 -0700 Subject: newb question: file searching In-Reply-To: <1155070517.448510.149380@b28g2000cwb.googlegroups.com> References: <1155067111.892386.130610@n13g2000cwa.googlegroups.com> <1155067720.211789.208560@i42g2000cwa.googlegroups.com> <1155068675.101390.299110@i3g2000cwc.googlegroups.com> <1155070517.448510.149380@b28g2000cwb.googlegroups.com> Message-ID: <1155072727.338040.16880@n13g2000cwa.googlegroups.com> jaysherby at gmail.com wrote: > I must ask, in the interest of learning, what is > > [file for file in files if file.endswith(extension)] > > actually doing? I know that 'file' is a type, but what's with the set > up and the brackets and all? Other people explained the list comprehension, but you might be confused about the unfortunate choice of 'file' as the name in this example. 'file' is a built-in as you remarked. It is allowed, but a bad idea, to use names that are the same as built-ins. Some people characterize this as shadowing the built-in. A similar, common case is when people use the name 'list' for a list object. They shouldn't. The example could have been written as: [f for f in files if f.endswith(extension)] From mensanator at aol.com Sun Aug 27 14:58:16 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 27 Aug 2006 11:58:16 -0700 Subject: Learning Python References: <44f03c80$0$75042$14726298@news.sunsite.dk> <1156597310.493911.241160@i42g2000cwa.googlegroups.com> <44f0540a$0$75041$14726298@news.sunsite.dk> <1156659076.855399.87430@h48g2000cwc.googlegroups.com> Message-ID: <1156705096.687166.21000@i3g2000cwc.googlegroups.com> Tal Einat wrote: > Duncan Booth wrote: > > JAG CHAN wrote: > > > > > Whenever I try to open IDLE, my zone firewall tells me pythonw.exe is > > > trying to access the trusted zone. > > > Whenever I try to open new IDLE window I get the following message: > > > "IDLE's subprocess didn't make connection.Either IDLE can't start a > > > subprocess or personal firewall software is blocking the connection." > > > I will be grateful if you kindly suggest a way out, then, I won't have > > > to install another editor. > > > > You need to configure your firewall to permit IDLE to make the connection. > > Most firewall software when it warns you will give you the option of > > permitting this: > > > > e.g. Windows Firewall says "To help protect your computer, Windows Firewall > > has blocked some features of this program. Do you want to keep blocking > > this program?" with options "Keep Blocking", "Unblock", and "Ask me later". > > All you have to do is click "Unblock" and IDLE will work. > > IDLE doesn't connect to the internet, but it uses a socket interface to > communicate between two different processes. Some security software > falsely recognizes this as an attempt to connect to the internet, > although it is not a security hazard at all. > > > Another solution is to run IDLE with the -n flag, which will cause it > to run in one process (instead of two) and not create a socket. For the > most part you will not notice a difference in IDLE's behavior when > running it this way. > > On windows you can create a shortcut to idle.bat and add -n at the end > of the "target" entry. When running IDLE with -n, you should see "==== > No Subprocess ====" on one of the first lines of the Shell window. > > > You probably have your Windows security settings set quite high, > usually I don't see this on Windows systems with default settings. That's good to know (about the -n switch). On my computer at work, IDLE normally works ok, but if I'm running a complicated query on MS-Access (the kind that takes a half hour to complete) I can't run IDLE because of the socket problem. Why would that be? It's obviously not a security settings or firewall problem. Is the request for a socket timing out due to cpu load? > > - Tal > reduce(lambda m,x:[m[i]+s[-1] for i,s in enumerate(sorted(m))], > [[chr(154-ord(c)) for c in '.&-&,l.Z95193+179-']]*18)[3] From grahn+nntp at snipabacken.dyndns.org Sun Aug 20 05:47:40 2006 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 20 Aug 2006 09:47:40 GMT Subject: text editor suggestion? References: <44e66724$0$2363$c3e8da3@news.astraweb.com> <44e6ab26$0$12557$c3e8da3@news.astraweb.com> Message-ID: On Sat, 19 Aug 2006 02:06:15 -0400, John Salerno wrote: > Ben Finney wrote: > >> The two big names in text editing, Vim and Emacs, will both meet these >> criteria easily. They also have the advantage that you'll find one or >> the other, or both, on just about any Unix system intended for use by >> a programmer. And they're installable on Windows, and they will be ported to anything you're likely to encounter, for the rest of your life. >> There is also an enormous amount of support for both these editors, >> for all manner of text editing tasks, available online. It's a good >> idea to learn at least one of them very well, rather than learn a >> bunch of less-popular editors for specific tasks. That's an important point, IMHO. At least if you're living in Unix, plain old text editing is one of the most common tasks you do, and you rarely end up in situations where you're forced to use domain-specific editors (except when using web applications, where you are often limited to the text editing facilities of your web browser). I usually don't like the idea of becoming addicted to one simgle program, but I make an exception for text editing. I'm so much more productive in emacs than anywhere else, and the things I learn while (say) programming in Python translate directly to writing documentation, writing C code, or massaging and browsing large data sets. > I'd really like to learn vim, but I spent days just trying to figure out > how to get the syntax highlighting and indentation working, where these > settings are and how to edit them, and it still doesn't work for me. That's to be expected, and to be honest, you'd have the same problem with the editor I'd suggest, emacs. I've accepted that there are huge areas of emacs that I don't know and which would be useful to me if I had known them. It took almost ten years to discover dabbrev-expand, and I only found out about open-rectangle last week. And noone can tell me /which/ features I'm missing, because everyone uses their editor in a different way. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From mariano.difelice at gmail.com Thu Aug 31 08:28:49 2006 From: mariano.difelice at gmail.com (mardif) Date: 31 Aug 2006 05:28:49 -0700 Subject: wxNotebook color change In-Reply-To: <1157026185.987725.275010@e3g2000cwe.googlegroups.com> References: <1157020467.883961.282800@p79g2000cwp.googlegroups.com> <1157026185.987725.275010@e3g2000cwe.googlegroups.com> Message-ID: <1157027329.739038.275380@p79g2000cwp.googlegroups.com> No no!!! Your example is OK, great! but is not my problem: If you set: frame.SetBackgroundColour(wx.RED) On unix, you can see that label "form1" and "form2" are grey, and others elements are red. But on Windows, on the same line of "form1" and "form2", the color is not red, but grey as labels. I want to color this space RED!!! Rob Wolfe wrote: > mardif wrote: > > Hi ! > > > > this is my problem: > > > > I've a wxNotebook object, which contains 2 Panels. > > On up, there is TAB section, I have 2 tabs. > > I want to color the TAB section with ( for example ) red color. > > > > I've tried with SetBackgroundColour() for wxNotebook object and for 2 > > panel inside, but it doesn't works. > > why?? > > Presumably you forgot to refresh window. Try this: > > > import wx > > app = wx.PySimpleApp() > > frame = wx.Frame(None, -1, "Notebook") > nb = wx.Notebook(frame, -1) > form1 = wx.Panel(nb, -1) > nb.AddPage(form1, "Form1") > form2 = wx.Panel(nb, -1) > form2.SetBackgroundColour(wx.RED) > nb.AddPage(form2, "Form2") > nb.SetSelection(1) > frame.Refresh() > frame.Show(True) > > app.MainLoop() > > > HTH, > Rob From rogue_pedro at yahoo.com Wed Aug 16 03:45:50 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 16 Aug 2006 00:45:50 -0700 Subject: Python form Unix to Windows References: <1155712427.551814.247010@74g2000cwt.googlegroups.com> Message-ID: <1155714350.414644.29500@m79g2000cwm.googlegroups.com> Pradeep wrote: > Hi friends, > > We are changing the python application from Unix to Windows. The source > code of Python application should work well in windows. How to make > changed to windows environment. > In Python code we have login module, ftp, socket programming. > > Please help in changing the code from Unix envirnment to Windows > Environment. > > Thanks in Advance. > > Regards, > Pradeep Simplest way: Run the app in windows, see what breaks (probably less than you might think), fix it. I have written large apps that required less than a dozen, or no, changes to move between windows and *nix. YMMV Peace, ~Simon From __peter__ at web.de Thu Aug 3 13:14:15 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 03 Aug 2006 19:14:15 +0200 Subject: What is the best way to print the usage string ? References: Message-ID: Leonel Gayard wrote: > Notice that the string messes the indentation in my script. The > indentation is correct, and if the script is invoked without > arguments, the usage string is printed correctly. > > Now, how can I achieve the same result while keeping a clean > indentation ? How is this done in python world ? In C, I would do > this: > > ;; This buffer is for notes you don't want to save, and for Lisp > evaluation. ;; If you want to create a file, visit that file with C-x C-f, > ;; then enter the text in that file's own buffer. > > if (argc < N) { > printf("Usage: blah blah blah\n" > "Some more lines in the usage text\n" > "Some more lines here too\n"); > exit(1); > } > > The whitespace at the beginning of the string helps me keep the > indentation clean, and the construct "a" "b" is syntactic sugar that > allows me to create a large string without concatenating them at > runtime. > > How can I get this in Python ? >>> print ("You can do that in Python too.\n" ... "Personally, though,\n" ... "I wouldn't bother.") You can do that in Python too. Personally, though, I wouldn't bother. Like in C, you get a single string: >>> "a" "b" 'ab' The parentheses are just there to allow you to spread that string over multiple lines. Peter From vincentping at gmail.com Mon Aug 21 00:10:54 2006 From: vincentping at gmail.com (vincent) Date: 20 Aug 2006 21:10:54 -0700 Subject: Is there a python system to admin MySQL database online? Message-ID: <1156133454.275533.96470@m79g2000cwm.googlegroups.com> Just like the phpMySQLadmin? Thanks for reply! From daniel1 at telenet.be Mon Aug 7 11:11:35 2006 From: daniel1 at telenet.be (daniel Van der Borght) Date: Mon, 07 Aug 2006 15:11:35 GMT Subject: screensaver in Python Message-ID: Programming a screensaver in Python, where and/or how di I start ? Daniel VdB From JohnRoth1 at jhrothjr.com Sat Aug 19 18:45:55 2006 From: JohnRoth1 at jhrothjr.com (John Roth) Date: 19 Aug 2006 15:45:55 -0700 Subject: Questions on unittest behaviour In-Reply-To: References: Message-ID: <1156027555.276075.110100@m79g2000cwm.googlegroups.com> Collin Winter wrote: > While working on a test suite for unittest these past few weeks, I've > run across some behaviours that, while not obviously wrong, don't > strike me as quite right, either. Submitted for your consideration: > > 1) TestCase.tearDown() is only run if TestCase.setUp() succeeded. It > seems to me that tearDown() should always be run, regardless of any > failures in setUp() or the test method itself. > I'm undecided if this is a new feature (so it should go in for 2.6) or > a bug fix; I'm leaning toward the latter. I strongly disagree. First, this is the documented behavior for all xUnit ports (see jUnit), second, it's the responsibility of a routine to clean up for itself. > 2) The TestLoader.testMethodPrefix attribute currently allows anything > to be assigned to it, including invalid objects and the empty string. > While the former will cause errors to be raised when one of > TestLoader's loadTestsFrom*() methods is called, the empty string will > raise no exception; rather, the loadTestsFrom*() methods will > interpret every possible attribute as being a test method, e.g., > meaning you get things like assertEqual(), failUnlessEqual(), etc, > when TestLoader.loadTestsFromTestCase() is run. > > I propose protecting testMethodPrefix with a property that validates > the assigned value, restricting input to non-empty instances of str. I > see this as a bug fix that should go in before 2.5-final. Several points. First, since it's been this way since day one and nobody has complained, it's not a bug. That means it's a feature, and 2.5 is in a complete, absolute, utter, total and thorough feature freeze. This is not the place to get Guido's attention. As far as I'm aware, he doesn't read this newsgroup. On the other hand, you might be working with the crew on pythondev; I only read the summaries. If you are, then you already know what I mentioned above. If you aren't, your odds of getting a new test suite into 2.5 final are somewhere on the far side of zero. > 3) TestLoader.loadTestsFromTestCase() accepts objects that are not > test cases and will happily look for appropriately-named methods on > any object you give it. This flexibility should be documented, or > proper input validation should be done (a bug fix for 2.5). I'm pretty sure I use this. Making it go away would cause me to have to find another way around the misbegotten prefix selection mechanism. There's a lot of discussion around something that's called "behavior driven development" which is neither here nor there other than that group of people considers the whole notion of a name with a fixed element to be a problem with constructing really meaningful test names. > 4) TestLoader.loadTestsFromName() (and by extension, > loadTestsFromNames(), too) raises an AttributeError if the name is the > empty string because -- as it correctly asserts -- the object does not > contain an attribute named ''. I recommend that this be tested for and > ValueError be raised (bug fix for 2.5). Prior point about 2.5 being in a freeze. Take it to the pythondev mailing list if you really want action. As far as I'm concerned, this is a "so what." There are much deeper issues with unittest than this. > This of course leads into the question of how much input validation > should be done on these names. Should loadTestsFrom{Name,Names}() make > sure the names are valid attribute names, or is this overkill? What _I_ want is a method of selecting tests from a class that doesn't depend on pattern matching the name. I've got it rigged to not do that, and I feel that my names are now significantly better. > 5) When TestLoader.loadTestsFrom{Name,Names}() are given a name that > resolves to a classmethod on a TestCase subclass, the method is not > invoked. From the docs: > > > The specifier name is a ``dotted name'' that may resolve either to a module, a test > > case class, a TestSuite instance, a test method within a test case class, or a > > callable object which returns a TestCase or TestSuite instance. > > It is not documented which of these tests takes priority: is the > classmethod "a test method within a test case class" or is it a > callable? The same issue applies to staticmethods as well. These are all new since pyUnit (renamed to unittest for inclusion into the standard library) was written. My viewpoint is that it's a feature that's looking for a use case. As I intimated above, my current practice is to not use the supplied mechanism for locating tests. I don't use it for locating test classes either. > Once I get answers to these questions, I can finish off the last few > bits of the test suite and have it ready for 2.5-final. Answers? On this list? I'm not even sure you can get coherent opinions here. John Roth > > Thanks, > Collin Winter From bdesth.quelquechose at free.quelquepart.fr Thu Aug 10 16:47:44 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 10 Aug 2006 22:47:44 +0200 Subject: How to write a Installer for a Python App in Linux In-Reply-To: <1155240625.157696.143230@i42g2000cwa.googlegroups.com> References: <1155240625.157696.143230@i42g2000cwa.googlegroups.com> Message-ID: <44db9939$0$6062$636a55ce@news.free.fr> diffuser78 at gmail.com a ?crit : > Hi, > > I have known python for about 3-4 months now. My knowledge is still > very limited. > > I wrote a small app using wxPython. Now, I want to create an installer > for it (on Linux platform.) for the people I developed this small > utility. > > These people use some customized variant of Red Hat Linux. I found on > the web python2.4 and the corresponding wxPython files. > > How can I write a Installer file which will install all the needed > programs in the correct path, so that my wxPython app is ready to run > and end user doesn't need to bother installing required files. > > Give me some pointers and I will try to write the script on my own. > > Every help is greatly appreciated. > Look for distutil and EasyInstall (-> Python Eggs) From sjmachin at lexicon.net Fri Aug 11 07:05:55 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 11 Aug 2006 21:05:55 +1000 Subject: Reading unformatted big-endian files In-Reply-To: References: Message-ID: <44dc6491$1@news.eftel.com> On 11/08/2006 8:35 PM, Andrea Gavana wrote: > I hope performances will not change so much: fortran is > very fast in reading files (but I use it only in this case, I love to > use Python)... well, let's see :-D Well FORTRAN would have to have *something* going for it :-) I vaguely recall in a previous incarnation tarting up a vanilla ratfor "compiler" with switch statements and macros and all sorts of goodies so that life was less unbearable :-) [this was *before* f77] Suggestions: (1) Upgrade to 2.5 as soon as it goes final -- struct's performance has been improved. (2) Consider the possibility of not unpacking all three variables if you don't need to -- for example if you are ignoring everything until you hit a record that starts with 'DIMENS ', you don't need to unpack anything, just do: if buff[:8] == 'DIMENS ': How big are your files, anyway? Cheers, John From steve at holdenweb.com Wed Aug 23 19:42:07 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 24 Aug 2006 00:42:07 +0100 Subject: radio buttons in curses In-Reply-To: References: Message-ID: Fabian Braennstroem wrote: > Sorry, me again... > Does nobody have an idea or is it to stupid? > > * Fabian Braennstroem wrote: > >>Hi, >> >>I want to add some radio and check buttons to my curses >>script. As I understand it, there are no buttons in the >>'basic' curses module. Now, I found the curses-extra module, >>but I not able to download and install it. >> >>Does anybody have an idea, where I can download the module >>or, even better, how I can create radio and check buttons >>with the 'ordinary' curses module? Would be nice... >> >>Greetings! >> Fabian >> >>-- >>http://mail.python.org/mailman/listinfo/python-list >> > > > Greetings! > Fabian > Sounding a bit like a "no", looks like. Did you Google much? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From rosedb0 at gmail.com Thu Aug 24 21:29:42 2006 From: rosedb0 at gmail.com (hiaips) Date: 24 Aug 2006 18:29:42 -0700 Subject: OS X and Python - what is your install strategy? In-Reply-To: <1156460483.616400.120160@i3g2000cwc.googlegroups.com> References: <1156460483.616400.120160@i3g2000cwc.googlegroups.com> Message-ID: <1156469382.356341.281450@i3g2000cwc.googlegroups.com> metaperl wrote: > I'm about to get a new OS X box on which I will rewrite a bunch of data > munging scripts from Perl to Python. I know that there are several port > services for OS X (fink, darwin ports, opendarwin). So I am not sure > whether to use their port of Python or whether to build from scratch or > use the Python image file. Also ActivePython is something of a choice > but for some reason not a front-running one for me. I tend to like > Gentoo-style compile from source over pre-bundled all-in-one solutions > like ActivePython. > > I'm not going to do much other than maybe install Plone and do some XML > and CSV processing. Most everything I need is in the Python stdlib. > Maybe down the road some graphics and web stuff (I like Clever Harold > or Pylons for that... but I still ahve not examined the 900 other web > app options in Python :) These days, I install the OS X universal binary provided on the Python language web site. You can find it at http://www.python.org/download/releases/2.4.3. It's more comprehensive and much more up-to-date than the version included in OS X. From pupeno at pupeno.com Tue Aug 1 17:02:46 2006 From: pupeno at pupeno.com (Pupeno) Date: Tue, 01 Aug 2006 21:02:46 +0000 Subject: Hierarchical unit tests Message-ID: <44cfc171$0$18509$9b4e6d93@newsread2.arcor-online.net> Hello, Having A(unittest.TestCase) and B(A), the unittests framework seems not to run A's test when testing B, right ? If so, is there any way to 'fix' it ? that is, make all tests in A, also run for B ? Thanks. -- Pupeno (http://pupeno.com) From paddy3118 at netscape.net Sun Aug 6 02:48:33 2006 From: paddy3118 at netscape.net (Paddy) Date: 5 Aug 2006 23:48:33 -0700 Subject: More int and float attributes In-Reply-To: <1154846489.880041.120280@m79g2000cwm.googlegroups.com> References: <1154780600.348169.158150@i42g2000cwa.googlegroups.com> <1154807223.104418.230270@i3g2000cwc.googlegroups.com> <1154810987.818618.110350@h48g2000cwc.googlegroups.com> <1154846489.880041.120280@m79g2000cwm.googlegroups.com> Message-ID: <1154846913.279343.15040@p79g2000cwp.googlegroups.com> Paddy wrote: > bearophileHUGS at lycos.com wrote: > > Paddy: > > > Or do you mean the ability to choose between hardware supported float > > > s? e.g. float and double precision? > > > > No, I mean just having the ability to ask the float (his attribute) > > what are the max and min values it can represent, etc. > > > > stop = float.max > > ... > > > > I don't know any simple way to know that values now. And importing sys > > to know the max int looks stupid. > > > > maxi = int.max > > mini = int.min > > ... > > > > Such attributes can be given to the Decimal values too, if you want. > > > > Bye, > > bearophile > Hi bearophille, > decimals have their context; maybe floats could have your read-only > 'context' values made available somehow. I don't know if their is an > issue with making this (static) data available from all float > instances, so maybe it should go in sys. > > Maybe people, (me included), don't pay enough attention to the > trade-offs inherent in floating point arithmatic. I was taught about > difference equations, and rounding errors. I regularly compute answers > in programs without regard to floating point precision because the > defaults chosen work for most of my cases, but if I needed to be more > precise then I too would need some of the info you suggest. > > Question: do the scientific packages supported by Python supply this > data in a regular manner? > > - Paddy. > > P.S. My appologies to any professional 'counters of currencies' out > their who may have been offended by my earlier use of the term 'bean > counters' - You probably earn much more than me - don't call in my > loans - I have babes in arms to feed.... :-) P.P.S. Just looking at the values you propose, if some of them can be computed reliably from others (in the given float precision), then they should NOT be included, but the module documentation should state how they can be derived. From gelists at gmail.com Sat Aug 19 17:02:15 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Sat, 19 Aug 2006 18:02:15 -0300 Subject: How to get the ascii code of Chinese characters? References: <1155986298.643983.157460@i3g2000cwc.googlegroups.com> <1155990488.395220.178810@74g2000cwt.googlegroups.com> <1155999554.486951.303480@i42g2000cwa.googlegroups.com> Message-ID: On 2006-08-19 16:54:36, Peter Maas wrote: > Gerhard Fiedler wrote: >> Well, ASCII can represent the Unicode numerically -- if that is what the OP >> wants. > > No. ASCII characters range is 0..127 while Unicode characters range is > at least 0..65535. Actually, Unicode goes beyond 65535. But right in this sentence, you represented the number 65535 with ASCII characters, so it doesn't seem to be impossible. >> For example, "U+81EC" (all ASCII) is one possible -- not very >> readable though -- representation of a Hanzi character (see >> http://www.cojak.org/index.php?function=code_lookup&term=81EC). > > U+81EC means a Unicode character which is represented by the number > 0x81EC. Exactly. Both versions represented in ASCII right in your message :) > UTF-8 maps Unicode strings to sequences of bytes in the range 0..255, > UTF-7 maps Unicode strings to sequences of bytes in the range 0..127. > You *could* read the latter as ASCII sequences but this is not correct. Of course not "correct". I guess the only "correct" representation is the original Chinese character. But the OP doesn't seem to want this... so a non-"correct" representation is necessary anyway. > How to do it in Python? Let chinesePhrase be a Unicode string with > Chinese content. Then > > chinesePhrase_7bit = chinesePhrase.encode('utf-7') > > will produce a sequences of bytes in the range 0..127 representing > chinesePhrase and *looking like* a (meaningless) ASCII sequence. Actually, no. There are quite a few code positions in the range 0..127 that don't "look like" anything (non-printable). And, as you say, this is rather meaningless. > chinesePhrase_16bit = chinesePhrase.encode('utf-16be') > > will produce a sequence with Unicode numbers packed in a byte > string in big endian order. This is probably closest to what > the OP wants. That's what you think... but it's not really ASCII. If you want this in ASCII, and readable, I still suggest to transform this sequence of 2-byte values (for Chinese characters it will be 2 bytes per character) into a sequence of something like U+81EC (or 0x81EC if you are a C fan or 81EC if you can imply the rest)... that's where we come back to my original suggestion :) Gerhard From johnjsal at NOSPAMgmail.com Wed Aug 9 16:42:18 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 09 Aug 2006 20:42:18 GMT Subject: why does getpass() show the input? Message-ID: I'm guessing this might have something to do with my particular system? >>> getpass.getpass() Warning: Problem with getpass. Passwords may be echoed. Password: hello 'hello' From g.brandl-nospam at gmx.net Sun Aug 20 14:01:34 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Sun, 20 Aug 2006 20:01:34 +0200 Subject: import In-Reply-To: <1156096550.873958.289300@m79g2000cwm.googlegroups.com> References: <1156093283.529579.80600@i42g2000cwa.googlegroups.com> <1156093799.775420.51970@m73g2000cwd.googlegroups.com> <1156094307.576025.3430@i3g2000cwc.googlegroups.com> <1156096550.873958.289300@m79g2000cwm.googlegroups.com> Message-ID: 01 wrote: > Georg Brandl wrote: >> figo_wei01 at 126.com wrote: >> > bugnthecode ??? >> > >> >> How are you trying to import it? Is it in the same directory as your >> >> other script? If not is your python path set correctly? >> >> >> >> When importing a module that you have written you exlude the .py >> >> extension. You should be using: >> >> import hello >> >> >> >> Hope that helps, >> >> Will >> > >> > i am on a windows platform. i have written scrip named 123.py. it can >> > be run. ok i save it to C:\Python24 ,exactly the same dir where python >> > works. but " import 123" doesnt work. >> >> You can't import modules whose names have non-identifier names with >> plain "import". Or would you like "123" to refer to a module? >> >> If you have to do this (and I have a strong feeling that you haven't) >> use the built-in function __import__(). >> > you have to name your program with the name mymodule,or something like > that when you use "import". does python have a clear declaration on > how to name a module? A module name can be everything also usable as a Python identifier. This means that it contains only letters, digits and underscores and doesn't start with a digit. Running a file as the main file, using "python 123.py" works because Python then won't need to provide the file name as a name in the script. Georg From paul at subsignal.org Thu Aug 3 09:51:12 2006 From: paul at subsignal.org (=?ISO-8859-1?Q?paul_k=F6lle?=) Date: Thu, 03 Aug 2006 15:51:12 +0200 Subject: Using Python for my web site In-Reply-To: <1154454290.20290.189.camel@devilbox> References: <1154361480.915174.262720@b28g2000cwb.googlegroups.com> <1154409902.320511.114320@75g2000cwc.googlegroups.com> <1154416278.20290.183.camel@devilbox> <1hqlf4twmexrt$.dlg@gelists.gmail.com> <1154454290.20290.189.camel@devilbox> Message-ID: Cliff Wells wrote: > For myself, I handle user-installation of TurboGears pretty much like I > do all user-installed Python packages: using setuptools. Any user who > uses easy_install or 'python setup.py install' gets their packages > automatically installed into a subdirectory of their home directory and > that takes precedence over the system installed packages. Works like a > charm. May I ask how you handle clashes with packages already installed in site-packages? Once I tried something like ~/lib/python and set up distutils accordingly, easy_install wouldn't work if the package was installed system-wide... thanks Paul From rdrink at gmail.com Tue Aug 29 14:19:47 2006 From: rdrink at gmail.com (rdrink) Date: 29 Aug 2006 11:19:47 -0700 Subject: eval() woes References: <1156735954.796051.290600@i3g2000cwc.googlegroups.com> <1156740704.380857.76670@i42g2000cwa.googlegroups.com> <1156817948.765024.13770@p79g2000cwp.googlegroups.com> <1156824826.778486.251380@74g2000cwt.googlegroups.com> <1156830108.838003.9810@m79g2000cwm.googlegroups.com> Message-ID: <1156875586.919345.84760@h48g2000cwc.googlegroups.com> Thanks everyone for you thoughtful replies... And yes Simon you are right... I do need to learn how to read 'tracebacks' (and de-bugging tools in general)... but you are the first person to give me a step-by-step explination, thank you. And LOL you all caught my dropped single-quote ;-) .... but unfortunately that was just a typo, not generated by my code. And Simon thanks for this.... > That's a lot of calls to str() to change the parts of parts *back* into > strings after changing them into ints. Why don't you just say > something like: > > soL, siL, siR, soR = parts > oL, iL, iR, oR = map(int, parts) > oLoL = int(soL + soL) > oLiL = int(soL + siL) > . > . > . > etc... > ? ... I've never used mapping before, so this will be a good start. > If you're calling this function as many times as you indicate below > (just under a quarter of a million(!) if I understand you correctly, > 480*500 = 240,000) , it might even result in a human-noticeable speed > up. ;-) Oh it get's worse that that... it'll be (possibly) up to 500 times per equation, for 334 equations, for 480 'seed numbers'... 500 * 334 * 480 = 80,327,000 calculations =:-o So every little speed up helps! ---- > Ok, so there you go. At this point in the program parts[1] is '-', > which isn't an int literal, so the script raises an exception. One > very good thing to do here, as others have already mentioned, would be > to "print parts" at the beginning of your equate() function. That way > you could see exactly which data are causing the problem. Ok guys I'm not such a noob I didn't try that ;-) but unfortunately it didn't enlighten anything. However, as Simon points out... > None of this has anything to do with the error you posted. You're not > even getting as far as calling eval() or pow(). > The traceback tells you, unambiguously, that it's the latter, the > variable cast. the one thing I didn't mention (in trying to spare everyone having to read *all* my code) is that the above mentioned list 'parts' of which I am trying to use parts[1] etc, is passed in from another function... and though I have gone over it repaetedly, looking for possible sources of errors, Simons suggestion points to the problem originating there... so I'll just have to keep looking. Unfortunately I am going to have to put this project* away for a while now, so let me just thank everyone again for helping a newcomer (I hope someday I can return the favor) and let's retire this thread. * BTW If any of you are interested in details of the project it's self feel free to email me. Thanks again! From gregpinero at gmail.com Thu Aug 31 13:02:24 2006 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Thu, 31 Aug 2006 13:02:24 -0400 Subject: Basic import Questions (with bonus profiling question) In-Reply-To: References: <312cfe2b0608310849m6967e2cx259046143728b29e@mail.gmail.com> Message-ID: <312cfe2b0608311002s3c24cd42t1206ebdc198a69c7@mail.gmail.com> On 8/31/06, Fredrik Lundh wrote: > several seconds? sounds bad. what does the following script print on > your machine? > > import time, subprocess, sys > > t0 = time.time() > for i in range(10): > subprocess.call([sys.executable, "-c", "pass"]) > print time.time() - t0 It prints 1.92199993134 What does that mean? By the way, I thought I was importing just a file path from a module but like you said it was importing the entire module. I got rid of that import statement and the time dropped from 7 seconds to 1.5 seconds. Any other tips for speeding up python load time for IIS? (I mean really simply tips, I don't have time anything soon to fool with fastCGI for IIS or setting up ASP) -Greg From paolopantaleo at gmail.com Wed Aug 2 05:55:38 2006 From: paolopantaleo at gmail.com (Paolo Pantaleo) Date: Wed, 2 Aug 2006 11:55:38 +0200 Subject: Behavior on non definded name in Cheetah Message-ID: <83e8215e0608020255i5bda0fd3oc11ae4f064ae7648@mail.gmail.com> [I hope I am posting to the right place] I have a cheetah template something like this: x is: $x y is: $y z is: $z [Actually more complicated] If for example $y is not defined I get an exception and the parsing of the template stops. Is there any way to substitute $y with an emty string and making cheeta going on with parsing? Thnx PAolo -- if you have a minute to spend please visit my photogrphy site: http://mypic.co.nr From Kiran.Karra at gmail.com Fri Aug 25 12:54:13 2006 From: Kiran.Karra at gmail.com (Kiran) Date: 25 Aug 2006 09:54:13 -0700 Subject: namespace problems Message-ID: <1156524852.973852.76800@h48g2000cwc.googlegroups.com> Hi all, I am trying to get the following to work, but cant seem to do it the way i want to. ok, so I come into python and do the following: >>> x = 1 then, i have a file called test.py in which i say: print x Now, after having defined x =1 in the python interpreter, i come in and say: import test it has a problem, which i can understand, because it is in its own namespace, but even if i say: from test import * the interpreter still gives me the error: NameError: name 'x' is not defined the only way i can get it to work is if i say: execfile('./test.py') how can i get this to work by importing and not execfile? thanks for your help! From gdamjan at gmail.com Thu Aug 31 20:24:15 2006 From: gdamjan at gmail.com (Damjan) Date: Fri, 01 Sep 2006 02:24:15 +0200 Subject: Broadcast server References: <1157015655.323891.154720@p79g2000cwp.googlegroups.com> Message-ID: <44f77d3c$0$75041$14726298@news.sunsite.dk> swell at netcourrier.com wrote: > I would like to write a server with the low level API of python ( > socket+select and/or socket+thread ) that allow me to register client > and update them every X seconds ( could be the time, the temperature, a > stock quote, a message , ... ). > > How to write the server that keep hot connections with clients and > update them when events are trigerred. I don't know how to begin this , > i look at the python doc but the doc is more related to client updating > the server and i am not sure of the right design that could be use > here. I'd suggest to find the Richard W. Stevens book "Unix Network Programing". You'll learn a lot about networking from that book. It's based on C, but you'll see that the concepts can be easily used with Python too. Find that book, and don't forget the stdlib docs: http://docs.python.org/lib/module-socket.html http://docs.python.org/lib/module-select.html -- damjan From rogue_pedro at yahoo.com Sat Aug 26 15:04:39 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 26 Aug 2006 12:04:39 -0700 Subject: rollover effect In-Reply-To: References: <1156607403.741240.25000@74g2000cwt.googlegroups.com> <1156608042.466471.210270@m73g2000cwd.googlegroups.com> <1156608554.489516.243640@h48g2000cwc.googlegroups.com> <1156609000.477885.289150@h48g2000cwc.googlegroups.com> <1156609368.745082.324510@h48g2000cwc.googlegroups.com> <1156611065.857764.129500@b28g2000cwb.googlegroups.com> <1156611342.994894.288160@m79g2000cwm.googlegroups.com> Message-ID: <1156619079.447393.303340@75g2000cwc.googlegroups.com> SuperHik wrote: > groves wrote: > > Simon Forman wrote: > >> groves wrote: > >>> Sorry, as I am new to python so couldn't understand what yu were > >>> asking. > >>> Now the problem is that i annot use pmw in my project..is thre anyother > >>> alternative by which I can have a rollover mouse effect on the canvas. > >>> thanks > >> Not a problem. Although "IDE" and "GUI" are terms that are not > >> specific to python. But you still haven't answered my question? Are > >> you using Tkinter? wxWidgets? Gtk bindings? > >> > >> Assuming that you're using Tkinter, what prevents you from using Pmw? > >> > >> Peace, > >> ~Simon > > > > Yes I am using Tkinter... > > the thing is I I m new to Tkhave not used PMW bfore..Nd inter... > > So just though If there is any alternative,,,as i don't have much time > > > PMW uses Tkinter too, so there is nothing "new", > it just has more "complicated" widgets already > written for you using Tkinter... Also, the time it would take to learn how to use Pmw's "Balloon" widget would almost certainly be much less than rolling your own. There are a few tricky bits to getting it working right in Tkinter that Pmw makes short work of. Check out: http://pmw.sourceforge.net/doc/Balloon.html http://pmw.sourceforge.net/doc/howtouse.html HTH, ~Simon From skip at pobox.com Thu Aug 31 10:30:26 2006 From: skip at pobox.com (skip at pobox.com) Date: Thu, 31 Aug 2006 09:30:26 -0500 Subject: How ahead are you guys in the (Python) real world? In-Reply-To: <20060831041849.GG6257@performancedrivers.com> References: <1156821234.820929.299740@p79g2000cwp.googlegroups.com> <20060831041849.GG6257@performancedrivers.com> Message-ID: <17654.62082.40756.262513@montanaro.dyndns.org> Jack> I came away from the thread with the opposite conclusion for Jack> similar reasons. People would use a 2.3.6 if their OS upgraded it Jack> for them but those are the same people who won't upgrade to 2.4.x Jack> because it involves testing. 2.3.5 isn't broken for them or they Jack> would know it by now. 2.3.6 probably isn't broken for them but it Jack> can't help -- or they would have noticed a bug by now. In contrast, I generally do only a small amount of testing when a micro release of Python comes out before inflicting it on our users and developers, precisely because I have confidence that it only contains bug fixes. Since probably 2.2.1 there have been no new features in any micro releases that I can recall and, up to this point at least, no regressions in my experience. Micro updates seem like a pretty safe bet to me. Skip From fredrik at pythonware.com Thu Aug 24 04:13:13 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Aug 2006 10:13:13 +0200 Subject: what is the data from loads() In-Reply-To: References: Message-ID: leo wrote: > anyone know what is the data in loads()? > i mean what is the > ('c\000\000\000\000\001\000\000\000s\017... compiled and serialized Python code (the same kind of stuff that you'll find in PYC files). if you don't trust the source, don't run that program. From jbellis at gmail.com Sun Aug 27 19:13:29 2006 From: jbellis at gmail.com (Jonathan Ellis) Date: 27 Aug 2006 16:13:29 -0700 Subject: Pros/Cons of Turbogears/Rails? In-Reply-To: References: Message-ID: <1156720409.469663.12550@m73g2000cwd.googlegroups.com> Fredrik Lundh wrote: > kenneth.m.mcdonald at sbcglobal.net wrote: > > P.S. If I wanted to provide an image by streaming the > > file data directly over the connection, rather than by > > referring to an image file, how would I do that? I'd > > like to build code that would allow images to be assembled > > into a single-file photo album (zip or bsddb file), and > > so can't refer to them as individual image files. > > some browsers support special data URL:s for images, but that doesn't > work well for large images, and isn't portable. on the other hand, I > don't really see why there has to be 1:1 mapping between URL:s and image > files on your machine, especially if you're using a web application > framework... I think he's just asking "how do you specify a mimetype and stream binary data from within the framework." IIANM in TurboGears all you have to do is return a file-like object from your page handler. -Jonathan From hitesh287 at gmail.com Wed Aug 16 17:00:54 2006 From: hitesh287 at gmail.com (Hitesh) Date: 16 Aug 2006 14:00:54 -0700 Subject: Adding a char inside path string In-Reply-To: <12e71hnet3e7c99@corp.supernews.com> References: <1155737700.290268.248250@i42g2000cwa.googlegroups.com> <1155744057.573884.111850@m73g2000cwd.googlegroups.com> <1155757548.080769.213490@p79g2000cwp.googlegroups.com> <1155759163.627377.72590@74g2000cwt.googlegroups.com> <12e70d6h4pb3l65@corp.supernews.com> <1155760716.499472.189490@p79g2000cwp.googlegroups.com> <12e71hnet3e7c99@corp.supernews.com> Message-ID: <1155762054.479806.265310@b28g2000cwb.googlegroups.com> I post a crappy solution but I can add few more stuff to make it fail proof. i.e. I can search for ".exe -u" But if someone names folder like "folder.exe u". This script could fail. Or if in padded garbase I get ".exe u" These are two known issues I have to takcle. Thanks everyone for your help. Grant Edwards wrote: > On 2006-08-16, Hitesh wrote: > > > anything after .exe should be truncated (or deleted). > > That will fail if any directory names contain the string > ".exe", but if that's what you want, it's trivial enough: > > for s in ["asdfasdf.exe -u", "soemthing/else", "asdf.exe/qwerqwer/qwerqwer.exe"]: > print `s`, > i = s.find(".exe") > print i, > if i >= 0: > s = s[:i+4] > print `s` > > -- > Grant Edwards grante Yow! Yow! It's some people > at inside the wall! This is > visi.com better than mopping! From carsten at uniqsys.com Thu Aug 31 16:50:00 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 31 Aug 2006 16:50:00 -0400 Subject: re.compile() doesn't work under Windows? In-Reply-To: References: Message-ID: <1157057400.17878.58.camel@dot.uniqsys.com> On Thu, 2006-08-31 at 17:38, ddtl wrote: > Hello everybody. > > My script uses re.compile() function, and while it rans without errors > under Linux, when I ran that script under Windows I get the following > error: > > Traceback (most recent call last): > File "C:\a\projects\re.py", line 4, in ? > import re > File "C:\a\projects\re.py", line 95, in ? > main() > File "C:\a\projects\re.py", line 37, in main > s_exp = re.compile(op['-s']) > AttributeError: 'module' object has no attribute 'compile' > > What is the problem here? re module is installed and is on the path - > for example, the following code works and doesn't cause any errors: > > import re > re.compile('a') > > What else could cause such an error? Your script is called re, so "import re" is making the script import itself instead of the re module from the library. -Carsten From paddy3118 at netscape.net Fri Aug 18 13:13:51 2006 From: paddy3118 at netscape.net (Paddy) Date: 18 Aug 2006 10:13:51 -0700 Subject: sum and strings In-Reply-To: References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> Message-ID: <1155921231.537033.159460@p79g2000cwp.googlegroups.com> Sybren Stuvel wrote: > Paddy enlightened us with: > > Well, after all the above, there is a question: > > > > Why not make sum work for strings too? > > Because of "there should only be one way to do it, and that way should > be obvious". There are already the str.join and unicode.join methods, > which are more powerful than sum. > > Sybren I get where you are coming from, but in this case we have a function, sum, that is not as geeral as it could be. sum is already here, and works for some types but not for strings which seems an arbitrary limitation that impede duck typing. - Pad. P.S. I can see why, and am used to the ''.join method. A newbie introduced to sum for integers might naturally try and concatenate strings using sum too. From cliff at develix.com Thu Aug 3 00:22:35 2006 From: cliff at develix.com (Cliff Wells) Date: Wed, 02 Aug 2006 21:22:35 -0700 Subject: Using Python for my web site In-Reply-To: References: <1154361480.915174.262720@b28g2000cwb.googlegroups.com> <44ce3a5c$0$18952$626a54ce@news.free.fr> <1154367359.931684.106650@m73g2000cwd.googlegroups.com> <44ce4530$0$28242$626a54ce@news.free.fr> <19zmaoel1tn3$.dlg@gelists.gmail.com> <1154567858.20290.324.camel@devilbox> Message-ID: <1154578955.20290.332.camel@devilbox> On Wed, 2006-08-02 at 23:13 -0300, Gerhard Fiedler wrote: > Thanks, that's one of the conclusions to which I also came. That final > question was missing, even though I felt it was implied. I really had no > clue that this is such a touchy subject. Every opinion in technology seems to be touchy for someone ;-) > Another one is that it seems (here I go again :) that there is something > like a marriage between Python and PostgreSQL (or in other words, that > Python fans that develop web apps have a tendency to favor PostgreSQL). Is > there something like this? (Here is the question :) > I don't think so. If I had to venture an opinion, my impression has been that the MySQL/PostgreSQL division lies more along the line between web applications and other types of apps. For some reason, web people seem to either prefer MySQL or (more likely) fall back to it as a default. If there's a bias toward PostgreSQL in the Python crowd, I suspect that's due to the fact that Python's presence seems to be more weighted toward non-web programming relative to other languages (this being due to Python's general applicability, not an implication Python isn't suited for the web). Regards, Cliff -- From snail at objmedia.demon.co.uk Thu Aug 10 12:49:52 2006 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Thu, 10 Aug 2006 17:49:52 +0100 Subject: do people really complain about significant whitespace? References: <1154986984.740638.241130@m79g2000cwm.googlegroups.com> <2AY13sCznQ2EFw8+@objmedia.demon.co.uk> Message-ID: In message , Gerhard Fiedler writes >> http://www.americanscientist.org/template/AssetDetail/assetid/51982 >> >> The Semicolon Wars > >Good reading :) Thanks. Found something else relevant to this thread. The Pliant language. Appears to use whitespace indentation for grouping. http://fullpliant.org/pliant/language/parser/default_syntax.html Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk/software.html Computer Consultancy, Software Development Windows C++, Java, Assembler, Performance Analysis, Troubleshooting From sjmachin at lexicon.net Tue Aug 1 01:41:07 2006 From: sjmachin at lexicon.net (John Machin) Date: 31 Jul 2006 22:41:07 -0700 Subject: BCD List to HEX List In-Reply-To: <12ctj11hgs26n29@corp.supernews.com> References: <1154301233.360818.93450@s13g2000cwa.googlegroups.com> <0abzg.1576$W93.173@dukeread05> <1154302086.623471.88710@m73g2000cwd.googlegroups.com> <1154311512.865261.306920@b28g2000cwb.googlegroups.com> <12cqs9m6qo379b9@corp.supernews.com> <1154319534.597480.264620@s13g2000cwa.googlegroups.com> <7x7j1tsvm7.fsf@ruckus.brouhaha.com> <1Rozg.1791$W93.1716@dukeread05> <1154380117.092577.58400@m73g2000cwd.googlegroups.com> <1154385339.695918.155840@s13g2000cwa.googlegroups.com> <7qwzg.2558$W93.2107@dukeread05> <1154392791.954980.78190@i42g2000cwa.googlegroups.com> <1154393509.059503.231590@b28g2000cwb.googlegroups.com> <12ctj11hgs26n29@corp.supernews.com> Message-ID: <1154410866.942251.65910@h48g2000cwc.googlegroups.com> Grant Edwards wrote: > On 2006-08-01, Philippe Martin wrote: > > >> Perhaps if Philippe could divulge the part number that's in > >> the bottom right corner of the manual that he has, and/or any > >> part number that might be mentioned in the first few pages of > >> that manual, enlightenment may ensue .... > > > > That was cute ... over and out ! > > Or perhaps it may not. > > Methinks it was all just a rather good troll. > > -- Now we have a few more questions i.e. apart from what CPU is in Phillipe's device: 1. WHO was Philippe replying to -- Simon or me? 2. WHAT was cute? 3. Grant thinks WHAT might have been a rather good troll by WHOM? Ah well never mind ... I think I'll just report the whole thread to thedailywtf and move on :-) From f.braennstroem at gmx.de Sun Aug 20 14:41:56 2006 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Sun, 20 Aug 2006 20:41:56 +0200 Subject: radio buttons in curses Message-ID: Hi, I want to add some radio and check buttons to my curses script. As I understand it, there are no buttons in the 'basic' curses module. Now, I found the curses-extra module, but I not able to download and install it. Does anybody have an idea, where I can download the module or, even better, how I can create radio and check buttons with the 'ordinary' curses module? Would be nice... Greetings! Fabian From rganesan at myrealbox.com Wed Aug 16 04:12:50 2006 From: rganesan at myrealbox.com (Ganesan Rajagopal) Date: Wed, 16 Aug 2006 13:42:50 +0530 Subject: Memory usage of an 'empty' python interpreter References: <1155710349.127768.17280@h48g2000cwc.googlegroups.com> Message-ID: >>>>> neokosmos writes: > I was wondering what the approximate amount of memory needed to load a > Python interpreter (only, no objects, no scripts, no nothing else) in a > Linux 2.6 environment. According to ps, it appears to be 3312 bytes, > which seems absurdly low to me. However, when I check the size of my > Python executable, it looks like it is only about 5600 bytes in size, > so maybe this is reasonable? It is, when you consider that ps reports in kilobytes :-). It's meaningless just to compare the size of the python binary. In your case it's obvious that the python binary is linking to a shared python library. Ganesan -- Ganesan Rajagopal From sjdevnull at yahoo.com Wed Aug 16 04:01:33 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 16 Aug 2006 01:01:33 -0700 Subject: what is the keyword "is" for? In-Reply-To: References: <1155625097.784052.31330@p79g2000cwp.googlegroups.com> <1155681780.830614.86950@75g2000cwc.googlegroups.com> Message-ID: <1155715293.150415.14590@75g2000cwc.googlegroups.com> Sybren Stuvel wrote: > Dan Bishop enlightened us with: > >>>> a = b = 1e1000 / 1e1000 > >>>> a is b > > True > >>>> a == b > > False > > If "a is b" then they refer to the same object, hence a == b. It > cannot be otherwise, unless Python starts to defy logic. I copied your > code and got the expected result: > > >>> a = b = 1e1000 / 1e1000 > >>> a is b > True > >>> a == b > True Probably depends on the implementation. 1e1000/1e1000 yields a NaN here, and I get True for "a is b" but False for "a==b". Presumably comparing a NaN for equality (any comparison?) always yields False. From Bulkan at gmail.com Wed Aug 2 20:30:53 2006 From: Bulkan at gmail.com (placid) Date: 2 Aug 2006 17:30:53 -0700 Subject: serial ports, threads and windows In-Reply-To: References: Message-ID: <1154565053.913013.294220@i42g2000cwa.googlegroups.com> Tom Brown wrote: > When it runs on Windows, could it be: > > 1) Just struggling to run inside of VMware? i have gut feeling that it could be that this is the problem. From siona at chiark.greenend.org.uk Wed Aug 16 08:07:42 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 16 Aug 2006 13:07:42 +0100 (BST) Subject: what is the keyword "is" for? References: <1155625097.784052.31330@p79g2000cwp.googlegroups.com> <1155681780.830614.86950@75g2000cwc.googlegroups.com> <1155715396.532997.81890@b28g2000cwb.googlegroups.com> Message-ID: Simon Forman wrote: >Python 2.4.3 (#2, Apr 27 2006, 14:43:58) >[GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2 >Type "help", "copyright", "credits" or "license" for more information. > >|>> a = b = 1e1000 / 1e1000 >|>> a is b >True >|>> a == b >False I agree with you: $ python Python 2.4.1 (#2, May 5 2005, 11:32:06) [GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = b = 1e1000 / 1e1000 >>> a is b True >>> a == b False Or maybe I don't: $ python2.3 Python 2.3.5 (#2, Sep 4 2005, 22:01:42) [GCC 3.3.5 (Debian 1:3.3.5-13)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = b = 1e1000 / 1e1000 >>> a is b True >>> a == b True See: http://mail.python.org/pipermail/python-bugs-list/2004-February/022133.html -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From tdelaney at avaya.com Sun Aug 6 23:13:39 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Mon, 7 Aug 2006 13:13:39 +1000 Subject: Question about using python as a scripting language Message-ID: <2773CAC687FD5F4689F526998C7E4E5F01877C93@au3010avexu1.global.avaya.com> Steve Lianoglou wrote: > One thing you could do is use the eval or compile methods. These > functions let you run arbitray code passed into them as a string. > > So, for instance, you can write: > my_list = eval('[1,2,3,4]') This is just asking for trouble. my_list = eval('import shutil; shutil.rmtree('/')') Terry's approach is much better. Another alternative is to create a dictionary mapping an action name to a function. Basically the same as Terry's solution, but the dictionary lookup is explicit (as opposed to being hidden as method names). Tim Delaney From cerutti at tds.net Mon Aug 21 15:42:17 2006 From: cerutti at tds.net (Neil Cerutti) Date: Mon, 21 Aug 2006 19:42:17 GMT Subject: List Splitting References: <1156187837.378252.36420@m73g2000cwd.googlegroups.com> Message-ID: On 2006-08-21, Steven wrote: > Hello everyone, > > I'm trying to work through a bit of a logic issue I'm having with a > script I'm writing. Essentially, I have a list that's returned to > me from another command that I need to regroup based on some aribitrary > length. > > For the purposes of this question, the list will be: > > t = [ "a", "b", "c", "n", "a", "a", "t", "t", "t" ] > > Now, I know that every 3rd element of the list belongs together: > > Group 1 = 0, 3, 6 > Group 2 = 1, 4, 7 > Group 3 = 2, 5, 8 from itertools import islice grouped = [] grouped.append(list(islice(t, 0, None, 3)) grouped.append(list(islice(t, 1, None, 3)) grouped.append(list(islice(t, 2, None, 3)) grouped.sort() This can probably be simplified and generalized, but I'm a novice, and that's a start. -- Neil Cerutti From miki.tebeka at gmail.com Tue Aug 8 14:40:05 2006 From: miki.tebeka at gmail.com (Miki) Date: 8 Aug 2006 11:40:05 -0700 Subject: Which Python API for PostgreSQL? In-Reply-To: References: Message-ID: <1155062405.719852.259040@m73g2000cwd.googlegroups.com> Hello Scott, > Which one do you use? psycopg2 (http://initd.org/tracker/psycopg/wiki/PsycopgTwo) > What do you like about it? Compiles and works. Has support for Postgres array types. Also thread safe. HTH, Miki http://pythonwise.blogspot.com/ From superflit at gmail.com Wed Aug 30 10:47:39 2006 From: superflit at gmail.com (flit) Date: 30 Aug 2006 07:47:39 -0700 Subject: What make a great community Message-ID: <1156949259.255949.323150@i42g2000cwa.googlegroups.com> Hi all, I had one problem with csv files. And I put the message on 2 microsoft board and in this group. Results: No response from microsoft, and always 3 responses for posts on this lists. I just want to say thank you for all. And notice that this is a great community.. Flit The brazilian newbie From gagsl-py at yahoo.com.ar Fri Aug 18 20:21:49 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 18 Aug 2006 21:21:49 -0300 Subject: Python for arcgis In-Reply-To: <200608170208.HAA13239@WS0005.indiatimes.com> References: <200608170208.HAA13239@WS0005.indiatimes.com> Message-ID: <7.0.1.0.0.20060818212124.05ab8768@yahoo.com.ar> At Thursday 17/8/2006 00:25, subramanian2003 wrote: > From where can I get the python tutorial for arcgis customisation?. Tried google? Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From ajaksu at gmail.com Mon Aug 14 13:16:37 2006 From: ajaksu at gmail.com (ajaksu) Date: 14 Aug 2006 10:16:37 -0700 Subject: p-gal: photo gallery generator with templating support References: <7xk65buyf9.fsf@ruckus.brouhaha.com> Message-ID: <1155575797.856782.26370@p79g2000cwp.googlegroups.com> Paolo Pantaleo wrote: > www.sf.net/projects/ppgal Ciao Paolo! The homepage (http://paolopan.freehostia.com/p-gal/ ) looks weird in my SeaMonkey 1.0.4, contents appear below GoogleAds instead of at the right. Some feedback and a couple of questions at http://tinyurl.com/qgbth (points to http://sourceforge.net/tracker/index.php?func=detail&aid=1540122&group_id=169372&atid=850133 ) Best regards, Daniel From tim.golden at viacom-outdoor.co.uk Tue Aug 22 05:38:29 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 22 Aug 2006 10:38:29 +0100 Subject: How can I enumerate all windows services and disable some of them? Message-ID: [could.net at gmail.com] | I know that Module win32service has some functions on manipulating | win32 services. | But I still have 2 questions: | 1. how to enumerate all services? | 2. how to disable a certain one? You can use WMI to do this if you want. Have a look at this example: http://tgolden.sc.sabren.com/python/wmi_cookbook.html#automatic_services and then at the Win32_Service WMI class: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/ wmi/win32_service.asp and in particular at the StartService method TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From no at spam.com Thu Aug 10 19:59:56 2006 From: no at spam.com (Farshid Lashkari) Date: Thu, 10 Aug 2006 16:59:56 -0700 Subject: error handling In-Reply-To: <1155253063.322440.97300@b28g2000cwb.googlegroups.com> References: <1155253063.322440.97300@b28g2000cwb.googlegroups.com> Message-ID: <4MPCg.902$0F5.681@fed1read04> Chris wrote: > But sometimes you can have too many of these statements in your > program, and it starts to get tangled and nasty looking. Is there a way > I can modify sys.error so that when the interpreter comes accross an > IndexError it prints "That number is way too big!" before it exits? Hi, Try placing the try/except block around the main function of your program: if __name__ == '__main__': try: main() except IndexError: sys.exit("That number is way too big!") -Farshid From steve at REMOVEME.cybersource.com.au Tue Aug 22 01:05:25 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 22 Aug 2006 15:05:25 +1000 Subject: how do you get the name of a dictionary? References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> <1156218818.720059.69640@p79g2000cwp.googlegroups.com> Message-ID: On Mon, 21 Aug 2006 20:53:38 -0700, jojoba wrote: > However, regarding your comment about the phone book, I have a > question: > You say: > >> If you know a person's name, you can look up their number in the phone >> book easily. If you know their phone number, it is much, much harder to >> look up their name -- unless you go to the time and effort of keeping a >> "reverse phone book". > > > By reverse phone book, do you mean something like listing all the > numbers in order, so as to optimize searching from phone number to > name... Something like that. > and the implicaiton being that for python, it is much faster to > find the data structure from the name, than the name from the data > structure? > If this is true, then you are quite right, and i am quite silly! > I guess i was just thinking that all else equal, searching for one side > (names) should be as fast as searching the other side (dictionaries), > and hence recovering the mappings of name(s) to dictionary is equally > fast both ways. > If this is not true, then certainly, you are correct in saying that > python need not spend its time managing a copious list of names and > dictionaries. > But does this really entail an overhaul of python to make such a thing > happen? Yes. Python uses dictionaries as "namespaces". When Python compiles a line like "y = len(x) + 1", it parses the line into something vaguely like this: (name y) (equals) (name len)(name x) (operator +) (value 1) Then at run-time it looks up the names. It does this by keeping names in a Python dictionary: {'str': (object id 45), 'math': (object id 991), 'x': (object id 5065), 'b': (object id 9120), 'len': (object id 23), 'y': (object id 237), ... } Notice that virtually everything in Python is in a namespace dictionary, including modules and built-in functions. Keep in mind that there isn't just one such namespace dictionary, there are lots of them, one for each level of code. Classes have their own namespaces, so do modules. You can explore two of these namespaces with the functions locals() and globals(). Because the namespace is a dictionary, it is easy to go from the name to the object, but it is hard to go from the object to the name. And there may be objects which exist, but don't have names: you won't find them in the namespace dictionary at all. What I've described is a simplification of what really happens, but it gives you an idea of the basic principles. -- Steven D'Aprano From ray_usenet at yahoo.com Mon Aug 21 08:10:37 2006 From: ray_usenet at yahoo.com (Ray) Date: 21 Aug 2006 05:10:37 -0700 Subject: Python and STL efficiency In-Reply-To: References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> Message-ID: <1156162237.274636.17850@i3g2000cwc.googlegroups.com> Fredrik Lundh wrote: > in the Python example, the four strings in your example are shared, so > you're basically copying 40000 pointers to the list. > > in the C++ example, you're creating 40000 string objects. > > In which case, Licheng, you should try using the /GF switch. This will tell Microsoft C++ compiler to pool identical string literals together. :) From cginboston at hotmail.com Wed Aug 16 06:07:51 2006 From: cginboston at hotmail.com (Chaz Ginger) Date: Wed, 16 Aug 2006 10:07:51 GMT Subject: Global Objects... In-Reply-To: <1155693205.957108.199920@h48g2000cwc.googlegroups.com> References: <1155693205.957108.199920@h48g2000cwc.googlegroups.com> Message-ID: <44E2EE77.50805@hotmail.com> KraftDiner wrote: > I have a question.. > > myGlobalDictionary = dictionary() > > > class someClass: > def __init__(self): > self.x = 0; > def getValue(self, v) > myGlobalDictionary.getVal(v) > > > myGlobalDictionary doesn't seem to be visible to my someClass methods. > Why? What should I do? > Is it an oversight that you forgot the ':' on the getValue definition? You also forgot to do the return. I say the code should look like: def getValue(self,v) : return myGlobalDictionary[v] I am also confused as to what getVal() does. Chaz From tenax.raccoon at gmail.com Thu Aug 17 14:03:12 2006 From: tenax.raccoon at gmail.com (Jason) Date: 17 Aug 2006 11:03:12 -0700 Subject: trouble understanding inheritance... References: <1155753183.207393.116940@m79g2000cwm.googlegroups.com> <1155754767.694480.256200@h48g2000cwc.googlegroups.com> <1155756282.851876.46470@b28g2000cwb.googlegroups.com> <1155757992.706040.288890@74g2000cwt.googlegroups.com> Message-ID: <1155837792.651543.45540@i3g2000cwc.googlegroups.com> KraftDiner wrote: > c = [a, b] > for c in [a,b]: > c.getName() > > but when does baseClass ever get used? > Why did i even have to define it? > One reason for using base classes are for logical reasons. Oranges and Apples are different, but they are both fruits. Python has both unicode strings and 8-bit ASCII strings. Both are strings and share a common base class: the 'basestring' class. A second reason is for code sharing. Let's say Python's string class does everything you want already... except for one little thing. You want the split method to return a list with some extra information. Why re-invent the wheel trying to implement the other string methods when you can reuse everything that's already been done? >>> class MyString(str): ... def split(self): ... "Perform some extra work this version of split" ... wordList = str.split(self) # Call the original method ... return ['Extra'] + wordList + ['Information'] # Do additional work! ... >>> In Python, we often rely on duck typing. "If it looks like a duck, quacks like a duck, it's a duck." If we can treat it like a string, we can consider it a string. If we can't treat it like a string, Python will let us know by raising an exception. We can catch this exception and try something different, or let the exception stop the program and let the user know something went wrong. Duck typing allows us to re-use code very efficiently. I'll demonstrate it with a function and the class defined above. >>> def GetWords(stringValue): ... "Print the list of words in a string" ... print 'Words are: %s' % stringValue.split() ... >>> stringValue = str('Hello, world!') >>> unicodeValue = unicode('These are different strings') >>> myStringValue = MyString('good, hopefully useful') >>> >>> GetWords(stringValue) Words are: ['Hello,', 'world!'] >>> GetWords(unicodeValue) Words are: [u'These', u'are', u'different', u'strings'] >>> GetWords(myStringValue) Words are: ['Extra', 'good,', 'hopefully', 'useful', 'Information'] >>> As shown above, the GetWords() function works fine with my new string class. Any methods that I didn't redefine keep their old behavior. For example, I didn't define the upper() method in MyString, but I can still use it: >>> stringValue.upper() 'HELLO, WORLD!' >>> myStringValue.upper() 'GOOD, HOPEFULLY USEFUL' >>> While we rely on duck typing in Python, we occassionally want special behavior for certain types of data. Currently, you can pass anything into the GetWords() function that has a method named 'split'. It does not have to be a string: >>> class NotAString(object): ... def split(self): ... return 'I am not a string!' ... >>> otherDataValue = NotAString() >>> GetWords(otherDataValue) Words are: I am not a string! >>> Sometimes, we want some specialized behavior. Lists, tuples, and strings all act like sequences (meaning, you can get their length and use them in for-loops). Often, though, you'll want to treat strings differently. You can check the type directly, or you can check by using the isinstance() built-in function. isinstance() checks to see if a variable is an instance of a class or any of its subclasses. Remember the first reason given, of using a base class to logically organize other classes? This is it in practice. I'll demonstrate below: >>> def CheckOnlyBuiltinStrings(stringValue): ... "Tells us whether or not stringValue is a str or unicode string." ... if type(stringValue) is str or type(stringValue) is unicode: ... print 'A built-in string type: %s' % stringValue ... else: ... print 'Not a built-in string type: %s' % stringValue ... >>> def CheckAllStrings(stringValue): ... "Tells us whether or not stringValue is a string." ... # The basestring class is a superclass for all string classes. ... if isinstance(stringValue, basestring): ... print 'Is a string: %s' % stringValue ... else: ... print 'Not a string: %s' % stringValue ... >>> CheckOnlyBuiltinStrings(stringValue) A built-in string type: Hello, world! >>> CheckOnlyBuiltinStrings(unicodeValue) A built-in string type: These are different strings >>> CheckOnlyBuiltinStrings(myStringValue) Not a built-in string type: good, hopefully useful >>> >>> CheckAllStrings(stringValue) Is a string: Hello, world! >>> CheckAllStrings(unicodeValue) Is a string: These are different strings >>> CheckAllStrings(myStringValue) Is a string: good, hopefully useful >>> CheckAllStrings(42) Not a string: 42 >>> How do you know when you should use type() checks, when you should use isinstance(), and when you should just try to use the data? That depends, and there have been many lively debates on this subject in the newsgroup. I recommend that you should only use as much type checking as needed, and the less is better. A bit long, but I hope this helps you out. --Jason From fredrik at pythonware.com Wed Aug 16 14:46:07 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Aug 2006 20:46:07 +0200 Subject: It is __del__ calling twice for some instances? In-Reply-To: References: Message-ID: Max Yuzhakov wrote: > This is a sample code for clearness: that code snippet doesn't create any foo() instances, what I can see... From cginboston at hotmail.com Tue Aug 22 15:08:34 2006 From: cginboston at hotmail.com (Chaz Ginger) Date: Tue, 22 Aug 2006 19:08:34 GMT Subject: key not found in dictionary In-Reply-To: <1156272596.613723.219280@h48g2000cwc.googlegroups.com> References: <1156272596.613723.219280@h48g2000cwc.googlegroups.com> Message-ID: <44EB5632.3060505@hotmail.com> KraftDiner wrote: > I have a dictionary and sometime the lookup fails... > it seems to raise an exception when this happens. > What should I do to fix/catch this problem? > > desc = self.numericDict[k][2] > KeyError: 589824 <---- This is the error that is being produced, > because there is no key > 589824. > As stated you can wrap the access in the try - except - else statement, as in try: foo['bar'] except : # Handle the error. pass else : # We have it, so use it... print foo['bar'] Or you can use the has_key() and test it first. For example if foo.has_key('bar'): print 'we have it' else : print 'we don't have bar.' That'll do it for me. Chaz. From rob at digital-crocus.com Thu Aug 10 05:59:06 2006 From: rob at digital-crocus.com (Robin Haswell) Date: Thu, 10 Aug 2006 10:59:06 +0100 Subject: Advice on a TCP passthru daemon for HTTP proxy rotation Message-ID: Hey there Soon we will have many squid proxies on many seperate connections for use by our services. I want to make them available to users via a single HTTP proxy - however, I want fine-grained control over how the squid proxies are selected for each connection. This is so I can collect statistics, control usage on each proxy, monitor what's going on - etc. However I don't want to implement the HTTP proxy protocol in Python, and would much rather let my daemon run as a man-in-the-middle for TCP, similar to this netcat command: rob at aranea:~$ mknod backpipe p rob at aranea:~$ nc -l -p 8080 < backpipe | nc ganesh 8080 > backpipe Basically when my daemon received a connection (call it "c1"), it makes a connection to one of my squid proxies ("c2"), then all data which gets read from c1 is written to c2 - all data read from c2 is written to c1. I'm pretty sure there's an elegant way to do this but I was wondering if anyone had any input? I've tried GIYF'ing this but it's difficult to search for :P Thanks guys -Rob From f.braennstroem at gmx.de Tue Aug 8 01:42:53 2006 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Tue, 8 Aug 2006 07:42:53 +0200 Subject: access abook addressbook with curses References: Message-ID: Hi Ben, * Ben C wrote: > On 2006-08-06, Fabian Braennstroem wrote: >> Hi Ben, >> >> * Ben C wrote: >>> On 2006-08-05, Fabian Braennstroem wrote: >>>> Hi, >>>> >>>> I want to get access to my abook address file with python. >>>> Does anyone have some python lines to achive this using >>>> curses? If not, maybe anybody has small python program doing >>>> it with a gui!? >>> >>> You can just parse the abook addressbook with the ConfigParser, try >>> this: >>> >>> import os >>> from ConfigParser import * >>> >>> abook = ConfigParser() >>> abook.read(os.environ["HOME"] + "/.abook/addressbook") >>> >>> for s in abook.sections(): >>> print abook.items(s) >> >> Thanks! I found a different example too: >> >> import ConfigParser >> import string >> >> config = ConfigParser.ConfigParser() >> >> config.read("/home/fab/.abook/addressbook") >> >> # print summary >> print >> for number in [2,200]: >> print string.upper(config.get(str(number), "email")) >> print string.upper(config.get(str(number), "name")) >> print string.upper(config.get(str(number), "city")) >> print string.upper(config.get(str(number), "address")) >> >> but the problem seems to be that abook does not write every >> field, so I get an exception when there is a field missing: >> >> Traceback (most recent call last): >> File "configparser-example-1.py", line 13, in ? >> print string.upper(config.get(str(number), "city")) >> File "/usr/lib/python2.4/ConfigParser.py", line 520, in get >> raise NoOptionError(option, section) >> ConfigParser.NoOptionError: No option 'city' in section: '2' >> >> Section 2 looks like: >> >> [2] >> name=Andrs Gzi >> email=anes.oi at ik.e >> nick=oz >> >> Is there a workaround? > > You can construct the parser with a dictionary of defaults: > > config = ConfigParser.ConfigParser({"city" : "unknown", > "zip" : "unknown"}) > > that kind of thing. > > Or catch the exceptions. Or use config.options("2") to see what options > exist in section 2 before you try to read them. Thanks! I will try it out! Greetings! Fabian From exarkun at divmod.com Tue Aug 29 16:04:14 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 29 Aug 2006 16:04:14 -0400 Subject: Generator chaining? In-Reply-To: Message-ID: <20060829200414.1717.647712328.divmod.quotient.33985@ohm> On Tue, 29 Aug 2006 22:41:37 +0300, John Doe wrote: >This is sort of a feature request/idea: Chaining generators. > >If you have two lists (or tuples) and you add them, the result is a >concatenation of the two. >I think it would be nice if it was possible to do something similar with >generators. The best way to explain is by code example: > >def add_generators(gen1, gen2): > for x in gen1: > yield x > for y in gen2: > yield y > >Just a thought... You can chain any iterators using itertools.chain(). Jean-Paul From duncan.booth at invalid.invalid Sat Aug 19 11:13:29 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Aug 2006 15:13:29 GMT Subject: how do you get the name of a dictionary? References: Message-ID: Tim Chase wrote: > >>> [name for name in dir() if id(eval(name)) == id(banana)] > ['banana', 'spatula'] > Please, if you are going to do something like this, then please at least use the 'is' operator. Using id(expr1)==id(expr2) is just plain stupid: it will actually work in this case, but as soon as you get into a mindset of testing for the same object by comparing object ids you are going to shoot yourself in the foot. The first of the following tests returns True, which looks sensible at first glance (even though it shouldn't), but what of the second one? >>> class C: def method1(self): pass def method2(self): pass >>> inst = C() >>> id(inst.method1)==id(inst.method1) True >>> id(inst.method1)==id(inst.method2) True Much better to use 'is' and get consistent results >>> inst.method1 is inst.method1 False (In case I didn't make it clear, the problem in general with comparing the result of calling 'id' is that as soon as the first call to id returns, any object created when evaluating its parameter can be freed, so the second call to id can reuse memory and get the same answer even though the objects are different.) From jorge.vargas at gmail.com Mon Aug 28 17:56:24 2006 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Mon, 28 Aug 2006 17:56:24 -0400 Subject: Coding style and else statements In-Reply-To: <44f355d6$0$8812$88260bb3@free.teranews.com> References: <44f355d6$0$8812$88260bb3@free.teranews.com> Message-ID: <32822fe60608281456v7a4f6193nb449054cc3889c11@mail.gmail.com> On 8/28/06, tobiah wrote: > def foo(thing): > > if thing: > return thing + 1 > else: > return -1 > > def foo(thing): > > if thing: > return thing + 1 > return -1 > > Obviously both do the same thing. The first is > possibly clearer, while the second is more concise. > > Comments? if there is nothing the else will check why put it there? > > -- > Posted via a free Usenet account from http://www.teranews.com > > -- > http://mail.python.org/mailman/listinfo/python-list > From alpersoyler at yahoo.com Tue Aug 29 02:55:59 2006 From: alpersoyler at yahoo.com (alper soyler) Date: Mon, 28 Aug 2006 23:55:59 -0700 (PDT) Subject: a question about my script Message-ID: <20060829065559.81733.qmail@web56505.mail.re3.yahoo.com> Hi all, I am trying to get some files from an ftp site by ftplib module and I wrote the below script. However I have a problem. With my script, I login to ftp.genome.jp site. then, I am changing the directory to pub/kegg/genomes/afm and I am downloading "a.fumigatus.pep" file. However, what I want is to connect pub/kegg/genomes directory and in this directory there are 3 letters name files e.g. 'afm' and in each of these 3 letters files there is a file with the extension of '.pep' like a.fumigatus.pep. I want to get these '.pep' files from the 3 letter named files. If you help me I will be very glad. Thanks you in advance. Regards, Alper from ftplib import FTP def handleDownload( block): file.write(block) print ".", ftp = FTP('ftp.genome. jp') print ftp.login() directory = 'pub/kegg/genomes/ afm' print 'Changing to ' + directory ftp.cwd(directory) ftp.retrlines( 'LIST') filename = 'a.fumigatus. pep' print 'Opening local file ' + filename file = open(filename, 'wb') print 'Getting ' + filename ftp.retrbinary( 'RETR ' + filename, handleDownload) print 'Closing file ' + filename file.close() print 'Closing FTP connection' print ftp.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: From beliavsky at aol.com Tue Aug 15 16:16:27 2006 From: beliavsky at aol.com (beliavsky at aol.com) Date: 15 Aug 2006 13:16:27 -0700 Subject: programming with Python 3000 in mind Message-ID: <1155672987.522793.47080@74g2000cwt.googlegroups.com> At http://www-03.ibm.com/developerworks/blogs/page/davidmertz David Mertz writes "Presumably with 2.7 (and later 2.x versions), there will be a means of warning developers of constructs that are likely to cause porting issues [to Python 3000]. In the simplest case, this will include deprecated functions and syntax constructs. But presumably the warnings may cover "potential problems" like the above example." The current beta version of Python is 2.5 . How can a Python programmer minimize the number of changes that will be needed to run his code in Python 3000? In general, he should know what is being removed from Python 3000 and if possible use the "modern" analogs in Python. A manager of Python programmers might want external evidence of portability, though (such as an absence of interpreter warnings). Some basic syntax such as print "hello world" is going away to make print look like a function. IMO, fixing what is not broken because of the aesthetic tastes of the BDFL is a bad idea. His reasoning is at http://mail.python.org/pipermail/python-dev/2005-September/056154.html . From nospam at invalid.com Tue Aug 22 14:34:01 2006 From: nospam at invalid.com (Jack) Date: Tue, 22 Aug 2006 11:34:01 -0700 Subject: https on ActiveState Python 2.4? References: <422le2df66glvl0hp6itavd5floh82a8cd@4ax.com> Message-ID: Thanks for the reply. I found some openSSL patches for earlier versions of ActiveState Python. It involves .pyd files and they look for earlier versions of Python DLLs and don't run on ActiveState Python 2.4. I suspect the regular Python solution would have the same problem or even more problems because it's not a pure .py patch. "Dennis Lee Bieber" wrote in message news:422le2df66glvl0hp6itavd5floh82a8cd at 4ax.com... > On Mon, 21 Aug 2006 15:31:20 -0700, "Jack" > declaimed the following in comp.lang.python: > >> I'm trying to use urllib to retrieve an https page but I am >> getting an "unknown url type: https" >> >> It seems that ActiveState Python doesn't have SSL support. >> Any advice? >> > > I've not tried, but it may be that the "regular" Python (of the same > language level) may have SSL as a DLL/PYD & .py set and you could just > copy them into the ActiveState install directory... > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com wulfraed at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-asst at bestiaria.com) > HTTP://www.bestiaria.com/ From cliff at develix.com Tue Aug 1 01:09:37 2006 From: cliff at develix.com (Cliff Wells) Date: Mon, 31 Jul 2006 22:09:37 -0700 Subject: code to retrieve web mail? In-Reply-To: <060801000110020.01Aug06$rookswood@suburbian.com> References: <060801000110020.01Aug06$rookswood@suburbian.com> Message-ID: <1154408977.20290.139.camel@devilbox> On Tue, 2006-08-01 at 01:47 +0000, John Savage wrote: > I have a free web mail address and would like to use python to retrieve > files that have been emailed to me. The basic code would accommodate > cookies, a login name and password, then download using the full URL I > can provide. From postings here I thought mechanize held promise, but > I've found it to contain filenames that are invalid for MSDOS (too many > characters, and/or too many dots in the name, etc.) so I have little hope > that the mechanize module can be used. > > I'm running python2.4.2 on plain MSDOS (not windows), so would appreciate > a pointer to sample code that can do the job. I know that curl has this > capability, but I'll learn something by tinkering with python code. PyCurl certainly does have that capability, although the docs were practically non-existent last I looked (and I've not tried it on DOS). Still Google will help get you through it, along with the examples included with the package, and once it's working PyCurl does an outstanding job. You might take a look at Beautiful Soup for parsing the HTML once PyCurl has fetched it for you: http://www.crummy.com/software/BeautifulSoup/ Also, no matter what method you finally end up with, you'll undoubtedly need to mangle long filenames into 8.3 names, at least for attachments and the like. Regards, Cliff -- From jmpurser at gmail.com Thu Aug 31 14:30:19 2006 From: jmpurser at gmail.com (John Purser) Date: Thu, 31 Aug 2006 11:30:19 -0700 Subject: problem with appending to a list, possibly mysqldb related In-Reply-To: <7DFJg.2719$No6.53311@news.tufts.edu> References: <7DFJg.2719$No6.53311@news.tufts.edu> Message-ID: <20060831113019.143ecbf8.jmpurser@gmail.com> On Thu, 31 Aug 2006 18:11:15 GMT John Salerno wrote: > Here's the code: > > class MyFrame(wx.Frame): > > def __init__(self): > wx.Frame.__init__(self, None, wx.ID_ANY) > panel = wx.Panel(self) > dbconn = self.connect_db() > dbconn.execute("select namefirst, namelast from master") > bb_players = [] > > for x in dbconn.fetchall(): > bb_players.append(' '.join(x)) > > cb = PromptingComboBox(panel, 'Choose A Player', > choices=bb_players, style=wx.CB_SORT) > > def connect_db(self): > connection = MySQLdb.connect('localhost', 'john', '*******', > 'bbdatabank') > return connection.cursor() > > > The error seems to be in the for loop. I get this: > > Traceback (most recent call last): > File "C:\Python24\myscripts\bbdata_access\bbdata.py", line 71, in > -toplevel- > app = MyApp(False) > File "C:\Python24\Lib\site-packages\wx-2.6-msw-ansi\wx\_core.py", > line 7700, in __init__ > self._BootstrapApp() > File "C:\Python24\Lib\site-packages\wx-2.6-msw-ansi\wx\_core.py", > line 7352, in _BootstrapApp > return _core_.PyApp__BootstrapApp(*args, **kwargs) > File "C:\Python24\myscripts\bbdata_access\bbdata.py", line 64, in > OnInit frame = MyFrame() > File "C:\Python24\myscripts\bbdata_access\bbdata.py", line 15, in > __init__ > name = ' '.join(x) > TypeError: sequence item 0: expected string, NoneType found > >>> John, I'd say you had a record with a null value for the namefirst field. The join method don't like that. John Purser -- You are destined to become the commandant of the fighting men of the department of transportation. From aleax at mac.com Sat Aug 12 19:58:06 2006 From: aleax at mac.com (Alex Martelli) Date: Sat, 12 Aug 2006 16:58:06 -0700 Subject: Make $1000's Monthly! References: <1155297208.125825.69660@74g2000cwt.googlegroups.com> Message-ID: <1hjyv3f.1r1cvdin207pjN%aleax@mac.com> AlbaClause wrote: ... > Just to bring this thread back on topic, you could also make thousands of > dollars monthly by becoming a professional Python coder or consultant. ;-) Yes, easily -- according to SD Magazine's yearly surveys, Python programmers have been the best-paid ones for years in a row now (I believe the worst-paid ones are Visual Basic programmers, as a group). Alex From python.list at tim.thechases.com Fri Aug 4 14:03:40 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 04 Aug 2006 13:03:40 -0500 Subject: Why do I require an "elif" statement here? In-Reply-To: <1154712731.375032.203570@m79g2000cwm.googlegroups.com> References: <1154712731.375032.203570@m79g2000cwm.googlegroups.com> Message-ID: <44D38BFC.6010800@tim.thechases.com> > Could somebody tell me why I need the "elif char == '\n'" in > the following code? > > This is required in order the pick up lines with just spaces > in them. > Why doesn't the "else:" statement pick this up? Following through with the below code: if the line consists of only a newline, it gets ignored due to the "if line[0] == whitespace" line. However, if the line consists of only whitespace followed by a newline you *do* successfully get to the "else" in question. There's no other place for you to go. However, what happens then? If you fall into you the top half of your "if x > 0 ..." statement: you strip **all** *true* whitespace from the line with your lstrip() call. Since there's nothing between your "whitespace" (simple spaces) and the \n, the \n gets swallowed by the lstrip() call. Thus, you output.write() an empty string. I recommend a few judiciously placed "print repr(thing)" lines as you try to debug to see where things aren't what you expect them to be. As another sidelight, rather than using the "i=0, i+= 1" aspect, you can use the more pythonic idiom of for i, char in enumerate(line): (taking into consideration that i becomes zero-based). This will automatically update "i" on each pass. -tkc > > OLD_INDENT = 5 # spaces > NEW_INDENT = 4 # spaces > > print 'Reindent.py:' > print '\nFrom file %s' % infile > print 'Change %i space indentation to %i space indentation.' % ( > OLD_INDENT, NEW_INDENT) > print 'And place revised file into %s' % outfile > > whitespace = ' ' > n = 0 > nline = 0 > > for line in input.readlines(): > nline += 1 > # Only look at lines that start with a space. > if line[0] == whitespace: > i = 0 > for char in line: > i += 1 > if char == whitespace: > pass > elif char == '\n': # Why do I need this for a > blank line with only spaces? > output.write(line) > break > else: # Why doesn't the blank line > get picked up here? > x = line.count(whitespace*OLD_INDENT,0,i) > # Reindent lines that have exactly a multiple of > OLD_INDENT. > if x > 0 and (i-1)%OLD_INDENT == 0: > output.write(whitespace*NEW_INDENT*x+line.lstrip()) > n += 1 > break > else: > output.write(line) > break > else: > output.write(line) > > input.close() > output.close() > print 'Total number of %i lines reindented out of %i lines.' % (n, > nline) > From pedro.werneck at terra.com.br Wed Aug 9 14:19:17 2006 From: pedro.werneck at terra.com.br (Pedro Werneck) Date: Wed, 9 Aug 2006 15:19:17 -0300 Subject: __contains__ vs. __getitem__ In-Reply-To: References: Message-ID: <20060809151917.6867405e.pedro.werneck@terra.com.br> On Wed, 09 Aug 2006 16:51:23 GMT "David Isaac" wrote: > Looking forward: > Can I count on this independence of __getitem__ and __contains__? > I would like to understand whether it will be safe to count on this > behavior. With the builtin 'dict' implementation, dict.__contains__() use the dict_has_key() C function, and does not touch your subclass __getitem__ python method. I don't think it can be called 'safe'... it may lead to very inconsistent behavior. It's like overridind both __eq__ and __ge__ with a different behavior. It's better for you to override __contains__() too. -- Pedro Werneck From grante at visi.com Sun Aug 27 11:59:49 2006 From: grante at visi.com (Grant Edwards) Date: Sun, 27 Aug 2006 15:59:49 -0000 Subject: avoiding file corruption References: <1156664673.325201.271140@i42g2000cwa.googlegroups.com> <12f3bo1t1ccr858@corp.supernews.com> <1156690278.496811.221660@b28g2000cwb.googlegroups.com> Message-ID: <12f3gblt2esl3cd@corp.supernews.com> On 2006-08-27, Amir Michail wrote: > How often do you need to open a file multiple times for writing? Not very often, but I don't think it should be illegal. That's probably a result of being a 25 year user of Unix where it's assumed that the user knows what he's doing. > As a high-level language, Python should prevent people from > corrupting data as much as possible. For somebody with a Unix background it seems overly restrictive. -- Grant Edwards grante Yow! Youth of today! Join at me in a mass rally visi.com for traditional mental attitudes! From snail at objmedia.demon.co.uk Thu Aug 10 05:44:04 2006 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Thu, 10 Aug 2006 10:44:04 +0100 Subject: do people really complain about significant whitespace? References: <1154986984.740638.241130@m79g2000cwm.googlegroups.com> <2AY13sCznQ2EFw8+@objmedia.demon.co.uk> Message-ID: In message , Gerhard Fiedler writes >I mean the code should be written so that as few as possible comments are >necessary to understand it. I don't mean that additional comments are a bad >thing. Agreed. Concise code is always good. Just found this on c.l.ruby. Seems kind of relevant. My apologies if someone has posted this already -- I just received it: http://www.americanscientist.org/template/AssetDetail/assetid/51982 The Semicolon Wars Every programmer knows there is one true programming language. A new one every week -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk/software.html Computer Consultancy, Software Development Windows C++, Java, Assembler, Performance Analysis, Troubleshooting From chris.lyon at spritenote.co.uk Tue Aug 8 10:48:39 2006 From: chris.lyon at spritenote.co.uk (chris.lyon at spritenote.co.uk) Date: 8 Aug 2006 07:48:39 -0700 Subject: Dallas One wire tempreture measurement. Message-ID: <1155048519.496470.304650@75g2000cwc.googlegroups.com> a previous thread http://mail.python.org/pipermail/python-list/2002-June/107616.html discussed this issue, and Dave Moor kindly pointed to his solution. However this is no longer a current link, does anyone know if there is a currently available solution? From http Sat Aug 26 20:34:29 2006 From: http (Paul Rubin) Date: 26 Aug 2006 17:34:29 -0700 Subject: random writing access to a file in Python References: <5a9ue2lrjh214ecmme09fsodhm3ico1ntm@4ax.com> <7xhczzqoi3.fsf@ruckus.brouhaha.com> <7xbqq7f6q7.fsf@ruckus.brouhaha.com> Message-ID: <7xd5anf23u.fsf@ruckus.brouhaha.com> Claudio Grondi writes: > Does it mean, that in case of very large files: > the size of available memory for the sorting operation (making it > possible to work on larger chunks of data in memory) has less impact > on the actual sorting speed than > the speed of the data transfer from/to storage device(s) Transfer speed and parallelism matters most, if the cpu can keep up. Parallelism means you want multiple drives that you can do i/o to simultaneously without having to seek. Random access helps simulate this, but only somewhat. Large database installations always want lots of parallel disks for similar reasons to this. The basic method of sorting large files has traditionally been: 1) Read the file in pieces p(1),p(2),...,p(n) where each piece is as big as will fit in memory. Sort each piece with your favorite in-memory sort, and write out sorted pieces that we'll designate r(1,1),...r(1,n). The r(a,b)'s are called "runs". Use multiple output devices (tape or disk drives) to write out the runs, i.e. each output tape will contain its own bunch of runs. 2) Read back a bunch of the runs in parallel, i.e. say you have written r(1,1),r(1,2),...,r(1,5) to five separate tape drives. Read them back simultaneously and merge them (requires very little external memory) into a new "second level" run called r(2,1). Similarly merge r(1,6),...,r(1,10) to the second level run r(2,2), and so forth. 3) Merge the second level runs into third level runs, and so forth recursively until there's only one giant run. That is the sorted output. The amount of memory determines the size of the initial "first level" runs, which determines how many recursive merges are needed, so more memory helps. The number of levels of recursion also depends on the "merge order", i.e. the number of runs merged at each merge step. You really want each merge to read from M physical input devices that are separate from the output device(s). There are obviously a lot of optimizations that the above description is missing, and there's a lot of strategy about how to organize the merges, e.g. if you have 8 drives, do you use 4 for input and 4 for output, or 5 in and 3 out, or what? Is this some kind of production deployment problem you're working on, or do you just have a big pile of data you need to sort once? If you need to deploy across multiple machines (i.e. you can't just buy a giant machine if you need to do this sorting frequently), then I'd suggest reading up on the subject, starting with Knuth vol 3. From nicolas at pontoizeau.org Tue Aug 22 11:59:01 2006 From: nicolas at pontoizeau.org (Nicolas Pontoizeau) Date: Tue, 22 Aug 2006 17:59:01 +0200 Subject: unicode "table of character" implementation in python In-Reply-To: References: Message-ID: 2006/8/22, Brian Beck : > Nicolas, check out the unicodedata module: > http://docs.python.org/lib/module-unicodedata.html > > Find "import unicodedata" on this page for how to use it: > http://www.amk.ca/python/howto/unicode > > I'm not sure if it has built-in support for finding which language block a > character is in, but a table like this might help you: > http://www.unicode.org/Public/UNIDATA/Blocks.txt As usual, Python has a solution that goes beyond my needs! Thanks for the links I will dive into it. Nicolas -- http://www.nicolas.pontoizeau.org/ Nicolas Pontoizeau - Promotion EFREI 2005 From gagsl-py at yahoo.com.ar Tue Aug 22 15:15:18 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 22 Aug 2006 16:15:18 -0300 Subject: Job Jar In-Reply-To: <1156272471.494356.245460@i42g2000cwa.googlegroups.com> References: <1156271103.398243.45870@b28g2000cwb.googlegroups.com> <1156272471.494356.245460@i42g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20060822161334.04bdc410@yahoo.com.ar> At Tuesday 22/8/2006 15:47, D wrote: >Thanks, Fredrik - but could I adapt them so that, instead of using them >for bug tracking (don't need version control, etc.), they're just used >for keeping track of simple tasks? Roundup is generic enough to be used for almost anything... It has nothing to do with version control. Gabriel Genellina Softlab SRL p5.vert.ukl.yahoo.com uncompressed Tue Aug 22 18:27:05 GMT 2006 __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From slawomir.nowaczyk.847 at student.lu.se Thu Aug 10 09:36:58 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Thu, 10 Aug 2006 15:36:58 +0200 Subject: do people really complain about significant whitespace? In-Reply-To: <1155207711.454940.89370@m73g2000cwd.googlegroups.com> References: <1155207711.454940.89370@m73g2000cwd.googlegroups.com> Message-ID: <20060810153003.EF50.SLAWOMIR.NOWACZYK.847@student.lu.se> On Thu, 10 Aug 2006 04:01:51 -0700 Rob Wolfe wrote: #> > if x==1: #> > #> > the newline is inserted automatically when you type ":"? That's a #> #> Exactly. Really? The newline? I know it *indents* automatically. But it definitely doesn't insert newline when I try it. I even downloaded revision 4.63 and I really do not see any code for doing that. py-electric-colon only seems to dedent code. #> > functionality I would like to see, but it doesn't seem to work #> > this way. #> #> Here is fragment of my python-mode.el: Please note that this comment doesn't say anything about automatically inserting newlines, only about indenting (actually, dedenting) as needed. Anyway, this is probably becoming off-topic here. -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) Cursor: What you become when your computer crashes. From btowle at carnegielearning.com Mon Aug 21 15:38:24 2006 From: btowle at carnegielearning.com (Brendon Towle) Date: Mon, 21 Aug 2006 15:38:24 -0400 Subject: List Splitting Message-ID: Not the most elegant solution, perhaps, but: >>>t = [ "a", "b", "c", "n", "a", "a", "t", "t", "t" ] >>>outlist = [] >>>for x in range(3): ... temp=[] ... for y in range(len(t)/3): ... temp.append(t[3*y+x]) ... outlist.append(temp) >>>outlist [['a', 'n', 't'], ['b', 'a', 't'], ['c', 'a', 't']] -- Brendon Towle, PhD Cognitive Scientist +1-412-690-2442x127 Carnegie Learning, Inc. The Cognitive Tutor Company ? Helping over 375,000 students in 1000 school districts succeed in math. -------------- next part -------------- An HTML attachment was scrubbed... URL: From st at tobiah.org Wed Aug 23 18:59:58 2006 From: st at tobiah.org (tobiah) Date: Wed, 23 Aug 2006 15:59:58 -0700 Subject: smtplib needs me to put from/to headers in the message? Message-ID: <44ecd0c9$0$8817$88260bb3@free.teranews.com> In the example at: http://docs.python.org/lib/SMTP-example.html The text of the email message ends up with the From: and To: headers in it, and yet the call to sendmail() on the server object requires me to specify them again. Shouldn't smptlib just make the headers for me, given the 'from' and 'to' addresses? Perhaps this allows me to spoof the 'from' address. Still, I might as well just make all of the headers myself, and pass the message as a single argument to sendmail(). Or perhaps I'm missing it altogether. Thanks, Tobiah -- Posted via a free Usenet account from http://www.teranews.com From effigies at gmail.com Sat Aug 19 08:18:08 2006 From: effigies at gmail.com (Chris Johnson) Date: 19 Aug 2006 05:18:08 -0700 Subject: Small Troll on notation of variables over time In-Reply-To: References: Message-ID: <1155989888.393972.90200@p79g2000cwp.googlegroups.com> Hendrik van Rooyen wrote: > Hi there, > > I can write: > > s = 'some string' > then print s[1] will be the string 'o' > > and a while later I can write: > > s = 'other some string' > then print s[1] will be the string 't' > > and then: > > s = [1,2,3,4] > then print s[1] will be the number 2 > > and still later: > > s = {1:'boo',2:'foo',3:'shoo'} > when print s[1] will yield the string 'boo' > > Now how about introducing an index that works over time, > such that s{0} (the default so as to not break any existing code) > implies the current object bound to the name s, > with s{1} being the previous one, and so on... > > This will mean that s{2}[1] is the string 't' > and s{3}[1] is the string 'o' > while s{4} should be None... > > It should be easy to implement this, as all that needs to be done is to > change the "pointer" (or whatever) to the object with a stack of them > at the time the binding or rebinding is done... > > I first thought of using s{-1} for the previous "value" but that > suffers from the regrettable disadvantage that it implies the > existence of an s{1} - i.e. a future value - and I could not think > of a way to achieve this - so the minus sign adds no information > and should therefore be left out... > > What do you guys think? I think it's pointless. If you want access to more than one of these variables, don't use the same name. That and if a symbol is still in scope, then all of its previous values still have active references, so they won't get deallocated by the garbage collector, meaning a lot of overhead that most people will not take advantage of. From lance.ellinghaus at eds.com Tue Aug 22 16:52:26 2006 From: lance.ellinghaus at eds.com (Ellinghaus, Lance) Date: Tue, 22 Aug 2006 16:52:26 -0400 Subject: Pure Python Oracle module Message-ID: Does anyone know of a pure Python module for Oracle similar to Java's pure Oracle module? Thank you! Lance Ellinghaus -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Wed Aug 9 11:11:21 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 9 Aug 2006 08:11:21 -0700 Subject: Question about using python as a scripting language In-Reply-To: References: <1154925950.226476.76390@m73g2000cwd.googlegroups.com> Message-ID: <1155136281.492743.202860@i3g2000cwc.googlegroups.com> Wildemar Wildenburger wrote: > Steve Lianoglou wrote: > > Delaney, Timothy (Tim) wrote: > >> This is just asking for trouble. > >> > >> my_list = eval('import shutil; shutil.rmtree('/')') > > > > Hah .. wow. > > > > And in related news: you still shouldn't be taking candy from > > strangers. > > > > Point well taken. Thanks for flagging that one. > > Heck, whenever *is* it OK to use eval() then? 1. When you deliberately want to give the user power to run Python code. (For example, I've written an HTML generator--who hasn't--that uses eval and exec to expand in-line Python code. Perfectly ok as long as you don't let untrusted users run the program.) 2. When you construct Python code within your program using no untrusted data Carl Banks From __peter__ at web.de Wed Aug 2 03:55:43 2006 From: __peter__ at web.de (Peter Otten) Date: Wed, 02 Aug 2006 09:55:43 +0200 Subject: cleaner way to write this try/except statement? References: Message-ID: John Salerno wrote: > The code to look at is the try statement in the NumbersValidator class, > just a few lines down. Is this a clean way to write it? i.e. is it okay > to have all those return statements? Is this a good use of try? Etc. > > Thanks. > > ---------------------------- > > import wx > > > class NumbersValidator(wx.PyValidator): > > def __init__(self): > wx.PyValidator.__init__(self) > > def Clone(self): > return NumbersValidator() > > def Validate(self, parent): > text_ctrl = self.GetWindow() > text = text_ctrl.GetValue() > > try: > if not text or int(text) <= 0: > wx.MessageBox('Enter a valid time.', 'Invalid time > > entered', wx.OK | wx.ICON_ERROR) > return False > else: > return True > except ValueError, error: > wx.MessageBox('Enter a valid time.', 'Invalid time entered', > wx.OK | wx.ICON_ERROR) > return False > > def TransferToWindow(self): > return True > > def TransferFromWindow(self): > return True Here's how I might do it: def is_positive_int_str(s): try: value = int(s) except ValueError: return False return value > 0 class PositiveIntegerValidator(wx.PyValidator): # ... def Validate(self, parent): text = self.GetWindow().GetValue() if is_positive_int_str(text): return True wx.MessageBox(...) return False Two usability notes: - "Invalid time entered" is a confusing message when you actually want a positive integer. - Pop-up messages are a major annoyance. An alternative would be to change the text color of the control and show a hint as to what input you expect in a status bar. Peter From python at hope.cz Mon Aug 7 04:55:42 2006 From: python at hope.cz (Lad) Date: 7 Aug 2006 01:55:42 -0700 Subject: How to get hours and minutes from 'datetime.timedelta' object? Message-ID: <1154940942.707530.291130@m79g2000cwm.googlegroups.com> Hello, what is the best /easest way how to get number of hours and minutes from a timedelta object? Let's say we have aa=datetime.datetime(2006, 7, 29, 16, 13, 56, 609000) bb=datetime.datetime(2006, 8, 3, 17, 59, 36, 46000) so c=bb-aa will be datetime.timedelta(5, 6339, 437000) I can easily get days ( c.days) but I still can not figure out how easily to get hours and minutes Any idea? Thank you for help L. From bootiack at yahoo.com Fri Aug 18 06:09:04 2006 From: bootiack at yahoo.com (gavino) Date: 18 Aug 2006 03:09:04 -0700 Subject: who needs python when u have happs? Message-ID: <1155895744.355472.239040@m73g2000cwd.googlegroups.com> What applications benefit from HAppS? HTTP requests and SMTP envelopes encapsulate transactions and not vice versa. Note: doing otherwise with LAMP is considered bad design because it implies a requirement to maintain and garbage collect database connections arbitrarily. So this should not be a high hurdle. All operating data fits in memory (store blobs on disk.) Note: Although this seems like a high hurdle, COTS servers with 12gb of memory are readily accessible and some vendors let you reach up to 500gb of RAM. FYI, eBay has around 50M active users. If you maintained 1k of queryable data for each of their users, you would need only 50GB. (You would also need to recompile your app for 64bits so the math is a little more involved but you get my point). You don't need more CPU power to server your app than you can obtain in a single machine. Note: I have not benchmarked this code yet, but another Haskell server was benchmarked at near 1000 HTTP transactions per second on a Pentium 4 in 2000. Modern web servers with similar architecture can serve 10k HTTP transactions per second. eBay serves 400M page views per day, which comes to an average load of 5000 hps and a peak load of perhaps 50k hps. In other words, an OTS 8 CPUs system, could handle all of eBay's HTTP traffic. I am not saying that using HAppS, you could serve all of eBay on a single box. I am saying that your application is likely to be well within the constraints required for HAppS to make sense for it. From jacob at cd.chalmers.se Sun Aug 27 19:59:56 2006 From: jacob at cd.chalmers.se (Jacob Hallen) Date: Sun, 27 Aug 2006 23:59:56 +0000 (UTC) Subject: Don't use __slots__ (was Re: performance of dictionary lookup vs. object attributes) References: <1156621904.481215.243080@m73g2000cwd.googlegroups.com> <1156625365.346825.18630@74g2000cwt.googlegroups.com> Message-ID: In article <1156625365.346825.18630 at 74g2000cwt.googlegroups.com>, Patrick Maupin wrote: >I didn't actually sense any dander on your part, so it was probably a >bit unfortunate that I chose to respond to that particular message. I >do (rightly or wrongly) sense some dander on Aahz's part, and this was >the second or third thread where I saw him respond in a similar terse >fashion, but I wasn't really motivated to respond until I saw your >response to his response to, well, you know... > >And I know that the BDFL thinks it's a mistake, and he's probably >right. In my previous post, I attempted to rationalize why this is >true. For a start, Guido is probably continually hounded by people >asking stupid __slots__ questions. > >Nonetheless, this is one of the few topics on CLP where innocent, >rational questions are more often than not answered with "because I >said so", so I was trying to inject a bit of nuance into the >discussion. (For most similar technical questions, someone will post a >pointer to a post or document which explains in clear technical detail >WHY things are bad, but for this issue there seems to be no comparable >source -- just that rant of the BDFL, which certainly carries a lot of >weight in terms of best practices, but which I find woefully inadequate >in terms of explanations which are dumbed-down enough for me to >follow.) > >Also, as I noted, I _do_ use them on occasion, so if there really _are_ >potential pitfalls there, I would like to understand exactly what they >are, so my ears perk up whenever I notice a __slots__ discussion, but >so far I have been repeatedly disappointed, in that I always see >someone saying "don't do that" but I have never seen a cogent technical >argument about how my scripts which __slots__ are going to suddenly, >irretrievably break one day. The proper use of__slots__is to save space in objects. Instead of having a dynamic dict that allows adding attributes to objects at anytime, there is a static structure which does not allow additions after creation. This saves the overheadof one dict for every object that uses slots. While this is sometimes a useful optimisation, it would be completely unnecessary if the Python interpreter was dynamic enough so that it would only require the dict when there actually were additions to the object. Unfortunately there is a side effect to slots. They change the behaviour of the objects that have slots in a way that can be abused by control freaks and static typing weenies. This is bad, because the contol freaks should be abusing the metaclasses and the static typing weenies should be abusing decorators, since in Python,there should be only one obvious way of doing something. Making CPython smart enough to handle saving space without __slots__ is a a major undertaking, which is probably why it is not on the list of changes for P3k (yet). Jacob Hall?n -- From gelists at gmail.com Thu Aug 3 09:37:35 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Thu, 3 Aug 2006 10:37:35 -0300 Subject: opposite of import References: <1154605835.465468.97550@m79g2000cwm.googlegroups.com> <8c7f10c60608030517i1e68433bn569150d379648087@mail.gmail.com> <8c7f10c60608030526u59e97c79m1032d62d1d639fb@mail.gmail.com> Message-ID: On 2006-08-03 09:26:54, Simon Brunning wrote: >> import amodule >> amodule.afunction() # Works fine >> >> del amodule >> amodule.afunction() # Will die now > > Note that this doesn't get rid of a module entirely. Python will still > holds on to the module, and if you just import it again at this point, > it won't be re-executed - you'll just get another reference to the > original module. Is that guaranteed, or is that just until the garbage collector has removed the module (at some arbitrary point)? Gerhard From bdesth.quelquechose at free.quelquepart.fr Sun Aug 27 15:47:11 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 27 Aug 2006 21:47:11 +0200 Subject: Very weird behavior that's driving me crazy In-Reply-To: <44e2c4c3$0$20039$9b4e6d93@newsspool4.arcor-online.net> References: <44e2c4c3$0$20039$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <44f1f40d$0$27583$626a54ce@news.free.fr> Pupeno a ?crit : (snip) > > and then I have another module called SensorSingleton that emulates the > hard-to-code-on-python singleton (snip) What do you mean "hard to code on python singleton" ? From boris.dusek at gmail.com Mon Aug 28 12:49:23 2006 From: boris.dusek at gmail.com (=?iso-8859-1?B?Qm9yaXMgRHWaZWs=?=) Date: 28 Aug 2006 09:49:23 -0700 Subject: Truly platform-independent DB access in Python? In-Reply-To: References: <1156748466.739709.117850@h48g2000cwc.googlegroups.com> Message-ID: <1156783763.551531.147700@p79g2000cwp.googlegroups.com> Dennis Lee Bieber wrote: > On 28 Aug 2006 00:01:06 -0700, "bobrik" > declaimed the following in comp.lang.python: > > > > for that platform. Do you know of any Python solution for MySQL access > > that is 100% platform-independent? > > > Subprocess module invoking the MySQL command line utilities? Of > course, parsing the results will be painful... > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com wulfraed at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-asst at bestiaria.com) > HTTP://www.bestiaria.com/ Hmm, that is very interesting; and parsing won't be IMHO such a problem if the columns will be tab-separated. Thanks for your tip! From tomi.lindberg.NO_SPAM at pp.inet.fi.invalid Wed Aug 2 08:01:54 2006 From: tomi.lindberg.NO_SPAM at pp.inet.fi.invalid (Tomi Lindberg) Date: Wed, 02 Aug 2006 12:01:54 GMT Subject: Class definition within function Message-ID: Hi, With the following function definition, is it possible to create an instance of class C outside the function f (and if it is, how)? And yes, I think this is one of those times when the real question is why :) >>> def f(): class C(object): def __init__(self): self.a = 'a' return C() >>> x = f() >>> x.a 'a' >>> y=f.C() Traceback (most recent call last): File "", line 1, in -toplevel- y=f.C() AttributeError: 'function' object has no attribute 'C' >>> -- Tomi Lindberg From sjmachin at lexicon.net Sun Aug 6 19:27:28 2006 From: sjmachin at lexicon.net (John Machin) Date: 6 Aug 2006 16:27:28 -0700 Subject: strftime replacement which supports Unicode format strings? References: <44d5ecc0$1@news.uni-ulm.de> Message-ID: <1154906848.234940.96080@75g2000cwc.googlegroups.com> Dennis Benzinger wrote: > Is there a library with a strftime replacement which supports Unicode > format strings? > Not that I know of. I presume that you're not happy with workarounds like: #>>> import datetime #>>> now = datetime.datetime.now() #>>> now.strftime('Year=%Y Month=%m Day=%d') 'Year=2006 Month=08 Day=07' #>>> now.strftime(u'Year=%Y Month=%m Day=%d') Traceback (most recent call last): File "", line 1, in ? TypeError: strftime() argument 1 must be str, not unicode #>>> u'Year=%s Month=%s Day=%s' % tuple(now.strftime('%Y/%m/%d').split('/')) u'Year=2006 Month=08 Day=07' #>>> You could generalise that by lashing up a function uniftime(obj, unifmt) which would work on any obj with a strftime method: parse the unifmt, build a strfmt with the components you want and some carefully chosen separator (maybe a control character e.g. FS), call obj.strftime(strfmt).split(FS) to get your components, then blend the components into the unicode constant parts of your unifmt -- easy :-) Cheers, John From jmcmonagle at velseis.com.au Thu Aug 3 23:51:28 2006 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Fri, 04 Aug 2006 13:51:28 +1000 Subject: two embedded problem. one maybe is python bug. In-Reply-To: References: Message-ID: <1154663488.5003.45.camel@kuepper.vels-int.com.au> On Fri, 2006-08-04 at 11:10 +0800, yy x wrote: > hi,all, > > > > the content of a.py : > #coding:gb2312 > #/usr/local/bin/python > import random > print random.randint(0,10) > > the c program: > #include > int main() > { > Py_Initialize(); > PyRun_SimpleString("import sys"); > PyRun_SimpleString("sys.path.append('.')"); > > PyRun_SimpleString("import a"); > Py_Finalize(); > > return 0; > } > > the gcc cmd line: > > g++ -o a a.c > -I/usr/local/include/python /usr/local/lib/libpython -lm -lpthread > -ldl > > First problem: > > when i run the a, the error msg is : > > Traceback (most recent call last): > File "", line 1, in ? > File "./a.py", line 1 > SyntaxError: encoding problem: with BOM > > > > but if i first import a.py through the python cmd line. This problem > disappears.(but second problem appears)(now I think the a import > a.pyc not a.py) > > I think it's python bug, isn't it? > > Second problem, > > Traceback (most recent call last): > File "", line 1, in ? > File "a.py", line 3, in ? > import random > File "/usr/local/lib/python2.4/random.py", line 44, in ? > from math import log as _log, exp as _exp, pi as _pi, e as _e > ImportError: /usr/local/lib/python2.4/lib-dynload/math.so: undefined > symbol: PyExc_OverflowError. > > > > Pls give me some advice, i am crazy.thanks > > > Sorry, but both programs work fine on my system (Mandriva Linux 2006 -2.6.12 kernel, python 2.4.1, gcc 4.0.1). Obviously I had to change a couple of paths to includes and libraries, but apart from that running a.py and the compiled c program worked fine. Perhaps it would help if you told us a bit about your particular configuration. Regards, John -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From ccurvey at gmail.com Thu Aug 17 10:10:52 2006 From: ccurvey at gmail.com (Chris Curvey) Date: 17 Aug 2006 07:10:52 -0700 Subject: 2.4.3, unittest and socket logging Message-ID: <1155823851.915902.67050@m79g2000cwm.googlegroups.com> Hi all, I just upgraded to 2.4.3 (from 2.4.1) on Windows. Now each time I run my unit tests, they always throw this error at the end of the test run: Error in atexit._run_exitfuncs: Traceback (most recent call last): File "c:\python24\lib\atexit.py", line 24, in _run_exitfuncs func(*targs, **kargs) File "c:\python24\lib\logging\__init__.py", line 1333, in shutdown h.close() File "c:\python24\lib\logging\handlers.py", line 448, in close logging.Handler.close(self) File "c:\python24\lib\logging\__init__.py", line 674, in close del _handlers[self] KeyError: The classes that are being tested do use socket handlers for logging, but I'm not sure if I should have been expecting this error, or what I should be doing to make it stop. (It's not critical, but it sure is annoying.) From john106henry at hotmail.com Wed Aug 16 13:41:50 2006 From: john106henry at hotmail.com (John Henry) Date: 16 Aug 2006 10:41:50 -0700 Subject: inheritance? In-Reply-To: <1155740537.807207.210950@i42g2000cwa.googlegroups.com> References: <1155695711.057312.8020@p79g2000cwp.googlegroups.com> <1155740537.807207.210950@i42g2000cwa.googlegroups.com> Message-ID: <1155750106.974307.173430@i42g2000cwa.googlegroups.com> As others pointed out already, this kind of "if then else" determination of type is best avoided. If it looks like a duck, quakes like a duck, must be a duck. KraftDiner wrote: > Steven D'Aprano wrote: > > On Tue, 15 Aug 2006 19:35:11 -0700, KraftDiner wrote: > > > > > I have two classes: > > > > > > class implicitClass: > > > def __init__(self): > > > def isIVR(self): #This is a class private method. > > > > The convention is to flag classes as "private" with a leading underscore: > > > > def _isIVR(self): > > > > or double underscores for "really private, no, honestly": > > > > def __isIVR(self): > > > > but google on "python name mangling" before using that. > > > > [snip] > > > > > As you can see the interface is almost identical. > > > > > > How can I define a base class that will abstract > > > the type such that I don't know if its really and inplicit > > > or explicit object? > > > > Something like this? > > > > > > class baseClass: > > def __init__(self): > > raise NotImplementedError("Don't instantiate the base class!") > > def fromfile(self): > > def getElement(self): > > # etc. > > > > > > class implicitClass(baseClass): > > def __init__(self): > > # code > > def _isIVR(self): > > # code > > def fromfile(self, fileObj, byteOrder): > > # code > > # etc. > > > > Now, you can define instance = implicitClass() or explicitClass(). When > > you come to use instance, you don't need to know whether it is one or the > > other. If you need to type-test, call "isinstance(instance, baseClass)". > > > > The only minor issue is that the fromfile method has a different > > interface. If you really want to do duck typing, they need to have the > > same interface. That might be as simple as: > > > > class explicitClass(baseClass): > > def fromfile(self, fileObj, byteOrder=None): > > # byteOrder is ignored; it is included only for > > # compatibility with implicitClass > > > > > > Is that what you're asking for? > > > Yes I believe so but in fromfile I want to call the appropriate > method depending on the in a parameter in fromfile... > like: > class baseClass: > def fromfile(self, fileObj, byteOrder=None, explicit=False): > if explicit: > call fromfile of explicit class > else: > call fromfile of implicit class > > How is that done? > > > > > > > > -- > > Steven D'Aprano From charles.hebert at gmail.com Wed Aug 30 09:22:34 2006 From: charles.hebert at gmail.com (charles.hebert at gmail.com) Date: 30 Aug 2006 06:22:34 -0700 Subject: where or filter on list In-Reply-To: <44F58DF8.7000308@websafe.com> References: <1156939493.558819.8410@i42g2000cwa.googlegroups.com> <44F58DF8.7000308@websafe.com> Message-ID: <1156944154.370085.6360@m73g2000cwd.googlegroups.com> Thanks all ! > Question: what if two values are equidistant? >>> def closest(foo,v): ... intermed = [(abs(v), v) for v in foo] ... intermed.sort() ... return [x[1] for x in intermed if x[0] == intermed[0][0]] ... >>> print closest([-20,-10,10,15],0) [-10, 10] Works fine ! (now with sorted ... ?) From steve at holdenweb.com Tue Aug 29 00:14:47 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 29 Aug 2006 05:14:47 +0100 Subject: Pros/Cons of Turbogears/Rails? In-Reply-To: <1156819473.592153.141940@i42g2000cwa.googlegroups.com> References: <1156726071.579429.44650@b28g2000cwb.googlegroups.com> <1156740469.645955.52080@i3g2000cwc.googlegroups.com> <1156768355.275370.129680@h48g2000cwc.googlegroups.com> <1156819473.592153.141940@i42g2000cwa.googlegroups.com> Message-ID: Ray wrote: > Paul Boddie wrote: > >>>But at least in most developers' perception, it is (not necessarily in >>>the absolute sense, but perhaps relative to Django or Turbogears). >>>Mind, it doesn't even need to be true, we're talking of perception >>>here. >> >>So actual maturity isn't important when using a technology: it's >>"perceived maturity" that counts, right? > > > Well depends on "counts" in what sense. Counts as in the managers up > there perceive something as mature, despite proofs of the contrary, > certainly "counts", because then we'll end up having to work with a > probably immature technology (nothing about RoR here, I'm talking in > general). Yet with more people using it, its actual maturity will > inevitably rise as well, maybe eventually to a level near that of its > perceived maturity. > > "Counts" as in to us developers who are actually spending our lives > doing this? Perhaps yes too. If you're well-versed in something that is > widely perceived to be mature, you may find it easier to win bread for > your family, even if you have a painful time using it. > > >>Any continuation down that >>particular path of reasoning surely leads you to the point where you >>claim, in concert with the developers, that increasing levels of >>inconvenience caused by gratuitous changes or broken documentation is >>not caused by bugs or general immaturity but by "features". I guess >>this is the definition of "opinionated software" that some people are >>so excited about. >> >>[...] >> >> >>>Sadly, there are more Java guys who know about Ruby than Python, >>>despite the fact that Python predates Ruby by quite a few years... >>>(this must be that Bruce Tate dude's fault! ) >> >>If you only listen to Bruce Tate et al, I imagine you could have the >>above impression, but I'd be interested to see hard facts to back up >>those assertions. > > > Yeah, see, the thing is that Python is not lacking luminaries endorsing > it either, e.g.: Eric Raymond and Bruce Eckel. But for some reason this > "Python is good" meme is not that viral. I wonder why... > > And, since when do hard facts matter anyway? I've met a number of > people who've told me they'd program in Eiffel if they could. And hey, > perhaps in its day Eiffel *was* the best OO language out there. > Certainly it looked cleaner than C++! :) > Also remember that there are still lots of Python users who keep the fact quiet because they regard it as a strategic advantage. They don't *want* Python usage to spread, or they'll lose their advantage. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From johan2sson at gmail.com Sun Aug 27 19:16:25 2006 From: johan2sson at gmail.com (johan2sson at gmail.com) Date: 27 Aug 2006 16:16:25 -0700 Subject: naive misuse? Message-ID: <1156720585.068907.244240@i3g2000cwc.googlegroups.com> The documentation for PyThreadState_SetAsyncExc says "To prevent naive misuse, you must write your own C extension to call this". Anyone care to list a few examples of such naive misuse? Johan From jean.moser at neuf.fr Fri Aug 11 05:24:49 2006 From: jean.moser at neuf.fr (jean-jeanot) Date: 11 Aug 2006 02:24:49 -0700 Subject: Read a file with open command Message-ID: <1155288288.954142.293000@i3g2000cwc.googlegroups.com> I can access to a file with the command: file_obj = open ( " D:\My documents\Textfile.txt",'r') When I now try to read a file with the following command: file_obj = open ("D:\My documents\File.ods",'r') it doesn't function. The extension ods is coming from OpenOffice.org Calc. Why ? jean-jeanot From pmaupin at gmail.com Wed Aug 16 23:22:54 2006 From: pmaupin at gmail.com (Patrick Maupin) Date: 16 Aug 2006 20:22:54 -0700 Subject: no longer can set breakpoint on 'pass' statement? References: <2dOEg.7770$oa1.4354@news02.roc.ny> Message-ID: <1155784974.666049.139060@75g2000cwc.googlegroups.com> I don't know for sure if this is the issue, but Python _used_ to include line number information in the actual codestream (via instructions), and now I think it's a separate table for speed reasons. So perhaps the previous ability to set breakpoints on pass instructions was merely an artifact of code which updated the current line number. Regards, Pat Mark Winrock wrote: > Can someone point me to some documentation as to why pdb breakpoints are > not working on 'pass' statements (at least on 2.4.1)? > > I was used to that working in the 2.2.3 build I was using up to this > last year. I just cant seem to find anything on it. > > Thanks! From kbk at shore.net Wed Aug 16 03:16:58 2006 From: kbk at shore.net (Kurt B. Kaiser) Date: Wed, 16 Aug 2006 03:16:58 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200608160716.k7G7GwcP015299@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 404 open ( +2) / 3376 closed (+16) / 3780 total (+18) Bugs : 860 open ( -1) / 6131 closed (+17) / 6991 total (+16) RFE : 229 open ( +1) / 235 closed ( +1) / 464 total ( +2) New / Reopened Patches ______________________ option to leave tempfile.NamedTemporaryFile around on close (2006-08-10) http://python.org/sf/1537850 opened by djmdjm Patch to fix __index__() clipping (2006-08-11) CLOSED http://python.org/sf/1538606 opened by Travis Oliphant Patch cElementTree to export CurrentLineNumber (2006-08-11) http://python.org/sf/1538691 opened by Robin Bryce Replace unicode.__eq__ exceptions with a warning (2006-08-11) CLOSED http://python.org/sf/1538956 opened by M.-A. Lemburg Add readinto method to StringIO and cStringIO (2006-08-12) http://python.org/sf/1539381 opened by Alexander Belopolsky Backports from trunk to release24-maint (2006-08-15) http://python.org/sf/1540329 opened by flub tarfile __slots__ addition (2006-08-14) http://python.org/sf/1540385 opened by Brian Harring Patches for OpenBSD 4.0 (2006-08-15) http://python.org/sf/1540470 opened by djmdjm Use Py_ssize_t for rangeobject members (2006-08-15) http://python.org/sf/1540617 opened by Alexander Belopolsky except too broad (2006-08-15) http://python.org/sf/1540849 opened by Jim Jewett with is now a blockopener (2006-08-15) CLOSED http://python.org/sf/1540851 opened by Jim Jewett IOBinding overly broad except (2nd try) (2006-08-15) CLOSED http://python.org/sf/1540856 opened by Jim Jewett except too broad (2006-08-15) CLOSED http://python.org/sf/1540857 opened by Jim Jewett IOBinding broad except - try 3 (2006-08-15) CLOSED http://python.org/sf/1540859 opened by Jim Jewett CodeContext visibility (2006-08-15) http://python.org/sf/1540869 opened by Jim Jewett broken shortcut keys (2006-08-15) http://python.org/sf/1540874 opened by Jim Jewett make IDLE honor the quit() builtin (2006-08-15) CLOSED http://python.org/sf/1540892 opened by Jim Jewett Patches Closed ______________ Add notes on locale module changes to whatsnew25.tex (2006-08-03) http://python.org/sf/1534027 closed by akuchling Build ctypes on OpenBSD x86_64 (2006-08-08) http://python.org/sf/1536908 closed by theller Fix __index__() clipping really big numbers (2006-07-29) http://python.org/sf/1530738 closed by ncoghlan PyShell.recall - fix indentation logic (2006-07-25) http://python.org/sf/1528468 closed by kbk Patch to fix __index__() clipping (2006-08-11) http://python.org/sf/1538606 closed by nnorwitz Replace unicode.__eq__ exceptions with a warning (2006-08-11) http://python.org/sf/1538956 closed by lemburg Replace the ctypes internal '_as_parameter_' mechanism (2006-08-02) http://python.org/sf/1532975 closed by theller writelines() in bz2 module does not raise check for errors (2006-08-06) http://python.org/sf/1535500 closed by gbrandl trace.py on win32 has problems with lowercase drive names (2006-08-07) http://python.org/sf/1536071 closed by gbrandl Give Cookie.py its own _idmap (2006-07-13) http://python.org/sf/1521882 closed by gbrandl socket.gethostbyaddr fix for machines with incomplete DNS (2006-06-23) http://python.org/sf/1511317 closed by gbrandl with is now a blockopener (2006-08-15) http://python.org/sf/1540851 closed by kbk IOBinding overly broad except (2nd try) (2006-08-15) http://python.org/sf/1540856 closed by jimjjewett except too broad (2006-08-15) http://python.org/sf/1540857 closed by jimjjewett IOBinding broad except - try 3 (2006-08-15) http://python.org/sf/1540859 closed by jimjjewett make IDLE honor the quit() builtin (2006-08-15) http://python.org/sf/1540892 closed by kbk New / Reopened Bugs ___________________ 2nd issue with need for speed patch (2006-08-09) http://python.org/sf/1537167 opened by Robin Bryce Missing platform information in subprocess documentation (2006-08-09) CLOSED http://python.org/sf/1537195 opened by Aaron Bingham urllib2 httplib _read_chunked timeout (2006-08-09) http://python.org/sf/1537445 opened by devloop Installation on Windows Longhorn (2006-08-10) http://python.org/sf/1537601 opened by O.R.Senthil Kumaran import on cElementTree on Windows (2006-08-09) http://python.org/sf/1537685 reopened by thomasbhickey import on cElementTree on Windows (2006-08-09) http://python.org/sf/1537685 opened by Thomas B Hickey indent changes when copying command (2006-08-10) CLOSED http://python.org/sf/1538445 opened by mjd__ PyThreadState_SetAsyncExc bug (2006-08-11) http://python.org/sf/1538556 opened by ganges master pyo's are not overwritten by different optimization levels (2006-08-11) http://python.org/sf/1538778 opened by Toshio Kuratomi Long command lines don't work on Windows (2006-08-12) http://python.org/sf/1539295 opened by Albert Strasheim distutils example code missing imports (2006-08-13) CLOSED http://python.org/sf/1539336 opened by Albert Strasheim Identifiers begining with __ renamed (2006-08-14) CLOSED http://python.org/sf/1539847 opened by W Barnes warnings in interactive sessions (2006-08-14) http://python.org/sf/1539925 opened by M.-A. Lemburg Closing a pipe can lead to uncompleted command (2006-08-14) http://python.org/sf/1539954 opened by Stefan Sonnenberg Insane format string should cause ValueError (2006-08-14) CLOSED http://python.org/sf/1539955 opened by Nick Coghlan SocketServer.ForkingMixIn.collect_children() waits on pid 0 (2006-08-14) http://python.org/sf/1540386 opened by Neal Norwitz cgi.py error on parsing/handling content-disposition (2006-08-15) http://python.org/sf/1540529 opened by Dirk Holtwick Bugs Closed ___________ PyArg_ParseTupleAndKeywords potential core dump (2006-07-17) http://python.org/sf/1523610 closed by gbrandl Missing platform information in subprocess documentation (2006-08-09) http://python.org/sf/1537195 closed by gbrandl Concatenation on a long string breaks (2006-07-21) http://python.org/sf/1526585 closed by arigo import on cElementTree on Windows (2006-08-09) http://python.org/sf/1537685 closed by gbrandl cgi.FieldStorage memory usage can spike in line-oriented ops (2005-01-30) http://python.org/sf/1112549 closed by gvanrossum tokenize module does not detect inconsistent dedents (2005-06-21) http://python.org/sf/1224621 closed by gbrandl fix inplace assignment for immutable sequences (2006-02-21) http://python.org/sf/1436226 closed by gbrandl BROWSER path with capital letters (2006-07-27) http://python.org/sf/1529655 closed by sf-robot struct.pack raises TypeError where it used to convert (2006-07-28) http://python.org/sf/1530559 closed by nnorwitz indent changes when copying command (2006-08-11) http://python.org/sf/1538445 closed by kbk distutils example code missing imports (2006-08-12) http://python.org/sf/1539336 closed by nnorwitz Segmentation fault when importing expat from xml.parser (2005-07-27) http://python.org/sf/1246405 closed by sf-robot CSV regression in 2.5a1: multi-line cells (2006-04-05) http://python.org/sf/1465014 closed by sf-robot Installing documentation doesn't make it show up (2003-07-06) http://python.org/sf/766842 closed by sf-robot infinite __str__ recursion in thread causes seg fault (2003-07-31) http://python.org/sf/780714 closed by sf-robot Identifiers begining with __ renamed (2006-08-14) http://python.org/sf/1539847 closed by gbrandl Insane format string should cause ValueError (2006-08-14) http://python.org/sf/1539955 closed by gbrandl CTypes _as_parameter_ not working as documented (2006-08-03) http://python.org/sf/1533481 closed by theller PythonLauncher uses incorrect working directory (2006-07-23) http://python.org/sf/1527397 closed by sf-robot Quitter object masked (2006-05-01) http://python.org/sf/1479785 closed by kbk New / Reopened RFE __________________ csv module: add header row to DictWriter (2006-08-10) http://python.org/sf/1537721 opened by ed_abraham Allow choice of copy function in shutil.copytree (2006-08-14) http://python.org/sf/1540112 opened by Tony From ssmoot at gmail.com Mon Aug 28 11:30:17 2006 From: ssmoot at gmail.com (Sam Smoot) Date: 28 Aug 2006 08:30:17 -0700 Subject: Pros/Cons of Turbogears/Rails? In-Reply-To: <1156726071.579429.44650@b28g2000cwb.googlegroups.com> References: <1156726071.579429.44650@b28g2000cwb.googlegroups.com> Message-ID: <1156779017.805723.231250@74g2000cwt.googlegroups.com> fuzzylollipop wrote: > uh, no, Python predates Ruby by a good bit > Rails might be "older" than Turbogears but it still JUST went 1.0 > officially. Wow that's a lot of FUD, especially since you're beating up on Rails for it's docs and maturity, when I doubt (but couldn't prove) turbogears comes close. Lets be specific: 12/13/05: http://dev.rubyonrails.org/changeset/3303 > It can't be called "mature' by any defintition. It's easy to deploy a site without running into bugs as long as you're not dealing with any edge-cases. As far as OSS solutions go, that pretty well fits my definition of "mature". So there's one. > Rails has no documentation, period. The authors acknowledge this > openly. Why you would just talk out of your ass like this escapes me. http://api.rubyonrails.org (Look at any of the :Base classes for overviews) http://rubydoc.org (For basic Ruby help) http://rails.techno-weenie.net/ (Help with the lesser known areas of RoR, and tips & tricks) http://www.bigbold.com/snippets/tags/rails (Snippets other people have found useful) http://wiki.rubyonrails.com/rails/pages/Howtos (Lots of "Getting Started" type how-tos) http://caboo.se (A blog aggregation of some of the committer's ) Then again, you could just google for "rails documentation" (here's a link: http://www.google.com/search?client=safari&rls=en&q=rails+documentation&ie=UTF-8&oe=UTF-8 ) And the top link will take you to a page on the Wiki that describes all of this. Until you want to start writing plugins and such, this documentation pretty much fits the bill. Could there be more? Yes. Is it perfect? Obviously not. Is finding documentation going to be a problem for anyone willing to spend a few minutes with Google or on IRC asking questions if you're genuinely trying? I seriously doubt it. > again, Ruby can't be considered 'mature' by any definition. It seems like you're the one confusing things now. Ruby is obviously a pretty mature language. There are definite feature holes (encoding aware Strings, native Threads), but the community, documentation, tutorials (by far the best of any language I've learned), are all pretty mature. Is Rails mature? Compared to JSP? Probably not... compared to TurboGears? (The entire point of this topic, which you conveniently side-step by managing to not mention it once) Easily. So if you decide to reply, might I suggest spending a few minutes with Google to get your facts straight next time? Oh, and keeping an eye on the actual topic might be a good idea too. From tim.golden at viacom-outdoor.co.uk Wed Aug 16 04:09:23 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 16 Aug 2006 09:09:23 +0100 Subject: What would be the best way to run python client in the background Message-ID: | Tim Golden wrote: | | > [gel] | > | > | I have written a python client server app [...] | > | I want to run the client end of the app more or less invisibly | > | (no console) on the XP clients when ever a users logs on. [Tim G] | > The normal way is to run a Win32 service. There are several | > posts on the subject around the Python and Python-Win32 | > mailing lists / newsgroups. The alternative is to set something | > to run when any user logs in to run without a window. Again, | > there are posts on the subject, including one I seem to remember | > from Robin Becker, which tell how to do this kind of thing. [gel] | Yes running the client as a service seems to be the way to go. I have | had a bit of a look at the py2exe way of doing it, but have not got my | head around it yet. What would be your preferred way of creating a | service for an XP client? I've always coded pretty much from scratch, reusing a tried-and-trusted skeleton and fitting things in. That said, I've never had to put together a service that was anything more than lightweight. The attached template I culled from someone's webpage, can't remember where I'm afraid. I believe people have had success in using py2exe to create a service but I haven't tried it myself. Hopefully more experienced service-writers will chime in with coherent advice. You might also try the python-win32 mailing list, since not everyone who reads that reads this I imagine. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ -------------- next part -------------- A non-text attachment was scrubbed... Name: service_template.py Type: application/octet-stream Size: 1103 bytes Desc: service_template.py URL: From nogradi at gmail.com Fri Aug 25 18:54:12 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Sat, 26 Aug 2006 00:54:12 +0200 Subject: Avoiding if..elsif statements In-Reply-To: <1156545375.962486.49540@h48g2000cwc.googlegroups.com> References: <1156545375.962486.49540@h48g2000cwc.googlegroups.com> Message-ID: <5f56302b0608251554s35b695c0wad9d5848e72a5ac3@mail.gmail.com> > Code: > > value = self.dictionary.get(keyword)[0] > > if value == "something": > somethingClass.func() > elsif value == "somethingElse": > somethingElseClass.func() > elsif value == "anotherthing": > anotherthingClass.func() > elsif value == "yetanotherthing": > yetanotherthingClass.func() > > Is it possible to store these function calls in a dictionary so that I > could just call the dictionary value? How about (untested): def x(): print 'x' def y(): print 'y' funcdict={ 'valuex': x, 'valuey': y } funcdict['valuex']() From anthra.norell at tiscalinet.ch Tue Aug 1 04:10:18 2006 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Tue, 1 Aug 2006 10:10:18 +0200 Subject: Html character entity conversion Message-ID: <014401c6b541$edbb13c0$0201a8c0@mcuf7> Pak (or Andrei, whichever is your first name), My proposal below: ----- Original Message ----- From: Newsgroups: comp.lang.python To: Sent: Sunday, July 30, 2006 8:52 PM Subject: Re: Html character entity conversion > danielx wrote: > > pak.andrei at gmail.com wrote: > > > Here is my script: > > > > > > from mechanize import * > > > from BeautifulSoup import * > > > import StringIO > > > b = Browser() > > > f = b.open("http://www.translate.ru/text.asp?lang=ru") > > > b.select_form(nr=0) > > > b["source"] = "hello python" > > > html = b.submit().get_data() > > > soup = BeautifulSoup(html) > > > print soup.find("span", id = "r_text").string > > > > > > OUTPUT: > > > привет > > > питон > > > ---------- > > > In russian it looks like: > > > "?????? ?????" > > > > > > How can I translate this using standard Python libraries?? > > > > > > -- > > > Pak Andrei, http://paxoblog.blogspot.com, icq://97449800 > > I've been proposing solutions of late using a stream editor I recently wrote, realizing each time how well it works in a vareity of different situations. I can only hope I am not beginning to get on people's nerves (Here he comes again with his damn thing!). I base the following on proposals others have made so far, because I haven't used unicodes and know little about them. If nothing else, I do think this is a rather elegant way to translate the ampersands to the unicode stirngs. Having to read them through an 'eval', though, doesn't seem to be the ultimate solution. I couldn't assign a unicode string to a variable so that it would print text as Claudio proposed. Here is my htm example: >>> htm = StringIO.StringIO (''' Deuxième question L´élève doit lire et traduire: привет питон
''') And here is my SE hack: >>> import SE # Available at the Cheese Shop >>> Ampersand_Filter = SE.SE (' "~&#[0-9]+;~==(10)" ') >>> for line in htm: line = line [:-1] ampersand_codes = Ampersand_Filter (line [:-1]) # A list of the ampersand codes found in the current line if ampersand_codes: # From it we edit the substitution defintiions for the current line substitutions = '' for code in ampersand_codes.split ('\n')[:-1]: substitutions = '%s%s=\\u%04x\n' % (substitutions, code, int (code [2:-1])) # And make a custom Editor just for the current line Line_Unicoder = SE.SE (substitutions) unicode_line = Line_Unicoder (line) print eval ('u"%s"' % unicode_line) else: print line Deuxième question L´élève doit lire et traduire: ?????? ?????
This is a text book example of dynamic substitutions. Typically SE compiles static substituions lists. But with 2**16 (?) unicodes, building a static list would be absurd if at all possible. So we dynamically make custom substitutions for each line after extracting the ampersand escapes that may be there. Next we would like to fix the regular ascii ampersand escapes and also strip the tags. That is a simple question of preprocessing the file. >>> Legibilizer = SE.SE ('htm2iso.se "~<(.|\n)*?>~=" "~~=" ') 'htm2iso.se' is a substitutions definition file that defines the standard ascii ampersands to characters. It is included in the SE package. You can name as many definition files as you want. In a definition string the name of a file is equivalent to its contents. >>> htm.seek (0) >>> htm_no_tags = Legibilizer (htm.read ()) >>> for line in htm_no_tags.split ('\n'): if line.strip () == '': continue ampersand_codes = Ampersand_Filter (line) ... (same as above) Deuxi?me question L'?l?ve doit lire et traduire: ?????? ????? Whether this serves your purpose I don't really know. How you can use it other than read it in the IDLE window, I don't know either.I tried to copy it out, but it doesn't survive the operation and the paste has question marks or squares in the place of the Russian letters. Regards Frederic From jojoba12 at hotmail.com Sun Aug 6 14:21:39 2006 From: jojoba12 at hotmail.com (jojoba) Date: 6 Aug 2006 11:21:39 -0700 Subject: why did wxpython MakeActiveXclass stopped working?!?!!?!? References: <1154884250.224877.229650@p79g2000cwp.googlegroups.com> Message-ID: <1154888499.881410.24130@i3g2000cwc.googlegroups.com> Hi Phillipe! Thanks for the response! Unfortunately, i have also reinstalled pywin32, and i still get the same error. Isn't this weird? You know what else. I have a py2exe version of this code, that actually runs fine, using the embedded windows media player. But Im guessing i made that py2exe distributable with older pywin32 and older wxpython. This makes me think that one of the newer versions of pywin32 or wxpython is giving me that error trouble. Any other ideas on how to rectify this? Thanks again, jojoba Philippe Martin wrote: > Philippe Martin wrote: > > > jojoba wrote: > > > >> HI > >> I wrote a little wxpython program with an embedded windows media > >> player. > >> It worked great. Recently, I reinstalled windows and then wxpython > >> (most likely a newer version than i had before). Now when i run the > >> exact same code, i get this error: > >> > >> File "C:\Documents and > >> Settings\jojoba.DEMO-019591FB22\Desktop\Projects\SrAsse > >> ts\sr.py", line 353, in __init__ > >> self.CreateActiveXplayer() > >> File "C:\Documents and > >> Settings\jojoba.DEMO-019591FB22\Desktop\Projects\SrAsse > >> ts\sr.py", line 363, in CreateActiveXplayer > >> self.Player = PlayerActiveXClass(self, -1) > >> File > >> "C:\Python24\Lib\site-packages\wx-2.6-msw-ansi\wx\lib\activexwrapper.py", > >> line 108, in axw__init__ > >> (0, 0, sz.width, sz.height), self._wnd, ID) > >> File "C:\Python24\Lib\site-packages\pythonwin\pywin\mfc\activex.py", > >> line 23, > >> in CreateControl > >> self.__dict__["_obj_"] = win32ui.CreateControl(clsid, windowTitle, > >> style, re > >> ct, parent, id, None, False, lic_string) > >> win32ui: The window can not be created as it has an invalid handle > >> > >> > >> Here is a snippet from my code: > >> > >> from wxPython.lib.activexwrapper import MakeActiveXClass > >> import win32com > >> from win32com import client > >> > >> class wxWMPlayer(wxPanel): > >> def __init__(self, parent): > >> wxPanel.__init__(self, parent, -1, > >> style=wxCLIP_CHILDREN|wxNO_FULL_REPAINT_ON_RESIZE) > >> self.MixMaster = parent > >> self.ID3data = {} > >> self.InitWindowProperties() > >> self.CreateActiveXplayer() > >> > >> def InitWindowProperties(self): > >> self.WindowsMediaPlayerTopSizer = wxBoxSizer(wxVERTICAL) > >> self.SetSizer(self.WindowsMediaPlayerTopSizer) > >> self.SetAutoLayout(1) > >> > >> def CreateActiveXplayer(self): > >> PlayerModule = > >> > > > win32com.client.gencache.EnsureModule('{6BF52A50-394A-11D3-B153-00C04F79FAA6}', > >> 0,1,0) > >> PlayerActiveXClass = > >> MakeActiveXClass(PlayerModule.WindowsMediaPlayer, eventObj = self) > >> self.Player = PlayerActiveXClass(self, -1) > >> self.Player.isPlaying = 0 > >> self.Player.uiMode = 'full' > >> self.WindowsMediaPlayerTopSizer.Add(self.Player, 1, wxEXPAND) > >> > >> > >> Any ideas anyone...i have reinstalled wxpython to no avail....Please > >> help anyone.... > >> thanks, > >> jojoba > > > > > > Did you reinstall pywin32 ? > > > > Philippe > > Well I'm silly: it would not import. From eric_brunel at despammed.com Tue Aug 1 08:56:03 2006 From: eric_brunel at despammed.com (Eric Brunel) Date: Tue, 01 Aug 2006 14:56:03 +0200 Subject: Strange Tkinter Grid behaviour Problem References: Message-ID: On Tue, 01 Aug 2006 14:14:51 +0200, H J van Rooyen wrote: > Hi, > > Still struggling with my GUI exercise - > > I have the following lines of code in a routine that is bound at > to > an instance of Entry : > > self.disp.Amount_des = Label(self.disp, text = self.dis_string, > fg = > 'black', bg = 'yellow') > self.disp.Amount_des.grid(row = self.rownum, column=0, sticky = > 'nesw') > > self.disp.Amount = Label(self.disp, text = self.retstring, fg = > 'black', > bg = 'green') > self.disp.Amount.grid(row = self.rownum, column=1, sticky = > N+S+E+W) > > The second call to the grid method fails as follows: > > Exception in Tkinter callback > Traceback (most recent call last): > File "E:\PYTHON24\lib\lib-tk\Tkinter.py", line 1345, in __call__ > return self.func(*args) > File "C:\WINDOWS\DESKTOP\Entry1.py", line 243, in entryend > self.disp.Amount.grid(row = self.rownum, column=1, sticky = N+S+E+W) > TypeError: cannot concatenate 'str' and 'instance' objects > > If I change the N+S+E+W to the 'nsew' form, it works no problem... > > Weird - at other places in the program the form: sticky = N+S+E+W works > without > a problem. Simple: you have in this context a local or global variable named either N, S, W or E, shadowing the constant defined in the Tkinter module. You can find it by inserting a line like: print repr(N), repr(S), repr(W), repr(E) before your self.disp.Amount.grid in your code. This line should print: 'n' 's' 'w' 'e' but I guess it won't... The solutions are: - Rename your variable. - Always use the string form, i.e 'nswe'. This is the standard in native tk. The N, S, W and E constants are just defined for convenience in Tkinter. - Do not use "from Tkinter import *" to import the module, but something like "import Tkinter as tk", and then prefix all names in this module by 'tk.'. So your code above becomes: self.disp.Amount = tk.Label(self.disp, text = self.retstring, fg = 'black', bg = 'green') self.disp.Amount.grid(row = self.rownum, column=1, sticky = tk.N+tk.S+tk.E+tk.W) (I'm personnally not a big fan of this last solution, since I find it clobbers the code a lot and decreases readability. But it's usually the best way to avoid name clashes...) [snip] HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From inyeol.lee at siliconimage.com Wed Aug 16 15:06:28 2006 From: inyeol.lee at siliconimage.com (Inyeol Lee) Date: Wed, 16 Aug 2006 12:06:28 -0700 Subject: inheritance? In-Reply-To: <1155751628.114929.194250@75g2000cwc.googlegroups.com> References: <1155695711.057312.8020@p79g2000cwp.googlegroups.com> <1155751628.114929.194250@75g2000cwc.googlegroups.com> Message-ID: <20060816190628.GL20230@siliconimage.com> On Wed, Aug 16, 2006 at 11:07:08AM -0700, KraftDiner wrote: [...] > Here I tried this example and maybe this will explain the difficulties > I'm having. > 1) at the time the baseClass is constructed shouldn't the constructor > of the appropriate > type be called. > 2) getName is doing nothing... > > class baseClass: > def __init__(self): > pass > def fromfile(self, str): > if (str == 'A'): > a = typeA() > else: > a = typeB() > def getName(self): > pass > > class typeA(baseClass): > def __init__(self): > self.name='A' > print 'typeA init' > def fromfile(self, str=None): > print 'typeA fromfile' > def getName(self): > print self.name > > class typeB(baseClass): > def __init__(self): > self.name='B' > print 'typeB init' > def fromfile(self, str=None): > print 'typeB fromfile' > def getName(self): > print self.name > > bc = baseClass() > bc.fromfile('A') > bc.getName() > bc.fromfile('B') > bc.getName() > bc.getName() > > log: > typeA init > typeB init > I didn't follow up this thread from the begining, but I think this is what you want; Python 2.4.3 (#1, Mar 31 2006, 09:09:53) [GCC 2.95.3 20010315 (release)] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> class baseClass: ... @staticmethod ... def fromfile(string): ... if string == "A": ... return typeA() ... else: ... return typeB() ... def getName(self): ... print self.name ... >>> class typeA(baseClass): ... def __init__(self): ... self.name = "A" ... print "typeA init" ... >>> class typeB(baseClass): ... def __init__(self): ... self.name = "B" ... print "typeB init" ... >>> a = baseClass.fromfile("A") typeA init >>> a.getName() A >>> b = baseClass.fromfile("B") typeB init >>> b.getName() >>> B >>> -- Inyeol Lee From johnjsal at NOSPAMgmail.com Tue Aug 8 11:51:17 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 08 Aug 2006 15:51:17 GMT Subject: using python at the bash shell? In-Reply-To: References: <44d7e364$0$24980$c3e8da3@news.astraweb.com> Message-ID: Thomas Bartkus wrote: > I am just validating your experience by saying that coming from Python is a > barrier to my learning BASH. The more I work with Linux/BASH, the more I > see how I might have used BASH to script something I have already done in > Python. But the question that always comes up is why bother with BASH at > all ;-) And with Python available everywhere, .... > > I've just reconsiled to pick up my BASH by osmosis and concentrate on > (much!) cleaner scripting with Python. Glad to know I'm not alone! But I'm certainly much happier using Python than bash anyway. All I really want to learn as far as the shell is concerned are the 'natural' things you can do, such as directory/file manipulation, installing programs, etc. I don't have much of a need to learn the actual programming parts of the bash language, especially when I can do the same with Python, which is so much cooler. :) From python.list at tim.thechases.com Tue Aug 1 12:13:30 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 01 Aug 2006 11:13:30 -0500 Subject: Finding the name of a class In-Reply-To: References: <44cf7538$0$29435$626a54ce@news.free.fr> Message-ID: <44CF7DAA.7000907@tim.thechases.com> >> While this is surely true, would somebody explain why I had such trouble >> finding this? > > I think __name__ is an attribute of the class itself, not the instance: That makes sense, but what doesn't make sense is why, when you do a dir(Foo), you don't get '__name__' in the returned list of available things Python knows about a Foo. >>> class Foo(object): ... pass ... >>> myClass = Foo >>> myInstance = Foo() >>> # does myClass have a '__name__' attribute? >>> '__name__' in dir(myClass) False >>> # that's a negative, buster >>> '__name__' in dir(myInstance) False >>> # haha, just kidding, it really did have a __name__ >>> # proof that dir() isn't showing everything: >>> myClass.__name__ 'Foo' >>> myInstance.__name__ Traceback (most recent call last): File "", line 1, in ? AttributeError: 'Foo' object has no attribute '__name__' It's the >>> '__name__' in dir(myClass) False >>> myClass.__name__ 'Foo' that throws me. What other super-secret tricks have I missed because dir() didn't tell me about them? -a still-confused tkc From bruce+usenet at cenderis.demon.co.uk Sat Aug 26 12:26:57 2006 From: bruce+usenet at cenderis.demon.co.uk (Bruce Stephens) Date: Sat, 26 Aug 2006 17:26:57 +0100 Subject: ASN.1 encoder & decoder References: <87odu8e9ty.fsf@cenderis.demon.co.uk> Message-ID: <8764gfcvji.fsf@cenderis.demon.co.uk> Doug Stell writes: > I looked at pyasn1. Unfortunately, it is not useful and provides a C > interface. Thanks, anyhow. What makes you say that? It appears to me (looking at the code in CVS) to be written entirely in Python, and the home page, shows examples clearly with a Python interface. I've no idea whether or not it's useful in any other sense. [...] From firmly888 at hotmail.com Mon Aug 21 22:46:13 2006 From: firmly888 at hotmail.com (firmly888 at hotmail.com) Date: 21 Aug 2006 19:46:13 -0700 Subject: The most powerful computer security tools Message-ID: <1156214773.768806.265170@b28g2000cwb.googlegroups.com> DiskNumen: www.FirmlySoft.com DiskNumen, the most powerful computer security tool, will make everything intact after your reboot even if there are Virus, Hacker, Rascal software, error operation or even your purposive breakage. Your computer can be prevented from any attack by DiskNumen through the way of solidifying disk into CD. Have you ever been anguished by these problems: * Virus software destroy the computer system, leading to the resetting of the system and the decline of the computer running speed; * Once the rascal software interrupt you ,it will exhaust your resources ,besides,the pop-up dialog boxes make you feel disgusted; * The hacker software always hide behind you wondering steal sth from you; * System malfunctions appear frequently due to the mistaken operation of the employees; * Hidden troubles brought by the unauthorized software installation of the employees; * No place to store the top-secret files makes you feel upset; * Large quantities of future troubles turn up resulting the deletion of the top-secret files. ...... Want to get rid of the attack of the virus, hacker and rascal software? Want to store your top-secret files in a safe place? Want to break away from all the problems above? Why not try FirmlySoft? FirmlySoft , the Disk Numen , is a copied file protector . It does the security work of the file and the operating system through the methods below: 1. Solidified Partition : It is to divided and solidify the designated HD into partitions just like CD . It is temporary for you to do any operation to the partitions that is solidified , and it will resume immediately after you turn off the computer . 2. Opened Folders : This function is relative to the Solidified Partition . We often use some catalogues of the Solidified Partition , such as My Document and the Desktop , which are required to be revised and reserved . To this kind of catalogues, you can set them as the Opened Folder , that is to say you can succeed in revising and reserving the catalogues but not affecting your using habit . 3. File Lockfast : It is a perfect place to reserve your top-secret files , without the password no one can scan your files 4. Folder Lock: Since the space of the File Lockfast is limited , to the common files , it is secure to add a lock to your folder. From sjmachin at lexicon.net Fri Aug 11 07:18:49 2006 From: sjmachin at lexicon.net (John Machin) Date: 11 Aug 2006 04:18:49 -0700 Subject: Python checking for None/Null values References: <1155291204.446003.93760@m73g2000cwd.googlegroups.com> <1155292928.980276.228690@p79g2000cwp.googlegroups.com> Message-ID: <1155295129.115883.71310@i42g2000cwa.googlegroups.com> Fuzzydave wrote: > > HistoryRep is an array value so historyRep[0] to [7] all have values > in them but historyRep[8] and [9] do not as the query does not always > return a full 10 values. I am trying to check all of the historyRep > items > to check if they are empty/null/None (whatever the term is in python) > and make it return an empty value or a none to the screen. I did print > historyRep[8] out and it falls over, I am assuming if its an array and > if the SQL query only returns 8 records instead of 10 then the last > two array values i am checking for litterly don't exist instead of > being > null but i can't find a if exists style function either? Just paste this in immediately after getting the result back from the query; it's not necessarily the fastest way but it's effin' obvious what it's doing :-) while len(historyRep) < 10: historyRep.append(None) Cheers, John From duncan.booth at invalid.invalid Wed Aug 30 03:43:44 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 Aug 2006 07:43:44 GMT Subject: A Sort Optimization Technique: decorate-sort-dedecorate References: <1156719092.603277.57390@b28g2000cwb.googlegroups.com> <1156723602.192984.49610@m79g2000cwm.googlegroups.com> <280820061150081729%jgibson@mail.arc.nasa.gov> <7.0.1.0.0.20060829132302.05c9e758@yahoo.com.ar> <44F480EF.9080202@durchholz.org> <1f7befae0608291225o12985c18u95137d9b6ba928e2@mail.gmail.com> Message-ID: Tim Peters wrote: > [/T] >>> OTOH, current versions of Python (and Perl) > > [/F] >> just curious, but all this use of (& Perl) mean that the Perl folks have >> implemented timsort ? > > A remarkable case of independent harmonic convergence: > > http://mail.python.org/pipermail/python-dev/2002-July/026946.html > > Come to think of it, I don't actually know whether a /released/ Perl > ever contained the development code I saw. Looks like it got added to > Perl 5.8: > > http://perldoc.perl.org/sort.html > The difference in style between Perl and Python is quite interesting: Perl lets you specify the algorithm which you think it going to be best for your code, but in a global manner which means your pragmas may or may not have the desired effect (which sounds a headache for maintenance). Python simply gets on with the job. What the perl docs don't say though is whether they do any of the fancy timsort optimisations. I guess not, or at least not all of them: the Perl docs warn that mergesort can be much slower if there are a lot of duplicates, and from the Python dev thread above we can see that early timsort was also much slower for that case (~sort) but in the final version there is no effective difference. From gh at gregor-horvath.com Wed Aug 9 16:28:28 2006 From: gh at gregor-horvath.com (Gregor Horvath) Date: Wed, 09 Aug 2006 22:28:28 +0200 Subject: Dallas One wire tempreture measurement. In-Reply-To: <1155048519.496470.304650@75g2000cwc.googlegroups.com> References: <1155048519.496470.304650@75g2000cwc.googlegroups.com> Message-ID: chris.lyon at spritenote.co.uk schrieb: > a previous thread > > http://mail.python.org/pipermail/python-list/2002-June/107616.html > > discussed this issue, and Dave Moor kindly pointed to his solution. > However this is no longer a current link, does anyone know if there is > a currently available solution? > I am using digitemp with this code: def GetActT(): "Liest aus Digittemp die temp" digi = os.popen("digitemp -q -a -o2 -c /home/gh/.digitemprc") f = digi.readlines() digi.close() return float(f[0].split()[1]) -- Servus, Gregor http://www.gregor-horvath.com From miki.tebeka at gmail.com Tue Aug 8 14:36:40 2006 From: miki.tebeka at gmail.com (Miki) Date: 8 Aug 2006 11:36:40 -0700 Subject: Looking for an intellisense with good help IDE for Python In-Reply-To: <1155022590.845074.256900@i42g2000cwa.googlegroups.com> References: <1155022590.845074.256900@i42g2000cwa.googlegroups.com> Message-ID: <1155062200.732123.37500@m79g2000cwm.googlegroups.com> Hello Terrence, > I would like an IDE that shows me all methods and functions I can call > on a particular data item. For instance, iter() can be called on any > sequence, but it is not a method. > > Nonetheless, I would like for something to show me every thing that I > can call on a particular data item. > > This includes % after a string. > > I would also like browseable help with good examples on whatever > methods and functions and operators it pops up. The IDLE that will come (soon) with Python 2.5 with have some intellisense. Not all that you requested but some of it. HTH, Miki http://pythonwise.blogspot.com/ From rpdooling at gmail.com Thu Aug 10 09:52:37 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 10 Aug 2006 06:52:37 -0700 Subject: Absolute beginner - is this feasible? In-Reply-To: References: <1155213953.799292.207930@p79g2000cwp.googlegroups.com> Message-ID: <1155217957.383577.113670@h48g2000cwc.googlegroups.com> Michiel Sikma wrote: > I don't know if writing to a > Word file is possible. It's a proprietary format, afterall. see: Python To Word Capture script output in MS Word http://gflanagan.net/site/dotnet/05/RunPythonScriptFromWord.html rd From sp1d3rx at gmail.com Fri Aug 4 14:08:22 2006 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 4 Aug 2006 11:08:22 -0700 Subject: Why do I require an "elif" statement here? In-Reply-To: <1154712731.375032.203570@m79g2000cwm.googlegroups.com> References: <1154712731.375032.203570@m79g2000cwm.googlegroups.com> Message-ID: <1154714902.770382.162110@m73g2000cwd.googlegroups.com> Jim, what you wrote should work correctly. I'm curious as to why you are doing it this way though. An easier way would be to take out all this character processing and use the builtin string processing. See this code: ------------------------------- whitespace = " " old_indent = 3 new_indent = 5 x = " starts with 3 spaces" x = x.replace(whitespace*old_indent, whitespace*new_indent) ------------------------------- In this example though, it will replace the 3 spaces no matter where they are at, not just in the beginning... still, it's probably more practical for most use cases. Jim wrote: > Could somebody tell me why I need the "elif char == '\n'" in the > following code? > This is required in order the pick up lines with just spaces in them. > Why doesn't > the "else:" statement pick this up? > > OLD_INDENT = 5 # spaces > NEW_INDENT = 4 # spaces > > print 'Reindent.py:' > print '\nFrom file %s' % infile > print 'Change %i space indentation to %i space indentation.' % ( > OLD_INDENT, NEW_INDENT) > print 'And place revised file into %s' % outfile > > whitespace = ' ' > n = 0 > nline = 0 > > for line in input.readlines(): > nline += 1 > # Only look at lines that start with a space. > if line[0] == whitespace: > i = 0 > for char in line: > i += 1 > if char == whitespace: > pass > elif char == '\n': # Why do I need this for a > blank line with only spaces? > output.write(line) > break > else: # Why doesn't the blank line > get picked up here? > x = line.count(whitespace*OLD_INDENT,0,i) > # Reindent lines that have exactly a multiple of > OLD_INDENT. > if x > 0 and (i-1)%OLD_INDENT == 0: > output.write(whitespace*NEW_INDENT*x+line.lstrip()) > n += 1 > break > else: > output.write(line) > break > else: > output.write(line) > > input.close() > output.close() > print 'Total number of %i lines reindented out of %i lines.' % (n, > nline) From lamthierry at gmail.com Thu Aug 31 16:38:32 2006 From: lamthierry at gmail.com (Thierry Lam) Date: 31 Aug 2006 13:38:32 -0700 Subject: HTTPS Login In-Reply-To: References: Message-ID: <1157056712.085122.187560@m79g2000cwm.googlegroups.com> Instead of using the following: > req = urllib2.Request("https://web.site.com/default.aspx", params) > data = urllib2.urlopen(req) Try: data = urllib.urlopen("https://web.site.com/default.aspx", param) Thierry Tom Grove wrote: > I am trying to login to a secure website and I am having some difficulty > understanding the process. Here is what I have with my limited > knowledge of the subject: > > ##Start Code## > #!/usr/bin/env > python > > > > import > urllib > > import > urllib2 > > > > # > Main > > params = > urllib.urlencode({ > > "user" : > "username", > > "pass" : > "password" > > }) > > > > req = urllib2.Request("https://web.site.com/default.aspx", > params) > data = > urllib2.urlopen(req) > > > > for line in > data.readlines(): > > print line > ##End Code## > > This just doesn't seem to work. It just brings me back to a login screen. > > If you can lend a hand it would be much appreciated. > > -Tom From hg at nospam.com Wed Aug 30 13:40:24 2006 From: hg at nospam.com (hg) Date: Wed, 30 Aug 2006 12:40:24 -0500 Subject: active python windows In-Reply-To: References: Message-ID: squall_leonheart7 at netzero.net wrote: > When I test my program the graphics window opens over the top of the > command line, but for some odd reason the command line remains the > active window, so I have to click on the grphics window to make it the > active window. I was just curious as to why this might be happening and > if it was possible to change it. > > > _____________________________________________________________________ > PrivatePhone - FREE telephone number & voicemail. > A number so private, you can make it public. > http://www.privatephone.com > > What GUI Lib ? What O/S hg From kay.schluehr at gmx.net Thu Aug 31 15:14:22 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 31 Aug 2006 12:14:22 -0700 Subject: python loops In-Reply-To: <1157050085.120921.31840@h48g2000cwc.googlegroups.com> References: <1157050085.120921.31840@h48g2000cwc.googlegroups.com> Message-ID: <1157051662.297120.30560@m73g2000cwd.googlegroups.com> Putty wrote: > In C and C++ and Java, the 'for' statement is a shortcut to make very > concise loops. In python, 'for' iterates over elements in a sequence. > Is there a way to do this in python that's more concise than 'while'? > > C: > for(i=0; i > > python: > while i < length: > i += 1 As AlbaClause had demonstrated you can iterate over indices as well using the for-statement and the range() function. But you can also combine iterating over elements and indices at the same time using the builtin enumerate() type: for i, item in enumerate(("s1","s2")): print i,item 0 s1 1 s2 From brojohan at hotmail.com Fri Aug 18 17:18:42 2006 From: brojohan at hotmail.com (Bror Johansson) Date: Fri, 18 Aug 2006 23:18:42 +0200 Subject: Python for EXIF-info-additions ? Message-ID: <4kmp5jFctg9cU1@individual.net> Is there somewhere some Python-module that can be used for adding EXIF-info to JPEG files? (Modules for extraction of EXIF-data are easily found, but lacks - as I see it - capacity to add new tags.) /BJ From cemerick at snowtide.com Wed Aug 23 12:54:07 2006 From: cemerick at snowtide.com (Chas Emerick) Date: Wed, 23 Aug 2006 12:54:07 -0400 Subject: Python + Java Integration In-Reply-To: References: Message-ID: On Aug 23, 2006, at 12:30 PM, Diez wrote: > - ruby has no notion of java-library support. So if anything lures > java > developers from J2EE-land to rails, its the framework itself. > Which, by my > standards, is at least met if not excelled by TurboGears and > Django. So > it's marketing, but of a different kind, we need. People move in crowds, and although the initial draw to Ruby was Rails, that translated into "Ruby is the next Java", which is a force to be reckoned with in and of itself. I think the fact that Ruby doesn't have a Java library migration path is exactly why JPype is a great opportunity for Python. Django and TG will not (regardless of their technical merits) catch up to Rails in terms of broader mindshare for years, if ever. Having them (and pylons! :-) is obviously fantastic, but opening up a new front of comparison where Python is the obvious choice is where Python can score points, rather than try to catch up. > - jython, after a period of seemingly inactivity, makes huge progress > towards python2.2 and python2.3. Which will open up new > possibilities just > the other way round: use existing, powerful python libraries > written in > post-2.1 from jython, neatly integrating java and python. Now there is > jRuby trying to do the same for ruby - but I never heard of it before > (googled it for this post), so it seems not to be as important as > jython > certainly is You bet, Jython is a great concept, and it's another arrow in Python quiver. I don't think it comes close to nullifying JPype's potential to help Python's stature with Java developers, though -- it's orthogonal to JPype, and therefore complimentary. Chas Emerick Founder, Snowtide Informatics Systems Enterprise-class PDF content extraction cemerick at snowtide.com http://snowtide.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From atbusbook at aol.com Fri Aug 25 15:33:58 2006 From: atbusbook at aol.com (atbusbook at aol.com) Date: 25 Aug 2006 12:33:58 -0700 Subject: Duck typing alows true polymorfisim In-Reply-To: <1156534086.698353.81850@m73g2000cwd.googlegroups.com> References: <1156532721.879808.40990@i3g2000cwc.googlegroups.com> <1156534086.698353.81850@m73g2000cwd.googlegroups.com> Message-ID: <1156534438.410656.213990@74g2000cwt.googlegroups.com> What was i thinkinng repace * with + i was'nt thinking i origanaly thaught of sum of squares so i put a * insted of a + From sjmachin at lexicon.net Fri Aug 11 06:17:07 2006 From: sjmachin at lexicon.net (John Machin) Date: 11 Aug 2006 03:17:07 -0700 Subject: Reading unformatted big-endian files References: Message-ID: <1155291427.774028.300310@m79g2000cwm.googlegroups.com> Andrea Gavana wrote: > "err=8" means that, if an error occours in > reading the file, > it should go to the label "8 continue" and continue reading the file Silently ignoring errors when reading a file doesn't sound like a good idea to me at all, especially if different records have different formats. > > Well, does anyone have some suggestion about which kind of > material/tutorial on similar things I should read? How can I deal in > Python with variables that must be 8-chars or 4-chars in order to read > correctly the file? (a) read the docs on the struct module (b) eyeball this rough untested translation: 8<--- def filereader(filename): import struct f = open(fname, 'rb') # 'rb' is read binary, very similar to C stdio fmt = '>8si4s' # Assuming unformatted means binary, # and integer means integer*4, which is signed. # Also assuming that the 3-variable records are fixed-length. fmtsz = struct.calcsize(fmt) while True: buff = f.read(fmtsz) if not buff: # EOF break keyword, number, keytype = struct.unpack(fmt) keyword = keyword.rstrip() # remove trailing spaces keytype = keytype.rstrip() if keyword == 'DIMENS': # 'dimens' is neither declared nor initialised in the FORTRAN # so I'm just guessing here ... buff2 = f.read(4) dimens = struct.unpack('>i', buff2) break print keyword, number, keytype # or whatever # reached end of file (dimens *NOT* defined), # or gave up (dimens should have a value) f.close() # not absolutely necessary especially when only reading if __name__ == "__main__": import sys filereader(sys.argv[1]) 8<--- If this doesn't work, and it's not obvious how to fix it, it might be a good idea when you ask again if you were to supply a FORTRAN-independent layout of the file, and/or a dump of a short test file that includes the DIMENS/dimens caper -- you can get such a dump readily with the *x od command or failing that, use Python: #>>>repr(open('thetestfile', 'rb').read(100)) # yes, I said *short* HTH, John From justin.azoff at gmail.com Sun Aug 6 13:41:34 2006 From: justin.azoff at gmail.com (Justin Azoff) Date: 6 Aug 2006 10:41:34 -0700 Subject: Why do I require an "elif" statement here? In-Reply-To: <1154882081.470315.279350@h48g2000cwc.googlegroups.com> References: <1154712731.375032.203570@m79g2000cwm.googlegroups.com> <1154812783.619385.293820@n13g2000cwa.googlegroups.com> <1154824177.621769.311390@m73g2000cwd.googlegroups.com> <1154882081.470315.279350@h48g2000cwc.googlegroups.com> Message-ID: <1154886094.645371.248550@b28g2000cwb.googlegroups.com> danielx wrote: > I'm surprised no one has mentioned neat-er, more pythonic ways of doing > this. I'm also surprised no one mentioned regular expressions. Regular > expressions are really powerful for searching and manipulating text. [snip] I'm surprised you don't count my post as a neat and pythonic way of doing this. I'm also surprised that you mention regular expressions after neat and pythonic. While regular expressions often serve a purpose, they are rarely neat. > Anyway, here's my solution, which does Not use regular expressions: > > def reindent(line): > ## we use slicing, because we don't know how long line is > head = line[:OLD_INDENT] > tail = line[OLD_INDENT:] > ## if line starts with Exactly so many spaces... > if head == whitespace*OLD_INDENT and not tail.startswith(' '): > return whitespace*NEW_INDENT + tail > else: return line # our default [snip] This function is broken. Not only does it still rely on global variables to work, it does not actually reindent lines correctly. Your function only changes lines that start with exactly OLD_INDENT spaces, ignoring any lines that start with a multiple of OLD_INDENT. -- - Justin From timgerr at gmail.com Sat Aug 19 22:43:16 2006 From: timgerr at gmail.com (timgerr at gmail.com) Date: 19 Aug 2006 19:43:16 -0700 Subject: Search or compai problem In-Reply-To: References: <1155941745.802556.299470@m73g2000cwd.googlegroups.com> <1155960973.701182.36060@i42g2000cwa.googlegroups.com> Message-ID: <1156041796.382722.19000@b28g2000cwb.googlegroups.com> Gabriel Genellina wrote: > At Saturday 19/8/2006 01:16, timgerr at gmail.com wrote: > > >it is really lstusers (it is an L not a # 1), Some of the output from > >print lstUsers has the output of None. I and trying to filter the None > >out of the list. I come from a perl background and this is how I do > >thing in perl > > None is a unique object used as "nothing" or "no value". > Try reading the Python tutorial, it's easy and you will learn a lot of things. > > > Gabriel Genellina > Softlab SRL > > > > > Thanks, I did not know that. Then I should look for a null value? Tim From bdesth.quelquechose at free.quelquepart.fr Mon Aug 28 16:47:32 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 28 Aug 2006 22:47:32 +0200 Subject: Python web service ... In-Reply-To: <1156590455.555359.247410@h48g2000cwc.googlegroups.com> References: <1156590455.555359.247410@h48g2000cwc.googlegroups.com> Message-ID: <44f353a8$0$5210$626a54ce@news.free.fr> nicolasg at gmail.com a ?crit : > Hi folks, I have accomplished to make a python program that make some > image manipulation to bmp files. > I now want to provide this program as a web service. A user can visit a > site and through a web interface he should upload the file to the web > server , the server then will do the image process with the python > program I have wrote and when it finish the user must get the image > file back . > > My question is how difficult is to set up a web server that can run > python easy ? should I try ZOPE or there is something better in mind ? Unless you have other compelling reasons to use Zope, you would be better IMHO with either CGI, apache+mod_python, or a standalone Python web server like CherryPy. From johnjsal at NOSPAMgmail.com Fri Aug 18 10:25:51 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 18 Aug 2006 14:25:51 GMT Subject: sqlite3 or mysqldb? In-Reply-To: <1155828940.134549.147780@75g2000cwc.googlegroups.com> References: <1155828940.134549.147780@75g2000cwc.googlegroups.com> Message-ID: Paul Boddie wrote: > There's plenty of scope for writing non-standard SQL even in the most > common operations. Moreover, defining tables can be awkward because the > set of supported data types and the names used can vary in a seemingly > unnecessary fashion between systems. Good point. I forgot that sqlite doesn't have as strict of data typing as mysql, so that might cause some problems as well. Oh well, basically I'm just looking for something to learn from, so it's still probably better to go with a simpler one that I will still be able to apply to the more complex ones if needed. From jaywgraves at gmail.com Thu Aug 10 16:15:09 2006 From: jaywgraves at gmail.com (jay graves) Date: 10 Aug 2006 13:15:09 -0700 Subject: "running" code on client side with cherrypy? References: <1155239338.574898.193520@m79g2000cwm.googlegroups.com> Message-ID: <1155240909.620857.233020@b28g2000cwb.googlegroups.com> Mr BigSmoke wrote: > Hi All, > I'm developing a website to handle some code/application version > control on a intranet. I'm using cherrypy and pysvn. Everything runs > quite good but i want the user to be able to checkout some projects > from the server. The user(on the client side) selects a folder in his > machine (i.e.: C:\Project1) and the server should checkout > (download/copy) all the project selected to the client machine. But > what happens is that the webserver shckout the project on the same > folder selected by the user but at server side. Everything works if > the user gives a network path (like \\pcname\sharedFolder). Any hint? The folder is created on the server because that is where the CherryPy code is running. It's not running on the client. Security concerns dictate that this will never work the way you want. It's a fundamental restriction of the web. How would the user feel if they accidentally selected 'C:\windows\' as the download path and their computer got messed up? ;-) Or more likely, a spyware website could download a trojan to your computer when you thought your were downloading a movie. When this kind of thing happens today it's considered an exploit. The reason that the UNC path works is that you are on an intranet and the target PC has a shared folder. If you are actually signed on the the web server and you open a CMD prompt you could key an equivalent copy command and it would work. CherryPy is just doing the same thing. But if your CheryPy app was exposed to the internet and I was running it and asked to save the code to \\jgraves\share it would not work because your intranet does not have a machine named 'jgraves' (presumably). I think the best that you could do would be to give a link to a zip file and let the user choose the path they want to unzip to once they have downloaded the file. As for working with SVN, I really like TortoiseSVN but you would have to install it on all machines which is what you are trying to avoid (I think.) Sorry to be the bearer of bad news. ... jay graves From steve at REMOVEME.cybersource.com.au Fri Aug 25 00:13:48 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Fri, 25 Aug 2006 14:13:48 +1000 Subject: how do you get the name of a dictionary? References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> <1156264475.968894.221710@p79g2000cwp.googlegroups.com> <1156266720.205126.284050@i3g2000cwc.googlegroups.com> Message-ID: On Wed, 23 Aug 2006 12:16:45 +0200, Fredrik Lundh wrote: > Steven D'Aprano wrote: > >> Here's a traceback. One of the arguments to spam() is too small. Can you >> tell which one just by looking at the traceback? >> >>>>> a, b, c, d = range(4) >>>>> spam(a, b, c, d) >> Traceback (most recent call last): >> File "", line 1, in ? >> File "", line 6, in spam >> File "", line 5, in eggs >> File "", line 4, in beans >> ValueError: x is too small >> >> Of course you can't. x could be any one of a, b, c or d, and the traceback >> doesn't give you enough information to tell which. > > for some reason, your example gives a different error on my machine: > > StrawManError: Attempt to construct Reductio ad absurdum argument failed Sheesh Fredrik, what's eating you? I'm trying to have a civil discussion, and you're being deliberately obtuse. If I'm factually wrong, if I've made an error of fact or logic, and somebody points out where the error lies, I will accept that. I am always willing to learn. But making fatuous, and false, accusations of strawman and reductio ad absurdum fallacies doesn't invalidate my point that there are occasions where the traceback refers to a object with one name, but the object was created in a different scope with a different name. I'm not making an extraordinary claim here -- what I said should be so obvious it verges on the banal. The traceback reports the name of the object in the scope the error occurred in. The line of code responsible for putting the wrong data into that object can occur in a different scope, with a different name. Is that really so hard to grasp? I don't know what more I can do to get through to you that I *don't* expect Python's object model to change to fix this one single issue. I've said it AT LEAST twice times so far: such a change would be a lot of cost for very minimal benefit. But after the undeserved roasting that Jojoba received, it is only right to that we recognise that there are valid cases for objects to know their own name -- even if, in the majority of cases, those valid uses aren't worth the cost of implementing them. -- Steven D'Aprano From riko at despammed.com Wed Aug 23 02:52:53 2006 From: riko at despammed.com (Mc Osten) Date: Wed, 23 Aug 2006 08:52:53 +0200 Subject: Python and STL efficiency References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <1hkh28d.xscw4v1y4v9a6N%riko@despammed.com> <1hkh6lb.6dsnh51lj8z96N%riko@despammed.com> <1156252193.524186.107520@b28g2000cwb.googlegroups.com> <1156299389.336939.211670@i42g2000cwa.googlegroups.com> Message-ID: <1hkildy.73vcuzyxlsgeN%riko@despammed.com> wrote: > That's to say, > python is still much faster? Yes it is. But of course you can't sat that "Python is faster than C++". We found that the code to do this, written in the most natural way, is a lot faster in Python. However, if you optimze the code, C++ gets almost as fast. In other benchmarks C++ outperforms Python and is 10 or 100 times faster. > Maybe someone can post this to the c++ maillist and they will tell how > to accelerate it. There are enough C++ experts here to do it. The point is another. -- blog: http://www.akropolix.net/rik0/blogs | Uccidete i filosofi, site: http://www.akropolix.net/rik0/ | tenetevi riso e forum: http://www.akropolix.net/forum/ | bacchette per voi. From sjmachin at lexicon.net Tue Aug 1 23:55:09 2006 From: sjmachin at lexicon.net (John Machin) Date: 1 Aug 2006 20:55:09 -0700 Subject: BCD List to HEX List In-Reply-To: <1154486431.531771.261730@s13g2000cwa.googlegroups.com> References: <5S8zg.1553$W93.658@dukeread05> <1154296114.094452.158000@p79g2000cwp.googlegroups.com> <1154298390.280625.206560@75g2000cwc.googlegroups.com> <1154299830.987261.9800@b28g2000cwb.googlegroups.com> <1154301233.360818.93450@s13g2000cwa.googlegroups.com> <0abzg.1576$W93.173@dukeread05> <1154361998.861851.157210@h48g2000cwc.googlegroups.com> <1154375956.397032.166310@p79g2000cwp.googlegroups.com> <1154411021.642620.255750@s13g2000cwa.googlegroups.com> <1154412245.996874.199260@h48g2000cwc.googlegroups.com> <1154446262.681764.73100@75g2000cwc.googlegroups.com> <1154472559.132312.12550@75g2000cwc.googlegroups.com> <1154486431.531771.261730@s13g2000cwa.googlegroups.com> Message-ID: <1154490909.292197.129530@m73g2000cwd.googlegroups.com> bryanjugglercryptographer at yahoo.com wrote: > John Machin wrote: > > bryanjugglercryptographer at yahoo.com wrote: > > > > >My version assumes three subroutines: extracting > > > nibbles, shifting, and adding, Those are pretty simple, so I asked > > > if he needed them rather than presenting them. > > > Assuming we have > > > them, the algorithm is three lines long. > > > > Perhaps you could enlighten us by publishing (a) the spec for each of > > the get_nibble(s), shift, and add subroutines (b) the three-line > > algorithm (c) what the algorithm is intended to achieve ... > > "For each nibble n of x" means to take each 4 bit piece of the BCD > integer as a value from zero to sixteen (though only 0 through 9 > will appear), from most significant to least significant. The OP's input, unvaryingly through the whole thread, even surviving to his Javacard implementation of add() etc, is a list/array of decimal digits (0 <= value <= 9). Extracting a nibble is so simple that mentioning a "subroutine" might make the gentle reader wonder whether there was something deeper that they had missed. > "Adding" > integers and "shifting" binary integers is well-defined > terminology. Yes, but it's the *representation* of those integers that's been the problem throughout. > I already posted the three-line algorithm. It > appeared immediately under the phrase "To turn BCD x to binary > integer y," and that is what it is intended to achieve. Oh, that "algorithm". The good ol' num = num * base + digit is an "algorithm"??? The problem with that is that the OP has always maintained that he has no facility for handling a binary integer ("num") longer than 16 bits -- no 32-bit long, no bignum package that didn't need "long", ... > > > > He took a while to state the problem, but was clear from the start > > > that he had lists of digits rather than an integer datatype. > > > > Yes, input was a list [prototyping a byte array] of decimal digits. The > > OUTPUT was also a list of something. A few messages later, it became > > clear that the output desired was a list of hexadecimal digits. Until > > he revealed that the input was up to 24 decimal digits, I was pursuing > > the notion that a solution involving converting decimal to binary (in a > > 32-bit long) then to hexadecimal was the way to go. > > > > What is apparently needed is an algorithm for converting a "large" > > number from a representation of one base-10 digit per storage unit to > > one of a base-16 digit per storage unit, when the size of the number > > exceeds the size (8, 16, 32, etc bits) of the "registers" available. > > I read his "Yes I realized that after writing it." response to > Dennis Lee Bieber to mean Bieber was correct and what he wanted > was to go from BCD to a normal binary integer, which is base 256. Where I come from, a "normal binary integer" is base 2. It can be broken up into chunks of any size greater than 1 bit, but practically according to the wordsize of the CPU: 8, 16, 32, 64, ... bits. Since when is base 256 "normal" and in what sense of normal? The OP maintained the line that he has no facility for handling a base-256 number longer than 2 base-256 digits. The dialogue between Dennis and the OP wasn't the epitome of clarity: [OP] My apologies, I clearly made a mistake with my calculator, yes the resulting array I would need is [0xb,0xc,0x6,0x1,0x4,0xe] [Dennis] Take note that this[**1**] is NOT a BCD form for "12345678". BCD (typically packed) uses four bits per decimal digit. That would make "12345678" => 0x12, 0x34, 0x56, 0x78 (ignoring matters of big/little end). The binary representation of 12345678, in bytes, is 0xBC, 0x61, 0x4E 0xb, 0xc... is really 0x0B, 0x0C... 8-bits per byte, with MSB set to 0000. Compare: BCD 00010010 00110100 01010110 01111000 binary 10111100 01100001 01001110 your 00001011 00001100 00000110 00000001 00000100 00001110 [OP] Yes I realized that [**2**] after writing it. ... [**1**] Dennis's "this" refers to the OP's *output* which is patently not what the OP was calling BCD. [**2**] The referent of the OP's "that" can't be determined unambiguously, IMHO. > The point of posting the simple high-level version of the > algorithm was to show a general form that works regardless of > particular languages, register sizes and storage considerations. > Those matters can effect the details of how one shifts a binary > integer left one bit, but shifting is not complicated in any > plausible case. > > > Is that what you have? > > I'm sorry my post so confused, and possibly offended you. It didn't confuse me. I was merely wondering whether you did in fact have a method of converting from base b1 (e.g. 10) to base b2 (e.g. 16) without assembling the number in some much larger base b3 (e.g. 256). Offended? Experts have tried repeatedly, and not succeeded :-) Cheers, John From dylanhughes at gmail.com Wed Aug 23 20:11:15 2006 From: dylanhughes at gmail.com (DH) Date: 23 Aug 2006 17:11:15 -0700 Subject: Taking data from a text file to parse html page Message-ID: <1156378275.662140.214650@h48g2000cwc.googlegroups.com> Hi, I'm trying to strip the html and other useless junk from a html page.. Id like to create something like an automated text editor, where it takes the keywords from a txt file and removes them from the html page (replace the words in the html page with blank space) I'm new to python and could use a little push in the right direction, any ideas on how to implement this? Thanks! From gelists at gmail.com Mon Aug 14 20:31:06 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Mon, 14 Aug 2006 21:31:06 -0300 Subject: hide python code ! References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155300852.497741.73230@74g2000cwt.googlegroups.com> <1155301468.870340.82920@b28g2000cwb.googlegroups.com> <1155307415.855555.124760@i3g2000cwc.googlegroups.com> <1155309563.898182.195950@p79g2000cwp.googlegroups.com> <1155313092.743230.33950@m73g2000cwd.googlegroups.com> <44e10b95$0$15787$14726298@news.sunsite.dk> Message-ID: <6wc7gvt9v1bd$.dlg@gelists.gmail.com> On 2006-08-14 20:48:45, Damjan wrote: > I think you increase your chances of Microsoft not even being in the same > room with your software 100-fold if you release it under.. say GPL. ... and have the money to run a law suit? Patents, licenses etc are only as strong as the money that backs them, mostly. Gerhard From larry.bates at websafe.com Thu Aug 17 15:51:10 2006 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 17 Aug 2006 14:51:10 -0500 Subject: Dynamic objects In-Reply-To: <1155841453.166739.75210@b28g2000cwb.googlegroups.com> References: <1155841453.166739.75210@b28g2000cwb.googlegroups.com> Message-ID: <44E4C8AE.8000708@websafe.com> Mark Shewfelt wrote: > Hello, > > I have implemented a series of classes representing a Building, its > respective Equipment, and then various Components of that equipment > like so (as you'll be able to tell, I'm a newbie): > > class Building: > equipment = {} > def AddEquipment( name, data ): > equipment[ name ] = Equipment( data ) > > class Equipment: > components = {} > def AddComponent( name, data ): > components[ name ] = Component( data ) > > class Component: > data = "" > > These classes are used like so: > > test = Building() > test.AddEquipment( "equipment 1", data ) > test.AddEquipment( "equipment 2", data ) > test.equipment["equipment 1"].AddComponent( "component 1", data ) > test.equipment["equipment 1"].AddComponent( "component 2", data ) > test.equipment["equipment 2"].AddComponent( "component 3", data ) > > But it appears as though the instance of "equipment 1" has ALL of the > components in its components dictionary. I was hoping that the > test.equipment["equipment 1"].components dictionary would only have > those components that were assigned to "equipment 1". > > I have implemented __init__ functions for all of the classes, but all > they do is initialize some data that I haven't shown here. > > I think I'm trying to use a C++ way of doing this (without the new > operator) so if anyone would be so kind as to help with the Python way > of doing this sort of thing I will be eternally grateful. > > Cheers, > > Mark Shewfelt > With the way you defined Building multiple buildings would share equipment dictionary as it is defined as a class variable and you want an instance variable (I'm pretty sure). You probably wanted (not tested): class Building: def __init__(self): self.equipment = {} def AddEquipment(name, data): equipment[name]=Equipment(data) same for Equipment class and Component class. class Equipment: def __init__(self): self.components={} def AddComponent(name, data): components[name]=Component(data) class Component: def __init__(self, data) self.data=data -Larry Bates From rogue_pedro at yahoo.com Wed Aug 16 03:42:15 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 16 Aug 2006 00:42:15 -0700 Subject: round not rounding to 0 places References: <1155712764.516132.251800@m73g2000cwd.googlegroups.com> Message-ID: <1155714135.418714.56200@i42g2000cwa.googlegroups.com> Fuzzydave wrote: > I have been using a round command in a few places to round > a value to zero decimal places using the following format, > > round('+value+', 0) > > but this consistantly returns the rounded result of the value > to one decimal place with a zero > > EG: > > 4.97 is returned as 5.0 when i want it returned as 5, does > anyone know why this is and if i can get the round to make > the value 5? > > David P |>> n = 4.97 |>> round(n) 5.0 |>> int(round(n)) 5 |>> help(round) Help on built-in function round in module __builtin__: round(...) round(number[, ndigits]) -> floating point number Round a number to a given precision in decimal digits (default 0 digits). This always returns a floating point number. Precision may be negative. HTH, ~Simon BTW, '+value+' ..? Huh? From gagsl-py at yahoo.com.ar Thu Aug 24 12:40:57 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 24 Aug 2006 13:40:57 -0300 Subject: sum and strings In-Reply-To: <44EDCFDE.9060604@tim.thechases.com> References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <1155922208.930580.135080@m79g2000cwm.googlegroups.com> <1156365271.487489.62640@m73g2000cwd.googlegroups.com> <44ECC789.1010202@tim.thechases.com> <44EDCFDE.9060604@tim.thechases.com> Message-ID: <7.0.1.0.0.20060824132656.050af940@yahoo.com.ar> At Thursday 24/8/2006 13:12, Tim Chase wrote: >The interpreter is clearly smart enough to recognize when the >condition occurs such that it can throw the error...thus, why not >add a few more smarts and have it simply translate it into >"start+''.join(sequence)" to maintain predictable behavior >according to duck-typing? sequences don't have to be homogeneous, and iterators cant go back. But let GvR say that in his own words: http://mail.python.org/pipermail/python-dev/2003-April/034854.html Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From daniel.huangfei at gmail.com Tue Aug 15 04:04:46 2006 From: daniel.huangfei at gmail.com (daniel) Date: 15 Aug 2006 01:04:46 -0700 Subject: what is the keyword "is" for? In-Reply-To: <44e16d6a$1@nntp0.pdx.net> References: <1155625097.784052.31330@p79g2000cwp.googlegroups.com> <44e16d6a$1@nntp0.pdx.net> Message-ID: <1155629086.617707.132900@b28g2000cwb.googlegroups.com> many thanks to Sybren and Kirk for your helpful explanation. when I tried to check the stuff out, found sth interesting that if you define variables in a style like this: a = b = ['a', 'b'] changing one list affects the other, and they still refer to same object. in fact, seems all compound types (dictionary for instance) behave in this way. however, when list is replaced with other built-in types like integers : a = b = 3 changing one of them cause the two objects differ... best regards. daniel From fredrik at pythonware.com Tue Aug 15 17:38:29 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 15 Aug 2006 23:38:29 +0200 Subject: programming with Python 3000 in mind In-Reply-To: <1155677243.626081.188200@i42g2000cwa.googlegroups.com> References: <1155672987.522793.47080@74g2000cwt.googlegroups.com> <1155677243.626081.188200@i42g2000cwa.googlegroups.com> Message-ID: Andr? wrote: > When it comes to *teaching/learning* Python, it makes much more sense > to have print() as a function (same with exec) given what it does > -compared with the purpose of the other keywords. that's rubbish, of course, and seems to assume that python students, in general, are obsessed with hyper-generalization. they're not. From chef.ya at gmail.com Mon Aug 14 22:25:56 2006 From: chef.ya at gmail.com (Chef YA) Date: Tue, 15 Aug 2006 04:25:56 +0200 Subject: Redirecting output (Cherif YAYA) Message-ID: Hi, I'm writing a script and I need to use a tierce console application. I'd like to be able to redirect this application output to a wxPython frame. I know that wxPython can redirect standard output automatically to a default frame. However, I'd rather like to direct the output to a frame I have control on. Is there a way to that simply? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From ask at me Fri Aug 11 19:46:16 2006 From: ask at me (alf) Date: Fri, 11 Aug 2006 19:46:16 -0400 Subject: iterator wrapper In-Reply-To: <1155340917.733325.74780@i3g2000cwc.googlegroups.com> References: <8cednRaDbu_RkkDZnZ2dnUVZ_sKdnZ2d@comcast.com> <1155339879.395139.182050@m73g2000cwd.googlegroups.com> <1155340917.733325.74780@i3g2000cwc.googlegroups.com> Message-ID: Simon Forman wrote: >>>>>class LW(object): # ListWrapper >>... def __init__(self, i): >>... self.theiter = i >>... def next(self): >>... return [self.theiter.next()] I hoped one lamda would take care of it but looks like it is a simplest choice. > |>> I = ([n] for n in i) This is nice but I am iterating thru hude objects (like MBs) so you know ... Thx for responding ... A. From fredrik at pythonware.com Mon Aug 28 15:27:12 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 28 Aug 2006 21:27:12 +0200 Subject: How to store ASCII encoded python string? In-Reply-To: <1156792022.792854.90700@i42g2000cwa.googlegroups.com> References: <1156792022.792854.90700@i42g2000cwa.googlegroups.com> Message-ID: micahc at gmail.com wrote: > I currently have a Python program that reads in emails from a POP3 > server. As soon as the message is read in it is fed directly into a > PostgreSQL database for storage. Later, it is broken down into it's > parts and displayed to the user. > > My problem is that when I try to pass "\tsome text\xa7some more text\n" > into the database it gives me a unicode decode error. "\xa7" is not a valid ASCII character, so that's not really an "ASCII encoded" string. looks like your database expects Unicode strings, but you're passing in binary data. to solve this, you can: 1) change the database table to use a "blob" field instead of a text field or 2) configure the database interface to pass 8-bit strings through to the database engine (if possible; see the database interface documentation for details) or 3) convert the data to Unicode before passing it to the database interface, and leave it to the interface to convert it to whatever encoding your database uses: data = ... get encoded string from email ... text = data.decode("iso-8859-1") ... write text to database ... From caseyhHAMMER_TIME at istar.ca Thu Aug 3 02:18:56 2006 From: caseyhHAMMER_TIME at istar.ca (Casey Hawthorne) Date: Thu, 03 Aug 2006 06:18:56 GMT Subject: Can Your Programming Language Do This? Joel on functional programming and briefly on anonymous functions! Message-ID: Can Your Programming Language Do This? Joel on functional programming and briefly on anonymous functions! http://www.joelonsoftware.com/items/2006/08/01.html -- Regards, Casey From akameswaran at gmail.com Tue Aug 15 12:03:44 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 15 Aug 2006 09:03:44 -0700 Subject: Best IDE for Python In-Reply-To: References: <1155541849.350392.31190@h48g2000cwc.googlegroups.com> Message-ID: <1155657824.729616.161420@b28g2000cwb.googlegroups.com> I've had a similar experience and tried about everything. Personally - eclipse with PyDev has been the winner for me. I also still do a bunch of Java coding - so there is an added benefit of one tool across languages. The final thing I really like with eclipse is the svn plugins - making life very easy. Also, if your doing web/xml and other stuff - there is a plugin for eclipse for it ;) Not all the plugins work as seemlessly together (i abandon eclipse for the majority of plone/zope stuff - most of it isn't python - and setting up eclipse to be happy with the output of archgen has not been worth the bother - I'm sure it's possible) PyLint can kind of be a pain if your on a low powered box, but tweaking the settings (and I had to do a bit of tweaking) can alleviate the problems, but still let you reap the benefits. Anand Yu-Xi Lim wrote: > Michiel Sikma wrote: > > By FOS, do you mean FOSS (Free and Open Source Software)? I've never > > seen the acronym FOS used. > > Maybe he was trying for "Free Open Source IDE" without the > semi-redundant "Software" > > > I personally use Eclipse with PyDev. > > http://www.eclipse.org/ > > http://pydev.sourceforge.net/ > > Eclipse+PyDev has the advantage over emacs when it comes to big > projects, IMO. It has features like refactoring, better project > management, code coverage. emacs has the advantage of being faster and > smaller, and if all you need is a syntax-aware (smart indentation, > syntax highlighting) editor and integrated debugger, emacs is more than > enough. > > I've tried the other free IDEs like IDLE, SPE, eric3, TruStudio (for > Eclipse), Boa, Komodo, WingIDE. I have various issues with them, > including instability, poor automatic indentation, bad GUI (too many > subwindows or uncustomizable), costly, no refactoring, and no project > management. > > It's strangely ironic. I consider Eclipse to be a lousy Java IDE > especially compared to commercial offerings and yet that's what the > project started out as. From david_wahler at bic.ky Mon Aug 7 09:06:33 2006 From: david_wahler at bic.ky (david_wahler at bic.ky) Date: 7 Aug 2006 08:06:33 -0500 Subject: [ANN] rest2web 0.5.0 Beta 1 Released Message-ID: <20060807130633.16606.qmail@BICSRV1011.bic.ky> I'll be out of the office until approximately August 20th. If you have any questions, please email support at bic.ky. -- David Wahler From stk at mevis.de Thu Aug 10 01:20:55 2006 From: stk at mevis.de (Stephan Kuhagen) Date: Thu, 10 Aug 2006 07:20:55 +0200 Subject: #!/usr/bin/python or #!/usr/bin/env python? References: Message-ID: Erik Max Francis wrote: > The problem is that there are endless ways to do that, and figuring out > all the cases makes `file` an sh interpreter, not the magic number > detector it's supposed to be. It makes it into a pattern-matcher, not an interpreter. But that it is already. But right, there are endless ways to do that, but only one or a very small subset is common. The way I cited is the way mentioned in the Tclsh-manpage, so it can be (not must, but can) as the standard-header of a Tcl-Script on Unix-like systems. Even if the construct sometimes differs a little bit, "file" should be able to identify, since the manpage of "file" says, that it is not a pure magic-number-detector. The first part explains how the magic-number-thing works and then what is done, when that fails: "If a file does not match any of the entries in the magic file, it is examined to see if it seems to be a text file. [...] Once file has determined the character set used in a text-type file, it will attempt to determine in what language the file is written. The language tests look for particular strings (cf names.h) that can appear anywhere in the first few blocks of a file. For example, the keyword .br indicates that the file is most likely a troff(1) input file, just as the keyword struct indicates a C program. These tests are less reliable than the previous two groups, so they are performed last." This is not the most reliable way, as the man-page says, but it should work: if in the first some blocks you can find a statement with a continued comment-line and the exec-trick, "file" can at least guess, that it is a Tcl-file. So this would be a valid method to detect that files type, because a troff-file is a troff file, even when there is no .br in the first few blocks, but "file" tries to identify it anyway. "file" is not meant to be to ignore troff files, just because they are sometimes hard to detect. The same applies to Tcl-files, I think. Not perfectly reliable, but worth a try, since it is, according to the Tclsh-manpage, the common header-pattern for a Tcl-script. So "file" can not be perfect and reliable in every case, but it should try to take a good guess. If you do not care about the Tcl-headers (and why should you, this is comp.lang.python... ;-), you are right with your reasoning. But if you accept, that file can not be perfect anyway and want it to be as good as possible, then it is some kind of bug or missing feature in "file" that it recognizes (or tries to) some morphing file formats but not another (which is fairly wide spread, even if Tcl is not a modern buzz-word-language these days). Stephan From gagsl-py at yahoo.com.ar Wed Aug 23 14:28:55 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 23 Aug 2006 15:28:55 -0300 Subject: swapping numeric items in a list In-Reply-To: References: Message-ID: <7.0.1.0.0.20060823152758.03e17610@yahoo.com.ar> At Wednesday 23/8/2006 14:44, Jiang Nutao wrote: >array.byteswap() won't work for me easily. I tried this before my 1st post. >I defined > > aa = array('H', [0x12, 0x34, 0x56, 0x78]) > >Then did byteswap aa.byteswap(). The result was > > array('H', [0x1200, 0x3400, 0x5600, 0x7800]) > >You can see it byteswapped within each item. Use array('b') or 'B'. 'H' are two-byes integers. Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From shejo284 at gmail.com Thu Aug 24 05:14:20 2006 From: shejo284 at gmail.com (Sheldon) Date: 24 Aug 2006 02:14:20 -0700 Subject: Concatenating arrays Message-ID: <1156410860.815262.25770@i3g2000cwc.googlegroups.com> Good day everyone, I would like to know if anyone has a fast and concise way of concatenating two 2D arrays of same dimensions? Whenever I try: a = concatenate(b,c) I get erroneous data as if the axises were incorrectly chosen. As far as I can see concatenate((b,c),0) does it vertically while a 1 does it horizontally. But the results does not reflect this. What am I missing here? I am using Numeric. Any help is appreciated, Sheldon From g.brandl-nospam at gmx.net Fri Aug 18 17:36:56 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Fri, 18 Aug 2006 23:36:56 +0200 Subject: how do you get the name of a dictionary? In-Reply-To: <1155936774.578249.259290@74g2000cwt.googlegroups.com> References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <1155936774.578249.259290@74g2000cwt.googlegroups.com> Message-ID: Andy Terrel wrote: > Why bang your head? Because there's no chance that the original request is sane. If you want your objects to know their name, give them a name as an attribute. > It was a stupid hack that has lots of problems, > but done in a way that is readable. Sure I could do something more > functional or one lined like: > > Banana={} > names = filter(lambda x:id(eval(x))==id(Banana),dir()) > > but I am guessing that it is harder to read by many. Anywho I can > think of plenty of reasons it would fail, but it really depends on the > app. Georg From michiel at thingmajig.org Tue Aug 15 09:26:28 2006 From: michiel at thingmajig.org (Michiel Sikma) Date: Tue, 15 Aug 2006 15:26:28 +0200 Subject: Beginner Textbook In-Reply-To: <12e3i9gr0edeb74@corp.supernews.com> References: <12e3gkdhjngum6a@corp.supernews.com> <12e3i9gr0edeb74@corp.supernews.com> Message-ID: Op 15-aug-2006, om 15:16 heeft M_M het volgende geschreven: > Thanks - a very bright lot of 13 year olds- need the challenge! > -- > http://mail.python.org/mailman/listinfo/python-list I think that every 13 year old should be taught Python. It's an extremely intuitive language that can mean a lot to their understanding of the workings of computers. Or at least a whole lot more than just the basic Microsoft Word stuff... Actually, I might take back what I said earlier. I'm sure that they'll do just fine after a few lessons. I was able to make my 14 year old sister understand a C program that converts Fahrenheit to Celsius, afterall... :) Michiel From bborcic at gmail.com Wed Aug 9 09:26:12 2006 From: bborcic at gmail.com (Boris Borcic) Date: Wed, 09 Aug 2006 15:26:12 +0200 Subject: How to reverse tuples in a list? In-Reply-To: <1155081671.728757.228050@p79g2000cwp.googlegroups.com> References: <1155081671.728757.228050@p79g2000cwp.googlegroups.com> Message-ID: <44d9e298$1_2@news.bluewin.ch> Applying the perl motto (there is more than one way to do it) sure enough leads to a perlish solution... as measured by line noise. >>> t = [('a', 11,1.0), ('b',22,2.0),('c',33,3.0)] >>> zip(*zip(*t)[::-1]) [(1.0, 11, 'a'), (2.0, 22, 'b'), (3.0, 33, 'c')] From bayazee at gmail.com Fri Aug 11 21:09:41 2006 From: bayazee at gmail.com (Bayazee) Date: 11 Aug 2006 18:09:41 -0700 Subject: hide python code ! In-Reply-To: <1155307415.855555.124760@i3g2000cwc.googlegroups.com> References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155300852.497741.73230@74g2000cwt.googlegroups.com> <1155301468.870340.82920@b28g2000cwb.googlegroups.com> <1155307415.855555.124760@i3g2000cwc.googlegroups.com> Message-ID: <1155344981.894548.280730@m73g2000cwd.googlegroups.com> Hi, ThnaX for Your Answers ... i am an open source programmer ... ! and i never like to write a closed source app or hide my codes ! it just a question that i must answer/solve it! one of site ( www.python.ir ) users asked this question ! but unfortunately i have't any solution to it ! so i ask it here to know your concepts ... so sorry for my inferior question but i realy want to know a way to do it(if it possible) ! and it is't mean that i want to do it ! Best Regard's From fredrik at pythonware.com Fri Aug 25 08:52:18 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Aug 2006 14:52:18 +0200 Subject: performance of dictionary lookup vs. object attributes References: <7008329d0608250138m3207567elf3e32ee67cb5eb2a@mail.gmail.com> Message-ID: Andre Meyer wrote: > Is the test meaningful and are you surprised by the results? surprised by the amount of code you needed to test this, at least. and you might wish to use the proper spelling for v = self.obj.__getattribute__(a) which is v = getattr(obj, a) and is quite a bit faster, at least in CPython. (you should also use setattr() instead of __setattr__; in general, if you find your- self *calling* a method named __method__, there's most likely a better way to do it). > I am, actually, because I would have assumed that attribute access with an > object should be faster because lookup can be precompiled. huh? you're using a reflection API; there's no way the compiler can figure out in advance what you're going to pass to getattr(). From rogue_pedro at yahoo.com Sun Aug 20 21:50:00 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 20 Aug 2006 18:50:00 -0700 Subject: string validation/ form validation In-Reply-To: <1156122233.814935.144940@h48g2000cwc.googlegroups.com> References: <1156122233.814935.144940@h48g2000cwc.googlegroups.com> Message-ID: <1156125000.044308.77580@i42g2000cwa.googlegroups.com> OriginalBrownster wrote: > Hi there: > > I just had a quick thought of something that might be useful to me when > creating my web app and I wanted some help on the idea; since this > group has been helpful in the past. > > in my app I have a few html forms that require the user to enter in > data, in string form > > is it possible to validate if the string is in a valid form..such as > check if its a list > > An example > > ask the user to enter in a list seperated by commas > > so i want something like "apple,banana,grapes" > > is there a way to validate that it was entered that way? > > Any help would be appreciated Yes. Please read this: http://www.catb.org/~esr/faqs/smart-questions.html Peace, ~Simon From jarrod.roberson at gmail.com Wed Aug 9 16:05:03 2006 From: jarrod.roberson at gmail.com (fuzzylollipop) Date: 9 Aug 2006 13:05:03 -0700 Subject: Announcing Switch, the CSS Preprocessor! In-Reply-To: <1155149749.559985.177250@b28g2000cwb.googlegroups.com> References: <1155149749.559985.177250@b28g2000cwb.googlegroups.com> Message-ID: <1155153903.774783.179440@m73g2000cwd.googlegroups.com> Dave wrote: > Powered by Mod_Python, Switch CSS is a full featured, production ready > > The sourceforge project link follows. We could really use some tire > kickers... This group was invaluable in the early development process, > so we're announcing it officially here, and on mod_python first. > > https://sourceforge.net/projects/switchcss/ > > Thanks, > Dave Worley Is there any documentation or anything available? The sourceforge home page is empty? From johnjsal at NOSPAMgmail.com Mon Aug 7 21:03:39 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 07 Aug 2006 21:03:39 -0400 Subject: using python at the bash shell? Message-ID: <44d7e364$0$24980$c3e8da3@news.astraweb.com> Hi all. I just installed Ubuntu and I'm learning how to use the bash shell. Aside from the normal commands you can use, I was wondering if it's possible to use Python from the terminal instead of the normal bash commands (e.g. print instead of echo). My main reason for asking is that I like using Python for everything, and if I don't need to learn the bash 'language', then I won't just yet. Thanks. From onurb at xiludom.gro Tue Aug 8 06:50:19 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 08 Aug 2006 12:50:19 +0200 Subject: Newbie - How to iterate list or scalar ? In-Reply-To: <1155030787.666942.277610@m79g2000cwm.googlegroups.com> References: <1155030787.666942.277610@m79g2000cwm.googlegroups.com> Message-ID: <44d86c6c$0$21149$7a628cd7@news.club-internet.fr> Andy Dingley wrote: > I seem to be writing the following fragment an awful lot, and I'm sure > it's not the best and Pythonic way to do things. Any advice on better > coding style? > > pluginVersionNeeded is a parameter passed into a method and it can > either be a simple scalar variable, or it can be a list of the same > variables. My problem is how to iterate it, whether it's a a list or > not. > > I can't simply throw it into the for...in loop -- if the scalar > variable were to be a string (which is considered to be atomic in my > application) then Python sees this string as iterable and iterates over > the characters in it! Yes, this is a common gotcha. Problem is that, as someone here noticed sometimes ago, what should be a scalar and what should be an iterable is often application or context dependent... And according to the context, string being iterable can be either a royal PITA or the RightThing(tm). > > versionsNeeded = pluginVersionNeeded > if isinstance( versionsNeeded, list): > versionsToTest = versionsNeeded > else: > versionsToTest = [ versionsNeeded ] > for versionNeeded in versionsToTest: > pass Too much names essentially refering to the same thing IMHO... this could be simplified to: if not isinstance(pluginVersionNeeded, list): pluginVersionNeeded = [pluginVersionNeeded] for versionNeeded in pluginVersionNeeded: pass The second problem here is that, given the above (I mean in your original snippet) use of versionsToTest, there's really no reason to assume it should be a list - any iterable could - and IMHO should - be accepted... expect of course for strings (royal PITA case, duh). AS far as I'm concerned, I'd rather either: 1/ test versionsToTest against basestring (which is the parent class for both strings and unicode) and turn it into a list if needed if isinstance( pluginVersionsNeeded, basestring): pluginVersionsNeeded = [pluginVersionsNeeded] for versionNeeded in pluginVersionsNeeded: pass The problem is that it limits 'scalars' to strings (and unicodes), and will fail with say ints or floats etc... This could be handled with a tuple of 'to-be-considered-as-scalar' types: scalars = (basestring, int, float) if isinstance( pluginVersionsNeeded, scalars): pluginVersionsNeeded = [pluginVersionsNeeded] for versionNeeded in pluginVersionsNeeded: pass 2/ test for pluginVersionsNeeded.__iter__ (an attribute of most iterables except strings...): if not hasattr(pluginVersionsNeeded, '__iter__'): pluginVersionsNeeded = [pluginVersionsNeeded] for versionNeeded in pluginVersionsNeeded: pass It's probably the most general scheme, but won't work if you intend to consider tuples as scalars since tuples have the __iter__ attribute. Also, if this is a common pattern in your module, you perhaps want to abstract this out (example for both of the above solutions): 1/ def enumerateVersion(versions, scalars=(basestring, int, float)): if isinstance(versions, scalars): yield versions raise StopIteration # not required but clearer IMHO else: for version in versions: yield version NB : the default arg 'scalars' let you customize what is to be considered as a scalar... 2/ def enumerateVersion(versions): if hasattr(versions, '__iter__'): for version in versions: yield version raise StopIteration # not required but clearer IMHO else: yield versions and in the calling code: ... for versionNeeded in enumerateVersions(pluginVersionNeeded): do_whatever_with(versionNeeeded) ... HTH From tim.golden at viacom-outdoor.co.uk Wed Aug 30 10:03:50 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 30 Aug 2006 15:03:50 +0100 Subject: How ahead are you guys in the (Python) real world? Message-ID: [John Salerno] | Interesting question. Just as a curious follow-up (not being | someone who works in the programming world), why does it take | so long to move to the latest version, especially when there | aren't (I don't think) any changes that would break existing | code, such as moving to Python 2.4 from 2.2 or 2.3? Well, one answer would be: because it's really quite hard to work out if there are, in fact, no changes which would break existing code. Obviously, if everything's nicely tied up with tests etc. it should be plain-sailing. But if it's not... On Windows, you need to make sure you have or can build newly-linked .pyds for all your non-Python extensions. And you may well find that those extensions have had version bumps you haven't tracked since you first installed them... and the available binaries may not match the version you were using. So back to those tests you haven't got. Repeat to fade... Ultimately, an amount depends on the time / resource someone is prepared to commit to an uprade, given that the thing's running fine now. After all, you can always run several Python versions in parallel -- albeit with a judicious use of shortcuts etc. -- if you have code which wants to make use of juicy new features? TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From diffuser78 at gmail.com Wed Aug 9 13:18:16 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 9 Aug 2006 10:18:16 -0700 Subject: paramter passing question References: <1154724382.726685.258220@i3g2000cwc.googlegroups.com> <44D3E33B.8040200@websafe.com> Message-ID: <1155143896.012669.278970@i3g2000cwc.googlegroups.com> It partly works but I get error printed out on the console. Traceback (most recent call last): File "NewProject.py", line 87, in OnEdit win = MyFrame4(self, -1, "",sim_name=sim_name) File "NewProject.py", line 1098, in __init__ wx.Frame.__init__(self, *args, **kwds) File "/usr/lib/python2.4/site-packages/wx-2.6-gtk2-unicode/wx/_windows.py", line 476, in __init__ newobj = _windows_.new_Frame(*args, **kwargs) TypeError: 'sim_name' is an invalid keyword argument for this function Larry Bates wrote: > diffuser78 at gmail.com wrote: > > I wrote a small app in wxPython using wxGlade as designer tool. wxGlade > > brings and writes a lot of code by itself and thats where my confusion > > started. Its about parameter passing. Here is my little confusion. > > > > ***************CODE BEGINS************************************ > > class MyFrame1(wx.Frame): > > def __init__(self, *args, **kwds): > > ..... > > ..... > > def OnEdit(self, event): > > sim_name = 'some_string' > > win = MyFrame2(self, -1, "") > > win.Show(True) > > ******************************************************************** > > > > class MyFrame2(wx.Frame): > > def __init__(self, *args, **kwds): > > ..... > > ..... > > def onLaunch(self, event): > > ## This function needs to use the parameter sim_name which is > > in class MyFrame1-->OnEdit > > ***************CODE ENDS************************************ > > > > I want to pass sim_name parameter to MyFrame2 in def OnEdit function > > but I don't know how to do it. I tried couple of things but always got > > some error. I have done some parameter passing in normal Python code > > but *args and **kwds is a little confusing. > > > > Could you please tell me how to send parameter "sim_name" from > > MyFrame1(in OnEdit function) and how to recieve it in MyFrame2 so that > > I can use that parameter in MyFrame2 namespace. > > > > Every help is appreciated. > > > > Thanks > > > How about using the keyword args to pass it: > > class MyFrame1(wx.Frame): > def __init__(self, *args, **kwds): > ..... > ..... > def OnEdit(self, event): > sim_name = 'some_string' > win = MyFrame2(self, -1, "", sim_name=sim_name) > win.Show(True) > ******************************************************************** > > class MyFrame2(wx.Frame): > def __init__(self, *args, **kwds): > ..... > ..... > self.sim_name=kwds.get('sim_name', 'default sim_name') > > def onLaunch(self, event): > ## This function needs to use the parameter sim_name which is > ## self.sim_name can be used here > > -Larry Bates From johnjsal at NOSPAMgmail.com Tue Aug 15 11:35:46 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 15 Aug 2006 15:35:46 GMT Subject: Beginner Textbook In-Reply-To: <12e3gkdhjngum6a@corp.supernews.com> References: <12e3gkdhjngum6a@corp.supernews.com> Message-ID: M_M wrote: > Hi, > > I am looking for a simple text book to introduce 13 to 18 year olds to > python programming. Suggestion? > > New to python. This might be good for your needs. It teaches the basics of computer science using Python: http://www.amazon.com/gp/product/1887902996/sr=8-1/qid=1155656105/ref=pd_bbs_1/104-2407734-1621520?ie=UTF8 From sjmachin at lexicon.net Sun Aug 13 22:58:30 2006 From: sjmachin at lexicon.net (John Machin) Date: 13 Aug 2006 19:58:30 -0700 Subject: outputting a command to the terminal? In-Reply-To: <44dfc1cb$0$2397$c3e8da3@news.astraweb.com> References: <44df99f7$0$25025$c3e8da3@news.astraweb.com> <44dfc1cb$0$2397$c3e8da3@news.astraweb.com> Message-ID: <1155524310.136763.241830@h48g2000cwc.googlegroups.com> John Salerno wrote: > > I think I'll take a look at the subprocess module, just for fun. :) ... and for learning too :-) Also, consider that some operating system commands are built into the shell (i.e. not run as a separate process), which makes using the subprocess module a bit difficult -- for more fun and learning, check out os.system() Cheers, John From fredrik at pythonware.com Wed Aug 23 15:03:48 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Aug 2006 21:03:48 +0200 Subject: running windows 'start' cmd using spawnl In-Reply-To: References: Message-ID: Tor Erik wrote: > I need to start a program in a new cmd-window. To do this I need to > execute: start [command] > With os.system this is straight-forward. > But I need to do it with spawnl and P_NOWAIT. I.e, asynchronously. > The problem is that I need to know the path where start resides, > which I'm unable to find. os.startfile(command) could work. From shuanyu at gmail.com Sat Aug 19 10:59:14 2006 From: shuanyu at gmail.com (many_years_after) Date: 19 Aug 2006 07:59:14 -0700 Subject: How to get the ascii code of Chinese characters? In-Reply-To: <1155990488.395220.178810@74g2000cwt.googlegroups.com> References: <1155986298.643983.157460@i3g2000cwc.googlegroups.com> <1155990488.395220.178810@74g2000cwt.googlegroups.com> Message-ID: <1155999554.486951.303480@i42g2000cwa.googlegroups.com> hi: what I want to do is just to make numbers as people input some Chinese character(hanzi,i mean).The same character will create the same number.So I think ascii code can do this very well. John Machin wrote: > many_years_after wrote: > > Hi,everyone: > > > > Have you any ideas? > > > > Say whatever you know about this. > > > > Perhaps you had better explain what you mean by "ascii code of Chinese > characters". Chinese characters ("hanzi") can be represented in many > ways on a computer, in Unicode as well as many different "legacy" > encodings, such as GB, GBK, big5, two different 4-digit telegraph > codes, etc etc. They can also be spelled out in "roman" letters with or > without tone indications (digits or "accents") in the pinyin system -- > is that what you mean by "ascii code"? > > Perhaps you might like to tell us what you want to do in Python with > hanzi and "ascii codes", so that we can give you a specific answer. > With examples, please -- like what are the "ascii codes" for the two > characters in the common greeting that comes across in toneless pinyin > as "ni hao"? > > Cheers, > John From casevh at comcast.net Thu Aug 3 14:03:27 2006 From: casevh at comcast.net (casevh at comcast.net) Date: 3 Aug 2006 11:03:27 -0700 Subject: Negative division bug? In-Reply-To: References: Message-ID: <1154628207.885970.315200@i42g2000cwa.googlegroups.com> > I was just screwing around. > and found: > >>> -1/100 > -1 > Shouldn't it be zero? > 1/100 returns 0 > but -1/ANY_POSITIVE_INTEGER_NUMBER > returns -1 > > >>> -10/3 > -4 > > It behaves correct for positive numbers, but for negative > integers it seems to subtract one from the expected result. > That is the intended behavior. Look at the output of divmod(). >>> divmod(-1,100) (-1,99) Let (q,r) = divmod(d, v) with v > 0, the behavior is chosen so that 0<= r < v. casevh From fakeaddress at nowhere.org Fri Aug 4 05:32:45 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 04 Aug 2006 09:32:45 GMT Subject: Windows vs. Linux In-Reply-To: References: <1154301694.445639.99580@m79g2000cwm.googlegroups.com> <44cddfb3$0$7761$7a628cd7@news.club-internet.fr> <1154531160.066733.71210@s13g2000cwa.googlegroups.com> <2NDAg.1122$FN2.341@newssvr14.news.prodigy.com> Message-ID: <1vEAg.1123$FN2.891@newssvr14.news.prodigy.com> Duncan Booth wrote: > Bryan Olson wrote: > >> Not quite. The first slash is ambiguous and apparently ignored, >> but latter slashes are taken as a path separators. > > I'm not sure ambiguity enters into it. I think perhaps the bad detection of > the option happens because the CD command can ignore spaces in its > argument. Since it is ignoring spaces they don't actually require a space > after the option strings. You lost me. Spaces are significant in file names, and slashes within the path are used as path separators, as far as I can tell. Try cd'ing several subdirectories deep on XP with forward slashes. It works for me, and it could not if slashes were ignored as you suggested. > Any other Microsoft commands I try all complain about 'invalid switch'. The first I noticed were their build tools. Their version of "make", called "nmake", and their visual studio tools will accept either forward or backward slashes in paths. >> Have you determined why it didn't work on your XP box as it did >> on mine and on the machines at BestBuy? > > Simply that I hadn't changed to the root directory first so there was no > subdirectory named 'windows'. Ah, my example showed a particular root: "C:\". Does your system work the same if you set the current directly as shown? -- --Bryan From steve at holdenweb.com Tue Aug 29 00:12:50 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 29 Aug 2006 05:12:50 +0100 Subject: M$ windows python libs installed in arbitrary directories forcustomized python distributions In-Reply-To: References: <44f31d35$0$17268$9b622d9e@news.freenet.de> Message-ID: alf wrote: > Martin v. L?wis wrote: > >>>it's spelled "Windows installers" >> >>I want to second this. It was me who created the installer, and I don't >>like to see my name abbreviated as M$ (if you think you should write >>out the name of the MSI creator, please say "Martin's installer" :-). > > > > ok, let me clarify, by M$ I meant Micro$oft. > I suspect that's the significance of the smiley. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From tim.golden at viacom-outdoor.co.uk Wed Aug 23 10:48:23 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: 23 Aug 2006 07:48:23 -0700 Subject: How can I enumerate all windows services and disable some of them? In-Reply-To: References: Message-ID: <1156344503.143057.52810@p79g2000cwp.googlegroups.com> Tim Golden wrote: > [Tim Golden] > > | [could.net at gmail.com] > | > | | I know that Module win32service has some functions on manipulating > | | win32 services. > | | But I still have 2 questions: > | | 1. how to enumerate all services? > | | 2. how to disable a certain one? > | > | You can use WMI to do this if you want. > (continues talking to self...) In fact you *can* do this with WMI. eg, to disable the Alerter service: import wmi c = wmi.WMI () for service in c.Win32_Service (Caption="Alerter"): service.Change (StartMode="Disabled") TJG From SPAMworFREEwor at bellsouth.net Tue Aug 15 07:51:11 2006 From: SPAMworFREEwor at bellsouth.net (Charles Russell) Date: Tue, 15 Aug 2006 11:51:11 GMT Subject: TypeError: 'module' object is not callable (newby question) In-Reply-To: References: Message-ID: Charles Russell wrote: I haven't found the magic word to invoke a > .py script from the python prompt (like the command "source" in csh, > bash, tcl?) Seems to be execfile() From betatim at gmail.com Sun Aug 6 10:39:21 2006 From: betatim at gmail.com (betatim at gmail.com) Date: 6 Aug 2006 07:39:21 -0700 Subject: subprocesses and deadlocks Message-ID: <1154875161.540968.275080@b28g2000cwb.googlegroups.com> Hi, there are many ways of solving the problem of finite buffer sizes when talking to a subprocess. I'd usually suggest using select() but today I was looking for a more readable/understandable way of doing this. Back in 1997 Guido himself posted a very nice solution, write your input to a temporary file and then read that from your new process. His posting can be found here: http://groups.google.com/group/comp.lang.python/tree/browse_frm/thread/2b31d990a8613d93/17d3dea9089aad00?rnum=1&q=subprocess+deadlock&_done=%2Fgroup%2Fcomp.lang.python%2Fbrowse_frm%2Fthread%2F2b31d990a8613d93%2F63b0a786d87ba23b%3Flnk%3Dgst%26q%3Dsubprocess+deadlock%26rnum%3D6%26#doc_63b0a786d87ba23b Being a bit puzzled over this usage of tempfile I read its documentation and as expected it says: [...] The file is created using mkstemp. It will be destroyed as soon as it is closed (including an implicit close when the object is garbage collected). [...] your code should not rely on a temporary file created using this function having or not having a visible name in the file system. so how was Guido planning to get the contents of the file after closing it? Should we do a tf.flush() instead of the close to ensure everything is written, then read from it, using subprocess.Popen(....,stdin=tf,..) and only close it afterwards? Is it correct to assume that a named temporary file will be (sometimes) accesible while it has not been closed yet? cheers, tim From python.list at tim.thechases.com Wed Aug 2 13:37:36 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 02 Aug 2006 12:37:36 -0500 Subject: Programming newbie coming from Ruby: a few Python questions In-Reply-To: <1154539223.873418.286830@i42g2000cwa.googlegroups.com> References: <1154494954.082706.283750@b28g2000cwb.googlegroups.com> <44d06f9f$0$19127$626a54ce@news.free.fr> <1154539223.873418.286830@i42g2000cwa.googlegroups.com> Message-ID: <44D0E2E0.7050206@tim.thechases.com> > The Ruby crowd says you guys are no where near as friendly as > them! I was half expecting a nervous breakdown after writing > my first post here. Maybe the Ruby folks have to be friendlier to make up for their language of choice... :*) The python mailing list is your pretty typical technical mailing list: if you do your own homework, state your problem clearly (with full error messages, actual data, not writing in AOL/133t-speak, etc), and have already tried searching the web/docs, then you'll find folks here are quite helpful. Not just helpful, but *fast* in their helpfulness too. -tkc From haraldarminmassa at gmail.com Tue Aug 15 09:46:30 2006 From: haraldarminmassa at gmail.com (GHUM) Date: 15 Aug 2006 06:46:30 -0700 Subject: Compiling wxPython app for Windows; Single EXE In-Reply-To: <1155573542.310208.43190@i3g2000cwc.googlegroups.com> References: <1155573542.310208.43190@i3g2000cwc.googlegroups.com> Message-ID: <1155649590.275349.245200@p79g2000cwp.googlegroups.com> Daniel, I am using py2exe since more then 4 years, so I am rather biased. I read PyInstaller page and was positively impressed by the manual and all the good words. There is one major difference which will keep me with py2exe: with PyInstaller and single file there is: "When first started, it finds that it needs to extract these files before it can run "for real"." and with py2exe: Changes in 0.6.1: * py2exe can now bundle binary extensions and dlls into the library-archive or the executable itself. This allows to finally build real single-file executables. The bundled dlls and pyds are loaded at runtime by some special code that emulates the Windows LoadLibrary function - they are never unpacked to the file system. this "they are never unpacked to the file system" is the USP of py2exe to me at the moment. What is less then optimal with both packages, is that MSVCR71.DLL needs to be distributed separately :( Harald From paddy3118 at netscape.net Sun Aug 27 09:14:14 2006 From: paddy3118 at netscape.net (Paddy) Date: 27 Aug 2006 06:14:14 -0700 Subject: avoiding file corruption In-Reply-To: <1156664673.325201.271140@i42g2000cwa.googlegroups.com> References: <1156664673.325201.271140@i42g2000cwa.googlegroups.com> Message-ID: <1156684454.673072.157900@75g2000cwc.googlegroups.com> Amir Michail wrote: > Hi, > > Trying to open a file for writing that is already open for writing > should result in an exception. > > It's all too easy to accidentally open a shelve for writing twice and > this can lead to hard to track down database corruption errors. > > Amir I've never done this in anger so feel free to mock (a little :-). I'd have a fixed field at the beginning of the field that can hold the hostname process number, and access time of a writing process, togeher with a sentinal value that means "no process has access to the file". A program would: 1. wait a random time. 2. open for update the file 3. read the locking data 4. If it is already being used by another process then goto 1. 5. write the process's locking data and time into the lock field. 6 Modify the files other fields. 7 write the sentinal value to the locking field. 8. Close and flush the file to disk. I have left what to do if a process has locked the file for too long as a simple exercise for you ;-). - Paddy. From ajones1 at gmail.com Tue Aug 29 13:55:23 2006 From: ajones1 at gmail.com (Adam Jones) Date: 29 Aug 2006 10:55:23 -0700 Subject: Pros/Cons of Turbogears/Rails? In-Reply-To: <44f4339f$0$4881$626a54ce@news.free.fr> References: <1156726071.579429.44650@b28g2000cwb.googlegroups.com> <1156740469.645955.52080@i3g2000cwc.googlegroups.com> <1156768355.275370.129680@h48g2000cwc.googlegroups.com> <1156819473.592153.141940@i42g2000cwa.googlegroups.com> <1156842974.103231.86930@m73g2000cwd.googlegroups.com> <1156848642.090479.159740@p79g2000cwp.googlegroups.com> <1156853533.101407.232680@b28g2000cwb.googlegroups.com> <44f4339f$0$4881$626a54ce@news.free.fr> Message-ID: <1156874123.322190.236440@b28g2000cwb.googlegroups.com> Bruno Desthuilliers wrote: > Paul Boddie wrote: > > Ray wrote: > (snip) > >> We're a Java shop so > >> our developers are trained in Java, Struts, Tomcat, etc. Any switch to > >> a dynamic language will be a huge change. However it baffles me that > >> they are open to at least a PoC in Rails. but when I suggested Python, > >> they went: "nah we're not interested in Python. Rails it is." > >> > >> *shrugs* whatever it is, those guys are doing something right. > > > > Making the Java people feel like they're doing something wrong, I > > guess. And perhaps the Rails people realised that by giving those > > people who lack direction, motivation, conviction or a sense of purpose > > or control something to gravitate towards, some of them might feel > > empowered enough to evangelise their discovery to the rest of the > > group. > > > > FWIW, and while it's certainly not enough by itself to explain the > phenomenon, I think that Ruby's object model being much more > conventional than Python's may have some influence too on RoR's adoption > by the Java world. I don't know enough about Ruby to comment, but how is its object model "more conventional" than Python's? The only thing I can see is access control for methods, which seems like a silly thing to base a language decision on. > > > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" From kylotan at gmail.com Tue Aug 15 12:00:16 2006 From: kylotan at gmail.com (Ben Sizer) Date: 15 Aug 2006 09:00:16 -0700 Subject: hide python code ! In-Reply-To: <1155570126.905733.137850@m79g2000cwm.googlegroups.com> References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155300852.497741.73230@74g2000cwt.googlegroups.com> <1155301468.870340.82920@b28g2000cwb.googlegroups.com> <1155307415.855555.124760@i3g2000cwc.googlegroups.com> <1155309563.898182.195950@p79g2000cwp.googlegroups.com> <1155313092.743230.33950@m73g2000cwd.googlegroups.com> <1155320948.142524.124990@p79g2000cwp.googlegroups.com> <1155564295.361980.279350@m73g2000cwd.googlegroups.com> <1155570126.905733.137850@m79g2000cwm.googlegroups.com> Message-ID: <1155657616.103285.40040@75g2000cwc.googlegroups.com> Paul Boddie wrote: > Successful software businesses are not merely founded on the process of > having ideas and implementing them - they might also need to be > effective at delivering those ideas and going through the whole process > again and again. Writing a neat utility for Windows is not by itself > the foundation of a successful business - other factors are critical, > whether they be continuous improvements, service, support, or a number > of other things. Yes, but this was never about 'successful software businesses' as such. I'm not saying anyone deserves to earn a living just because they created something, but that it is useful for them to be able to reduce the ways in which others with more resources can replicate that creation. You don't even need to be a 'successful' business to kill a competitor, just to have more money in the bank for as long as the competition exists. (eg. MS vs Netscape, Creative vs Aureal.) > So, if we decide to ignore people waving pieces of paper around which > make some claim to an idea or some way of solving some problem, instead > investigating the actual code, others have pointed out already that if > you provide just a binary and there exist people who want to know what > you've done, those people will find it out whether you make it easy for > them or not. Yes, in much the same way that there is no point ever locking your doors or installing burglar alarms, as a determined thief will eventually steal your belongings. I find it strange that people (at least on c.l.py) often equate 'imperfect protection' with 'pointless protection'. The all-or-nothing attitude makes no sense. If you can halve the number of people who can deduce your algorithm, that helps. If you can double the time it takes for those people to deduce it, that also helps. If it took you months of R&D, the value of even imperfect protection rises. > Now, if we sidestep the issue of decompiling binaries and > cast the affected work as some kind of service, the question can now be > expressed as whether you should expect to be rewarded forever for > providing such a service. But what is 'forever'? Is it a single service for one customer that persists forever? Or is it a service that will be invoked many times by different customers forever? Since these are completely different scenarios, the answer is "it depends". > such issues could possibly increase competitive > pressure rather than enhance any supposed competitive advantage if > people felt that the market wasn't providing enough in the way of > choice in that area. I'm not interested in whether it's a sound business decision or not. I'm just interested in the developer's right and/or ability to make that call. > > I'm not saying I agree with extending the copyright period, however I > > do think you can't just compare it to 'a day at work'. It's a totally > > different set of circumstances which requires a different set of rules > > to both encourage artists to continue creating while benefitting > > society in the long run too. > > For some of those musicians (ie. probably not Sir Cliff Richard), it > probably was a day at work for which they were badly paid, whilst > others (eg. Sir Cliff Richard) went on to make quite a bit of money. Of > course, one can always argue that the result of this particular kind of > day at work is something that can be enjoyed again and again, but then > you should consider the issue of why the person working at the car > factory doesn't get paid royalties every time you turn the key in the > ignition (even if it's just $0.0001 each time). There's a key distinction to be made here, at least legally. Session musicians do work for hire - they're paid by the hour/day/whatever, and typically have no copyright to the work they perform on. They are analogous to the person at the car factory. Any royalties they receive - typically none - would be from the contractual agreement and nothing to do with copyright. On the other hand, writing musicians/composers typically will be paid absolutely nothing for their original creation. They never get paid for it as such, but they can (and typically do) yield the copyright to a publishing company in return for an agreed royalty rate on sales of the reproduced item. They don't so much get paid forever for a service rendered long ago, they just have their payment spread out over an indefinite period of time, and that is dependent on people buying that item. This is no different from me investing my own time and money into manufacturing 10,000 cars and selling them between now and 50 years from now. The major difference is that replicating creative work is typically much cheaper and easier than replicating automobiles, hence the existence of various laws safeguarding intellectual property, as without such laws there would be little incentive to create any such works that were non-trivial. No-one is going to pay you up front for it, so you need a way of protecting future potential income. Since that future income is typically strongly linked to the quality of your work, it's arguable that this is in fact a fairer business model than being paid a normal salary. -- Ben Sizer From arutz at mimoza.pantel.net Wed Aug 30 16:08:30 2006 From: arutz at mimoza.pantel.net (Antal Rutz) Date: Wed, 30 Aug 2006 22:08:30 +0200 Subject: Managing database tables through web-forms (automatically) Message-ID: <44F5F03E.9020505@mimoza.pantel.net> Hi, I want to manage database(sql) tables through the web: actions like insert/edit/list/delete. An application often needs just a database table to be easily managable through the web by the users. Now I realized that everytime I write a new app I need to rewrite the whole thing according to the actual database/table schema (forms/templates/validation/etc) What I'd need: A tool/module/anything that helps me to automate this process. Something that just needs defining some table scheme and not to rewrite the whole thing again. Big thanks if you can help me! -- --arutz From http Thu Aug 10 19:34:12 2006 From: http (Paul Rubin) Date: 10 Aug 2006 16:34:12 -0700 Subject: "running" code on client side with cherrypy? References: <1155239338.574898.193520@m79g2000cwm.googlegroups.com> <1155240909.620857.233020@b28g2000cwb.googlegroups.com> <1155246411.130360.74270@i42g2000cwa.googlegroups.com> Message-ID: <7xmzac5fnv.fsf@ruckus.brouhaha.com> "Mr BigSmoke" writes: > Tnx Jay... as i supposed there's no easy solution... I just thought > that, maybe, being on an intranet there was a possible solution... There are ways to ask the user for permission to install stuff on the client (that's how self-installers work) but they're messy and browser specific. From you at cogeco.ca Sun Aug 27 15:40:46 2006 From: you at cogeco.ca (AlbaClause) Date: Sun, 27 Aug 2006 15:40:46 -0400 Subject: Learning Python - Have Question. References: <8l2Ig.3933$ED.894@read2.cgocable.net> <1156626744.641752.281500@p79g2000cwp.googlegroups.com> <1156662608.080319.281310@74g2000cwt.googlegroups.com> Message-ID: Tal Einat wrote: > iapain wrote: >> First thing you have to remember while using python is "everything is >> an object". os.join.path concatenates one or more path for example >> os.path.join("c:", "myfolder") represent a path relative to current dir >> on c: drive. >> > > Actually, os.path.join() is a simple function, there's nothing > Obejct-Oriented about it. "Everything is an object" simply means that > functions are objects, but that doesn't mean that the design of > everything is Object-Oriented. It turns out that I was using os.path.join() properly in the first place. And you're right, it is a very simple function. Apparently, I was using os.walk() improperly. More specifically, I was not fully understanding how os.walk() worked. I've played with it some more in the Python interpreter and I now have a very good understanding of how it works. For example: import os d=os.walk('/server1') for a, b, c in d: pass This will place the path '/server1' in 'a', all directories in 'a' in a list called 'b', and all files in a list called 'c'. On the next iteration of the loop, 'a' will contain the path '/server1' with the path of the first directory in '/server1' appended. So 'a' will be '/server1/directory1', all of the directories in 'a' will be stored in 'b', and all of the files in 'a' will be stored in 'c'. So on the first iteration, a, b, and c would be: a = server1 b = directory1, directory2, directory3 c = file1, file2, file3 On the second iteration of the loop, a, b, and c would be: a = server1/directory1 b = subdirectory1, subdirectory2 c = d1file1, d1file2, d1file3 On the third iteration of the loop, a, b, and c would be: a = server1/directory1/subdirectory1 b = [] # there are no directories in subdirectory1 so b is empty. c = sd1file1, sdfile2 >> you could easily do it with python. Its more than your expectation. The >> best would be to call os.system(shell cmd). > > Using the shell for this is the least cross-platform solution possible. > Python's libraries have very corss-platform implementations of such > operations you should use them! > > In this case, it seems you're looking for os.listdir(dir_name). Just > call it with the path of a directory and it will return a list of names > of all the files and directories therein. You can use os.path.isdir(), > os.path.isfile(), etc. to figure out what type of file system object > each item in the list is. You can check premissions for the current > user with os.access(). Finally, you can find out more data about any > file with the "stat" module, which is more low-level. Thank you for this. The most daunting task in learning Python, is learning all of the modules and functions that are available. And there's a tonne of them. :-) -- -- There are several things that I will never be: * I will never be attracted to females. * I will never enjoy the company of others. Exactly how these realities bode for my enemy, is not of my concern. From pythonnews at nospam.jmbc.fr Thu Aug 17 01:42:09 2006 From: pythonnews at nospam.jmbc.fr (jean-michel bain-cornu) Date: Thu, 17 Aug 2006 07:42:09 +0200 Subject: wxPython Grid Question In-Reply-To: <1155788722.147173.58730@m73g2000cwd.googlegroups.com> References: <1155788722.147173.58730@m73g2000cwd.googlegroups.com> Message-ID: <44e40249$0$21144$7a628cd7@news.club-internet.fr> Hi, Jordan a ?crit : > Hey Peoples, > I'm wonderg if there is a way to make a subclass of wx.grid.Grid in > which the coloumn labels for the grid appear on the bottom of the grid > instead of the top. > > 1 2 3 4 5 > a| | | | | | > b| | | | | | > c| | | | | | > d| | | | | | > e| | | | | | > > Just in case that wasn't clear (and because I just feel like typing > more): The above grid has labels in the normal placement. The grid > below has the labels in the places I want them. > > a| | | | | | > b| | | | | | > c| | | | | | > d| | | | | | > e| | | | | | > 1 2 3 4 5 > I don't know a regular way to do that, and may be it's not the right place to ask that, but what you'd do is to build two grids with the same layout, one at the top without the column label, and another below without data lines. It could work, but looks strange, and is probably a source of confusion for users. rgds, jm From Bulkan at gmail.com Wed Aug 9 00:48:35 2006 From: Bulkan at gmail.com (placid) Date: 8 Aug 2006 21:48:35 -0700 Subject: Regd:Video Converter Programming In-Reply-To: <1155092497.011057.219180@m79g2000cwm.googlegroups.com> References: <1155092497.011057.219180@m79g2000cwm.googlegroups.com> Message-ID: <1155098914.953285.48410@i42g2000cwa.googlegroups.com> Ch3ru5 wrote: > Hi, > I want to write an avi to flv converter in php but i am a complete > newbie to it. > > I would like to know the basic flow of entire process of how a > converter code is written > (ie. the basic algorithm ) . > > Example: "You first create an flv stream , then compress the avi code , > then copy that code into the flv stream created ." > > The above flow may or may not be correct but what i want to know is > this flow . > > Any good tutorials or resources where i can learn the basics. > via a Google search for "python video convert" i found the following http://pymedia.org/ Cheers From robert.kern at gmail.com Thu Aug 24 22:31:12 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 24 Aug 2006 21:31:12 -0500 Subject: Best Practices for Python Script Development? In-Reply-To: <1156471481.265329.291360@m79g2000cwm.googlegroups.com> References: <1156471481.265329.291360@m79g2000cwm.googlegroups.com> Message-ID: metaperl wrote: > Usage > ===== > Most scripts will be run from cron and so should be driveable via > command-line options. > > optparse looks very good to me. And I had never thought about > required versus optional arguments in the way that it does. What an > eye-opener. > > Searching cheeseshop.python.org/pypi for getopt modules does not work > very well by the way. "Does not work very well" how? Are you just not finding anything? If so, it's probably because there really aren't any, and they wouldn't be referred to as "getopt modules." There's the (old) getopt module and the (preferred) optparse module in the standard library. optparse really does fill the niche quite thoroughly. However, if you like, there's the newcomer argparse that tries to improve upon optparse in several respects: http://argparse.python-hosting.com/ -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From mail at microcorp.co.za Wed Aug 2 12:31:36 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Wed, 2 Aug 2006 18:31:36 +0200 Subject: Is there an obvious way to do this in python? Message-ID: <000901c6b651$37ae16c0$03000080@hendrik> Hi, I want to write a small system that is transaction based. I want to split the GUI front end data entry away from the file handling and record keeping. Now it seems almost trivially easy using the sockets module to communicate between machines on the same LAN, so that I want to do the record keeping on one machine. I want to keep the "server" machine as simple as possible - just doing record keeping on a stimulus response basis - I would prefer it to do one thing at a time to completion because this style of operation, though limited in performance, keeps a lot of hassles out of life - a transaction has either completed, or it has not - recovery scenarios are relatively easy... Up to this point, I don't have a problem - my toy system can create a dummy transaction, and I can echo it from the "server" machine, with more than one "user" machine running - so I think it is feasible to have several tens of "data entry terminal" systems running, served by one not very strong machine. Now what I would really like to do is to differentiate between the 'User" machines, so that some can do a full range of transactions, and others a limited range. And I would like to make this flexible, so that it becomes easy to introduce new transactions, without having to run around updating the code in all the user machines, with the concomitant version number hassles. And I would like to do the whole thing in python - so my question is this - is it possible to do the equivalent of dynamic linking? - i.e. if I keep a list of what a user is allowed to do - can I somehow send him just the bits he needs to do the job, without having to change the static code on his machine? - it seems to me that the eval() thingy could possibly do this for me, by sending it data that makes it do import statements followed by calls to whatever... - will this work, or is there a better way? Or has all this been done already? - and no I don't want a web server and php and browsers and Java and html or xml... - I want to write something that works simply and reliably - its just short message accounting type data... - Hendrik From anthra.norell at tiscalinet.ch Fri Aug 25 17:10:26 2006 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Fri, 25 Aug 2006 23:10:26 +0200 Subject: RE Module References: <1156478366.165463.277480@h48g2000cwc.googlegroups.com><1156482547.386190.89790@74g2000cwt.googlegroups.com> <1156522465.742441.167760@m79g2000cwm.googlegroups.com> Message-ID: <004d01c6c88a$e41289a0$0201a8c0@mcuf7> Roman, I don't quite understand what you mean. Line separators gone? That would be the '\n', right? What of it if you process line by line, as your variable name 'row' suggests? As to the maximum size re can handle, I have no idea. I vaguely remember the topic being discussed. You should be able to find the discussions in the archives, if a knowlegeable soul doesn't volunteer the info right away. With SE it is of no concern. Anyway, I think the best thing to do is to just try with a real page: >>> f = urllib.urlopen (r'http://www.python.org') >>> page = f.read (); f.close () >>> import SE >>> Tag_Stripper = SE.SE (' "~<(.|\n)*?>~=" "~~=" ') >>> Tag_Stripper (page) ( ... page without tags, but lots of empty lines ...) If you want to take the empty lines out, do this: >>> Tag_Stripper = SE.SE (' "~<(.|\n)*?>~=" "~~=" | "~\r?\n\s+?(?=\r?\n)~=" | "~(\r?\n)+~=\n" ') "|" means do the preceding replacements (which happen to be deletions: replace with nothing) and go on from there. The expressions we added say: delete lines that contain only spaces. Do that (another "|"). And finally replace multiple consecutive line feeds with a single line feed. So you can develop interactively. Add a definition. See what it does. Add another one. One little step at a time. Hacking at its best! Frederic ----- Original Message ----- From: "Roman" Newsgroups: comp.lang.python To: Sent: Friday, August 25, 2006 6:14 PM Subject: Re: RE Module > Thanks for your help. > > A thing I didn't mention is that before the statement row[0] = > re.sub(r'<.*?>', '', row[0]), I have row[0]=re.sub(r'[^ > 0-9A-Za-z\"\'\.\,\#\@\!\(\)\*\&\%\%\\\/\:\;\?\`\~\<\>]', '', row[0]) > statement. Hence, the line separators are going to be gone. You > mentioned the size of the string could be a factor. If so what is the > max size before I see problems? > > Thanks again > Anthra Norell wrote: > > Roman, > > > > Your re works for me. I suspect you have tags spanning lines, a thing you get more often than not. If so, processing linewise > > doesn't work. You need to catch the tags like this: > > > > >>> text = re.sub ('<(.|\n)*?>', '', text) > > > > If your text is reasonably small I would recommend this solution. Else you might want to take a look at SE which is a stream edtor > > that does the buffering for you: > > > > http://cheeseshop.python.org/pypi/SE/2.2%20beta > > > > >>> import SE > > >>> Tag_Stripper = SE.SE (' "~<(.|\n)*?>~=" "~~=" ') > > >>> print Tag_Stripper (text) > > (... your text without tags ...) > > > > The Tag_Stripper is made up of two regexes. The second one catches comments which may nest tags. The first expression alone would > > also catch comments, but would mistake the '>' of the first nested tag for the end of the comment and quit prematurely. The example > > "re.sub ('<(.|\n)*?>', '', text)" above would misperform in this respect. > > > > Your Tag_Stripper takes input from files directly: > > > > >>> Tag_Stripper ('name_of_file.htm', 'name_of_output_file') > > 'name_of_output_file' > > > > Or if you want to to view the output: > > > > >>> Tag_Stripper ('name_of_file.htm', '') > > (... your text without tags ...) > > > > If you want to keep the definitions for later use, do this: > > > > >>> Tag_Stripper.save ('[your_path/]tag_stripper.se') > > > > Your definitions are now saved in the file 'tag_stripper.se'. You can edit that file. The next time you need a Tag_Stripper you can > > make it simply by naming the file: > > > > >>> Tag_Stripper = SE.SE ('[your_path/]tag_stripper.se') > > > > You can easily expand the capabilities of your Tag_Stripper. If, for instance, you want to translate the ampersand escapes (  > > etc.) you'd simply add the name of the file that defines the ampersand replacements: > > > > >>> Tag_Stripper = SE.SE ('tag_stripper.se htm2iso.se') > > > > 'htm2iso.se' comes with the SE package ready to use and as an example for writing ones own replacement sets. > > > > > > Frederic > > > > > > ----- Original Message ----- > > From: "Simon Forman" > > Newsgroups: comp.lang.python > > To: > > Sent: Friday, August 25, 2006 7:09 AM > > Subject: Re: RE Module > > > > > > > Roman wrote: > > > > I am trying to filter a column in a list of all html tags. > > > > > > What? > > > > > > > To do that, I have setup the following statement. > > > > > > > > row[0] = re.sub(r'<.*?>', '', row[0]) > > > > > > > > The results I get are sporatic. Sometimes two tags are removed. > > > > Sometimes 1 tag is removed. Sometimes no tags are removed. Could > > > > somebody tell me where have I gone wrong here? > > > > > > > > Thanks in advance > > > > > > I'm no re expert, so I won't try to advise you on your re, but it might > > > help those who are if you gave examples of your input and output data. > > > What results are you getting for what input strings. > > > > > > Also, if you're just trying to strip html markup to get plain text from > > > a file, "w3m -dump some.html" works great. ;-) > > > > > > HTH, > > > ~Simon > > > > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > > -- > http://mail.python.org/mailman/listinfo/python-list From aaronwmail-usenet at yahoo.com Mon Aug 7 14:01:00 2006 From: aaronwmail-usenet at yahoo.com (aaronwmail-usenet at yahoo.com) Date: 7 Aug 2006 11:01:00 -0700 Subject: Need a compelling argument to use Django instead of Rails In-Reply-To: <44d4bdee$0$15790$14726298@news.sunsite.dk> References: <1154077105.746752.153440@h48g2000cwc.googlegroups.com> <1154080209.603694.161170@i42g2000cwa.googlegroups.com> <1154092298.714808.158250@75g2000cwc.googlegroups.com> <44ca3420$0$30140$636a55ce@news.free.fr> <5hnlc25hfj56btkhdamfdi5gb5a3b8ts45@4ax.com> <1154354727.457387.142840@h48g2000cwc.googlegroups.com> <3scsc252be3d7a814ogj1ibnud3aothc1l@4ax.com> <1154512062.251725.177140@m73g2000cwd.googlegroups.com> <7xejvz5mwj.fsf@ruckus.brouhaha.com> <44d3817d$0$13470$636a55ce@news.free.fr> <44d4bdee$0$15790$14726298@news.sunsite.dk> Message-ID: <1154973660.634765.68700@i42g2000cwa.googlegroups.com> Damjan wrote: > Yes, but your mod_python programs still run with the privileges of the > Apache process, as are all the other mod_python programs. This means that > my mod_python program can (at least) read files belonging to you - > including your config file holding your database password.... I think a standard solution to this is to associate each virtual host server to a different port and have the main apache redirect to the port. Inetd makes sure that the vserver apache instance only stays alive while it's needed. It might be complicated to set up, but it works. Again, something like this is probably advisable anyway to limit the ways one vserver can damage another generally speaking. -- Aaron Watters === It's not the years. It's the mileage. -- Indiana Jones From you at cogeco.ca Sun Aug 20 00:51:18 2006 From: you at cogeco.ca (AlbaClause) Date: Sun, 20 Aug 2006 00:51:18 -0400 Subject: Permission Denied References: <1156038847.616137.61800@m79g2000cwm.googlegroups.com> Message-ID: hiaips wrote: > > Tom Strickland wrote: >> Hopefully this is a simple question. I've started to program in Python >> after an absence of about a year, so I'm very rusty. I wrote a short >> program and tried to run it using Python2.4 in Linux. I keep getting >> "permission denied" messages after entering the path to the program. I >> switched to the root directory and tried again, but got the same >> result.I ran a very similar program earlier and it ran fine. >> >> What am I doing wrong? The program is: >> >> >> #!/usr/bin/python2.4 >> i=1 >> while i<10000: >> print 'step 1',i >> i+=1 >> raw_input() >> print 'step 2' >> >> >> Thank you. >> >> Tom > > > Is your script executable? That's the problem I had when I wrote my first Python script. I wrote it using vi, and vi doesn't save files with the executable flag set. A simple 'chmod 755 script.py' fixed that right up. Then, to execute the file from from the shell prompt, I had to create a 'bin' directory in my home folder, cuz I didn't want to litter my /usr/local/bin folder with useless Python scripts. (Useless because I wrote them to learn the language and for no other practical purpose.) Of course, I had to uncomment a line or two in my .bashrc file too. Hey, what do I know? I'm as new to this as virgins are to... Well, you get the idea. :-p -- -- There are several things that I will never be: * I will never be attracted to females. * I will never enjoy the company of others. Exactly how these realities bode for my enemy, is not of my concern. From jzgoda at o2.usun.pl Sat Aug 26 16:35:01 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Sat, 26 Aug 2006 22:35:01 +0200 Subject: Don't use __slots__ (was Re: performance of dictionary lookup vs. object attributes) In-Reply-To: References: <1156508104.583914.323700@b28g2000cwb.googlegroups.com> <7.0.1.0.0.20060825122244.03790010@yahoo.com.ar> <1156621904.481215.243080@m73g2000cwd.googlegroups.com> Message-ID: skip at pobox.com napisa?(a): > That said, It's not mentioned on the Python3.0 page of the wiki: > > http://wiki.python.org/moin/Python3.0 > > or in PEP 3000: > > http://www.python.org/dev/peps/pep-3000/ > > and I see no discussion about it in the Python 3000 mailing list archives: > > http://mail.python.org/pipermail/python-3000/ > > though Ian Bicking asks about it here: > > http://wiki.python.org/moin/Python3%2e0Suggestions#head-fc89a0fe3f697418776925f4828ea863031fbbd2 Having that said, should we hope __slots__ would disappear in (some) future (tomorrow?!, in next 10 microseconds?!)? Please, don't left us hopeless. -- Jarek Zgoda http://jpa.berlios.de/ From rogue_pedro at yahoo.com Thu Aug 10 22:09:57 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 10 Aug 2006 19:09:57 -0700 Subject: Python share CPU time? In-Reply-To: <1155253594.681570.145910@b28g2000cwb.googlegroups.com> References: <1155146500.063665.282430@p79g2000cwp.googlegroups.com> <1155253594.681570.145910@b28g2000cwb.googlegroups.com> Message-ID: <1155262197.473682.5210@m73g2000cwd.googlegroups.com> Yannick wrote: > Thank you all for the detailled answers. > > What I would like to achieve is something like: > > # main loop > while True: > for robot in robots: > robot.start() > robot.join(0.2) # wait 200ms > if robot.is_active(): > robot.stop() > # run all the game physics, pause, frame/rate, etc... > > Unfortunately the stop() call doesn't exist in Python. > > By using a generator I would make the assumption that every robot is > playing fair, and would yield often. But I cannot control this as > eventually robots would be coded by third parties. > > Using Python scheduler would allow me to share time equally between > each robot, but then I would loose the ability to have a main thread > organizing everything. This is just a dim memory, but something called lambdaMOO was (is?) a Multi-User Dungeon that had (has?) a model of processing that allowed you to create programmed objects that received a "budget" of processor time. The objects would not work if they "ran out" of processor time... Perhaps something like this could help you? (Sorry to be so vague.) HTH, ~Simon From alpersoyler at yahoo.com Thu Aug 31 09:31:54 2006 From: alpersoyler at yahoo.com (alper soyler) Date: Thu, 31 Aug 2006 06:31:54 -0700 (PDT) Subject: a question about my script Message-ID: <20060831133154.20906.qmail@web56513.mail.re3.yahoo.com> Hi, I changed the script as you wrote below: from ftplib import FTP def handleDownload(block): file.write(block) print ".", ftp = FTP('ftp.genome.jp') print ftp.login() directory = 'pub/kegg/genomes' ftp.cwd(directory) k=0 for direct in ftp.nlst(): curdir = '%s/%s' % (directory, direct) ftp.cwd(curdir) for filename in ftp.nlst(): if not filename.endswith('.pep'): continue file = open(filename, 'wb') ftp.retrbinary('RETR %s/%s' % (curdir, filename), handleDownload) file.close() k=k+1 print ftp.close() However, it gave the same error message: 230 Anonymous access granted, restrictions apply. Traceback (most recent call last): File "ftp1.0.py", line 18, in ? ftp.cwd(curdir) File "/usr/lib/python2.4/ftplib.py", line 494, in cwd return self.voidcmd(cmd) File "/usr/lib/python2.4/ftplib.py", line 246, in voidcmd return self.voidresp() File "/usr/lib/python2.4/ftplib.py", line 221, in voidresp resp = self.getresp() File "/usr/lib/python2.4/ftplib.py", line 216, in getresp raise error_perm, resp ftplib.error_perm: 550 pub/kegg/genomes/aae: No such file or directory However, in ftp.genome.jp/pub/kegg/genomes/ site, there is 'aae' directory. What can be the reason? regards, alper ----- Original Message ---- From: Gabriel Genellina To: alper soyler Cc: Python-list at python.org Sent: Tuesday, August 29, 2006 10:26:57 AM Subject: Re: a question about my script At Tuesday 29/8/2006 03:55, alper soyler wrote: >I am trying to get some files from an ftp site by ftplib module and >I wrote the below script. However I have a problem. With my script, >I login to ftp.genome.jp site. then, I am changing the directory to >pub/kegg/genomes/afm and I am downloading "a.fumigatus.pep" file. >However, what I want is to connect pub/kegg/genomes directory and in >this directory there are 3 letters name files 3 letters *files*? or 3 letters *directories*? >e.g. 'afm' and in each of these 3 letters files there is a file with >the extension of '.pep' like a.fumigatus.pep. I want to get these >'.pep' files from the 3 letter named files. If you help me I will be >very glad. Thanks you in advance. Do a cwd() starting one level above (that is, pub/kegg/genomes); using ftp.dir() you can get the subdirectories, then iterate over all of them, using another dir() to find the .pep files needed. >directory = 'pub/kegg/genomes/ afm' Is that whitespace intentional? (If you just want to download the files and don't need really a Python script, try wget...) Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas -------------- next part -------------- An HTML attachment was scrubbed... URL: From mturillo at gmail.com Thu Aug 24 10:30:13 2006 From: mturillo at gmail.com (Perseo) Date: 24 Aug 2006 07:30:13 -0700 Subject: Python Expert In-Reply-To: References: <1156109528.138808.179610@i42g2000cwa.googlegroups.com> Message-ID: <1156429812.964300.230220@74g2000cwt.googlegroups.com> Hi again, I must create a webpage with this service not a standalone software. Is it correct, anyway? have you a little example to show me? Thanks for your suggestions. Frithiof Andreas Jensen wrote: > "Perseo" wrote in message > news:1156109528.138808.179610 at i42g2000cwa.googlegroups.com... > > Hi guys, > > > > we are looking for a python developer for a European project. This > > project is multilangual and free it is called EuroCv and it need a > > module for exporting data in PDF. > > A brute-force approach could be to sidestep PDF and design a > template(s) in LaTex containing fields identified by strings. LaTeX > can produce many formats, one of those is PDF. > > Then have your output module read the template, do a search & replace > of the fields with values (remembering to quote the characters that > LaTex will choke on and removing the codes for the blank fields) and > write the finished LaTeX document to disk. (Maybe there are even > templating modules in Python that will take care of this). > > Then compile the documents with latex, run the resulting *.dvi file > through dvipdf and return a link to it. This is a "compiler pattern". > You need a naming scheme to identify your file(s) but the rest is > pretty old. > > The Python application "scons" (a make replacement) can control the > "build" process - in case that you are not on a unix box - one could > have "build" application periodically looking for *.tex files and > compile them into *pdf whenever one is deposited in the right place. > Scons support distributed builds b.t.w. > > > > As web developer I try to create this > > module but It's too complicate for me. Check out the service > > www.eurocv.eu for more details. Contact us by Skype chat system our > > nick is eurocv. > > > > Thanks > > From skip at pobox.com Tue Aug 22 16:40:54 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 22 Aug 2006 15:40:54 -0500 Subject: Python and STL efficiency In-Reply-To: <1156278230.590485.35610@75g2000cwc.googlegroups.com> References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <1hkh28d.xscw4v1y4v9a6N%riko@despammed.com> <1hkh6lb.6dsnh51lj8z96N%riko@despammed.com> <1156252193.524186.107520@b28g2000cwb.googlegroups.com> <1hkhexv.18m65rl61swqyN%riko@despammed.com> <1156265848.875774.251640@i42g2000cwa.googlegroups.com> <1156278230.590485.35610@75g2000cwc.googlegroups.com> Message-ID: <17643.27606.152803.221895@montanaro.dyndns.org> Tim> But beware! For Python2.5 I had to change the code slightly, Tim> because it already realized that the expression Tim> '%s' % 'something' Tim> will be a constant expression, and evaluates it once only... so I Tim> had to replace '%s' with a variable, and I got the timings above Tim> which show Python2.5 to be slightly faster than Python2.4. Shouldn't you then get rid of any compiler optimizations your C++ compiler does? Why penalize 2.5 because it recognizes a useful optimization? Tim> (Next step would be to create a VB version and a Java version of Tim> the same program, oh and perhaps to try a version that would work Tim> with Jython... perhaps somehow w/o the 'set') I don't recall the example exactly, but couldn't you just create a set class that uses a dict under the covers and only implement the methods you need for the test? Skip From fuzzyman at gmail.com Fri Aug 11 19:25:14 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 11 Aug 2006 16:25:14 -0700 Subject: hide python code ! In-Reply-To: References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155300852.497741.73230@74g2000cwt.googlegroups.com> Message-ID: <1155338714.645665.150150@75g2000cwc.googlegroups.com> Terry Reedy wrote: > "Fuzzyman" wrote in message > news:1155300852.497741.73230 at 74g2000cwt.googlegroups.com... > > I never understand the knee-jerk reaction on this mailing list to > > answer people who ask this question by telling them they don't really > > want to do it... > > Let's clarify the question: "Dear Python programmers: please tell me for > free how I can hide my code from you and others like you." > And categorising their intent in this way is likely to make many genuine coders cross Python off their list and go and see if the Ruby community is any friendlier... Fuzzyman http://www.voidspace.org.uk/python/index.shtml > This question has nothing to do with preventing blind copying of > distributed software, whether in source or binary form. > > tjr From claudio.grondi at freenet.de Tue Aug 1 08:42:48 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Tue, 01 Aug 2006 14:42:48 +0200 Subject: Html character entity conversion In-Reply-To: References: Message-ID: Anthra Norell wrote: >>>>import SE # Available at the Cheese Shop I mean, that OP requested: 'How can I translate this using standard Python libraries??' so it's just only not on topic. Claudio Grondi From jorge.vargas at gmail.com Thu Aug 31 14:12:35 2006 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Thu, 31 Aug 2006 14:12:35 -0400 Subject: Pros/Cons of Turbogears/Rails? In-Reply-To: <1157037862.804249.81290@b28g2000cwb.googlegroups.com> References: <1157034321.926854.123520@m79g2000cwm.googlegroups.com> <1157037862.804249.81290@b28g2000cwb.googlegroups.com> Message-ID: <32822fe60608311112u7ad04f1bhb998351fb15d682@mail.gmail.com> On 31 Aug 2006 08:24:29 -0700, Adam Jones wrote: > > Jaroslaw Zabiello wrote: > > kenneth.m.mcdonald at sbcglobal.net wrote: > > > > > + SqlObject allows working with the DB tables without > > > using SQL itself. > > > > Rails has ActiveRecord ORM, which IMO has nicer and simpler > > syntax than SQLObject. Rails has migrations, TB - not (Migrations is > > versioning system for evolving database schema) > > I don't really see TG sticking with SQLObject. In moving to SQLAlchemy > it would pick up not only a migration system but also a much more > flexible abstraction system due to the use of a Data Mapper pattern > instead of the Active Record pattern. There already is an > implementation of Active Record on top of that, so that benefit stays > as well. > yes indeed as someone said earlier the support is already there and all that needs to be done is a migration path. > > > > > > > + Easy access to other libraries (such as the Python > > > Imaging Library) that Ruby, being a relatively newer > > > language, doesn't have equivalents to. > > > > Ruby is not so young you think. It became more popular > > when Rails has appeared. > > Although that is true there are not as many libraries available for > Ruby as there are for Python. This will probably change as the language > gains popularity, but for right now it pays to look into library > support before considering anything else about the language. > either that or all the hipy of RoR will go away. > > > > > + I find the templating system somewhat cleaner; code in > > > py: xml namespace allows pure .html templates, instead > > > of equivalent of .rhtml files. > > > > But rhtml is much more flexible because it can generate *any content*, > > not only xml. But Rails has THREE template systems: rhtml (main), rxml > > (for rss and xml generation) and rjs (for javascript and AJAX). > > Kid can be used to generate xhtml, rss, xml, pretty much anything that > is xml-based. I have even seen it used to generate xul applications for > firefox. The only thing on your list that it doesn't do is javascript. > Personally I would rather learn one templating language that is able to > treat all of my xml as xml no matter what use it is put to. > and for javascript you have mochikit which is really nice. > > > Actually that point right there is where I think TG is a lot more > competitive that you believe. When a new version of any of the > foundation projects comes out, or a better project to fill that > particular need, TG can absorb it in the next version. The TurboGears > developers can spend most of their time working on additional code that > makes the project more useful instead of bug fixes and minor feature > upgrades to the core components. This philosophy is proven to work for > most other open source projects, and I have yet to hear a good argument > why it would not be successful for a web framework. > I believe that is the most important part of TG, taking the best of the best, and letting the framework adapt and morphe. for example noone plan to move to SA, 0.1 came out a couple of people took and look and like it, then 0.2 was "mature enough" so people started thinking about the migration. after that some code was made and now we have TG with SA, eventually it will be the default. Same with templates, kid is really weak at generating non-xml, it has a plain text serializer but the input must be xml so that's overkill. So a new template frontend (chettah was born). Someone ones said on the mailing list TG is the Ubuntu of web frameworks, and I think I'll add and you can strip down the kernel and it wont break :) > -Adam > > -- > http://mail.python.org/mailman/listinfo/python-list > From mail at microcorp.co.za Fri Aug 25 03:15:10 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 25 Aug 2006 09:15:10 +0200 Subject: sum and strings References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <1155922208.930580.135080@m79g2000cwm.googlegroups.com> <1156365271.487489.62640@m73g2000cwd.googlegroups.com> <44ECC789.1010202@tim.thechases.com> <44EDCFDE.9060604@tim.thechases.com><7.0.1.0.0.20060824132656.050af940@yahoo.com.ar> Message-ID: <008301c6c816$4cb4f080$03000080@hendrik> "Fredrik Lundh" Wrote: 8<---------------------------------------- | (I still think a "join" built-in would be nice, though. but anyone who | argues that "join" should support numbers too will be whacked with a | great big halibut.) | | Strange this - you don't *LOOK* like a Gaulish Blacksmith... From duncan.booth at invalid.invalid Wed Aug 2 08:24:26 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 Aug 2006 12:24:26 GMT Subject: Class definition within function References: Message-ID: Tomi Lindberg wrote: > With the following function definition, is it possible to > create an instance of class C outside the function f (and if > it is, how)? And yes, I think this is one of those times > when the real question is why :) > > >>> def f(): > class C(object): > def __init__(self): > self.a = 'a' > return C() > > >>> x = f() > >>> x.a > 'a' > >>> y=f.C() > > Traceback (most recent call last): > File "", line 1, in -toplevel- > y=f.C() > AttributeError: 'function' object has no attribute 'C' > >>> > Well, you could use 'type(x)()', or object.__subclasses__() will include C for as long as the class actually exists. Choosing the correct C from object's subclasses could prove somewhat tricky though: remember you'll get a new C class every time you call 'f'. From gherron at islandtraining.com Tue Aug 8 02:32:01 2006 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 07 Aug 2006 23:32:01 -0700 Subject: import help In-Reply-To: <1155016977.405733.32170@n13g2000cwa.googlegroups.com> References: <1155016977.405733.32170@n13g2000cwa.googlegroups.com> Message-ID: <44D82FE1.7080000@islandtraining.com> placid wrote: > Hi all, > > How do i import a module that has an hypen/dash (-) in its name ? I get > a SytaxError exception > > Cheers > > You can't do that directly. However, the internals of the import mechanism are available to the programmer through a module named imp. It allows you to import a file whose name is specified in a string -- that should work for you. Gary Herron From codecraig at gmail.com Tue Aug 29 15:24:05 2006 From: codecraig at gmail.com (abcd) Date: 29 Aug 2006 12:24:05 -0700 Subject: block a network port Message-ID: <1156879445.723089.126630@m73g2000cwd.googlegroups.com> any ideas on how to block a network port from being used, or one that is currently in use? For example, say I want to block port 23 from being used. by used, I mean allowing connections to or from it. thanks in advance. From gagsl-py at yahoo.com.ar Mon Aug 14 17:40:26 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 14 Aug 2006 18:40:26 -0300 Subject: looking for a simple way to load a program from another python program.. In-Reply-To: <1155498660.285772.144140@m73g2000cwd.googlegroups.com> References: <1155498660.285772.144140@m73g2000cwd.googlegroups.com> Message-ID: <7.0.1.0.0.20060814183934.03a74e90@yahoo.com.ar> At Sunday 13/8/2006 16:51, Eric_Dexter at msn.com wrote: > I was looking for a simple way to load a simple python program from >another python program. > >I tried > >os.system(cabel) > >The file name is cabel.py a csound instrument editor.. > >NameError: global name 'cabel' is not defined Have you tried os.system("cabel.py") Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From http Fri Aug 25 19:32:46 2006 From: http (Paul Rubin) Date: 25 Aug 2006 16:32:46 -0700 Subject: ASN.1 encoder & decoder References: Message-ID: <7xd5ao4cip.fsf@ruckus.brouhaha.com> Doug Stell writes: > Can anyone provide guidance on building an ASN.1 decoder and encoder > in Python? This does not have to be a general purpose implementation, > drivenf from an ASN.1 template. It can be dedicated hard coded to a > particular template. There might be some useful code in www.trevp.com/tlslite . From ptmcg at austin.rr._bogus_.com Tue Aug 8 21:28:05 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 09 Aug 2006 01:28:05 GMT Subject: How to reverse tuples in a list? References: <1155081671.728757.228050@p79g2000cwp.googlegroups.com> Message-ID: "Noah" wrote in message news:1155081671.728757.228050 at p79g2000cwp.googlegroups.com... > I have a list of tuples > [('a', 1.0), ('b', 2.0), ('c', 3.0)] > I want to reverse the order of the elements inside the tuples. > [(1.0,'a'), (2.0, 'b'), (3.0, 'c')] > >>> tups = [('a', 1.0), ('b', 2.0), ('c', 3.0)] >>> map(tuple,map(reversed,tups)) [(1.0, 'a'), (2.0, 'b'), (3.0, 'c')] From ask at me Sun Aug 27 20:31:44 2006 From: ask at me (alf) Date: Sun, 27 Aug 2006 20:31:44 -0400 Subject: M$ windows python libs installed in arbitrary directories forcustomized python distributions In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > "alf" wrote: > > >>It turned out it is quite simple - I just install the python from >>python.org and all the libs needed. Then I take python2n.dll from >>c:\win*\system32 and move directly to PYTHONDIR. Then I can just tar/zip >>the PYTHON dir and distribute around so users do not have to deal with >>dozen of libs and packages. >> >>Small difficulty is a maintenance of such "distribution". Namely when I >>want install a new lib M$ installer just can not find my python >>installations probably due to missing registry entries. >> >>Is there any way to force the actual python site-lib for M$ installers???? > > > it's spelled "Windows installers", and code to do the necessary registry updates > can be found here: > > http://effbot.org/zone/python-register.htm > > > > > thx for the hint ... From ramasubramani.g at gmail.com Thu Aug 3 08:40:52 2006 From: ramasubramani.g at gmail.com (Rama) Date: Thu, 3 Aug 2006 18:10:52 +0530 Subject: Datetime question In-Reply-To: <1154607991.404201.23400@p79g2000cwp.googlegroups.com> References: <1154607991.404201.23400@p79g2000cwp.googlegroups.com> Message-ID: <3f8d3ac50608030540s68edf49cpeb82ea276788fde8@mail.gmail.com> the datetime object appears to have a replace method which could achieve what you want to do, albeith with some computation from your end first, >>> d = datetime.datetime(2006, 8, 3, 14, 13, 56, 609000) >>> dir(d) ['__add__', '__class__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getatt ribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__ne w__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__rsub__', '__seta ttr__', '__str__', '__sub__', 'astimezone', 'combine', 'ctime', 'date', 'day', ' dst', 'fromordinal', 'fromtimestamp', 'hour', 'isocalendar', 'isoformat', 'isowe ekday', 'max', 'microsecond', 'min', 'minute', 'month', 'now', 'replace', 'resol ution', 'second', 'strftime', 'time', 'timetuple', 'timetz', 'today', 'toordinal ', 'tzinfo', 'tzname', 'utcfromtimestamp', 'utcnow', 'utcoffset', 'utctimetuple' , 'weekday', 'year'] >>> d.replace(year=2007) datetime.datetime(2007, 8, 3, 14, 13, 56, 609000) >>> thanks, Rama On 3 Aug 2006 05:26:31 -0700, Lad wrote: > > In a datetime object I would like to change days and hours. > Or in other words, I would like to copy this datetime object but > increase days and hours. > Is it possible? > For example:If I have a datetime object like this > datetime.datetime(2006, 8, 3, 14, 13, 56, 609000) > > I would like to make a new ,for example like this > > datetime.datetime(2006, 8, 12, 10, 13, 56, 609000) > > is it possible to do so? > Thank you > L > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rpdooling at gmail.com Mon Aug 21 23:46:50 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 21 Aug 2006 20:46:50 -0700 Subject: how do you get the name of a dictionary? In-Reply-To: <1156204770.339106.151110@m73g2000cwd.googlegroups.com> References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> Message-ID: <1156218410.731536.250480@i3g2000cwc.googlegroups.com> >> im quite surprised at the arrogance laid >> out by some of the above Oh, nobody is being arrogant. They're having fun while answering your question. Most remember having the same question, or at least making the same discovery after careful reading. rd From sjmachin at lexicon.net Wed Aug 16 20:25:08 2006 From: sjmachin at lexicon.net (John Machin) Date: 16 Aug 2006 17:25:08 -0700 Subject: Memory usage of an 'empty' python interpreter In-Reply-To: <1155739133.958790.319420@b28g2000cwb.googlegroups.com> References: <1155710349.127768.17280@h48g2000cwc.googlegroups.com> <1155715912.930984.207150@i42g2000cwa.googlegroups.com> <1155716926.343428.263870@h48g2000cwc.googlegroups.com> <1155739133.958790.319420@b28g2000cwb.googlegroups.com> Message-ID: <1155774308.497134.56170@m79g2000cwm.googlegroups.com> Ant wrote: > > > Are you sure ps is reporting in bytes not KB? The bare interpreter in > > > Windows is 3368KB. > > > > Where did you get that from? With Python 2.4.3, on my machine (Win XP > > SP2): > > > > C:\junk>dir \python24\python* > > [snip] > > 29/03/2006 05:35 PM 4,608 python.exe > > 29/03/2006 05:35 PM 1,871,872 python24.dll > > 29/03/2006 05:35 PM 5,120 pythonw.exe > > He's asking for the memory required, not the disk space used by the > exe. The 3368KB is reported by the Task Manager. Doh! Low blood sugar -- that's the excuse du jour :-) Cheers, John From apardon at forel.vub.ac.be Tue Aug 29 00:28:23 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 29 Aug 2006 04:28:23 GMT Subject: Is this a good idea or a waste of time? References: <1156449402.022781.292840@p79g2000cwp.googlegroups.com> <1156485945.967160.238790@m73g2000cwd.googlegroups.com> <44f322cd$1@nntp0.pdx.net> <1156802762.331853.80000@75g2000cwc.googlegroups.com> Message-ID: On 2006-08-28, sjdevnull at yahoo.com wrote: > Antoon Pardon wrote: >> There seem to be enough problems that work with ints but not with >> floats. In such a case enforcing that the number you work with >> is indeed an int seems fully appropiate. > > I've _never_ seen a case where enforcing types in the manner of the OP > is appropriate. > > It fails with trivial wrappers like > > class myInt(int): > def printFormatted(self): > .......... > > Even looser checking with isinstance is rarely right. You may want to > exclude floats, but that doesn't mean you want to exclude int-like > objects that don't inherit from int. That may be true. But one may wonder if this is a failing of the programmer or a failing of the language that doesn't support such things. -- Antoon Pardon From thomas.samson at gmail.com Thu Aug 31 12:28:24 2006 From: thomas.samson at gmail.com (Thomas Samson) Date: Thu, 31 Aug 2006 18:28:24 +0200 Subject: genetic algorithms package for python ? References: Message-ID: <6hsfyfcrhsn.fsf@koollbox.kooll.org> Xiao Jianfeng writes: > Hi all, > > I am looking for a genetic algorithms package for Python. > > I have googled the web before posting and found some links. The link > of pygene(http://www.freenet.org.nz/python/pygene) cannot be opened. Strange, works for me... > > I also tried the recipe on ASPN, but it is too simple for my > application, and the ga model in SciPy, which is in testing in the > "sandbox". > > Are there any more genetic algorithms packages for Python ? > I am not (at all!) an specialist in genetic algorithms, but here are some links : http://pygp.sourceforge.net/ http://packages.qa.debian.org/g/genetic.html and of course, http://www.freenet.org.nz/python/pygene/ -- Thomas Samson BOFH Excuse #420: Feature was not beta tested From danielmarkhot at gmail.com Fri Aug 18 10:55:52 2006 From: danielmarkhot at gmail.com (Daniel Mark) Date: 18 Aug 2006 07:55:52 -0700 Subject: How to draw line on Image? Message-ID: <1155912952.668195.266340@b28g2000cwb.googlegroups.com> Hello all: I want to draw some shapes, such as lines, circles on an image. The input to the program is an image and the output from the program is a superimposed image. what kind of document or functions I should take a look for searching this question? The program doesn't show the image, but draws some shapes on the input image. Thank you -daniel From thunderfoot at gmail.com Thu Aug 17 10:15:54 2006 From: thunderfoot at gmail.com (thunderfoot at gmail.com) Date: 17 Aug 2006 07:15:54 -0700 Subject: List match In-Reply-To: <1155823451.766317.7640@74g2000cwt.googlegroups.com> References: <1155823451.766317.7640@74g2000cwt.googlegroups.com> Message-ID: <1155824154.577194.320060@b28g2000cwb.googlegroups.com> OriginalBrownster wrote: > Hi there: > > I know this probably is a very easy thing to do in python, but i wanted > to compare 2 lists and generate a new list that does not copy similar > entries. An example below > > list= ["apple", "banana", "grape"] > list2=["orange","banana", "pear"] > > now I want to compare these lits and generate a third list after > comparison > > list3 would be ["apple", "banana","grape","orange", "pear"] > > hence the double entry would not show up? > > Is there a way to do this?? > > Stephen How about: list3 = list1 + [item for item in list2 if item not in list1] print list3: ['apple', 'banana', 'grape', 'orange', 'pear'] From bill.pursell at gmail.com Wed Aug 16 15:18:25 2006 From: bill.pursell at gmail.com (Bill Pursell) Date: 16 Aug 2006 12:18:25 -0700 Subject: PySequence_SetItem In-Reply-To: <1155754847.392950.266180@h48g2000cwc.googlegroups.com> References: <1155754847.392950.266180@h48g2000cwc.googlegroups.com> Message-ID: <1155755905.233229.93440@74g2000cwt.googlegroups.com> Bill Pursell wrote: > The following code is pretty much straight out of > section 1.2.1.1 of the Python/C reference manual: > > #include > > int > main(void) > { > PyObject *l, *x; > > Py_Initialize(); > > l = PyList_New(3); > x = PyInt_FromLong(1L); > > if (l == NULL || x == NULL) { > PyErr_Print(); > exit (EXIT_FAILURE); > } > PySequence_SetItem(l, 0, x); > Py_DECREF(x); > > Py_Finalize(); > return EXIT_SUCCESS; > } Also note that the problem goes away if I replace the call to PySequence_SetItem with: PySequence_SetItem(l, 0, PyInt_FromLong(1L)); but the problem persists if I add a Py_INCREF(x) after the assignment of x. (Which seems like a completely silly thing to do, but I'm grasping at strings...) From steve at REMOVEME.cybersource.com.au Thu Aug 10 05:38:00 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 10 Aug 2006 19:38:00 +1000 Subject: MergeSort References: <1155153011.777935.151210@b28g2000cwb.googlegroups.com> Message-ID: On Wed, 09 Aug 2006 12:50:11 -0700, ben81 wrote: > Hi, > > the following code is adopted PseudoCode from Introduction to > Algorithms (Cormen et al). I'm assuming you are doing this as a learning exercise, because -- trust me on this -- nothing you write in pure Python code will come within cooee of the speed of Python's build-in sort method. > For some reason it can't get it to work. I > always get a index of out bounds exception or some weird result. No, don't tell us what the weird result is. I love to guess! Is it this? ImportError: No module named listutil Not that it matters, because listutil doesn't seem to be used in your code. > Secondly I'd like to know how to write this more pythonic. TIA. Document your code. Don't assume the reader will remember all the details of Merge Sort. I certainly don't. It will also help you understand how the algorithm works, which then will help you see what your code is doing that it shouldn't (such as trying to merge empty lists). Why are you appending 1001 to both sub-lists? -- Steven D'Aprano From sjmachin at lexicon.net Thu Aug 10 21:04:00 2006 From: sjmachin at lexicon.net (John Machin) Date: 10 Aug 2006 18:04:00 -0700 Subject: seaching a list... In-Reply-To: References: Message-ID: <1155258240.286580.286820@i3g2000cwc.googlegroups.com> bruce wrote: > hi larry... > > thanks for the reply... > > the issue i'm having is that i'm going to have to compare multiple rows of > information to the information in the db. so essentially i'd have to do a > hit to the db, for each row of information i want to compare if i did it > your way... (which was what i had thought about) > > the issue of doing the string/list compare/search is that i can get > everything from the db with one call... i can then iterate through memory > for each of my row information that i'm searching to see if it exists in the > db... > > memory searches should be faster than the network overhead, and the > associated multiple db calls... (1) Don't top-post. (2) Do as asked: supply some pseudo-code for comparing a row of query information with a row extracted from your database -- whether you are comparing on one/some/all columns and what type of comparison are vital pieces of information. How many query rows? How many database rows? From gagsl-py at yahoo.com.ar Tue Aug 29 02:03:09 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 29 Aug 2006 03:03:09 -0300 Subject: Is this a good idea or a waste of time? In-Reply-To: References: <1156449402.022781.292840@p79g2000cwp.googlegroups.com> <1156485945.967160.238790@m73g2000cwd.googlegroups.com> <44f322cd$1@nntp0.pdx.net> <1156802762.331853.80000@75g2000cwc.googlegroups.com> Message-ID: <7.0.1.0.0.20060829030019.03ce03f0@yahoo.com.ar> At Tuesday 29/8/2006 02:45, Antoon Pardon wrote: > >>That may be true. But one may wonder if this is a failing of the > >>programmer or a failing of the language that doesn't support > >>such things. > > > > In any case, I don't see how this supports the original claim that > > strict type checking input params is good practice. > >I'm not defending that claim. I'm just putting question marks >with the claim that strict type checking input parameters is >bad practice. I think others have shown enough examples of good things that can be done by *not* enforcing a specific type... Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From larry.bates at websafe.com Thu Aug 24 13:38:46 2006 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 24 Aug 2006 12:38:46 -0500 Subject: lambda In-Reply-To: <1156440070.549332.18830@i3g2000cwc.googlegroups.com> References: <1156440070.549332.18830@i3g2000cwc.googlegroups.com> Message-ID: <2J-dnc8Beay-eXDZnZ2dnUVZ_t6dnZ2d@comcast.com> fegge wrote: > what is a lambda expression? > You really should try Google first (python lambda): http://www.secnetix.de/~olli/Python/lambda_functions.hawk http://diveintopython.org/power_of_introspection/lambda_functions.html -Larry From john106henry at hotmail.com Sat Aug 5 14:12:19 2006 From: john106henry at hotmail.com (John Henry) Date: 5 Aug 2006 11:12:19 -0700 Subject: Pywin32 Excel question In-Reply-To: <1154753200.591305.316770@i42g2000cwa.googlegroups.com> References: <1154746648.811259.111460@h48g2000cwc.googlegroups.com> <1154753200.591305.316770@i42g2000cwa.googlegroups.com> Message-ID: <1154801539.067676.301410@h48g2000cwc.googlegroups.com> Somebody on the Pywin32 list helped. The problem is that: xlSel=xlSheet.Range("1:1,2:2,3:3").Select() is wrong. It should be: xlSel=xlSheet.Range("1:1,2:2,3:3") xlSel.Select() Then I can do the rest. And no, you don't want to do the xlSheet.Copy(). That copies the entire workbook and you end up with a new workbook. But you have to do xlSheet.Paste(). Go figure! mensanator at aol.com wrote: > John Henry wrote: > > I posted the following message to the Pywin32 list but if anybody here > > can help, it would be appreciated very much. > > > > ============================ > > Hi list, > > > > I have a need to copy 3 rows of data from the top of my Excel > > spreadsheet to another location. I would have throught that this > > should be very straightforward since I've done a fair amount of > > Excel/Python programming. Unforturnately, I am stuck on this one. > > > > The VB Macro says I need to: > > > > Range("1:1,2:2,3:3").Select > > Range("A3").Activate > > Selection.Copy > > Rows("20:20").Select > > ActiveSheet.Paste > > > > So, I figure the Python code would be something like: > > > > > > 1) xlSheet=xlApp.ActiveWorkbook.ActiveSheet > > 2) xlSel=xlSheet.Range("1:1,2:2,3:3").Select() > > 3) #xlSel=xlSheet.Range("A3").Activate() > > 4) xlSel.Copy() > > 5) xlSheet.Rows("20:20").Select() > > 6) xlSheet.Paste() > > > > Unfortunately, this doesn't work. After line 2, xlSel becomes "True" - > > not a "Selection" and so the code fails at line 4). I am not sure why > > I have to do the "Activate" on line 3 but it didn't matter, the code > > still fails at line 4. > > My first guess is that the True returned in step 2 merely tells you > the requested selection succeeded (the cells on the worksheet > became highlighted). What would happen if you requested 500 > columns? Would you get False? > > My second guess is that step 4 should be xlSheet.Copy() based > on your using xlSheet.Paste(). > > For that matter, step 5 doesn't assign the result of the select to a > variable. Perhaps that indicates that the assignment isn't necessary? > Or maybe you should test that the selection succeeded before > attempting to paste? > > > > > > > What am I doing wrong? > > > > Any help is greatly appreciated. > > > > Regards, From mzhou at cs.hku.hk Thu Aug 10 13:23:14 2006 From: mzhou at cs.hku.hk (Angelo Zhou) Date: Fri, 11 Aug 2006 01:23:14 +0800 Subject: How to execute a file outside module's namespace? In-Reply-To: References: Message-ID: <44DB6B82.4010705@cs.hku.hk> Slawomir Nowaczyk wrote: > Hello, > > Let's say I have a module "emacs", defining function eexecfile(file): > > def eexecfile(file): > # do other stuff > execfile(file,globals()) > # do other stuff > > Now, assume I have file test.py containing an assignment "x=1" > > If I run python and do: > > import emacs > emacs.eexecfile("test.py") > print emacs.x # works, x was put in module namespace > print x # doesn't work, x is not defined in main script namespace > > What is the best way to make "print x" work? Using the following: > > import __main__ > def eexecfile(file): > # do other stuff > execfile(file, __main__.__dict__) > # do other stuff > > seems to work, but it gives me a slightly uneasy feeling. Is this the > right way? > "from emacs import x" will expose x to the current namespace From roman.yakovenko at gmail.com Thu Aug 24 15:08:09 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Thu, 24 Aug 2006 22:08:09 +0300 Subject: [ANN]Py++ 0.8.1 In-Reply-To: <7465b6170608241156o5119227ds30b3b215c937e781@mail.gmail.com> References: <7465b6170608241156o5119227ds30b3b215c937e781@mail.gmail.com> Message-ID: <7465b6170608241208l3aa69addg7510722c1b42f15d@mail.gmail.com> I'm glad to announce the new version of Py++. Download page: http://language-binding.net/pyplusplus/download.html What is it? Py++ is an object-oriented framework for creating a code generator for Boost.Python library. Project home page: http://language-binding.net/pyplusplus/pyplusplus.html Changes: 1. Support for Boost.Python indexing suite version 2 was implemented. Indexing suite 2, provides support for almost all STD containers. 2. Py++ generates "stable" code. If header files were not changed, Py++ will not change any file. 3. Support for huge classes was added. Py++ is able to split registration code for the class to multiple cpp files. 4. User code could be added almost anywhere, without use of low level API. 5. Py++ will provide user with feedback: warnings about exported declarations. 6. Py++ now supports generation of documentation strings. 7. A lot of bugs were fixed. 8. Documentation was written. -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From http Sun Aug 27 20:31:39 2006 From: http (Paul Rubin) Date: 27 Aug 2006 17:31:39 -0700 Subject: Middle matching - any Python library functions (besides re)? References: <1156722194.089832.282510@74g2000cwt.googlegroups.com> Message-ID: <7xirkd4s5w.fsf@ruckus.brouhaha.com> "EP" writes: > Given that I am looking for matches of all files against all other > files (of similar length) is there a better bet than using re.search? > The initial application concerns files in the 1,000's, and I could use > a good solution for a number of files in the 100,000's. If these are text files, typically you'd use the Unix 'diff' utility to locate the differences. From sjdevnull at yahoo.com Wed Aug 16 18:00:32 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 16 Aug 2006 15:00:32 -0700 Subject: Calling a python script, and getting the returned result in C In-Reply-To: <1155764701.509056.207140@h48g2000cwc.googlegroups.com> References: <1155764701.509056.207140@h48g2000cwc.googlegroups.com> Message-ID: <1155765632.234541.206290@75g2000cwc.googlegroups.com> Shuaib wrote: > Hi! > > I have a python script which returns an Integer value. How do I call > this script from a C programe, and use the result returned? > > Thanks for your time. This is actually a C question, not a Python question. If all you need is the return value of the program, consider looking up the system() call. For more control, variations on popen and fork/exec may be fruitful on Unix (presumably OS X too), or CreateProcess* on MS-Windows. For more detailed help, try comp.unix.programmer or comp.os.ms-windows.programmer (or a similar newsgroup for whatever OS you're using). From ajaksu at gmail.com Fri Aug 11 22:18:18 2006 From: ajaksu at gmail.com (ajaksu) Date: 11 Aug 2006 19:18:18 -0700 Subject: long(Decimal) performance Message-ID: <1155349097.946873.279970@b28g2000cwb.googlegroups.com> Hello c.l.p.ers :) Running long(Decimal) is pretty slow, and the conversion is based on strings. I'm trying to figure out whether there is a good reason for using strings like in decimal.py (that reason would be bound to bite me down the road). This converts Decimal to long and is much faster in my test system (PIII 650MHz, but was written on a P133 a year ago :)). def dec2long(number): """ Convert decimal.Decimal to long. Hopefully faster than C{int(Decimal())}. @param number: A C{decimal.Decimal} value @return: Long from input """ if not isinstance(number, Decimal): raise TypeError, "dec2long requires an instance of Decimal" elif number._is_special: if number._isnan(): raise TypeError, "This Decimal is NaN, an ex-Number" elif number._isinfinity(): raise OverflowError, "Cannot convert infinity to long" else: longstring = str(number) if "e" in longstring: longsplit = longstring.split("e") elif "E" in longstring: longsplit = longstring.split("E") else: longsplit = [longstring, "0"] floatexp = long(len(longsplit[0].split(".")[1])) ftol = long(Decimal(longsplit[0]) * 10L**floatexp) longexp = long(int(longsplit[1]) - floatexp) result = ftol * 10L**longexp return result For the sake of camparison, here's decimal.py __int__: def __int__(self): """Converts self to an int, truncating if necessary.""" [snip: error checking] if self._exp >= 0: s = ''.join(map(str, self._int)) + '0'*self._exp else: s = ''.join(map(str, self._int))[:self._exp] if s == '': s = '0' sign = '-'*self._sign return int(sign + s) Then, some timings: >> example Decimal("7.252714899122810148399426210E+12378") >> %timeit v = dec2long(example) 10 loops, best of 3: 12 ms per loop >> %timeit v = long(example) 10 loops, best of 3: 283 ms per loop >> dec2long(example) == long(example) True Some anachronisms (like 10L) and very probably mistakes are present in that old hack, but it makes decimal somewhat more interesting for me. The answer to this message might be "decimal will be written in C very soon, so nevermind", but I'd love to hear that in fact the following function is wrong and there is a good reason long(Decimal) works based on strings... or that my function is silly but could be corrected. Thanks in advance and best regards, Daniel 'ajaksu' Diniz PS: my use case is Stirling's approximation of the factorial for large numbers, feel free to criticize that, too ;) From mail at microcorp.co.za Mon Aug 7 02:51:02 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Mon, 7 Aug 2006 08:51:02 +0200 Subject: Is there an obvious way to do this in python? References: <44d128e5$0$13484$636a55ce@news.free.fr><1154602887.279222.37980@75g2000cwc.googlegroups.com> Message-ID: <00bd01c6b9f1$15d252c0$03000080@hendrik> "Dennis Lee Bieber" wrote: | On Sat, 5 Aug 2006 11:20:59 +0200, "H J van Rooyen" | declaimed the following in comp.lang.python: | | > | > no such luck - reality will probably be Linux for server, and a horrible mix of | > windoze machines on the client side - from 95 through 98 and 2000 to XP... will | > have to get SAMBA running at least - and it could be tricky with some of the | > older hardware/software around - but that is another fight, that I would have to | > solve anyway. | > | Well, other than the security differences -- which may not apply | when the clients are mounting a share, only when the define a shareable | partition -- I think the Windows side may be similar all the way | through. | | > This is more the kind of thing I had in mind - but I was not thinking in terms | > of having the redirecting done by the OS and network file sharing - stupid I | > suppose... | > | | Not really -- if one first is thinking in terms of "internet", which | means unsecured global operations, instead of an internal-only, behind | firewall, system. *grin* you are being too kind - I was at no stage thinking internet... | | > | add the "share" to the pythonpath (hence you want a uniform system | > | configuration so each machine mounts the share on the same name). | > | | > | > I will have to think of a solution to this *shudders* - config files, maybe... | > | I think Windows can be set to "reconnect on start-up", but it may be | better just to add a BAT file to the client machines' system start-up | directory containing the command line that mounts such a share. | | This is a good idea - thanks - Hendrik From steve at holdenweb.com Fri Aug 18 12:26:52 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 18 Aug 2006 17:26:52 +0100 Subject: sum and strings In-Reply-To: <1155916977.972148.37190@b28g2000cwb.googlegroups.com> References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <7xr6zel2r2.fsf@ruckus.brouhaha.com> <1155916977.972148.37190@b28g2000cwb.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Paul Rubin: > >>Sybren Stuvel: >> >>>Because of "there should only be one way to do it, and that way should >>>be obvious". There are already the str.join and unicode.join methods, >> >>Those are obvious??? > > > They aren't fully obvious (because they are methods of the separator > string), but after reading some documentation about string methods, and > after some tests done on the Python shell, you too can probably use > then without much problems. > Using a bound method can make it a little more obvious. >>> cat = "".join >>> cat(['one', 'two', 'three']) 'onetwothree' >>> cat([u'one', u'two', u'three']) u'onetwothree' >>> regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From lsumnler at gmail.com Mon Aug 14 15:54:55 2006 From: lsumnler at gmail.com (len) Date: 14 Aug 2006 12:54:55 -0700 Subject: Newbie Python SQL Message-ID: <1155585295.185352.87190@b28g2000cwb.googlegroups.com> Hi all Could someone recommend a tutoral, book, white paper, etc. I am trying to write a python program which takes a CSV file and through SQL insert update my SQL files. The SQL files contain a parent file with multiply child and grandchildren plus various files for doing validation. I am using the mxODBC module for access to the SQL files. I have, through the IDLE connected done some simple queries and some testing of insert. I believe I am past the initial stage on the SQL stuff but just can't get to the next level. I have picked up several python book, but all take a very introductory approach. Any recommendation would be appreciated. Len Sumnler From simp at simp.com Sat Aug 26 23:43:03 2006 From: simp at simp.com (BG Simp) Date: Sun, 27 Aug 2006 03:43:03 GMT Subject: MapReduce, Distributed Computing, and Ruby Message-ID: Interesting concept; a drop dead simple distributed library in Ruby. Anything similar in Python? http://tech.rufy.com/2006/08/mapreduce-for-ruby-ridiculously-easy.html From me at invalid.address.com Sat Aug 12 23:11:58 2006 From: me at invalid.address.com (jason) Date: Sun, 13 Aug 2006 03:11:58 GMT Subject: [OT] John Salerno In-Reply-To: <44de73c3$0$12587$c3e8da3@news.astraweb.com> References: <44dd3a65$0$2381$c3e8da3@news.astraweb.com> <44de73c3$0$12587$c3e8da3@news.astraweb.com> Message-ID: <2MwDg.456444$C62.9766@fe12.news.easynews.com> John Salerno wrote: > Alan Connor wrote: > >> Almost certainly bogus. I wouldn't believe anything in this >> fellow's headers or articles. >> >> TROLL. >> I don't help trolls. > > > Ok, I don't know how seriously to take this post, so I won't spend much > time addressing it. All I will say is yes, this is really me and I am > asking a genuine question. Basically just killfile alan connor. It will greatly improve the signal to noise ratio here. He's one of usenets most pathetic and whinest trolls. From rogue_pedro at yahoo.com Sun Aug 13 14:24:55 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 13 Aug 2006 11:24:55 -0700 Subject: open() and Arabic language In-Reply-To: <1155492625.573013.78440@74g2000cwt.googlegroups.com> References: <1155492625.573013.78440@74g2000cwt.googlegroups.com> Message-ID: <1155493495.494510.283330@m73g2000cwd.googlegroups.com> MaaSTaaR wrote: > Hello ... > > firstly , sorry for my bad English . > > i have problem with open() function when i use it with file which name > in Arabic , the open() will not find the file , and i am sure the file > is exist . > > > so how i can solve this problem ? On this page http://www.amk.ca/python/howto/unicode , there is a brief section near the bottom on "Unicode filenames". If your problem is related to Unicode, this may help you, but I'm not sure. HTH, ~Simon From tom-2006 at jaguarpaw.get-rid-of-this-bit.co.uk Wed Aug 23 12:20:56 2006 From: tom-2006 at jaguarpaw.get-rid-of-this-bit.co.uk (Tom E H) Date: Wed, 23 Aug 2006 17:20:56 +0100 Subject: Accessing application data portably Message-ID: <20060823162056.GA4698@weber> My Python application includes some data files that need to be accessed by modules I distribute with it. Where can I put them, and how should I arrange my code, so that it works across platforms? On Linux, I could install the data to "/usr/lib/myprogram/datafile", and on Windows to "datafile" relative to where the executable (made by py2exe) is installed. Then I could detect the operating system, and choose appropriately. To be that explicit seems undesirable. Any cleverer ideas? Tom (Please CC me on replies: I'm not subscribed. The From address is munged) From jantod at gmail.com Tue Aug 29 13:10:29 2006 From: jantod at gmail.com (Janto Dreijer) Date: 29 Aug 2006 10:10:29 -0700 Subject: ntp in python References: <1156846722.129525.254120@i42g2000cwa.googlegroups.com> Message-ID: <1156871429.560618.303540@m79g2000cwm.googlegroups.com> Jeremy Sanders wrote: > Janto Dreijer wrote: > > > I want to measure the packet delivery delays over various network > > links. For this I need to synchronise the times of the sender and > > receiver, either against NTP or eachother. > > Couldn't you just use NTP itself to get the delivery delay? You can read the > delay out from the ntpdc console using dmpeers, or lopeers in ntpq. You > could have two peers either side of the link and measure the delay from > NTP. > > You may also be able to query remote ntp servers to get their delays to > their peers. Unfortunately I don't think that would work for me. I need the delay of a stream of packets. Not just a single delay number. More specifically: I'm testing RTP (VoIP) packet speeds and would like to predict lag (ignoring jitter...separate measurement). From fredrik at pythonware.com Thu Aug 24 15:12:34 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Aug 2006 21:12:34 +0200 Subject: callable to disappear? In-Reply-To: References: <1156357324.838315.234500@i42g2000cwa.googlegroups.com> Message-ID: Terry Reedy wrote: > 1. You cannot know for sure until you call and get a return. with that argument, you might as well remove functions and methods from the language. after all, anything can happen when you call a function. not to mention what import can do. scary. From btowle at carnegielearning.com Fri Aug 25 09:11:46 2006 From: btowle at carnegielearning.com (Brendon Towle) Date: Fri, 25 Aug 2006 09:11:46 -0400 Subject: Consistency in Python In-Reply-To: References: Message-ID: <1FE7929A-67AC-4351-8C74-B5D8DDFC8329@carnegielearning.com> > Date: 25 Aug 2006 04:22:37 -0700 > From: "Paul Boddie" > Subject: Re: Consistency in Python > To: python-list at python.org > Message-ID: <1156504957.511315.223360 at i3g2000cwc.googlegroups.com> > Content-Type: text/plain; charset="iso-8859-1" > > Paul McGuire wrote: >> >> But with mutators that return self, a client could write any of >> these: >> >> bx = Box().length(100).width(50).height(20) >> bx = Box().width(50).height(20).length(100) >> bx = Box().width(50).length(100).height(20) >> ...etc... >> >> and the results are the same. > > This is very convenient, and I've often thought about doing such > things > in my own APIs, but there can sometimes be subtle problems introduced > into programs when you decide to change the nature of such a mutator, > or if you have another type/class whose mutators are of a different > nature, such that the width method produces a new Box object (which is > quite similar to what the questioner seemed to have in mind) > instead of > mutating (or failing to mutate) the existing object. > > Indeed, it may be important to know whether you're creating new > objects > or not, and without metadata the most convenient way to communicate > this is quite probably to define a rigid interface (after all, why > should width or append return an object?) which cannot be implemented > on immutable things. So, it's possible that the above answers the question I have and I'm just not clever enough to see the answer. But: I had a case where I wanted to extract and return the top N elements of a list (where "top" meant "smallest numeric value"; the alternative for "largest numeric value" is a trivial modification). To me, the obvious answer was: def topNElements(lst, n): return lst.sort()[:n] But, of course, that fails with a TypeError, because lst.sort() returns None, which is not subscriptable. The function really needs to be: def topNElements(lst, n): lst.sort() return lst[:n] It gets worse if I want to include an invariant in the list before I sort it: def bogusTopNElementsWithInvariant(lst, n): return lst.append(INVARIANT).sort()[:n] def topNElementsWithInvariant(lst, n) lst.append(INVARIANT) lst.sort() return lst[:n] So, my question is: Someone obviously thought that it was wise and proper to require the longer versions that I write above. Why? B. -- Brendon Towle, PhD Cognitive Scientist +1-412-690-2442x127 Carnegie Learning, Inc. The Cognitive Tutor Company ? Helping over 375,000 students in 1000 school districts succeed in math. -------------- next part -------------- An HTML attachment was scrubbed... URL: From khemkaamit at gmail.com Thu Aug 31 03:04:12 2006 From: khemkaamit at gmail.com (Amit Khemka) Date: Thu, 31 Aug 2006 12:34:12 +0530 Subject: all ip addresses of machines in the local network In-Reply-To: <1156985646.373443.55810@m73g2000cwd.googlegroups.com> References: <1156387621.568779.191420@m73g2000cwd.googlegroups.com> <1156393371.550249.138930@75g2000cwc.googlegroups.com> <1156394781.155152.313080@i3g2000cwc.googlegroups.com> <1360b7230608240328r2c732f86ia8914aaba7a8fb83@mail.gmail.com> <1156985646.373443.55810@m73g2000cwd.googlegroups.com> Message-ID: <1360b7230608310004q337f3db3w13432ef7a1fc5b24@mail.gmail.com> > in my program so far, multiple threads (255 threads in total) spawned > at once with each one of them trying to call socket.gethostbyaddr(ip) > function. i.e. if exception thrown, no machine found. i used .join() to > wait for the threads to terminate. it's fully working however the > problem is that it's too slow. it takes approx. 14 seconds to process > (i tried using 'ping' but it's even slower.). > > my question is.. is there a way to improve performance of the program > if i know what the port number would be? in my case, the port number > will always be constant although i have no clue on what ip addresses > would be (that's the reason all of 255 different addresses must be > tested). > > i tried the same function with the port number specified, > gethostbyaddr(ip:portno), but it is even 10-second slower than using > the same function without a port number specified (i.e. approx. 25 > seconds to complete). You can save some (DNS) overheads by escaping the call "gethostbyaddr", assuming you are not interested in knowing the 'Names' of the machines in your Network. And directly attempt to find the machines which are listenting on the specified port. A simple way of doing this would be to use socket.connect((ip, port)), if the connections succeds you have your machine ! ( There are various other ways of scanning ports, have a look at: http://insecure.org/nmap/nmap_doc.html#connect ) Though I am not sure how 'fast' it would be. Also remember that the time in scanning is affected by network-type, response-time-of-remote-machine, number-of-machines scanned etc. I would still be interested, in seeing how nmap(with some smart options) compares with the python code. ( In my network "nmap -osscan_limit -p 22 -T5 Class_D_Network" completes in 1.5 seconds !) cheers, amit. -- ---- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. From hadeshuang at gmail.com Fri Aug 25 17:55:21 2006 From: hadeshuang at gmail.com (Pebblestone) Date: 25 Aug 2006 14:55:21 -0700 Subject: Python and STL efficiency In-Reply-To: <1156540873.326734.15600@i42g2000cwa.googlegroups.com> References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <1156533768.283454.48570@m73g2000cwd.googlegroups.com> <1156540873.326734.15600@i42g2000cwa.googlegroups.com> Message-ID: <1156542921.203293.199440@i42g2000cwa.googlegroups.com> Oh, I forgot. Your python's example (use direct index array index) of my corresponding lisp code works slower than the version which use 'append'. This let me think how python's list is implemented. Anyway, python's list is surprisingly efficient. bearophileHUGS at lycos.com wrote: > Pebblestone: > > (defun test4 () > > (let ((a (make-array 4000000 :element-type 'string > > :adjustable nil)) > > (b nil)) > > (dotimes (i 1000000) > > (progn > > (let ((j (1- (* 4 i)))) > > (setf (aref a (incf j)) "What do you know") > > (setf (aref a (incf j)) "so long ...") > > (setf (aref a (incf j)) "chicken crosses road") > > (setf (aref a (incf j)) "fool")))) > > (setf b (remove-duplicates a)) > > (map 'vector #'print b))) > > > That test4 function can be compared to this one, with explicit > preallocation (and xrange instead of range!): > > def f2(): > n = 1000000 > a = [None] * n * 4 > for i in xrange(0, n*4, 4): > a[i] = 'What do you know' > a[i+1] = 'so long...' > a[i+2] = 'chicken crosses road' > a[i+3] = 'fool' > for s in set(a): > print s > > But note this a list (that is an array, a list is a different data > structure) of python becomes filled with pointers. I don't know what > your CL does exactly. > > I can also suggest you to use Psyco too here > (http://psyco.sourceforge.net/): > > import psyco > psyco.bind(f2) > > It makes that f2 more than twice faster here. > > Bye, > bearophile From ajaksu at gmail.com Tue Aug 22 19:55:06 2006 From: ajaksu at gmail.com (ajaksu) Date: 22 Aug 2006 16:55:06 -0700 Subject: Job Jar References: <1156271103.398243.45870@b28g2000cwb.googlegroups.com> Message-ID: <1156290905.970017.110950@b28g2000cwb.googlegroups.com> Hi there Steve D wrote: > (...) Basically, I'd like to > create a web-based "job jar", that users in my office can access in > order to view, and "take ownership" of, misc. office tasks. I've seen this kind of feature working in Trac [1], but what you really want is task management software. Of the alternatives already mentioned, roundup is IMHO the most interesting given your request. Just yesterday I found TaskJuggler[2] (can't remember how) but the features sound like what you want. * Manages tasks, resources and costs * Automatic resource leveling, tasks conflict resolutions, and task filtering * Project tracking and status reporting * Flexible working hours and vacation handling This is pretty much "what this kind of software does", not "what taskjuggler does" :) There are hundreds of task managers out there worth a check. Just as examples of the diversity: * I use Planner [3], which is stand-alone and not so feature-rich, besides being too focused at central management IMHO. TaskCoach [4] (wxPython-based) seems pretty similar. * BaseCamp [5] is an online service, paid, new-ish and looks cool (has Python bindings) * dotProject [6] (PHP) looked cool when I tried it... a couple of years ago and before knowing any alternative In Python, faces [7] is the best match I know for your request (take a look at http://faces.homeip.net/examples.html). Tiny's Enterprise Resource Planning [8] might be good for you too. If you have time for that, consider evaluating some projects from: Freshmeat Office/Scheduling: http://freshmeat.net/browse/130/ Freshmeat Office/Groupware: http://freshmeat.net/browse/917/ SF Office/Scheduling: http://sourceforge.net/softwaremap/trove_list.php?form_cat=130 SF Project Management: http://sourceforge.net/softwaremap/trove_list.php?form_cat=607 Wishing you to make a wise choice and enjoy it, Daniel [1] http://willbarton.com/code/tracgantt [2] http://www.taskjuggler.org/ [3] http://live.gnome.org/Planner [4] http://taskcoach.sourceforge.net [5] http://www.basecamphq.com/ [6] http://www.dotproject.net/ [7] http://faces.homeip.net/ [8] http://tinyerp.com/ From grante at visi.com Wed Aug 16 16:55:19 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 16 Aug 2006 20:55:19 -0000 Subject: Adding a char inside path string References: <1155737700.290268.248250@i42g2000cwa.googlegroups.com> <1155744057.573884.111850@m73g2000cwd.googlegroups.com> <1155757548.080769.213490@p79g2000cwp.googlegroups.com> <1155759163.627377.72590@74g2000cwt.googlegroups.com> <12e70d6h4pb3l65@corp.supernews.com> <1155760716.499472.189490@p79g2000cwp.googlegroups.com> Message-ID: <12e71hnet3e7c99@corp.supernews.com> On 2006-08-16, Hitesh wrote: > anything after .exe should be truncated (or deleted). That will fail if any directory names contain the string ".exe", but if that's what you want, it's trivial enough: for s in ["asdfasdf.exe -u", "soemthing/else", "asdf.exe/qwerqwer/qwerqwer.exe"]: print `s`, i = s.find(".exe") print i, if i >= 0: s = s[:i+4] print `s` -- Grant Edwards grante Yow! Yow! It's some people at inside the wall! This is visi.com better than mopping! From justask at acme.com Thu Aug 3 21:24:43 2006 From: justask at acme.com (Vincent Delporte) Date: Fri, 04 Aug 2006 03:24:43 +0200 Subject: [Linux] What toolkit for a good grid/spreadsheet widget? References: <6fo4d2h0lnq2qcgi8jknh0ddmphhdgaulj@4ax.com> Message-ID: On Thu, 3 Aug 2006 22:07:04 +0100, Phil Thompson wrote: >PyQt4 has QTableWidget... Thx for the two pointers. Are those widgets more than just tables, ie. can I edit the contents, including displaying a combo box, can items be grouped or hierarchized, or are they just basic, read-only tables to display results? I need this kind of widget to build a 2+ column interface to let users type entries into the application as an alternative to MS Access-style complicated entry masks. From email at christoph-haas.de Sun Aug 20 15:43:48 2006 From: email at christoph-haas.de (Christoph Haas) Date: Sun, 20 Aug 2006 21:43:48 +0200 Subject: newbie question about import tools In-Reply-To: <1156102756.651208.220800@h48g2000cwc.googlegroups.com> References: <1156102756.651208.220800@h48g2000cwc.googlegroups.com> Message-ID: <200608202143.49885.email@christoph-haas.de> On Sunday 20 August 2006 21:39, pascal.roca at gmail.com wrote: > i have just downloas python and trying to import tools module > > C:\Documents and Settings\toto>python > Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v > Type "help", "copyright", "credits" or "license" > > >>> import tools > > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named tools > > >>> import os > >>> print os > > > > >>> import code > >>> print code > > > > > do i need to download tools.pyc ? There is no such thing as "tools" in the standard library (http://www.python.org/doc/current/lib/lib.html). Why do you expect something like that? Cheers Christoph From duncan.booth at invalid.invalid Thu Aug 3 10:02:32 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 Aug 2006 14:02:32 GMT Subject: opposite of import References: <1154605835.465468.97550@m79g2000cwm.googlegroups.com> <8c7f10c60608030517i1e68433bn569150d379648087@mail.gmail.com> <8c7f10c60608030526u59e97c79m1032d62d1d639fb@mail.gmail.com> Message-ID: Gerhard Fiedler wrote: > On 2006-08-03 09:26:54, Simon Brunning wrote: > >>> import amodule >>> amodule.afunction() # Works fine >>> >>> del amodule >>> amodule.afunction() # Will die now >> >> Note that this doesn't get rid of a module entirely. Python will >> still holds on to the module, and if you just import it again at this >> point, it won't be re-executed - you'll just get another reference to >> the original module. > > Is that guaranteed, or is that just until the garbage collector has > removed the module (at some arbitrary point)? > It is guaranteed that simply deleting the module from the module which imported it won't be sufficient to throw it away as other references to the module will remain (in particular the list of modules used by the import mechanism to ensure you get the same module if you re-import it again in the future). From laurent.pointal at limsi.fr Fri Aug 18 09:51:55 2006 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Fri, 18 Aug 2006 15:51:55 +0200 Subject: Subprocess confusion: how file-like must stdin be? In-Reply-To: References: <9sker3-7g8.ln1@lairds.us> <8skae2l0or9g5d53jdj9g4bafandib75qa@4ax.com> Message-ID: Cameron Laird a ?crit : > In article , > Nick Craig-Wood wrote: >> Dennis Lee Bieber wrote: >>> On Thu, 17 Aug 2006 17:16:25 +0000, claird at lairds.us (Cameron Laird) >>> declaimed the following in comp.lang.python: >>> >>>> Question: >>>> import subprocess, StringIO >>>> >>>> input = StringIO.StringIO("abcdefgh\nabc\n") >>> Here you override the builtin function "input()" >>>> # I don't know of a compact, evocative, and >>>> # cross-platform way to exhibit this behavior. >>>> # For now, depend on cat(1). >>>> p = subprocess.Popen(["cat"], stdout = subprocess.PIPE, >>>> stdin = response) >>> Here you specify the non-existant "response" >> Assume the OP meant to write this >> >>>>> import subprocess, StringIO >>>>> inp = StringIO.StringIO("abcdefgh\nabc\n") >>>>> p = subprocess.Popen(["cat"], stdout = subprocess.PIPE, stdin = inp) >> Traceback (most recent call last): >> File "", line 1, in ? >> File "/usr/lib/python2.4/subprocess.py", line 534, in __init__ >> (p2cread, p2cwrite, >> File "/usr/lib/python2.4/subprocess.py", line 830, in _get_handles >> p2cread = stdin.fileno() >> AttributeError: StringIO instance has no attribute 'fileno' > . > . > . > Yes; my apologies for the confusion I introduced by "editing > for publication", and doing it badly. > > Your interactive session does indeed exhibit the behavior that > puzzles me. My expectation was that StringIO and the std* > parameters to Popen() were made for each other; certainly there > are many cases where stdout and stderr can be redirected *to* a > StringIO. Is it simply the case that stdin demands a more > file-like object? While that disappoints me, I certainly can > program around it. My question, then: does stdin effectively > require something really in the filesystem, or perhaps the > stdout of a previous subprocess? Is there no built-in way to > feed it an in-memory construct? As this is a pipe at OS level, there may be no other way than using os-level tools (ie. real files with fileno), maybe creating an anonymous pipe, writing to it (relying on pipe buffering by the OS to avoid the creation of a writer thread), and giving this pipe (which should have a fileno) to the subprocess.Popen stdin parameter. Such a construction (pipe/writer thread) would be welcome as standard subprocess tool. A+ Laurent. From gmt at sdf-eu.org Wed Aug 16 14:34:16 2006 From: gmt at sdf-eu.org (Max Yuzhakov) Date: Wed, 16 Aug 2006 18:34:16 +0000 (UTC) Subject: It is __del__ calling twice for some instances? References: Message-ID: Max Yuzhakov writes: MY> print "difference = %d" % init_cnt-del_cnt Little correction. print "difference = %d" % (init_cnt-del_cnt) -- GMT More Then ... From maric at aristote.info Thu Aug 24 15:57:21 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 24 Aug 2006 21:57:21 +0200 Subject: String formatting with nested dictionaries In-Reply-To: References: <1156436560.040352.162580@b28g2000cwb.googlegroups.com> Message-ID: <200608242157.22072.maric@aristote.info> Le jeudi 24 ao?t 2006 21:02, Fredrik Lundh a ?crit?: > class wrapper: > ? ? ?def __init__(self, dict): > ????????self.dict = dict > ? ? ?def __getitem__(self, key): > ????????try: > ???????? ? ?return self.dict[key] > ????????except KeyError: > ??????? Quite the same idea, but without eval and the need to know the internal dict arborescence : In [242]: class nested_dict_wrapper : .....: def __init__(self, dic) : .....: self._all = [dic] + [nested_dict_wrapper(v) for v in dic.values() if isinstance(v, dict)] .....: def __getitem__(self, v) : .....: for i in self._all : .....: try : return i[v] .....: except KeyError: pass .....: raise KeyError(v + ' not found in dict and subdicts') .....: .....: In [248]: complex_dict = { '0': 'zero', '1':'one', 'in1' : {'2':'two'}, 'in2': {'3': 'three', '4' :'four', 'deeper':{'5':'five', '6':'six'}}, '7':'seven' } In [250]: "%%(%s)s "*7 % tuple(range(7)) % nested_dict_wrapper(complex_dict) Out[250]: 'zero one two three four five six ' In [251]: "%%(%s)s "*8 % tuple(range(8)) % nested_dict_wrapper(complex_dict) Out[251]: 'zero one two three four five six seven ' In [252]: "%%(%s)s "*9 % tuple(range(9)) % nested_dict_wrapper(complex_dict) --------------------------------------------------------------------------- exceptions.KeyError Traceback (most recent call last) /home/maric/ /home/maric/ in __getitem__(self, v) KeyError: '8 not found in dict and subdicts' -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From onurb at xiludom.gro Fri Aug 11 04:33:35 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 11 Aug 2006 10:33:35 +0200 Subject: hide python code ! In-Reply-To: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> Message-ID: <44dc40e0$0$21151$7a628cd7@news.club-internet.fr> Bayazee wrote: > hi > can we hide a python code ? > if i want to write a commercial software can i hide my source code from > users access ? > we can conver it to pyc but this file can decompiled ... so ...!! It's just the same with java byte-code or machine code. FWIW, I had a cracked (and localised) copy of Steinberg's Cubase midi sequencer v1.1 *before* v1.0 was publicly available in France... And believe me, they had made their best to protect the software (dongle etc...). The only secure way to protect "critical" code is to not distribute it - make it run on your own server, and require the application to access the server. From horpner at yahoo.com Wed Aug 30 09:43:07 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 30 Aug 2006 15:43:07 +0200 Subject: where or filter on list References: <1156939493.558819.8410@i42g2000cwa.googlegroups.com> Message-ID: On 2006-08-30, charles.hebert at gmail.com wrote: > Hi, > > Can anybody tell me how to to find the nearest value to zero in a list > ? > > To do that, i'm using list comprenhension : > >>>> foo = [-5,-1,2,3] # nearest value to zero ? >>>> [value for value in foo if math.fabs(value) == min([int(math.fabs(x)) for x in foo])] > [-1] > > Something simpler ? > How to extend this function to any given value ? A hand-crafted loop seems like an efficient solution: def closest_to(n, seq): m = 0 for i in xrange(1, len(seq)): if abs(n-seq[i]) < abs(n-seq[m]): m = i return seq[m] Putting my faith in Python builtins instead: def closest_to(n, seq): s = [abs(n-x) for x in seq] return seq[s.index(min(s))] -- Neil Cerutti From gagsl-py at yahoo.com.ar Mon Aug 14 17:55:59 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 14 Aug 2006 18:55:59 -0300 Subject: why the method get() of python Queue is hang on there? In-Reply-To: <1155569714.033758.94090@m79g2000cwm.googlegroups.com> References: <1155568212.888733.79920@b28g2000cwb.googlegroups.com> <1155569714.033758.94090@m79g2000cwm.googlegroups.com> Message-ID: <7.0.1.0.0.20060814185300.03a66340@yahoo.com.ar> At Monday 14/8/2006 12:35, zxo102 wrote: >Thanks for your guys. I got it. I thought Queue can be used anywhere >in the code and the second b.get() would return a "None". You can use a list as a generic queue, with append (== push) and pop(0) Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From g.brandl-nospam at gmx.net Wed Aug 30 08:07:07 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Wed, 30 Aug 2006 14:07:07 +0200 Subject: refering to base classes In-Reply-To: <44F56FF8.7030406@hotmail.com> References: <1156862012.068397.284040@m73g2000cwd.googlegroups.com> <1156909737.259769.36160@e3g2000cwe.googlegroups.com> <1156934636.822263.231440@b28g2000cwb.googlegroups.com> <44F56FF8.7030406@hotmail.com> Message-ID: Chaz Ginger wrote: > glenn wrote: >>> Shouldn't that be >>> >>> beagle = animal.dog() >>> >>> to create an instance? >>> >>> We've all done it ... >> lol - actually Im confused about this - there seem to be cases where >> instantiaing with: >> instance=module.classname() >> gives me an error, but >> instance=module.classname >> doesnt - so I got into that habit, except for where I had a constructor >> with parameters - except now Im feeling foolish because I cant >> replicate the error - which suggests I didnt understand the error >> message properly in the first place... arrgh >> I guess thats just part of the process of gaining a new language. >> >> glenn >> > > module.classname and module.classname() are two different things. If you > use module.classname() you invoke the __new__ and __init__ methods in > the class, and you might get an error from them. > > On the other hand module.classname will always work, assuming classname > really exists in module. What you get back is a sort of reference to the > class itself and not an instance of it. It is not a sort of reference to the class, it is *the class itself*. >>> class A: ... pass ... >>> A >>> Georg From rosedb0 at gmail.com Tue Aug 8 17:11:49 2006 From: rosedb0 at gmail.com (hiaips) Date: 8 Aug 2006 14:11:49 -0700 Subject: newb question: file searching In-Reply-To: <1155071433.686040.276080@m79g2000cwm.googlegroups.com> References: <1155067111.892386.130610@n13g2000cwa.googlegroups.com> <1155067720.211789.208560@i42g2000cwa.googlegroups.com> <1155068675.101390.299110@i3g2000cwc.googlegroups.com> <1155070517.448510.149380@b28g2000cwb.googlegroups.com> <1155071433.686040.276080@m79g2000cwm.googlegroups.com> Message-ID: <1155071509.526393.283100@m79g2000cwm.googlegroups.com> Oops, what I wrote above isn't quite correct. As another poster pointed out, you'd want to do for file in x[2]: ... --dave From miki.tebeka at gmail.com Tue Aug 8 15:01:11 2006 From: miki.tebeka at gmail.com (Miki) Date: 8 Aug 2006 12:01:11 -0700 Subject: Accessing Yahoo Mail withtout POP In-Reply-To: <1155050998.864753.198990@m79g2000cwm.googlegroups.com> References: <1155050998.864753.198990@m79g2000cwm.googlegroups.com> Message-ID: <1155063671.049833.74390@m73g2000cwd.googlegroups.com> Hello T, > Is there a way to access yahoo mail via its web interface? If so, can > someone give some pointers? http://www.crummy.com/software/BeautifulSoup/ http://wwwsearch.sourceforge.net/ClientForm/ HTH, Miki http://pythonwise.blogspot.com/ From steve at holdenweb.com Wed Aug 16 06:50:43 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 16 Aug 2006 11:50:43 +0100 Subject: programming with Python 3000 in mind In-Reply-To: References: <1155672987.522793.47080@74g2000cwt.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Tue, 15 Aug 2006 13:16:27 -0700, beliavsky wrote: > > >>The current beta version of Python is 2.5 . How can a Python programmer >>minimize the number of changes that will be needed to run his code in >>Python 3000? In general, he should know what is being removed from >>Python 3000 and if possible use the "modern" analogs in Python. > > > In general, you can't, as Python 3000 hasn't been nailed down yet. > > You shouldn't be asking "How do I write for a language that doesn't exist > yet?" but instead should ask: > > (1) How far away is Python 3000? > > Years away, although not that many years. Three? Four? > Two. > (2) Will there be automated tools for converting source code from Python 2 > to Python 3000? > > Almost certainly. > Yes. > (3) Once Python 3000 is released, will Python 2 still be supported and if > so, for how long? > > I'm sure there will be a nice long transition period, and if the Python > developers don't want to support Python 2, it will be a wonderful > opportunity for some commercial operation to charge for support. For the answers to questions like these see http://video.google.com/videoplay?docid=-6459339159268485356 which is Guido's rehearsal for his OSCON presentation on Python 3000. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From bearophileHUGS at lycos.com Wed Aug 9 16:23:47 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 9 Aug 2006 13:23:47 -0700 Subject: technique to enter text using a mobile phone keypad (T9 dictionary-based disambiguation) In-Reply-To: <1155154447.409931.55750@p79g2000cwp.googlegroups.com> References: <1155095477.440347.149350@m79g2000cwm.googlegroups.com> <1155154447.409931.55750@p79g2000cwp.googlegroups.com> Message-ID: <1155155027.385789.59280@75g2000cwc.googlegroups.com> Note that this is essentially a data-compression problem, so the most accurate solution is probably to use an instrumeted PAQ compressor in a certain smart way, but you have to work a lot to implement this solution, and maybe this problem doesn't deserve all this work. Bye, bearophile From steve at holdenweb.com Tue Aug 15 20:56:04 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 16 Aug 2006 01:56:04 +0100 Subject: Clean way to not get object back from instantiation attempt gone bad In-Reply-To: <44e245c0$0$20991$88260bb3@free.teranews.com> References: <44e245c0$0$20991$88260bb3@free.teranews.com> Message-ID: tobiah wrote: > Suppose I do: > > > myfoo = Foo('grapes', 'oranges') > > And in the __init__() of Foo, there is > a real problem with the consumption of fruit. > Is there a clean way to ensure that myfoo > will be None after the call? Would the > __init__() just do del(self), or is there > a better way to think about this? > There's no way that the __init__() method can change the object of which it's a method, since self is a variable local to the method (so changing it won't change the object) and the method is required to return None. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From john at castleamber.com Fri Aug 25 15:28:05 2006 From: john at castleamber.com (John Bokma) Date: 25 Aug 2006 19:28:05 GMT Subject: Duck typing alows true polymorfisim References: <1156532721.879808.40990@i3g2000cwc.googlegroups.com> Message-ID: atbusbook at aol.com wrote: > lets say you want a generic numerical algorithom like sum Hmmm, I thought you were going to announce that you were the first born son of Xah Lee. Actually you did! -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From slawomir.nowaczyk.847 at student.lu.se Thu Aug 3 16:08:06 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Thu, 03 Aug 2006 22:08:06 +0200 Subject: Static Variables in Python? In-Reply-To: <002101c6b55e$d947c330$0d7d12ac@kearfott.com> References: <1154379285.20290.51.camel@devilbox> <002101c6b55e$d947c330$0d7d12ac@kearfott.com> Message-ID: <20060803170040.A99D.SLAWOMIR.NOWACZYK.847@student.lu.se> On Tue, 01 Aug 2006 07:37:20 -0400 Michael Yanowitz wrote: #> I like the class idea, however I realize that the class object itself #> has to be global. But no more global than your original set_bit was... -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) To err is human, but to really fuck things up takes a computer. From tim.leeuwvander at nl.unisys.com Tue Aug 22 08:39:59 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 22 Aug 2006 05:39:59 -0700 Subject: Python and STL efficiency In-Reply-To: <1hkh6lb.6dsnh51lj8z96N%riko@despammed.com> References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <1hkh28d.xscw4v1y4v9a6N%riko@despammed.com> <1hkh6lb.6dsnh51lj8z96N%riko@despammed.com> Message-ID: <1156250399.018838.74780@74g2000cwt.googlegroups.com> Mc Osten wrote: > Fredrik Lundh wrote: > > > Python's memory allocator is also quite fast, compared to most generic > > allocators... > > In fact also in the two "slow" versions Python outperforms C++. > I didn't notice it in the first place. > But your C++ program outputs times in seconds, right? So all compilations except for the first two give results in less than a second, right? (meaning the optimizations of your standard-compilation give worst results than -O3?) BTW, I don't quite understand your gcc optimizations for the first 2 compiles anyways: two -O options with different values. Doesn't that mean the 2nd -O takes preference, and the compilation is at -O2 instead of -O3? Why both -O3 and -O2 at the command-line? Cheers, --Tim > -- > blog: http://www.akropolix.net/rik0/blogs | Uccidete i filosofi, > site: http://www.akropolix.net/rik0/ | tenetevi riso e > forum: http://www.akropolix.net/forum/ | bacchette per voi. From simon at brunningonline.net Wed Aug 23 12:37:26 2006 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 23 Aug 2006 17:37:26 +0100 Subject: how do you get the name of a dictionary? In-Reply-To: <1156350580.363393.256730@74g2000cwt.googlegroups.com> References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1156268752.574983.123520@75g2000cwc.googlegroups.com> <1156281268.865624.302070@b28g2000cwb.googlegroups.com> <1156283135.985893.186500@m73g2000cwd.googlegroups.com> <1156284812.469380.274370@b28g2000cwb.googlegroups.com> <1156350580.363393.256730@74g2000cwt.googlegroups.com> Message-ID: <8c7f10c60608230937k1aae9f97k402bc04e2e7753ba@mail.gmail.com> On 23 Aug 2006 09:29:40 -0700, jojoba wrote: > And what im saying is that isnt it silly that we need pass an entire > namespace, when a much simpler notion would be to have each object know > its own name(s) (even if that name doesnt exist). > Now, here's where everyone tells me this isnt possible, and how my > statement implies that i have no idea whatsoever of how python > works.... It's not inconcevable that Python could behave that way, it's just that it would impose an overhead on the 99.999% of Python users who would have no use for the feature. It's a price not worth paying. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From neokosmos at gmail.com Thu Aug 10 23:14:23 2006 From: neokosmos at gmail.com (neokosmos at gmail.com) Date: 10 Aug 2006 20:14:23 -0700 Subject: Python share CPU time? In-Reply-To: <1155264846.279626.62120@p79g2000cwp.googlegroups.com> References: <1155146500.063665.282430@p79g2000cwp.googlegroups.com> <1155253594.681570.145910@b28g2000cwb.googlegroups.com> <1155262197.473682.5210@m73g2000cwd.googlegroups.com> <1155264846.279626.62120@p79g2000cwp.googlegroups.com> Message-ID: <1155266063.730916.54700@m73g2000cwd.googlegroups.com> alex23 wrote: > Simon Forman wrote: > > This is just a dim memory, but something called lambdaMOO was (is?) a > > Multi-User Dungeon that had (has?) a model of processing that allowed > > you to create programmed objects that received a "budget" of processor > > time. The objects would not work if they "ran out" of processor > > time... > > It basically employs its own threading model to do just this. > SecondLife does much the same: any system that allows for the apparent > parallel running of code will. IIRC, LambdaMOO's threading model is based on cooperative multitasking, possibly with the ability to limit how many VM-level instructions a piece of code executes per timeslice (I'm not intimately familiar with it). However, such an ability to limit how many instructions are executed per timeslice really requires VM-level support. In LPMUDs, which I am much more familiar with, and which also implement a similar cooperative multitasking "thread model" (I put this in quotes because it's not really threading -- it's actually a near equivalent of generator-based microthreads), it's still possible to lag the game for long periods of time with any reasonable limit on the number of instructions per "tick." That might not matter much for a hypothetical Python-based robot game, if it weren't designed to be interactive. > LambdaMOO still exists, incidentally! You might also be interested in a > python-implemented version of the main MOO core, the unfortunately > named POO: http://www.strout.net/python/poo/ I believe POO's "thread model" is much the same as I've described above: inherently it's cooperative multitasking. Incidentally, if you don't like the name POO, there's also MOOP at moop.sourceforge.net. I don't know if MOOP is derived from POO, but they have similar descriptions and aims, so I wouldn't be *too* surprised. From http Mon Aug 7 16:38:25 2006 From: http (Paul Rubin) Date: 07 Aug 2006 13:38:25 -0700 Subject: format a number for output References: <1154962511.485221.229830@i3g2000cwc.googlegroups.com> Message-ID: <7xwt9kth6m.fsf@ruckus.brouhaha.com> "abcd" writes: > 1890284 > > would be: > > 1,890,284 "To iterate is human; to recurse, divine": def commafy(n): if n < 0: return '-' + commafy(-n) if n >= 1000: return '%s,%03d' % (commafy(n//1000), n % 1000) return '%s'% n I don't like the locale solution because of how messy locales are. From ptmcg at austin.rr._bogus_.com Tue Aug 1 10:41:55 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 01 Aug 2006 14:41:55 GMT Subject: Python-list Digest, Vol 35, Issue 10 References: Message-ID: Can someone PLEASE remove support at mathworks.co.uk from the subscriber list??? From mariano.difelice at gmail.com Tue Aug 22 04:32:14 2006 From: mariano.difelice at gmail.com (mardif) Date: 22 Aug 2006 01:32:14 -0700 Subject: wxWindow GetPosition() bug??? Message-ID: <1156235534.691321.154720@75g2000cwc.googlegroups.com> Hi, I've found a strange behavior in method GetPosition() of wxWindow class ( and derived ). On windows, if you create a window object frame = wx.Frame(None, -1, "TESTING") and you set the position to: frame.SetPosition( (300, 45000) ) If you call method GetPosition, the result will be: frame.GetPosition() >>> (300, 32767) 32767 is the integer limit. Why GetPosition() returns this value??? and why on Unix Platform this problem was not found?? thx very much! bye From martin at v.loewis.de Mon Aug 7 08:00:06 2006 From: martin at v.loewis.de (=?ISO-8859-2?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 07 Aug 2006 14:00:06 +0200 Subject: VisualStudio2005 supported in distutils In-Reply-To: References: <44D11BC3.40802@v.loewis.de> Message-ID: <44D72B46.2060802@v.loewis.de> Jarek Zgoda schrieb: > Sure, but what if I succesfully compile Python with VS 2005? Hier ist > der Hund begraben, distutils cann't handle this compiler so I'll be > unable to compile any extension for my home-baken Python. It sure can. Just open a "Visual Studio Command Prompt" (or whatever its name), and make sure MSSdk and DISTUTILS_USE_SDK are both set. Then distutils will use the compiler from PATH, rather than the pre-configured one. Regards, Martin From jiangnutao at gmail.com Wed Aug 23 18:45:04 2006 From: jiangnutao at gmail.com (Jason Jiang) Date: Wed, 23 Aug 2006 15:45:04 -0700 Subject: how to get file name of the running .py file Message-ID: Hi, How to get the name of the running .py file like the macro _FILE_ in C? Thanks. Jason From tjreedy at udel.edu Sun Aug 6 22:48:56 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 6 Aug 2006 22:48:56 -0400 Subject: Open letter to BDFL begging forgiveness. References: <1154898826.309400.66920@h48g2000cwc.googlegroups.com> Message-ID: "The Eternal Squire" wrote in message news:1154898826.309400.66920 at h48g2000cwc.googlegroups.com... I tried to send you a private response but Comcast rejected it ('not a customer'). tjr From chosechu at gmail.com Tue Aug 29 08:58:45 2006 From: chosechu at gmail.com (chosechu) Date: 29 Aug 2006 05:58:45 -0700 Subject: Extending the dict class In-Reply-To: References: <1156852916.254032.172390@b28g2000cwb.googlegroups.com> <44f4313e$0$26985$626a54ce@news.free.fr> <1156854958.228815.107090@m73g2000cwd.googlegroups.com> Message-ID: <1156856325.095181.303140@p79g2000cwp.googlegroups.com> Duncan Booth wrote: > If the order of the argument names matters, then it seems to me that should > be handled by the SOAP library, not pushed onto the end user whoch should > just be calling the function with the named arguments in the most > convenient order. > > Shouldn't SOAPpy be able to get this information out of the WSDL? Yes, SOAPpy could extract this from the WSDL specs. SOAPpy could also find another way to pass call parameters, but I kinda like the named parameters (seems really Python-like). Microsoft could also build SOAP services that parse XML without making ordering mandatory where nobody said it was. ... but we are living in a different dimension, one where I can extend the Python dict class but not touch 2 of its 3 constructors (of course the most useful ones). If you really want to know, I ended up at the socket level pushing templatized strings. Wish me luck with future server changes. From riko at despammed.com Wed Aug 23 17:24:10 2006 From: riko at despammed.com (Mc Osten) Date: Wed, 23 Aug 2006 23:24:10 +0200 Subject: Python and STL efficiency References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <1hkh28d.xscw4v1y4v9a6N%riko@despammed.com> <1hkh6lb.6dsnh51lj8z96N%riko@despammed.com> <1156252193.524186.107520@b28g2000cwb.googlegroups.com> <1hkhexv.18m65rl61swqyN%riko@despammed.com> <1156265848.875774.251640@i42g2000cwa.googlegroups.com> <1156290607.269119.88710@b28g2000cwb.googlegroups.com> <1hkil6j.xm4l6y1kwo13dN%riko@despammed.com> <1156317315.946762.215690@p79g2000cwp.googlegroups.com> <1hkioxy.42be4c1lg0jq5N%riko@despammed.com> <1156320792.011620.141030@m79g2000cwm.googlegroups.com> <1hkitqt.c17kl5o30nr4N%riko@despammed.com> <1156340217.774595.282950@75g2000cwc.googlegroups.com> Message-ID: <1hkjdl9.z4aksv1p8hlz2N%riko@despammed.com> Tim N. van der Leeuw wrote: > I have to admit to a stupid mistake, for which I feel quite ashamed - I > got the loop-size wrong in the Python code. So all Python results > posted by me were off by a factor of 10 :-( > I feel quite bad about that! Well, this makes *my* results quite surprising. I checked it threetimes. I loop 1000000 times in both Python and C++, and Python here is faster. -- blog: http://www.akropolix.net/rik0/blogs | Uccidete i filosofi, site: http://www.akropolix.net/rik0/ | tenetevi riso e forum: http://www.akropolix.net/forum/ | bacchette per voi. From steve at REMOVEME.cybersource.com.au Mon Aug 21 22:13:13 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 22 Aug 2006 12:13:13 +1000 Subject: sum and strings References: <1155883675.429106.291570@m73g2000cwd.googlegroups.com> <1155922208.930580.135080@m79g2000cwm.googlegroups.com> <1155952305.848495.7060@i3g2000cwc.googlegroups.com> <7x4pw9h3yy.fsf@ruckus.brouhaha.com> Message-ID: On Mon, 21 Aug 2006 12:55:14 +0200, Fredrik Lundh wrote: > Steven D'Aprano wrote: > >> That's a nonsense argument. There is no shortage of slow algorithms, and >> some of them are built into Python. When did O(n**2) become an error >> condition? And overhead matters: if I'm only doing a few concatenations, >> it is significantly faster to add the strings using + than to use join() >> (at least in Python 2.3 -- YMMV): >> >>>>> s = timeit.Timer("''.join(L)", "L=['a'*50, 'b'*50, 'c'*50]") >>>>> s.timeit() >> 1.3470098972320557 >>>>> t = timeit.Timer("a+b+c", "a,b,c = 'a'*50, 'b'*50, 'c'*50") >>>>> t.timeit() >> 1.0698421001434326 > > and what exactly does the fact that Python can do operator-based > dispatch much faster than it can do method-based dispatch have to > do with sum's inability to add strings ? Sorry, I don't get you here. Are you saying that string addition doesn't call the operands' __add__ methods? Obviously I would have preferred to have done a direct test of sum() versus join(), but I can't since sum() goes out of its way to make that difficult. Or maybe I can... >>> setup0 = """class Magic: ... def __add__(self, other): return other ... ... L = ['a', 'b'] ... M = Magic() ... """ >>> >>> t5 = timeit.Timer("sum(L, M)", setup) >>> t5.timeit() 12.319401025772095 That's bizarrely slow for concatenating two characters. It's an order of magnitude slower than doing a direct addition of two characters, and about one third the speed of a pure Python implementation: >>> setup1 = """def mysum(strlist): ... t = "" ... for s in strlist: t = t+s ... return t ... ... a, b, c, d, = 'a', 'b', 'c', 'd' ... """ >>> >>> t6 = timeit.Timer("mysum([a,b,c,d])", setup1) >>> t6.timeit() 4.3943448066711426 What's going on here? What have I missed? I know adding strings is O(n**2), but these results don't make any sense to me. -- Steven D'Aprano From fredrik at pythonware.com Wed Aug 30 01:43:24 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 30 Aug 2006 07:43:24 +0200 Subject: Allowing ref counting to close file items bad style? In-Reply-To: <9U6Jg.951$Xw6.283@trndny02> References: <9U6Jg.951$Xw6.283@trndny02> Message-ID: Dan wrote: > Is this discouraged?: > > for line in open(filename): > > > That is, should I do this instead?: > > fileptr = open(filename) > for line in fileptr: > > fileptr.close() depends on the use case; in a small program that you know will only read a few files, you can leave it to the system (especially on CPython). if you're about to process large number of files, or you're writing files, it's usually better to be explicit. note that to be really safe, you should use try/finally: f = open(filename) try: f.write(...) finally: f.close() From drodrig at magicbrain.com Sun Aug 13 11:17:23 2006 From: drodrig at magicbrain.com (drodrig) Date: 13 Aug 2006 08:17:23 -0700 Subject: Kill process based on window name (win32) References: <1155356918.399290.266470@p79g2000cwp.googlegroups.com> <1155362407_8127@sp6iad.superfeed.net> <1155410258.877085.86840@75g2000cwc.googlegroups.com> Message-ID: <1155482243.307372.6350@75g2000cwc.googlegroups.com> I am running the program mentioned below as an NT service on a terminal server. The service listens on a UDP port for any of a series of commands. In this case, the command "closeApps " will notify the service to close all the open apps for user (). So while the code below works great for a standalone app, it fails as a service because the window handles of each user are not retrievable (I should say I don't know how to retrieve them). Is this even possible? I looked at some of the Windows API calls but nothing stuck out. Suggestions? drodrig wrote: > Thank you Roger. Your advice did the trick. For anyone interested, the > basic code to terminate a process (politely) would be something like > this (hwnd is retrieved using win32gui.EnumerateWindows): > > # Get the window's process id's > t, p = win32process.GetWindowThreadProcessId(hwnd) > # Ask window nicely to close > win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0) > # Allow some time for app to close > time.sleep(10) > # If app didn't close, force close > try: > handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, p) > if handle: > win32api.TerminateProcess(handle,0) > win32api.CloseHandle(handle) > except: > pass: > > Roger Upole wrote: > > drodrig wrote: > > > Hi. > > > > > > I am trying to close/kill all processes that show visible windows on > > > Windows XP. So far I've created a script that uses win32gui.EnumWindows > > > to iterate through all windows, check for which windows are visible, > > > then send a WM_CLOSE message to the window to request that it closes. > > > Of course, not all apps want to close nicely. At this point I need to > > > use something like TerminateProcess to kill the app, but how do I find > > > the process id (hopefully based on the window id). > > > > > > Thanks for any help. > > > > > > > win32process.GetWindowThreadProcessId should do the trick. > > > > Roger From onurb at xiludom.gro Mon Aug 28 11:50:58 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 28 Aug 2006 17:50:58 +0200 Subject: Truly platform-independent DB access in Python? In-Reply-To: <1156778705.807852.140510@75g2000cwc.googlegroups.com> References: <1156748466.739709.117850@h48g2000cwc.googlegroups.com> <44f2bade$0$13039$626a54ce@news.free.fr> <1156778705.807852.140510@75g2000cwc.googlegroups.com> Message-ID: <44f310e3$0$26022$636a55ce@news.free.fr> Boris Du?ek wrote: > Bruno Desthuilliers wrote: >> bobrik wrote: >>> Hello, >>> >>> I am using the Python DB API for access to MySQL. But it is not >>> platform-independent >> It is. You don't have to change your Python code according to the OS or >> CPU. >> > What I mean is that wiht platform-independent access, I should be able > to not care on which operating system is the web server accessing my > scripts where I use MySQLdb When it comes to *using* MySQLdb, you don't care about the OS, CPU and whatnot. > which I have to install (and therfore > platform-dependently) compile myself. This is a very distinct problem. > The important point is that > MySQLdb is installed as an extra module. So you have to compile it > manually, Usually, cd && python setup.py install do the job. > but what if the OS with server accessing the site that is on > shared area changes? And what if Python is not installed on it ?-) Seriously, do you think that hosting companies swap OS very often ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From fredrik at pythonware.com Fri Aug 25 17:58:16 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Aug 2006 23:58:16 +0200 Subject: RE Module In-Reply-To: <44ef6207$0$8914$88260bb3@free.teranews.com> References: <1156478366.165463.277480@h48g2000cwc.googlegroups.com> <44ef3f95$0$8926$88260bb3@free.teranews.com> <1156539112.253232.321820@i3g2000cwc.googlegroups.com> <44ef5ba7$0$8907$88260bb3@free.teranews.com> <44ef6207$0$8914$88260bb3@free.teranews.com> Message-ID: tobiah wrote: > Also, how does the engine decide whether I am adjusting > the greed of the previous operator, or just asking > for another possible character? "?" always modifies the *preceeding* RE element. if the preceeding element is a pattern (e.g. a character or group), it means that the pattern is optional. if the preceeding element is a repeat modifier (*, +, or ?), it changes the greediness. > Suppose I want: > > "x*?" to match "xxxxxxxO" > > If the '?' means non greedy, then I should get 'x' back. no, because "*" means *ZERO* or more matches, not one or more. > If the '?' means optional character then I should get > the full string back. no, because "?" never means anything on its own; it's a pattern modifier, not a pattern. > Checking in python: > > ###################################### > import re > > s = 'xxxxxxx0' > > m = re.search("x*", s) > print "First way", m.group(0) > > m = re.search("x*?", s) > print "Second way", m.group(0) > ##################################### > First way xxxxxxx > Second way > > So now I'm really confused. It didn't do a non-greedy > 'x' match, nor did it allow the '?' to match the '0'. see above. reading the RE documentation again may also help. From B.Ogryczak at gmail.com Fri Aug 4 05:09:56 2006 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 4 Aug 2006 02:09:56 -0700 Subject: Which KDE IDE for Python? Message-ID: <1154682596.419636.70320@p79g2000cwp.googlegroups.com> Hi, Rigth now I'm using two IDEs for Python, KDevelop and Eric. Both have drawbacks. KDevelop is a multilanguage IDE, and doesn't really have anything special for Python. There's no Python debugger, no PyDOC integration, it's class browser doesn't display attributes. On the other side there's Eric, which is made just for Python. But.. it doesn't integrate with KDE, doesn't support remote files (fish://, ftp:// etc.). Does anyone know a better IDE for Python, that'll integrate nicely with KDE? From pavlovevidence at gmail.com Tue Aug 8 18:59:25 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 8 Aug 2006 15:59:25 -0700 Subject: do people really complain about significant whitespace? In-Reply-To: References: <1154986984.740638.241130@m79g2000cwm.googlegroups.com> <87bqqwyumq.fsf@benfinney.id.au> Message-ID: <1155077965.100108.232790@m79g2000cwm.googlegroups.com> Michiel Sikma wrote: > Op 8-aug-2006, om 1:49 heeft Ben Finney het volgende geschreven: > > > As others have pointed out, these people really do exist, and they > > each believe their preconception -- that significant whitespace is > > intrinsically wrong -- is valid, and automatically makes Python a > > lesser language. > > Well, I most certainly disagree with that, of course, but you gotta > admit that there's something really charming about running an auto- > formatting script on a large piece of C code, turning it from an > unreadable mess into a beautifully indented and organized document. The only time I get that satisfaction is when I run the formatter to format some C code I'm asked to debug. Quite often the problem was something that could have been easily spotted if the coder had used good indentation in the first place. Though they probably wouldn't have seen it anyways, considering the poor programming skills of most engineers (the classical definition, not computer engineers). The very fact the code formatters exist should tell you that grouping by indentation is superior. Carl Banks From exarkun at divmod.com Sat Aug 12 12:52:34 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sat, 12 Aug 2006 12:52:34 -0400 Subject: start a multi-sockets server (a socket/per thread) with different ports but same host In-Reply-To: <1155398402.738765.238610@m73g2000cwd.googlegroups.com> Message-ID: <20060812165234.1717.1385772235.divmod.quotient.20802@ohm> On 12 Aug 2006 09:00:02 -0700, zxo102 wrote: >Hi, > I am doing a small project using socket server and thread in python. > This is first time for me to use socket and thread things. > Here is my case. I have 20 socket clients. Each client send a set >of sensor data per second to a socket server. The socket server will >do two things: 1. write data into a file via bsddb; 2. forward the data >to a GUI written in wxpython. > I am thinking the code should work as follow (not sure it is >feasible) > 20 threads, each thread takes care of a socket server with a >different port. > I want all socket servers start up and wait for client connection. >In the attached demo code, It stops at the startup of first socket >server somewhere in the following two lines and waits for client call: > Threads aren't the best way to manage the concurrency present in this application. Instead, consider using non-blocking sockets with an event notification system. For example, using Twisted, your program might look something like this: from twisted.internet import reactor, protocol, defer class CumulativeEchoProtocol(protocol.Protocol): def connectionMade(self): # Stop listening on the port which accepted this connection self.factory.port.stopListening() # Set up a list in which to collect the bytes which we receive self.received = [] def connectionLost(self, reason): # Notify the main program that this connection has been lost, so # that it can exit the process when there are no more connections. self.factory.onConnectionLost.callback(self) def dataReceived(self, data): # Accumulate the new data in our list self.received.append(data) # And then echo the entire list so far back to the client self.transport.write(''.join(self.data)) def allConnectionsLost(): # When all connections have been dropped, stop the reactor so the # process can exit. reactor.stop() def main(): # Set up a list to collect Deferreds in. When all of these Deferreds # have had callback() invoked on them, the reactor will be stopped. completionDeferreds = [] for i in xrange(20): # Make a new factory for this port f = protocol.ServerFactory() # Make a Deferred for this port's connection-lost event and make # it available to the protocol by way of the factory. d = defer.Deferred() f.onConnectionLost = d completionDeferreds.append(d) f.protocol = CumulativeEchoProtocol # Start listening on a particular port number with this factory port = reactor.listenTCP(2000 + i + 1, f) # Make the port object available to the protocol as well, so that # it can be shut down when a connection is made. f.port = port # Create a Deferred which will only be called back when all the other # Deferreds in this list have been called back. d = defer.DeferredList(completionDeferreds) # And tell it to stop the reactor when it fires d.addCallback(lambda result: allConnectionsLost()) # Start the reactor so things can start happening reactor.run() if __name__ == '__main__': main() Hope this helps, Jean-Paul From jlara_garduno at hotmail.com Sun Aug 6 20:28:38 2006 From: jlara_garduno at hotmail.com (heavydada) Date: 6 Aug 2006 17:28:38 -0700 Subject: Question about using python as a scripting language Message-ID: <1154910518.506581.26470@b28g2000cwb.googlegroups.com> I'm writing a small game in python and I need to be able to run some scripts inside the game. In the game I have these creatures each with some attributes like name and weight and an action. Right now I'm saving all this information in an XML file, which I parse whenever I need it. I can handle the attributes like name and weight because these are just values I can assign to a variable, but the action part is what has me stumped. Each of the creatures has a different action() function (as in, each does something different). I was wondering how I can read commands from the XML file and then execute them in the game. I read a document that talked about this, but it was written in Visual Basic and used a method called callByName or something like that. It could call a function simply by sending the name as a string parameter. I was wondering if there was an equivalent in python. I just need some way of being able to read from the file what function the program needs to call next. Any help is appreciated. From johnjsal at NOSPAMgmail.com Thu Aug 10 11:40:03 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 10 Aug 2006 15:40:03 GMT Subject: Make Object Oriented? In-Reply-To: <44db51e1$0$21148$7a628cd7@news.club-internet.fr> References: <1155214883.129267.317570@p79g2000cwp.googlegroups.com> <44db51e1$0$21148$7a628cd7@news.club-internet.fr> Message-ID: Bruno Desthuilliers wrote: > eduardo.padoan at gmail.com wrote: >> It would be ease to create such a tool > > Hmmm ? May I express some very huge doubts here ? But the link he gave also says this: "Perfect Java programs can be written..." Ok, I think some of this group's less-than-favorable opinion of Java has rubbed off on me. :) From grante at visi.com Wed Aug 30 10:54:40 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 30 Aug 2006 14:54:40 -0000 Subject: How ahead are you guys in the (Python) real world? References: <1156821234.820929.299740@p79g2000cwp.googlegroups.com> Message-ID: <12fb9lgmt595b79@corp.supernews.com> On 2006-08-30, John Salerno wrote: > Ray wrote: > >> However I wonder, how fast are you guys moving from version to version >> at work? > > Interesting question. Just as a curious follow-up (not being > someone who works in the programming world), why does it take > so long to move to the latest version, Two reasons: 1) "If it ain't broke, don't f*** with it." 2) There's always something else that is broke. > especially when there aren't (I don't think) any changes that > would break existing code, After doing a few sowftware upgrades you quickly learn to never, ever believe that. The best working hypothesis is that upgrading will break things. So the questions when considering an upgrade are: 1) Is there a new feature I want? 2) Is that feature worth fixing the update breaking? -- Grant Edwards grante Yow! CALIFORNIA is where at people from IOWA or NEW visi.com YORK go to subscribe to CABLE TELEVISION!! From python.list at tim.thechases.com Thu Aug 3 15:51:20 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 03 Aug 2006 14:51:20 -0500 Subject: OS independent files In-Reply-To: <1154632873.085941.281850@75g2000cwc.googlegroups.com> References: <1154632873.085941.281850@75g2000cwc.googlegroups.com> Message-ID: <44D253B8.9020803@tim.thechases.com> > location prior to pickling something to it. But I have a question > about it. In Windows I can make a file with this: > > os.path.join("C:", "myfiles", "myfile.dat") > > If I want to make sure the file/directory is made in a user's home > directory (e.g. /home/users/path/to/file) but also compatible w/ > Windows, how would I rewrite this (if required)? Well, there in os.path you'll find expanduser() so you can do things like >>> homedir = os.path.expanduser("~") >>> filename = os.path.join(homedir, "myfiles", "myfile.dat") Seems to work well for me. -tkc From steven.bethard at gmail.com Mon Aug 14 12:33:56 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 14 Aug 2006 10:33:56 -0600 Subject: outputting a command to the terminal? In-Reply-To: <44df99f7$0$25025$c3e8da3@news.astraweb.com> References: <44df99f7$0$25025$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > Here's my new project: I want to write a little script that I can type > at the terminal like this: > > $ scriptname package1 [package2, ...] > > where scriptname is my module name and any subsequent arguments are the > names of Linux packages to install. Running the script as above will > create this line: > > sudo aptitude install package1 package2 ... > > It will run that line at the terminal so the package(s) will be installed. > > Now, the extra functionality I want to add (otherwise I would just > install them normally!) is to save the package names to a text file so I > can now the names of programs I've manually installed, if I ever want to > check the list or remove packages. > > So creating the proper bash command (sudo aptitude install ...) is easy, > and writing the names to a file is easy. But I have two questions: > > 1. First of all, does Linux keep track of the packages you manually > install? If so, then I won't have to do this at all. > > 2. Assuming I write this, how do output the bash command to the > terminal? Is there a particular module that Python uses to interact with > the terminal window that I can use to send the install command to the > terminal? I don't know the answer to the first bit here, but I think the following should get you most of what you want as far as the second bit is concerned: ---------------------------- scriptname.py ---------------------------- import argparse # http://argparse.python-hosting.com/ import subprocess import sys def outputfile(filename): return open(filename, 'w') if __name__ == '__main__': # parse the command line arguments parser = argparse.ArgumentParser() parser.add_argument('packages', metavar='package', nargs='+', help='one of the packages to install') parser.add_argument('--save', type=outputfile, default=sys.stdout, help='a file to save the package names to') namespace = parser.parse_args() # call the command command = ['sudo', 'aptitude', 'install'] + namespace.packages subprocess.call(command) # write the package name file for package_name in namespace.packages: namespace.save.write('%s\n' % package_name) ----------------------------------------------------------------------- $ scriptname.py -h usage: scriptname.py [-h] [--save SAVE] package [package ...] positional arguments: package one of the packages to install optional arguments: -h, --help show this help message and exit --save SAVE a file to save the package names to STeVe From ajaksu at gmail.com Mon Aug 14 16:43:34 2006 From: ajaksu at gmail.com (ajaksu) Date: 14 Aug 2006 13:43:34 -0700 Subject: OT: p-gal website In-Reply-To: References: <7xk65buyf9.fsf@ruckus.brouhaha.com> <1155575797.856782.26370@p79g2000cwp.googlegroups.com> Message-ID: <1155588214.070179.224540@75g2000cwc.googlegroups.com> Sorry for the OT post... Paolo Pantaleo wrote: > 14 Aug 2006 10:16:37 -0700, ajaksu : > > The homepage (http://paolopan.freehostia.com/p-gal/ ) looks weird in my > > SeaMonkey 1.0.4, contents appear below GoogleAds instead of at the > > right. > > Well... I designed the site for Firefox... Don't :) Even Firefox developers will tell you to avoid this. Develop for standards compliant browsers (including Firefox) by testing against the standards. Neither your HTML or CSS pass validation, both due to minor, easy-to-fix issues. > anyway I used CSS float directives and no tables. Good choice on CSS, but you do use (four) tables at that page, and one of them has an error (missing ). >... I don't know if I made something wrong, or > if it is a [not so unlikely] standard compliance problem. Well Firefox > too has some problems with floats. Before you can blame it on (some browser's) poor standards compliance, your (X)HTML+CSS must be standards compliant. Then, you have to figure out whether the browser showing what you intended is following standards on that case ;) > I copied the layout from http://www.topolinux.org/ - can you see this properly? Yes, I can see topolinux.org properly. If you look at topolinux.org's source, they have the big GAds IFrame at the bottom. But what I found really interesting is that they also have small IFrames at the right bottom (Visitatore), and that those have this property: google_ad_format = "110x32_as_rimg"; So I imagine that the format you used for your left IFrame can be part of the problem. BTW, it looks exactly the same (i.e., broken) with IE6. >From http://tinyurl.com/qnpru :

Where... .googlesquareleft { [snip] margin: 15px 10px 5px 10px; float: left; /*allows main content to wrap around google ad */ /* note: after this we need to use the clear class to clear the float at end of the container */ } Distinti saluti, Daniel From btowle at carnegielearning.com Thu Aug 10 09:27:31 2006 From: btowle at carnegielearning.com (Brendon Towle) Date: Thu, 10 Aug 2006 09:27:31 -0400 Subject: Python-list Digest, Vol 35, Issue 160 In-Reply-To: References: Message-ID: > Date: Thu, 10 Aug 2006 08:51:12 -0400 > From: Brendon Towle > Subject: Re: Eval (was Re: Question about using python as a scripting > language) > >> Date: 9 Aug 2006 14:12:01 -0700 >> From: "Simon Forman" >> Subject: Re: Eval (was Re: Question about using python as a scripting >> language) >> To: python-list at python.org >> Message-ID: <1155157921.662196.11210 at 75g2000cwc.googlegroups.com> >> Content-Type: text/plain; charset="iso-8859-1" >> >> Fredrik Lundh posted a great piece of code to parse a subset of >> python >> safely: >> >> http://groups.google.ca/group/comp.lang.python/browse_frm/thread/ >> 8e427c5e6da35c/a34397ba74892b4e > > This, as it turns out, was the most helpful pointer of them all -- > thanks! Actually, I spoke too soon. (I should have known better -- always test first.) But: >>>import SafeEval as se >>>se.safeEval('[["AAPL", 35.5, 0.45],["YHOO", 75.68, 0.01]]') [['AAPL', 35.5, 0.45000000000000001], ['YHOO', 75.680000000000007, 0.01]] >>>se.safeEval('[["AAPL", 35.5, 0.45],["YHOO", 75.68, -0.01]]') SyntaxError: malformed expression (-) Seems that parsing negative numbers is outside of the scope of this routine. Here's the source (which is Frederik's source with one minor renaming; I take no credit here); anyone have any ideas? B. ==== start source ==== import cStringIO, tokenize def sequence(next, token, end): out = [] token = next() while token[1] != end: out.append(atom(next, token)) token = next() if token[1] == "," or token[1] == ":": token = next() return out def atom(next, token): if token[1] == "(": return tuple(sequence(next, token, ")")) elif token[1] == "[": return sequence(next, token, "]") elif token[1] == "{": seq = sequence(next, token, "}") res = {} for i in range(0, len(seq), 2): res[seq[i]] = seq[i+1] return res elif token[0] in (tokenize.STRING, tokenize.NUMBER): return eval(token[1]) # safe use of eval! raise SyntaxError("malformed expression (%s)" % token[1]) def safeEval(source): src = cStringIO.StringIO(source).readline src = tokenize.generate_tokens(src) src = (token for token in src if token[0] is not tokenize.NL) res = atom(src.next, src.next()) if src.next()[0] is not tokenize.ENDMARKER: raise SyntaxError("bogus data after expression") return res ==== end source ==== -- Brendon Towle, PhD Cognitive Scientist +1-412-690-2442x127 Carnegie Learning, Inc. The Cognitive Tutor Company ? Helping over 375,000 students in 1000 school districts succeed in math. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVEME.cybersource.com.au Wed Aug 16 00:54:35 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 16 Aug 2006 14:54:35 +1000 Subject: programming with Python 3000 in mind References: <1155672987.522793.47080@74g2000cwt.googlegroups.com> Message-ID: On Tue, 15 Aug 2006 13:16:27 -0700, beliavsky wrote: > The current beta version of Python is 2.5 . How can a Python programmer > minimize the number of changes that will be needed to run his code in > Python 3000? In general, he should know what is being removed from > Python 3000 and if possible use the "modern" analogs in Python. In general, you can't, as Python 3000 hasn't been nailed down yet. You shouldn't be asking "How do I write for a language that doesn't exist yet?" but instead should ask: (1) How far away is Python 3000? Years away, although not that many years. Three? Four? (2) Will there be automated tools for converting source code from Python 2 to Python 3000? Almost certainly. (3) Once Python 3000 is released, will Python 2 still be supported and if so, for how long? I'm sure there will be a nice long transition period, and if the Python developers don't want to support Python 2, it will be a wonderful opportunity for some commercial operation to charge for support. -- Steven D'Aprano From fredrik at pythonware.com Thu Aug 31 12:38:30 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 31 Aug 2006 18:38:30 +0200 Subject: Basic import Questions (with bonus profiling question) In-Reply-To: <312cfe2b0608310849m6967e2cx259046143728b29e@mail.gmail.com> References: <312cfe2b0608310849m6967e2cx259046143728b29e@mail.gmail.com> Message-ID: Gregory Pi?ero wrote: > 1. Will "from somemodule import onething" take as long to start up as > import somemodule? yes; "from x import y" does an ordinary import of "x" under the hood. > 2. Is there anyway I can get at onething more quickly? not really, unless you're willing/able to refactor the module you're importing. > 3. If I put an import statement hidden away in some function, will > Python only do the import when that function is called? correct. "import" is an executable statement. > If I say, never use that function would that import statement affect > performance at all? nope. > Ultimately I have IIS running python as a CGI script and it seems to > just be taking many seconds to load a small page. I'm guessing the > issue is starting up the interpreter and loading all the modules. several seconds? sounds bad. what does the following script print on your machine? import time, subprocess, sys t0 = time.time() for i in range(10): subprocess.call([sys.executable, "-c", "pass"]) print time.time() - t0 From aleax at mac.com Fri Aug 4 22:04:35 2006 From: aleax at mac.com (Alex Martelli) Date: Fri, 4 Aug 2006 19:04:35 -0700 Subject: Python open a named pipe == hanging? References: Message-ID: <1hjk7cf.iswobo130hqzxN%aleax@mac.com> Donn Cave wrote: > In article , > Rochester wrote: > > > I just found out that the general open file mechanism doesn't work > > for named pipes (fifo). Say I wrote something like this and it > > simply hangs python: > > > > #!/usr/bin/python > > > > import os > > > > os.mkfifo('my fifo') > > > > open('my fifo', 'r+').write('some strings.') > > x = os.popen('cat my fifo').read() > > > > print x > > I believe your problem is that, by the time you open the > pipe for read, it has already been closed by its writer. Hmmm, no: the problem is, he never opens the pipe for write, because the open blocks (will not proceed until somebody opens the fifo for reading, which in turn won't happen here because the open blocks). Try: a = open('my_fifo', 'w') b = os.popen('cat my_fifo') a.write ... a.close() c = b.read() this STILL doesn't work, since the very first statement blocks. (I've also removed the 'r+' mode in favor of 'w', since opening a FIFO for reading AND writing produces undefined behavior, at least in all Unix versions and variants I'm familiar with). > If you contrive to keep the file pointer around until after > the reader has opened it, then you can read some data from The problem is that the writer can never finish opening it; the workaround is to have a separate process open it for reading first. > it. (You can't read "all" the data, though - since you still > have the file open, it has no end of file - so you can't > solve the problem exactly as stated above.) Actually, in CPython (1.5.2 to 2.5 included, at least), _IF_ open worked normally then the file WOULD be closed by the statement open('my fifo', 'r+').write('some strings.') as the file object's reference counts drops to 0 at this statement's end. (This would NOT necessarily happen in other Python implementations, such as Jython or IronPython, but I suspect THOSE implementations wouldn't have os.mkfifo...). > And the odds are fair that when you get this working, you > will run into some other inconvenient behavior. Named pipes > are a little tricky. Very -- particularly their blocking behavior at open (which appears to have perhaps tricked you in this case). Alex From onurb at xiludom.gro Thu Aug 10 11:33:52 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Thu, 10 Aug 2006 17:33:52 +0200 Subject: Make Object Oriented? In-Reply-To: <1155214883.129267.317570@p79g2000cwp.googlegroups.com> References: <1155214883.129267.317570@p79g2000cwp.googlegroups.com> Message-ID: <44db51e1$0$21148$7a628cd7@news.club-internet.fr> eduardo.padoan at gmail.com wrote: > It would be ease to create such a tool Hmmm ? May I express some very huge doubts here ? From justask at acme.com Sun Aug 13 18:30:50 2006 From: justask at acme.com (Vincent Delporte) Date: Mon, 14 Aug 2006 00:30:50 +0200 Subject: Compiling wxPython app for Windows; Single EXE References: <1155501974.513888.138610@m73g2000cwd.googlegroups.com> Message-ID: On 13 Aug 2006 13:46:14 -0700, "Tim N. van der Leeuw" wrote: >I have a wxPython app, which I compile into one EXE file. Then there's >just 1 support file needed: a MS DLL (which, once distributed, you will >not need to update). OK. So you compile the Python app into an EXE using py2exe, and then use eg. 7Zip to combine all the files into a single EXE, that 1. uncompresses itself in the directory validated by the user 2. when done, runs the Python EXE? From cliff at develix.com Tue Aug 15 04:09:01 2006 From: cliff at develix.com (Cliff Wells) Date: Tue, 15 Aug 2006 01:09:01 -0700 Subject: ReStructuredText In-Reply-To: <1155628608.16686.19.camel@devilbox> References: <1155628608.16686.19.camel@devilbox> Message-ID: <1155629341.16686.25.camel@devilbox> On Tue, 2006-08-15 at 00:56 -0700, Cliff Wells wrote: Ah, I got it. From the docs: (Auto-enumerated lists are new in Docutils 0.3.8.) and I've got 0.3.7 Damn. Thanks for the responses. Regards, Cliff -- From pavlovevidence at gmail.com Fri Aug 4 07:29:02 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 4 Aug 2006 04:29:02 -0700 Subject: Thread Question In-Reply-To: <1154676387.063576.100570@i42g2000cwa.googlegroups.com> References: <1153998422.670828.148360@m79g2000cwm.googlegroups.com> <1154019801.999805.150000@m73g2000cwd.googlegroups.com> <1154544553.990241.280030@i3g2000cwc.googlegroups.com> <1154590917.731457.106230@s13g2000cwa.googlegroups.com> <1154613366.350191.81880@m73g2000cwd.googlegroups.com> <1154676387.063576.100570@i42g2000cwa.googlegroups.com> Message-ID: <1154690942.385855.41130@m79g2000cwm.googlegroups.com> Ritesh Raj Sarraf wrote: > Carl Banks wrote: > > Then change the zipping part of download_from_web to acquire and > > release this lock; do zipfile operations only between them. > > > > ziplock.acquire() > > try: > > do_all_zipfile_stuff_here() > > finally: > > ziplock.release() > > I hope while one thread has acquired the lock, the other threads (which > have done the downloading work and are ready to zip) would wait. Exactly. Only one thread can hold a lock at a time. If a thread tries to acquire a lock that some other thread has, it'll wait until the other thread releases it. You need locks to do this stuff because most things (such as zipfile objects) don't wait for other threads to finish. Carl Banks From pianomaestro at gmail.com Fri Aug 25 01:18:16 2006 From: pianomaestro at gmail.com (pianomaestro at gmail.com) Date: 24 Aug 2006 22:18:16 -0700 Subject: lazy arithmetic In-Reply-To: References: <1156476992.102203.304450@p79g2000cwp.googlegroups.com> Message-ID: <1156483096.397300.110210@75g2000cwc.googlegroups.com> Gabriel Genellina wrote: > At Friday 25/8/2006 00:36, pianomaestro at gmail.com wrote: > > ># This is what I have in mind: > > > >class Item(object): > > def __add__(self, other): > > return Add(self, other) > > And this works fine... why make thinks complicated? Yes, I agree it's simpler, and up until now that's the way I always did it. Many Many times. Now I am looking for a way to build ensembles of these lazy classes at the meta-level. (think abstract algebra). > >Item.__add__ = Add > > This doesn't make sense... __add__ should be a method, not a class... No, that's not true. It can be this callable: def add(a, b): return Add(a,b) Item.__add__ = add So my thinking was this: why can't I use a callable class ? > x+y get translated to x.__add__(y) No that's not true at all. The self argument to __add__ ends up being the Add instance, not the Item instance: z=x+y is translated to z.__add__(y) Simon. From steve at holdenweb.com Wed Aug 30 17:04:30 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 30 Aug 2006 22:04:30 +0100 Subject: Managing database tables through web-forms (automatically) In-Reply-To: <44F5F03E.9020505@mimoza.pantel.net> References: <44F5F03E.9020505@mimoza.pantel.net> Message-ID: Antal Rutz wrote: > Hi, > > I want to manage database(sql) tables through the web: actions like > insert/edit/list/delete. > An application often needs just a database table to be easily managable > through the web by the users. > > Now I realized that everytime I write a new app > I need to rewrite the whole thing according to the actual > database/table schema (forms/templates/validation/etc) > > What I'd need: > A tool/module/anything that helps me to automate this process. > Something that just needs defining some table scheme and > not to rewrite the whole thing again. > > Big thanks if you can help me! > Django is the usual suggestion for this: once you have defined your database structures it will produce an administration interface automatically. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From yaipa at yahoo.com Thu Aug 10 20:57:13 2006 From: yaipa at yahoo.com (yaipa) Date: 10 Aug 2006 17:57:13 -0700 Subject: Switching a Dataprobe iP-415/815 (basic) using TCP Message-ID: <1155257833.315865.236110@74g2000cwt.googlegroups.com> >------------------------< #!/usr/bin/env python import socket import sys, time # ---------------------------------------------------------- # File: dataprobe.py # Author: Alan Haffner # Date: 2006-08-10 # Rev. .60 # # Tested on Linux only # # Usage: dataprobe.py # # $> dataprobe.py 5P 4 # $> 11110111 # $> 11111111 # # Note: dataprobe uses about 3 different TCP command protocols # across their product line, so check /w their tech support # on your model's specific command set. # ---------------------------------------------------------- # format the escape hexbyte as a type char esc = chr(int('1b',16)) # Construct the command which gets the status of the # dataprobe's (iP-415/815) relay array. # Uses dataprobe default password getRelayStateInfo = (("%cPASS" % esc)+'O') HOST = '192.168.1.254' # Default Dataprobe iP-815 address PORT = 9100 # The same port as used by the server # connect to dataport TCP server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) time.sleep(3) # send command to power stript TCP server # Uses dataprobe default password header = "%cPASS" % esc s.send(header + sys.argv[1].strip()) # sleep for one second longer than powercycle set time. # -- currently the dataprobe is set to a 3sec. pulse delay sleep_time = float(sys.argv[2].strip()) time.sleep(sleep_time) # Get Power Strip Bus Status # -- When using the P command, the first read will always # show the pulse transition s.send(getRelayStateInfo) d = s.recv(16) print d time.sleep(2) s.send(getRelayStateInfo) d = s.recv(16) print d # close TCP connection to dataprobe server s.close() >------------------------< From mail at microcorp.co.za Tue Aug 29 02:43:00 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 29 Aug 2006 08:43:00 +0200 Subject: time.clock() going backwards?? References: <12f6455mjvuqv72@corp.supernews.com> <12f64pkr124f358@corp.supernews.com> Message-ID: <003701c6cb4c$03b22f40$03000080@hendrik> "Grant Edwards" Wrote: | On 2006-08-28, Grant Edwards wrote: | | >>> For processors that run at (say) 2GHz, several million (say 10 | >>> million) represents a difference of 10e6/2e9 = 0.005 seconds | >>> between when the processors were sufficiently powered up to | >>> start counting cycles. | > | >> If it were so, than why can't the delta of time between the | >> processors be set to exact zero? | > | > This is | | Oops. Hit the wrong key. I meant to say: Thank god! - I know you are not an idiot - and for some minutes you had me guessing - I was beginning to think that my brain had finally been destroyed by drink - trying to figure out this enigmatic post... :-) - Hendrik 8<----------------- From george.sakkis at gmail.com Wed Aug 30 13:24:48 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 30 Aug 2006 10:24:48 -0700 Subject: Syntax suggestion. References: <1156954306.471779.117520@p79g2000cwp.googlegroups.com> Message-ID: <1156958688.378612.236790@p79g2000cwp.googlegroups.com> samir wrote: > Saluton! > > Being a fond of Python, I had this idea: Why not making Python a Unix > shell? It's been done; it's called "IPython": http://ipython.scipy.org/doc/manual/manual.html George From guyon.moree at gmail.com Tue Aug 1 12:53:00 2006 From: guyon.moree at gmail.com (=?iso-8859-1?B?R3V5b24gTW9y6WU=?=) Date: 1 Aug 2006 09:53:00 -0700 Subject: fast pythonic algorithm question In-Reply-To: <1154448932.079878.10720@p79g2000cwp.googlegroups.com> References: <1154443185.562918.140090@s13g2000cwa.googlegroups.com> <1154448932.079878.10720@p79g2000cwp.googlegroups.com> Message-ID: <1154451180.225377.244820@b28g2000cwb.googlegroups.com> Brian you are right, but in my case (host, port, protocol) is unique. bryanjugglercryptographer at yahoo.com schreef: > Guyon Mor?e wrote: > > i have a big list of tuples like this: > > > > [ (host, port, protocol, startime, endtime), .. ] etc > > > > now i have another big(ger) list of tuples like this: > > > > [(src_host, src_port, dest_src, dest_port, protocol, time), ... ] etc > > > > now i need to find all the items in the second list where either > > src_host/src_port or dest_host/dest_port matches, protocol matches and > > time is between starttime and end time. > > > > After trynig some stuff out i actually found dictionary lookup pretty > > fast. Putting the first list in a dict like this: > > > > dict[(host,port,protocol)] = (starttime, endtime) > > That only works if each (host,port,protocol) can appear with only > one (starttime, endtime) in your first big list. Do the variable > names mean what they look like? There's nothing unusual about > connecting to the same host and port with the same protocol, at > multiple times. > > You might want your dict to associate (host,port,protocol) with a > list, or a set, of tuples of the form (starttime, endtime). If the > lists can be long, there are fancier methods for keeping the set > of intervals and searching them for contained times or overlapping > intervals. Google up "interval tree" for more. > > > -- > --Bryan From bearophileHUGS at lycos.com Tue Aug 1 13:22:23 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 1 Aug 2006 10:22:23 -0700 Subject: Best way to read, and analyze a log file? In-Reply-To: <1154440597.436863.131750@i3g2000cwc.googlegroups.com> References: <1154440597.436863.131750@i3g2000cwc.googlegroups.com> Message-ID: <1154452943.852932.84960@p79g2000cwp.googlegroups.com> superflit at gmail.com: > 1- Read the data and put all variables in a list > 2- Read the data and put all the variables in dictionary? > the logs is in this format > xxxxxxxxxxxxxxxxxxxxxxxxxx > The separation is by byte size like > xxx three bytes for code x , xxxx bytes for hour, etc.. > I have two main objectives. > Show all data to user. > Analyze the data: like total sum, average,etc.. If you want to do all by yourself you can create a list of starting positions, and you can add None to it, so you can use it to slice a line with a loop. You can also create a list of types, so you can cast the string parts to their correct types, catching the exceptions. You can do it in a second loop for clarity, or the first one to speed up a bit. So you can just create a list of data for each input line, a dict may be unnecessary because the number of fields seems fixed. Bye, bearophile From jarrod.roberson at gmail.com Thu Aug 31 11:27:02 2006 From: jarrod.roberson at gmail.com (fuzzylollipop) Date: 31 Aug 2006 08:27:02 -0700 Subject: Pros/Cons of Turbogears/Rails? In-Reply-To: <1156768355.275370.129680@h48g2000cwc.googlegroups.com> References: <1156726071.579429.44650@b28g2000cwb.googlegroups.com> <1156740469.645955.52080@i3g2000cwc.googlegroups.com> <1156768355.275370.129680@h48g2000cwc.googlegroups.com> Message-ID: <1157038022.237121.127780@m73g2000cwd.googlegroups.com> Paul Boddie wrote: > > fuzzylollipop wrote: > > > uh, no, Python predates Ruby by a good bit > > > Rails might be "older" than Turbogears but it still JUST went 1.0 > > > officially. > > > It can't be called "mature' by any defintition. > > Version numbers are a fairly useless general metric of project > maturity, taken in isolation. > But 1.0 releases do mean something, it means the DEVELOPER of the package things it is just now ready for general consumption. That means something regardless of what the number is. Matter of fact, all major version releaese mean that, it is generally understood thing. x.0 means this is now ready for non-beta general use. From larry.bates at websafe.com Tue Aug 1 11:38:17 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 01 Aug 2006 10:38:17 -0500 Subject: Finding the name of a class In-Reply-To: References: Message-ID: <44CF7569.9020509@websafe.com> Kirk Strauser wrote: > Given a class: > >>>> class foo(object): >>>> pass > > how can I find its name, such as: > >>>> b = foo >>>> print something(b) > 'foo' > > I'm writing a trace() decorator for the sake of practice, and am trying to > print the name of the class that a traced method belongs to. This seems > like it should be easy, but I think I've been staring at the problem too > long. print print b.__class__.__name__ gives what you want -Larry Bates From fonnesbeck at gmail.com Tue Aug 8 10:43:02 2006 From: fonnesbeck at gmail.com (Chris Fonnesbeck) Date: Tue, 8 Aug 2006 10:43:02 -0400 Subject: fundamental issue with unittest Message-ID: <723eb6930608080743x3f6bc6a2p5bcb516faebfe869@mail.gmail.com> I have added a unit test to some of my code, following closely the examples in the python docs and python in a nutshell. However, when I try calling unittest.main(), I get the following: ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK --------------------------------------------------------------------------- exceptions.SystemExit Traceback (most recent call last) /Users/chris/ /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/PyMC/MCMC.py in runtest() 2916 2917 2918 def runtest(): 2919 # Run unit tests -> 2920 unittest.main() global unittest.main = /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/unittest.py in __init__(self=, module='__main__', defaultTest=None, argv=['/usr/local/bin/ipython'], testRunner=None, testLoader=) 757 self.progName = os.path.basename(argv[0]) 758 self.parseArgs(argv) --> 759 self.runTests() self.runTests = > 760 761 def usageExit(self, msg=None): /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/unittest.py in runTests(self=) 795 self.testRunner = TextTestRunner(verbosity= self.verbosity) 796 result = self.testRunner.run(self.test) --> 797 sys.exit(not result.wasSuccessful()) global sys.exit = result.wasSuccessful = > 798 799 main = TestProgram SystemExit: False Type exit or quit to exit IPython (%Exit or %Quit do so unconditionally). My unit testing code is here: class MCMCTest(unittest.TestCase): def testCoalMiningDisasters(self): """Run coal mining disasters example sampler""" print 'Running coal mining disasters test case ...' # Create an instance of the sampler self.sampler = DisasterSampler() # Specify the nimber of iterations to execute iterations = 10000 thin = 2 burn = 5000 chains = 2 # Run MCMC simulation for i in range(chains): self.failUnless(self.sampler.sample(iterations, burn=burn, thin=thin, plot=True)) # Run convergence diagnostics self.sampler.convergence() # Plot autocorrelation self.sampler.autocorrelation() # Goodness of fit self.failIf(any(self.sampler.goodness(iterations/10)['overall'] < 0.05)) def runtest(): # Run unit tests unittest.main() I appear to be subclassing appropriately, and the only method begins with "test", so I do not see the problem. Can anyone help me out? Thanks, C. -- Chris Fonnesbeck + Atlanta, GA + http://trichech.us -------------- next part -------------- An HTML attachment was scrubbed... URL: From gelists at gmail.com Thu Aug 3 10:06:29 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Thu, 3 Aug 2006 11:06:29 -0300 Subject: Windows vs. Linux References: <1154301694.445639.99580@m79g2000cwm.googlegroups.com> <44cddfb3$0$7761$7a628cd7@news.club-internet.fr> Message-ID: <1sfr35tw0q766$.dlg@gelists.gmail.com> On 2006-08-03 04:53:11, Sybren Stuvel wrote: >> Pretty much every production cost increase gets in the end paid by >> the consumer. With some localized changes, you may be lucky and >> don't buy any products that are affected, but with such a widespread >> change as this would be, it is more likely that almost everybody is >> affected close to average. > > You still don't tell me how I could be affected by a production cost > increase at a company I'm buying nothing from. You don't buy your gas as crude from Saudi Arabia oil well, do you? :) Their production cost increases may affect you nevertheless. There are very few products you buy that are only affected by costs generated in one company. Usually that's dozens, if not hundreds of companies in the chain. (That's not to say that all of them are relevant, price-wise, but it's more than one that's relevant, usually.) Take your pick, anything, and try to find out the price building chain. You may be surprised. Besides, you probably don't know whether it's not one of your direct suppliers who's affected. You're sure you don't buy from anybody running a Windows system? I'd bet against that, and I only bet when I know I win :) I'm not talking about something obvious like a 10% increase. An overall (average) 1% increase is easy to dismiss as not relevant -- but it's still 1%, if you add it up. (I'm not claiming it would be 1% though. Just an example number.) >> With that is also mostly the pressure gone to not increase -- >> because so many are affected that the few who are not happily >> increase the prices with the others. > > Either my English isn't as good as I thought, or that's simply > incomprehendable. Possibly the latter... I'll try again :) When there's a change in the cost structure of some companies, they try to pass that on through their prices. That's just natural. If the cost structure of a whole sector changes, that's easy, because all of them will want to increase by the same margin, and the cost structure of the whole sector remains the same. (See gas prices.) If almost all of a sector are affected, this still doesn't change (usually): the ones who are not affected often just go with the crowd and increase nevertheless, figuring they can gain more by increased margins than they would gain by increased market share due to lower prices. (There are all kinds of factors that affect this; not always a lower price gets reflected in a higher market share.) But they (or some of them) could also decide to stay at their lower price to gain market share. But if the production cost for 80% of a sector goes up, it may be that the 20% who don't have that cost increase stay low, but the average price of that sector still will go up. (Not everybody will move to the suppliers now with lower cost.) With that, the average production cost for companies that depend on that sector will go up. So there's an average hike anyway, even if some or all of the ones who don't have to increase actually don't. Gerhard From johnjsal at NOSPAMgmail.com Tue Aug 1 11:56:18 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 01 Aug 2006 15:56:18 GMT Subject: Finding the name of a class In-Reply-To: References: <44cf7538$0$29435$626a54ce@news.free.fr> Message-ID: Tim Chase wrote: > While this is surely true, would somebody explain why I had such trouble > finding this? I think __name__ is an attribute of the class itself, not the instance: >>> class Foo(object): pass >>> f = Foo() >>> f.__name__ Traceback (most recent call last): File "", line 1, in -toplevel- f.__name__ AttributeError: 'Foo' object has no attribute '__name__' >>> Foo.__name__ 'Foo' From pavlovevidence at gmail.com Wed Aug 9 20:51:20 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 9 Aug 2006 17:51:20 -0700 Subject: do people really complain about significant whitespace? References: <1154986984.740638.241130@m79g2000cwm.googlegroups.com> <87bqqwyumq.fsf@benfinney.id.au> <1155077965.100108.232790@m79g2000cwm.googlegroups.com> <44d9d949$0$14310$626a54ce@news.free.fr> <1155134902.103617.71810@i3g2000cwc.googlegroups.com> Message-ID: <1155171080.846801.221220@m79g2000cwm.googlegroups.com> Michiel Sikma wrote: > Op 9-aug-2006, om 16:48 heeft Carl Banks het volgende geschreven: > > > Even if this were legal code (it isn't), it's still more transparent > > than some of the C code I've seen. > > > > Carl Banks > > Still kind of too bad that means there won't ever be an International > Obfuscated Python Code Contest. > > #define _ -F<00||--F-OO--; > int F=00,OO=00;main(){F_OO();printf("%1.3f\n",4.*-F/OO/OO);}F_OO() > { > _-_-_-_ > _-_-_-_-_-_-_-_-_ > _-_-_-_-_-_-_-_-_-_-_-_ > _-_-_-_-_-_-_-_-_-_-_-_-_-_ > _-_-_-_-_-_-_-_-_-_-_-_-_-_-_ > _-_-_-_-_-_-_-_-_-_-_-_-_-_-_ > _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ > _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ > _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ > _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ > _-_-_-_-_-_-_-_-_-_-_-_-_-_-_ > _-_-_-_-_-_-_-_-_-_-_-_-_-_-_ > _-_-_-_-_-_-_-_-_-_-_-_-_-_ > _-_-_-_-_-_-_-_-_-_-_-_ > _-_-_-_-_-_-_-_ > _-_-_-_ > } > > :) > > Michiel > > (source: http://www0.us.ioccc.org/years.html#1988) *yawn* ;) Carl Banks From bj_666 at gmx.net Wed Aug 16 12:28:30 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 16 Aug 2006 18:28:30 +0200 Subject: Adding a char inside path string References: <1155737700.290268.248250@i42g2000cwa.googlegroups.com> <1155744057.573884.111850@m73g2000cwd.googlegroups.com> Message-ID: In <1155744057.573884.111850 at m73g2000cwd.googlegroups.com>, Hitesh wrote: > That works for a string. > But I am getting list of tuples from DB. > > rows = [('\\serverName\C:\FolderName1\FolderName2\example.exe',), > ('\\serverName\C:\FolderName1\FolderName2\example2.exe',), > ('\\serverName\C:\FolderName1\FolderName2\example3.exe',), > ('\\serverName\C:\FolderName1\FolderName2\example4.exe',)] > > I tried this: > for i in rows: > row = str(i) > path = row.replace("C:" , "c$") > print path > > I am getting path something like > > ('\\serverName\c$:\FolderName1\FolderName2\example.exe',) > > How on the earth I can remove those paranthesis? Well, don't convert the tuple to a string but get the string out of the tuple instead. for row in rows: path = row[0].replace('C:', 'C$') print path Ciao, Marc 'BlackJack' Rintsch From bignose+hates-spam at benfinney.id.au Mon Aug 7 19:49:01 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 08 Aug 2006 09:49:01 +1000 Subject: do people really complain about significant whitespace? References: <1154986984.740638.241130@m79g2000cwm.googlegroups.com> Message-ID: <87bqqwyumq.fsf@benfinney.id.au> "infidel" writes: > It just sounds like so much trivial nitpickery that it's hard to > believe it's as common as we've come to believe. As others have pointed out, these people really do exist, and they each believe their preconception -- that significant whitespace is intrinsically wrong -- is valid, and automatically makes Python a lesser language. One of the most stupid language-definition decisions that most people have come across is the Makefile format. If you're not familiar with it, spaces and tabs are *each* significant. Specifically, putting spaces where a tab is required will result in a file that, while it may be visually identical to a correctly formatted file, doesn't parse correctly. In hindsight it's trivial to predict the needlessly painful learning process that ensues. This is a very painful memory for many programmers, and the general opinion that results is "syntactically significant whitespace is bad". This is the phrase that always gets brought out, and it's often clear that the person hasn't considered *why* it's bad. The issue with the Makefile format (lampooned wonderfully by the Whitespace programming language) is that *invisible* differences in whitespace should not be significant. In a Makefile, you *must* mix spaces and tabs in the same file; this leaves the door wide open to invisible differences. In Python, an admonishment of "always indent each file consistently" suffices. Hope that goes some way to explaining one possible reason why rational people can consistently react in horror to the issue. -- \ "Friendship is born at that moment when one person says to | `\ another, 'What! You too? I thought I was the only one!'" -- | _o__) C.S. Lewis | Ben Finney From http Tue Aug 8 22:26:58 2006 From: http (Paul Rubin) Date: 08 Aug 2006 19:26:58 -0700 Subject: How to reverse tuples in a list? References: <1155081671.728757.228050@p79g2000cwp.googlegroups.com> Message-ID: <7xk65i4pal.fsf@ruckus.brouhaha.com> "Noah" writes: > I know I could do this long-form: > q = [] > y = [('a', 1.0), ('b', 2.0), ('c', 3.0)] > ... y = [tuple(reversed(t)) for t in y] From mauriceling at acm.org Thu Aug 10 03:01:23 2006 From: mauriceling at acm.org (Maurice LING) Date: Thu, 10 Aug 2006 07:01:23 GMT Subject: state of SOAP and python? In-Reply-To: References: Message-ID: <44dad9bf$1@news.unimelb.edu.au> Hi, I've been using SOAPpy for a number of my work. Looks good. maurice Mark Harrison wrote: > So I'm investigating doing some SOAP work... Any concensus on > what the best python libraries are for doing this? > > Too bad, xmlrpc is choking on our long longs. :-( > > Many TIA, > Mark > From vasudevram at gmail.com Wed Aug 9 14:13:28 2006 From: vasudevram at gmail.com (vasudevram) Date: 9 Aug 2006 11:13:28 -0700 Subject: Info on continuations? In-Reply-To: <44d8d652$0$18122$ed2619ec@ptn-nntp-reader02.plus.net> References: <1155048104.107797.220630@b28g2000cwb.googlegroups.com> <44d8d652$0$18122$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: <1155147208.187079.270460@n13g2000cwa.googlegroups.com> Michael wrote: > vasudevram wrote: > > > > > Hi, > > > > I am Googling and will do more, found some stuff, but interested to get > > viewpoints of list members on: > > > > Continuations in Python. > > > > Saw a few URLs which had some info, some of which I understood. But > > like I said, personal viewpoints are good to have. > > Python doesn't really support continuations. Generators (and co-routines in > general) have similar properties to continuations, however they're not > continuations. Closures are also sometimes considered cousins to > continuations, and python's support for those is pretty good IMO. (again > however, closures are not continuations). > > Since it looks like you're also looking for what continuations are, I think > the following is the simplest way of explaining them. If you've ever > programmed in BASIC, *in a way* if you think of methods/functions as a > named GOSUB, then continuation (in a way) are a way of giving a name to a > goto (it's more subtle than that though since a continuation os often > defined to "remember" state in a similar way to a closure). Like a function > you can pass them round as objects. Like a generator/closure they remember > the state they were in. > > *Personally* , I think python NOT supporting full continuations is a GOOD > thing, since full continuations, whilst powerful, are also a great source > of confusion for people. (That said, I have a usecase I'd find them useful > for - I think they'd be useful for plugin architectures - but IMO that > doesn't outweigh the risk of code obfuscation :-) > > One particular usecase that people seem to like continuations for, > specifically how they're used in seaside, is actually a subset of > functionality that python *can* support (to a large extent). > > Essentially the idea is to be able to take a web application and make it > look linear. CherryFlow allows you for example to write this: > > @expose > @flow > def example_flow(): > yield view.first_page() > if request.args["choice"] == "a": > yield view.choice_a_page() > else: > yield view.choice_b_page() > yield view.last_page() > > (example from: http://tinyurl.com/qzpqu ) > > This causes the user's browser to show a page where they have a choice of > "a" or "b". Depending on what they choose, they then either are presented > with choice_a_page or choice_b_page. Finally, no matter which option they > chose, you are presented with the last page. > > Something similar can be done using Kamaelia, though at present only the > mechanism exists there, without any sugar (http://tinyurl.com/n3bh7 - > specifically websiteSessionExampleComponent). The reason I mention it is to > say that it's relatively simple to do using python :-) > > I have to stress though, this usage of continuations in Seaside, as > emulate-able in python is a subset of the full power of continuations, > which isn't available in python at present. (Though it's possible hacking > greenlets could result in something). (In fact the way seaside uses them as > far as I can tell is more to implement co-routine like behaviour than > anything else (!)) > > Anyway, hope that's interesting/useful - looking at your other comments, > you're just looking for information and usecases at the moment :-) > > Regards, > > > Michael. Yes, that's quite right - only looking for info and use cases at present - and thanks for the info, it was interesting and useful :-) Need to check all the inputs out ... Vasudev From kent at kentsjohnson.com Tue Aug 1 14:36:48 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Tue, 01 Aug 2006 18:36:48 GMT Subject: Finding the name of a class In-Reply-To: <57a4q3xgf21.ln2@news.conpoint.com> References: <44CF7569.9020509@websafe.com> <57a4q3xgf21.ln2@news.conpoint.com> Message-ID: <4bNzg.323$NX2.46@newsreading01.news.tds.net> Kirk Strauser wrote: > Larry Bates wrote: > >> print print b.__class__.__name__ gives what you want > > That doesn't seem to do it, though. Here's the result of importing a module > from my company's internally-developed library: > >>>> from Daycos.TableCopier.copyfro import StateProcessor >>>> print StateProcessor.__class__.__name__ > type > > I'm looking for something that would print 'StateProcessor' but am not > having much luck. It looks like StateProcessor is a class; StateProcessor.__class__ is the class of a class, i.e. type. Try StateProcessor.__name__ Kent From mfenner at gmail.com Thu Aug 17 20:51:01 2006 From: mfenner at gmail.com (Mark E. Fenner) Date: Fri, 18 Aug 2006 00:51:01 GMT Subject: Optimizing Inner Loop Copy References: Message-ID: Michael Spencer wrote: > Mark E. Fenner wrote: > >> >> and the copy is taking the majority (42%) of my execution time. >> So, I'd like to speed up my copy. I had an explicit copy method that did >> what was needed and returned a new object, but this was quite a bit >> slower than using the standard lib copy.copy(). >> > How are you measuring? It seems to me that your Rule.copy method is a lot > faster than copy.copy: > > >>> r= Rule(range(100)) > >>> shell.timefunc(r.copy) > 'copy(...) 36458 iterations, 13.71usec per call' > >>> from copy import copy > >>> shell.timefunc(copy, r) > 'copy(...) 4498 iterations, 111.17usec per call' > Michael Michael, Thank you. I misinterpreted something somewhere ... the program is indeed faster using Rule.copy. I need to look over the rest of my profiling data, to see if I screwed up elsewhere as well. So, how to optimize Rule.copy()? Regards, Mark From wardm66 at gmail.com Sun Aug 13 00:03:19 2006 From: wardm66 at gmail.com (wardm) Date: Sun, 13 Aug 2006 14:03:19 +1000 Subject: Using a dictionary to pass data to/from embedded python functions References: <44dcf055@dnews.tpgi.com.au> <1hjy7rx.1sxrihq1jtyy68N%aleax@mac.com> <44de5c3b@dnews.tpgi.com.au> <1hjytek.1gh1ur81so4q0tN%aleax@mac.com> Message-ID: <44dea48c@dnews.tpgi.com.au> Thanks again for your help, I agree, it seems I need to read a good book on Python. One last question, will Python allow me to add new items to InterfaceModule.VarDictionary from the Python functions I call ? "Alex Martelli" wrote in message news:1hjytek.1gh1ur81so4q0tN%aleax at mac.com... > wardm wrote: > >> Thanks Alex for your help, (and advice on focusing the point of my >> question). >> >> I was able to compile and run your example OK, but when I try to use the >> "VarDictionary" in the >> MyScriptModule.py code, I get an exception. >> >> I added the following code to the C app just to add two entries to the >> Dictionary >> >> PyDict_SetItemString( m_pVarDictionary, "tk1", >> Py_BuildValue("s","test1Val")); >> PyDict_SetItemString( m_pVarDictionary, "tk2", >> Py_BuildValue("s","test2Val")); >> >> Then tried various things in the Python code to display the contents of >> the >> "VarDictionary", >> such as adding the "print VarDictionary" below. >> >> import InterfaceModule >> >> def functionName(): >> print "hello" >> print dir(InterfaceModule) >> print "that's all" >> print VarDictionary > > Note the wrong indentation in this latter print statement: this would > already cause a syntax error (unless the leading 'p' happened to be > aligned with the leading 'd' of 'def', in which case the function would > be terminated, the latest print would happen at import-time, and the > FOLLOWING statement: > >> return > > ...would then be a syntax error (return outside of function). But, > there's more: > > >> Even though "VarDictionary " is in the Dir, every time I try to use the >> "VarDictionary" the program fails. > > "VarDictionary" is in the dir(...) *** of InterfaceModule ***, of > course, so you need to refer to it as InterfaceModule.VarDictionary in > your Python code -- the barename, nor qualified by modulename, just will > not work, of course!!! > > Adding the two C code lines you quote, and changing the Python example > code to: > > def functionName(): > print "hello" > print dir(InterfaceModule) > print "VarDictionary is:", InterfaceModule.VarDictionary > print "that's all" > > changes that part of the output to: > > hello > ['VarDictionary', '__doc__', '__name__'] > VarDictionary is: {'tk2': 'test2Val', 'tk1': 'test1Val'} > that's all > > > With all due respect, it looks like you're trying to run before you can > walk -- or more specifically, to embed Python in C++ before you become > familiar with the most elementary and fundamental aspects of Python, > such as indentation and the need to qualify compound names. You might > want to consider getting a good Python book -- such as, my own Python in > A Nutshell (2nd ed), Aahz and Stef Maruch's Python For Dummies, Wesley > Chun's Core Python Programming (2nd ed) -- they're all very recent (mine > is just out, Aahz's and Stef's I believe is due to hit bookstores in > September or October), and any of them might serve you well (if you're > OK with books not necessarily covering the very latest release of Python > [and the issues you're having suggest that this is not really the > problem!], there are many other good books, such as Magnus Lie Hetland's > "Beginning Python", Beazley's "Python Essential Reference", Lutz and > Ascher's "Learning Python", From ray_usenet at yahoo.com Tue Aug 1 05:10:49 2006 From: ray_usenet at yahoo.com (Ray) Date: 1 Aug 2006 02:10:49 -0700 Subject: first book about python In-Reply-To: References: Message-ID: <1154423449.132732.321740@p79g2000cwp.googlegroups.com> wesley chun wrote: > if you only know shell scripting, you should still be able to pick up > much of the material in Core Python, esp. if you have done looping > and/or conditionals in the shell language. it is a large book and is > pretty comprehensive though, so if you're looking for a lighter intro, > the books gene's suggested should work -- i would also add Dive into > Python to that group. if possible, try to find sample chapters from > any book you're interested in before buying to make sure that it will > suit your needs. Hi Wesley, which edition of Python will your latest Core Python cover? Will it cover 2.5? Thanks Ray From timgerr at gmail.com Sat Aug 19 00:16:13 2006 From: timgerr at gmail.com (timgerr at gmail.com) Date: 18 Aug 2006 21:16:13 -0700 Subject: Search or compai problem In-Reply-To: <1155941745.802556.299470@m73g2000cwd.googlegroups.com> References: <1155941745.802556.299470@m73g2000cwd.googlegroups.com> Message-ID: <1155960973.701182.36060@i42g2000cwa.googlegroups.com> John Machin wrote: > Gallagher, Tim (NE) wrote: > > I am new to python and I want to compare 2 strings, here is my code: > > [start] > > > > import active_directory > > import re > > > > lstUsers = [] > > Using "lst" or "l" as a variable name is bad news in any language; with > many fonts they are too easily misread as "1st" or "1" respectively. > > > users = active_directory.root() > > for user in users.search ("sn='gallagher'"): > > **** Insert here: > print type(user.samAccountName), repr(user.samAccountName) > **** that may indicate where your problem *starts* > **** Then read the documentation for the active_directory module, in > particular what it says about the attributes of the objects in the > sequence returned by users.search. > > > > lstUsers.append(user.samAccountName) > > > > print "----------------------------------------" > > lstUsers.sort() > > > > ## Printing out what is inside of the arrar(list) > > What is "arrar(list)" ?? > > **** Here insert this code: > print lstUsers > **** Look at the elements in the list; do you see ..., 'None', ... or > do you see ..., None, ... > > > x = 0 > > while x < len(lstUsers): > > *Please* consider using a "for" statement: > > for item in lstUsers: > do_something_with(item) > > > if re.compile(lstUsers[x]).match("None",0): > > 1. Python or not, using regular expressions to test for equality is > extreme overkill. Use > if lstUsers[x] == "None": > 2. Python or not, it is usual to do > re.compile(constant pattern).match(variable_input) > not the other way around. > 3. The second arg to match defaults to 0, so you can leave it out. > > > > print "Somthing here" > > > > x = x + 1 > > > > [/end] > > > > When I do the: > > if re.compile(lstUsers[x]).match("None",0): > > print "Somthing here" > > > > Some of the items in lstUsers[x] are the word None. > > I am not sure why I cant do this > > > > I want to compare lstUsers[x] to the word "None", how can I do this. > > You *have* compared lstUsers[x] to the word "None" -- with the re > sledgehammer, but you've done it. Maybe what's in there is *not* the > string "None" :-) > > HTH, > John it is really lstusers (it is an L not a # 1), Some of the output from print lstUsers has the output of None. I and trying to filter the None out of the list. I come from a perl background and this is how I do thing in perl TIm From st at tobiah.org Fri Aug 25 17:44:08 2006 From: st at tobiah.org (tobiah) Date: Fri, 25 Aug 2006 14:44:08 -0700 Subject: RE Module In-Reply-To: References: <1156478366.165463.277480@h48g2000cwc.googlegroups.com> <44ef3f95$0$8926$88260bb3@free.teranews.com> <1156539112.253232.321820@i3g2000cwc.googlegroups.com> <44ef5ba7$0$8907$88260bb3@free.teranews.com> Message-ID: <44ef6207$0$8914$88260bb3@free.teranews.com> > In python's RE module, they're like Perl: > > Greedy: "<.*>" > Nongreedy: "<.*?>" > Oh, I have never seen that. In that case, why did Roman's first example not work well for HTML tags? '<.*?>' Also, how does the engine decide whether I am adjusting the greed of the previous operator, or just asking for another possible character? Suppose I want: "x*?" to match "xxxxxxxO" If the '?' means non greedy, then I should get 'x' back. If the '?' means optional character then I should get the full string back. Checking in python: ###################################### import re s = 'xxxxxxx0' m = re.search("x*", s) print "First way", m.group(0) m = re.search("x*?", s) print "Second way", m.group(0) ##################################### First way xxxxxxx Second way So now I'm really confused. It didn't do a non-greedy 'x' match, nor did it allow the '?' to match the '0'. -- Posted via a free Usenet account from http://www.teranews.com From alina.ghergu at gmail.com Thu Aug 17 06:21:43 2006 From: alina.ghergu at gmail.com (Alina Ghergu) Date: 17 Aug 2006 03:21:43 -0700 Subject: wxPython GUI update with data from a MySQL database In-Reply-To: References: <1155807053.375687.15930@i3g2000cwc.googlegroups.com> Message-ID: <1155810103.400344.292390@b28g2000cwb.googlegroups.com> Krzysztof Stachlewski wrote: > "Alina Ghergu" wrote in message > news:1155807053.375687.15930 at i3g2000cwc.googlegroups.com... > > Hi, > > > I have to query the database periodically. I don't have enough > > experience in programming and I would need some advice about the best > > approach in this matter. > > > > I tried to solve it using wx.Timer but from time to time MySQL server > > doesn't repond to queries. I use one db connection for all my queries. > > What is the error returned from MySQL when it is not responding to queries? > > Stach Hi Stach, The error is "Lost connection to MySQL server during query". Alina From gelists at gmail.com Sun Aug 6 10:26:46 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Sun, 6 Aug 2006 11:26:46 -0300 Subject: Thread Question References: <1153998422.670828.148360@m79g2000cwm.googlegroups.com> <1154019801.999805.150000@m73g2000cwd.googlegroups.com> <1154544553.990241.280030@i3g2000cwc.googlegroups.com> <1154605785.859713.26680@i3g2000cwc.googlegroups.com> <1154676179.037598.49710@i3g2000cwc.googlegroups.com> Message-ID: <10sumrcemiwrk$.dlg@gelists.gmail.com> On 2006-08-04 04:22:59, Ritesh Raj Sarraf wrote: > Gerhard Fiedler wrote: >> Rather than downloading and zipping in the same thread, you could run >> multiple threads like you're doing that only download files, and one >> zip-it-all-up thread. After downloading a file, the download threads >> place a message in a queue that indicates the file they have >> downloaded, and the zip-it-all-up thread takes messages out of that >> queue, one at a time, and zips the files. > > I was using this approach earlier. The problem with this approach is > too much temporary disk usage. > > Say I'm downloading 2 GB of data which is a combination of, say 600 > files. Now following this approach, I'll have to make sure that I have > 4 GB of disk space available on my hard drive. Not necessarily. You have a minimum speed of the zipping process, and a maximum speed of the download. Between the two you can figure out what the maximum required temp storage space is. It's in any case less than the full amount, and if the minimum zipping speed is faster than the maximum download speed, it's not more than a few files. But if you current solution works, then that's good enough :) It probably wouldn't be much faster anyway; only would avoid a few waiting periods. Gerhard From robert.kern at gmail.com Tue Aug 8 20:08:41 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 08 Aug 2006 19:08:41 -0500 Subject: How to reverse tuples in a list? In-Reply-To: <1155081671.728757.228050@p79g2000cwp.googlegroups.com> References: <1155081671.728757.228050@p79g2000cwp.googlegroups.com> Message-ID: Noah wrote: > I have a list of tuples > [('a', 1.0), ('b', 2.0), ('c', 3.0)] > I want to reverse the order of the elements inside the tuples. > [(1.0,'a'), (2.0, 'b'), (3.0, 'c')] Python 2.4+: y = [tuple(reversed(t)) for t in y] -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From bj_666 at gmx.net Mon Aug 21 13:10:17 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 21 Aug 2006 19:10:17 +0200 Subject: How to decode a string References: <1156170296.076521.174180@i3g2000cwc.googlegroups.com> <1156175385.580508.302330@m73g2000cwd.googlegroups.com> Message-ID: In <1156175385.580508.302330 at m73g2000cwd.googlegroups.com>, Lad wrote: > The text is from Mysql table field that uses utf8_czech_ci collation, > but when I try > `RealName`.decode('utf8'),where RealName is that field of MySQL > > I will get: > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 3: > ordinal > not in range(128) > > Can you please suggest the solution? Do you get this from converting the value from the database or from trying to print the unicode string? Can you give us the output of print repr(RealName) Ciao, Marc 'BlackJack' Rintsch From andy.terrel at gmail.com Fri Aug 18 17:32:54 2006 From: andy.terrel at gmail.com (Andy Terrel) Date: 18 Aug 2006 14:32:54 -0700 Subject: how do you get the name of a dictionary? In-Reply-To: References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> Message-ID: <1155936774.578249.259290@74g2000cwt.googlegroups.com> Why bang your head? It was a stupid hack that has lots of problems, but done in a way that is readable. Sure I could do something more functional or one lined like: Banana={} names = filter(lambda x:id(eval(x))==id(Banana),dir()) but I am guessing that it is harder to read by many. Anywho I can think of plenty of reasons it would fail, but it really depends on the app. Fredrik Lundh wrote: > Andy Terrel wrote: > > > for i in dir(): > > if eval(i) == Banana: > > print i > > (sound of head hitting desk) > > From skip at pobox.com Mon Aug 7 10:02:42 2006 From: skip at pobox.com (skip at pobox.com) Date: Mon, 7 Aug 2006 09:02:42 -0500 Subject: Nice unicode -> ascii translation? In-Reply-To: <1154916240.860577.35860@p79g2000cwp.googlegroups.com> References: <1154916240.860577.35860@p79g2000cwp.googlegroups.com> Message-ID: <17623.18434.473618.182720@montanaro.dyndns.org> crowell> However, I'd like to see the more sensible "Bela Fleck" instead crowell> of dropping '\xe9' entirely. Assuming the data are in latin-1 or can be converted to it, try my latscii codec: http://orca.mojam.com/~skip/python/latscii.py Skip From fredrik at pythonware.com Mon Aug 28 15:28:12 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 28 Aug 2006 21:28:12 +0200 Subject: unit test for a printing method In-Reply-To: <44f330ce$1@nntp0.pdx.net> References: <1156780399.289589.58750@m73g2000cwd.googlegroups.com> <44f330ce$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > For silly module myprog.py: > def A(s): > print '---'+s+'---' > in test_myprog.py: > import unittest > from cStringIO import StringIO # or from StringIO ... why are you trying to reinvent doctest ? From duncan.booth at invalid.invalid Fri Aug 4 06:14:37 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 4 Aug 2006 10:14:37 GMT Subject: Windows vs. Linux References: <1154301694.445639.99580@m79g2000cwm.googlegroups.com> <44cddfb3$0$7761$7a628cd7@news.club-internet.fr> <1154531160.066733.71210@s13g2000cwa.googlegroups.com> <2NDAg.1122$FN2.341@newssvr14.news.prodigy.com> <1vEAg.1123$FN2.891@newssvr14.news.prodigy.com> Message-ID: Bryan Olson wrote: > Duncan Booth wrote: >> I'm not sure ambiguity enters into it. I think perhaps the bad >> detection of the option happens because the CD command can ignore >> spaces in its argument. Since it is ignoring spaces they don't >> actually require a space after the option strings. > > You lost me. Spaces are significant in file names, and slashes > within the path are used as path separators, as far as I can > tell. Sorry I was unclear. It isn't that spaces are ignored, it is that they do not count as delimiters in the CD command. In all other DOS commands they count as argument delimiters unless they are inside quotes. >> Any other Microsoft commands I try all complain about 'invalid >> switch'. > > The first I noticed were their build tools. Their version of > "make", called "nmake", and their visual studio tools will > accept either forward or backward slashes in paths. > Ok, pedantically I meant the commands that come as part of the system. Most external tools such as Microsoft's compilers have always accepted forward slashes interchangeably with backslashes. They also usually accept '-' as an option character interchangeably with '/'. The 'standard' commands though seem to go to a lot of effort to reject forward slashes in paths, and the CD command seems to be the only one where this usage gets through the net. From thorsten at thorstenkampe.de Sat Aug 19 12:37:12 2006 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sat, 19 Aug 2006 17:37:12 +0100 Subject: text editor suggestion? References: <44e66724$0$2363$c3e8da3@news.astraweb.com> Message-ID: <1vth2bhkg31bq$.n5r3nrqxovpu.dlg@40tude.net> * John Salerno (2006-08-19 02:20 +0100) > Ok, I know it's been asked a million times, but I have a more specific > question so hopefully this won't be just the same old post. I've tried a > few different editors, and I really like UltraEdit, but it's > Windows-only and I'm working more on Linux nowadays. > > Here are my criteria: > > 1. syntax highlighting (highly customizable) > 2. auto/smart indenting > 3. ability to run script > 4. light-weight text editor, not an IDE > 5. cross-platform (not really necessary, but nice) EditPad Pro - runs perfectly under Wine http://www.editpadpro.com/convenience.html http://www.editpadpro.com/wine.html From bborcic at gmail.com Thu Aug 3 15:04:38 2006 From: bborcic at gmail.com (Boris Borcic) Date: Thu, 03 Aug 2006 21:04:38 +0200 Subject: cleaner way to write this try/except statement? In-Reply-To: <1154478191.557521.262950@m73g2000cwd.googlegroups.com> References: <44cfdbdd$1_6@news.bluewin.ch> <1154478191.557521.262950@m73g2000cwd.googlegroups.com> Message-ID: <44d248eb$1_3@news.bluewin.ch> Simon Forman wrote: > Boris Borcic wrote: >> John Salerno wrote: >>> The code to look at is the try statement in the NumbersValidator class, >>> just a few lines down. Is this a clean way to write it? i.e. is it okay >>> to have all those return statements? Is this a good use of try? Etc. >>> >>> Thanks. >>> >>> ---------------------------- >>> >>> import wx >>> >>> >>> class NumbersValidator(wx.PyValidator): >>> >>> def __init__(self): >>> wx.PyValidator.__init__(self) >>> >>> def Clone(self): >>> return NumbersValidator() >>> >>> def Validate(self, parent): >>> text_ctrl = self.GetWindow() >>> text = text_ctrl.GetValue() >>> >>> try: >>> if not text or int(text) <= 0: >>> wx.MessageBox('Enter a valid time.', 'Invalid time >>> entered', wx.OK | wx.ICON_ERROR) >>> return False >>> else: >>> return True >>> except ValueError, error: >>> wx.MessageBox('Enter a valid time.', 'Invalid time entered', >>> wx.OK | wx.ICON_ERROR) >>> return False >> well, assuming you are unsatisfied with the above, you could try to assert the >> validation condition and catch together all failures, eg : >> >> def Validate(self, parent): >> text_ctrl = self.GetWindow() >> text = text_ctrl.GetValue() >> try : >> assert int(text)>0 >> return True >> except (ValueError,AssertionError) : >> wx.MessageBox('Enter a valid time.', 'Invalid time entered', >> wx.OK | wx.ICON_ERROR) >> return False >> >> hth, BB > > Assertion statements "go away" when you run python with the '-O' or > '-OO' options. Makes me wonder how many use those options. I never do, this explains that. > They're only meant for debugging and shouldn't be used > as part of your actual program logic. That's too bad, and bound to evolve if the logic object space of Pypy gains users. > > You run the risk of introducing hard-to-find bugs if you use them like > this and somebody, somewhere, sometime runs your code in "optimized" > mode. Well, I wouldn't formulate it quite like that, but, as you say,... > > Peace, > ~Simon > Well, in that case let's just define def fail(exc) : raise exc and replace assert int(text)>0 by int(text)>0 or fail(ValueError) cheers, BB -- "On na?t tous les m?tres du m?me monde" From Tim.Gallagher at gd-ais.com Thu Aug 17 14:47:19 2006 From: Tim.Gallagher at gd-ais.com (Gallagher, Tim (NE)) Date: Thu, 17 Aug 2006 14:47:19 -0400 Subject: New to python Message-ID: <794CB73454A59D488ED061055AA282073CB822@miaa01-mail01.ad.gd-ais.com> Hello all, I am new to python and I have a few questions. I am an old Perl hacker been using Perl for many years. I wanted to give python a try, I am happy with it so far. Question: 1. Is there a repository that I can go to for modules? Perl has CPAN and I was wondering what the Python equivalent was. I guess that I had a few more that I cannot think of right now. Thanks Tim From roman.yakovenko at gmail.com Tue Aug 8 07:24:58 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Tue, 8 Aug 2006 14:24:58 +0300 Subject: beginner questions on embedding/extending python with C++ In-Reply-To: <1155029311.885266.131980@m73g2000cwd.googlegroups.com> References: <1155029311.885266.131980@m73g2000cwd.googlegroups.com> Message-ID: <7465b6170608080424g660a47f9u2d98b88cc7eeebaf@mail.gmail.com> On 8 Aug 2006 02:28:31 -0700, Qun Cao wrote: > Hi Everyone, > > I am a beginner on cross language development. My problem at hand is to > build a python interface for a C++ application built on top of a 3D > game engine. The purpose of this python interface is providing a > convenient scripting toolkit for the application. As for me, Boost.Python is the way to go. Fortunately you are not the first one, and I hope not the last one :-) : http://language-binding.net/pyplusplus/quotes.html#who-is-using-pyplusplus 1. Python-OGRE * http://lakin.weckers.net/index_ogre_python.html * http://tinyurl.com/mvj8d 2. http://cgkit.sourceforge.net/ - contains Python bindings for Maya C++ SDK 3. PyOpenSG - https://realityforge.vrsource.org/view/PyOpenSG/WebHome The goal of PyOpenSG is to provide python bindings for the OpenSG scene graph. > Since the main program is still going to be the C++ application, I > guess we need to embedding the python scripts in the C++ code. Boost.Python is the only tool that provides complete functionality( extending and embedding ). Also I think cgkit is dealing with the problem too. > But for this to work, the python code needs to know the Player class, > is it right? Right. Does that mean I need to build a python wrapper class for > Player and "import Player" in the python code? But because this > application is built on top of a game engine, Player class inherits > many classes from there, I cannot possibly wrapping them all, right? It depends on how much functionality you want to export. > Also, some global objects are probably needed in this code of adding > players, how can the python code access them? Boost.Python provides the functionality you need. > Btw, if you can point me to any source code of non-trivial projects > utilizing SWIG/Boost.Python, that would be very helpful. I found the > examples on the tutorials are far too simple. Those are tutorials, they should be simple, right :-) ? -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From martin at v.loewis.de Tue Aug 15 04:16:26 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 15 Aug 2006 10:16:26 +0200 Subject: what is the keyword "is" for? In-Reply-To: <1155629086.617707.132900@b28g2000cwb.googlegroups.com> References: <1155625097.784052.31330@p79g2000cwp.googlegroups.com> <44e16d6a$1@nntp0.pdx.net> <1155629086.617707.132900@b28g2000cwb.googlegroups.com> Message-ID: <44E182DA.20602@v.loewis.de> daniel wrote: > when I tried to check the stuff out, found sth interesting that if you > define variables in a style like this: > a = b = ['a', 'b'] > changing one list affects the other, and they still refer to same > object. in fact, seems all compound types (dictionary for instance) > behave in this way. > > however, when list is replaced with other built-in types like integers > : > a = b = 3 > changing one of them cause the two objects differ... Ah, but make a difference between "change a variable", and "change an object". py> a = b = [1,2,3] py> a[0] = 6 # don't change the variable a, just change the object py> a [6, 2, 3] py> b [6, 2, 3] py> a=[7,8,9] # change the variable a; # it's now a different object than b py> a [7, 8, 9] py> b [6, 2, 3] For some objects, "change the object" is impossible. If you have a = b = 3 then there is no way to change the object 3 to become 4 (say); integer objects are "immutable". So for these, to make a change, you really have to change the variable, not the value. Regards, Martin From fredrik at pythonware.com Thu Aug 24 18:38:02 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Aug 2006 00:38:02 +0200 Subject: List problem In-Reply-To: <1156458544.544455.192330@m73g2000cwd.googlegroups.com> References: <1156458544.544455.192330@m73g2000cwd.googlegroups.com> Message-ID: kevndcks at aol.com wrote: > For example i write the following code in the Python command line; > >>>> list = ['One,Two,Three,Four'] > > Then enter this command, which will then return the following; > > ['One,Two,Three,Four'] > > > Now the problem, reading through the Python tutorial's, it describe's > that list's can sliced, concatenated and so on etc > > So i write the following > >>>> list[1:] + ['Five'] > > Then the error returned is that 'str' and 'list' could not be > concatenated which is where it baffles me. if you got that error, you clearly didn't type what you say you typed: >>> list = ['One,Two,Three,Four'] >>> list ['One,Two,Three,Four'] >>> list[1:] + ['Five'] ['Five'] (note that the first list contains a single string; if you want to put multiple strings in a list, you need to be more careful with where you put the quotes.) From smeenehan at hmc.edu Fri Aug 4 09:40:23 2006 From: smeenehan at hmc.edu (smeenehan at hmc.edu) Date: 4 Aug 2006 06:40:23 -0700 Subject: Problem reading/writing files In-Reply-To: <1154692797.329732.73290@75g2000cwc.googlegroups.com> References: <1154661460.803694.241220@s13g2000cwa.googlegroups.com> <1154663988.871166.112930@s13g2000cwa.googlegroups.com> <1154692797.329732.73290@75g2000cwc.googlegroups.com> Message-ID: <1154698823.341957.249760@p79g2000cwp.googlegroups.com> Ok, now I'm very confused, even though I just solved my problem. I copied the entire contents of the original file (evil2.gfx) from my hex editor and pasted it into a text file. When I read from *this* file using my original code, everything worked fine. When I read the 21st byte, it came up as the correct \x00. Why this didn't work in trying to read from the original file, I don't know, since the hex values should be the same, but oh well... From rogue_pedro at yahoo.com Mon Aug 28 23:51:52 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 28 Aug 2006 20:51:52 -0700 Subject: Searching for text In-Reply-To: <1156813686.151600.146170@75g2000cwc.googlegroups.com> References: <1156809673.741444.110690@m73g2000cwd.googlegroups.com> <1156811812.783788.92910@74g2000cwt.googlegroups.com> <1156813686.151600.146170@75g2000cwc.googlegroups.com> Message-ID: <1156823511.968271.20240@75g2000cwc.googlegroups.com> robinsiebler wrote: > The other thing I failed to mention is that I need to ensure that I > find the fsType *before* I find the next FontName. Given these requirements, I'd formulate the script something like this: f = open(filename) NUM_LINES_BETWEEN = 7 Fo = '/FontName /ACaslonPro-Semibold' FS = '/FSType 8' def checkfile(f): # Get a (index, line) generator on the file. G = enumerate(f) for i, line in G: # make sure we don't find a FSType if FS in line: print 'Found FSType without FontName %i' % i return False # Look for FontName. if Fo in line: print 'Found FontName at line %i' % i try: # Check the next 7 lines for NO FSType # and NO FontName n = NUM_LINES_BETWEEN while n: i, line = G.next() if FS in line: print 'Found FSType prematurely at %i' % i return False if Fo in line: print "Found '%s' before '%s' at %i" % \ (Fo, FS, i) return False n =- 1 # Make sure there's a FSType. i, line = G.next() if FS in line: print 'Found FSType at %i' % i elif Fo in line: print "Found '%s' instead of '%s' at %i" % \ (Fo, FS, i) return False else: print 'FSType not found at %i' % i return False except StopIteration: print 'File ended before FSType found.' return False return True if checkfile(f): # File passes... pass Be sure to close your file object when you're done with it. And you might want fewer or different print statements. HTH Peace, ~Simon From http Mon Aug 14 11:31:06 2006 From: http (Paul Rubin) Date: 14 Aug 2006 08:31:06 -0700 Subject: [Announce] p-gal: photo gallery generator with templating support References: Message-ID: <7xk65buyf9.fsf@ruckus.brouhaha.com> "Paolo Pantaleo" writes: > I would anyone to take a look at my piece of code, and give me his > feedback about what is good and what should be improved. url? From __peter__ at web.de Wed Aug 2 03:41:11 2006 From: __peter__ at web.de (Peter Otten) Date: Wed, 02 Aug 2006 09:41:11 +0200 Subject: Hierarchical unit tests References: <44cfc171$0$18509$9b4e6d93@newsread2.arcor-online.net> Message-ID: Pupeno wrote: > Having A(unittest.TestCase) and B(A), the unittests framework seems not to > run A's test when testing B, right ? Wrong: $ cat hierarchical_tests.py import unittest class A(unittest.TestCase): def test_a(self): pass class B(A): def test_b(self): pass if __name__ == "__main__": unittest.main() $ python hierarchical_tests.py -v test_a (__main__.A) ... ok test_a (__main__.B) ... ok test_b (__main__.B) ... ok ---------------------------------------------------------------------- Ran 3 tests in 0.001s OK Peter From jiangnutao at gmail.com Wed Aug 23 15:26:38 2006 From: jiangnutao at gmail.com (Jason Jiang) Date: Wed, 23 Aug 2006 12:26:38 -0700 Subject: setting a breakpoint in the function of my module Message-ID: Hi, I have two modules: a.py and b.py. In a.py, I have a function called aFunc(). I'm calling aFunc() from b.py (of course I import module a first). The question is how to directly set a breakpoint in aFunc(). The way I'm doing now is to set a breakpoint in b.py at the line to call aFunc(), 'c' to it, then 's' to step in, then set the breakpoint inside aFunc() by 'b lineNumber'. It's too cumbersome. Thanks. Jason From rogue_pedro at yahoo.com Fri Aug 4 15:29:38 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 4 Aug 2006 12:29:38 -0700 Subject: Need help building boost python on mac os x. In-Reply-To: <1154710275.927380.226510@h48g2000cwc.googlegroups.com> References: <1154710275.927380.226510@h48g2000cwc.googlegroups.com> Message-ID: <1154719778.532791.82650@75g2000cwc.googlegroups.com> KraftDiner wrote: > Could someone point me to step by step instructions on building boost > python on mac os x? > I have bjam running.. I have the boost source... but the tests are > failing.. > Probably something to do with environement variables... > Anyone with time? You might also ask on the boost python list: http://www.boost.org/more/mailing_lists.htm HTH, ~Simon From anthra.norell at tiscalinet.ch Thu Aug 10 06:44:33 2006 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Thu, 10 Aug 2006 12:44:33 +0200 Subject: Escape sequences (colour) and padding with "%8s"% References: Message-ID: <00ae01c6bc69$f78033c0$0201a8c0@mcuf7> Anton, See if this suits your purpose: http://cheeseshop.python.org/pypi/SE/2.2%20beta Below the dotted line is how it works. Frederic ----- Original Message ----- From: "Anton81" Newsgroups: comp.lang.python To: Sent: Wednesday, August 09, 2006 7:48 PM Subject: Escape sequences (colour) and padding with "%8s"% > Hi all! > > I used escape sequences to produce colour output, but a construct like > > print "%8s" % str_with_escape > > doesn't do the right thing. I suppose the padding counts the escape > characters, too. > > What could be a solution? > > Anton ---------------------------------------------------------------------------------------------------------- # 1. List your ansi codes and invent concise place holders. Define each one like this 'symbol=ansi_escape'. >>> ansi_escapes = ''' ::=(x1b)[0m # Cancel all previous escapes :B:=(x1b)[1m # bold :blue:=(x1b)[34m # etc. ''' # 2. Mark your text up with your symbols marked_up_text = "this has some :B:bold:: text and some :blue:blue:: text and some :B::blue:text that is bold and blue::" # 3 Make an SE Stream Editor. >>> import SE >>> Ansiizer = SE.SE (ansi_escapes) # 4. Stream-Edit >>> ansiized_text = Ansiizer (marked_up_text) >>> ansiized_text 'this has some \x1b[1mbold\x1b[0mtext and some \x1b[34mblue\x1b[0m text and some \x1b[1m\x1b[34mtext that is bold and blue\x1b[0m' ---------------------------------------------------------------------------------------------------------- # Alternatively you may first write your definitions into a file. You then make your ansiizing Stream-Editor simply by naming the file, say 'your_path/ansi_definitions.se'. >>> Ansiizer = SE.SE ('your_path/ansi_definitions.se') ---------------------------------------------------------------------------------------------------------- # You can do files directly >>> Ansiizer ('some_path/text_file', 'some_path/text_file_ansiized') ---------------------------------------------------------------------------------------------------------- From riko at despammed.com Tue Aug 22 19:31:02 2006 From: riko at despammed.com (Mc Osten) Date: Wed, 23 Aug 2006 01:31:02 +0200 Subject: Python and STL efficiency References: <1156143136.020647.294290@i42g2000cwa.googlegroups.com> <1hkh28d.xscw4v1y4v9a6N%riko@despammed.com> <1hkh6lb.6dsnh51lj8z96N%riko@despammed.com> <1156252193.524186.107520@b28g2000cwb.googlegroups.com> <1hkhexv.18m65rl61swqyN%riko@despammed.com> <1156265848.875774.251640@i42g2000cwa.googlegroups.com> Message-ID: <1hki0kk.1qkp2w6r4lcqgN%riko@despammed.com> Tim N. van der Leeuw wrote: > My conclusion from that is, that the vector<> or set<> implementations > of GCC are far superior to those of VC++ 6, but that memory allocation > for GCC 3.4.5 (MinGW version) is far worse than that of MSCRT / VC++ 6. > (And Python still smokes them both). It would be interesting to test it with VC 8 (2005). I have it in my Parallels vm, but it looks like something is wrong. The very same code takes almost a minute, I suppose there is something wrong with it (Python is almost as fast as the python 2.4 on MacOS). -- blog: http://www.akropolix.net/rik0/blogs | Uccidete i filosofi, site: http://www.akropolix.net/rik0/ | tenetevi riso e forum: http://www.akropolix.net/forum/ | bacchette per voi. From g.brandl-nospam at gmx.net Wed Aug 23 02:50:07 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Wed, 23 Aug 2006 08:50:07 +0200 Subject: how do you get the name of a dictionary? In-Reply-To: References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> <1156264475.968894.221710@p79g2000cwp.googlegroups.com> <1156266720.205126.284050@i3g2000cwc.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Tue, 22 Aug 2006 10:12:00 -0700, BartlebyScrivener wrote: > >>>> how difficult would it be to assign a string name(s) >>>> to an object upon creation (and upon referencing)? >> >> Exactly the point that's being made. It's so easy just do it yourself: >> >> banana={"name":"banana"} >> >> Hey what is the name of my dictionary? >> >> banana["name"] >> >> But why build it into Python and force everyone else to do it, when >> most of the time nobody cares what the name is, or they already know? >> >> It's like forcing everybody everywhere always and forever to wear >> "Hello My Name Is" tags. > > On reflection, I'm wondering if we've been too harsh on Jojoba and not > thought this through, simply because "that's the way it's always been". > > Functions have a __name__ attribute. So do classes and modules. Why are > these three objects "special" that they know the name they were created > with, when other objects don't? Python doesn't attempt to track what name > they are known at *now*, just the name they were born with. Because they're not created by simple assignment, because they are usually created once, because new names are bound to them rarely, and because it's crucial to know their name in debugging, introspection etc. Georg From ahaas at airmail.net Thu Aug 3 16:28:35 2006 From: ahaas at airmail.net (Art Haas) Date: Thu, 3 Aug 2006 15:28:35 -0500 Subject: [ANNOUNCE] Thirty-fourth release of PythonCAD now available Message-ID: <20060803202835.GB6283@artsapartment.org> Hi. I'm pleased to announce the thirty-fourth development release of PythonCAD, a CAD package for open-source software users. As the name implies, PythonCAD is written entirely in Python. The goal of this project is to create a fully scriptable drafting program that will match and eventually exceed features found in commercial CAD software. PythonCAD is released under the GNU Public License (GPL). PythonCAD requires Python 2.2 or newer. The interface is GTK 2.0 based, and uses the PyGTK module for interfacing to GTK. The design of PythonCAD is built around the idea of separating the interface from the back end as much as possible. By doing this, it is hoped that both GNOME and KDE interfaces can be added to PythonCAD through usage of the appropriate Python module. Addition of other PythonCAD interfaces will depend on the availability of a Python module for that particular interface and developer interest and action. The thirty-fourth release builds on the graphics improvements from the previous release. A number of small optimizations again reduce unneeded screen redraws, and a variety of redraw issues have been corrected. The newest PythonCAD release is the first release using Cairo graphics routines for entity drawing. If the Cairo routines are not available on the system then the existing GDK routines will be used, so only people running PythonCAD on recent PyGTK/GTK+ releases will see the change. The latest release includes the new ability to rotate objects around an arbitrary point in addition to the entity display improvements. Finally, a variety of other bug fixes and code improvements are included in the release. A mailing list for the development and use of PythonCAD is available. Visit the following page for information about subscribing and viewing the mailing list archive: http://mail.python.org/mailman/listinfo/pythoncad Visit the PythonCAD web site for more information about what PythonCAD does and aims to be: http://www.pythoncad.org/ Come and join me in developing PythonCAD into a world class drafting program! Art Haas -- Man once surrendering his reason, has no remaining guard against absurdities the most monstrous, and like a ship without rudder, is the sport of every wind. -Thomas Jefferson to James Smith, 1822 From hancock at anansispaceworks.com Mon Aug 28 20:24:05 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Mon, 28 Aug 2006 19:24:05 -0500 Subject: Is this a good idea or a waste of time? In-Reply-To: <1156449402.022781.292840@p79g2000cwp.googlegroups.com> References: <1156449402.022781.292840@p79g2000cwp.googlegroups.com> Message-ID: <44F38925.1090205@anansispaceworks.com> asincero wrote: > Would it be considered good form to begin every method or function > with a bunch of asserts checking to see if the parameters are of the > correct type [...] > > This is something I miss from working with more stricter languages > like C++, where the compiler will tell you if a parameter is the > wrong type. If anything, I think it goes a long way towards the code > being more self documenting. Or is this a waste of time and not > really "the Python way"? Definitely "unpythonic". It's generally better to ask if an object "acts right" rather than if it "is right". In other words, if you're going to add two objects, it's more important that they support addition than that they are integers, longs, floats, or matrices. This makes your code more portable, because people might create new numeric types (say "measurements" or "rationals"). If you leave things open, then the author of such modules can use your code (they may have to test special cases if their objects don't behave the same way as you expect them to, but that becomes their problem). On the other hand, if your code just arbitrarily breaks because the objects fail a typecheck, that's an unnecessary obstacle. If you need assertions, it's better to ask more specifically what will break the code (e.g. objects that don't support addition -- which you can check by doing an addition or by looking for th __add__ method. But then, if you need addition support, then your code probably already has an addition, so why not just let it fail there?). So be more minimal and throw in checks for specific problems -- especially the ones that would cause a wrong result rather than an exception. Cheers, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From Bulkan at gmail.com Mon Aug 7 02:58:19 2006 From: Bulkan at gmail.com (placid) Date: 6 Aug 2006 23:58:19 -0700 Subject: embedding console in wxpython app In-Reply-To: <%FuBg.15999$W93.12002@dukeread05> References: <1154898390.542838.45710@i42g2000cwa.googlegroups.com> <%FuBg.15999$W93.12002@dukeread05> Message-ID: <1154933899.779817.101500@i42g2000cwa.googlegroups.com> Philippe Martin wrote: > Janto Dreijer wrote: > > > I'm writing a Linux filemanager using wxPython. I'd like to embed a > > bash console inside it. I have found the Logilab pyqonsole > > (http://www.logilab.org/projects/pyqonsole), but it uses PyQT. > > > > Does anyone know how to do this from wx? > > Is it possible to embed a PyQT widget inside wxPython? > > > > Thanks! > > Janto > > > How about just using bash and rerouting stdin/stdout ? What is that thing in Software Engineering (SE) ? that it is hard to find simple solutions (or any problem in life for that matter) I remember last year at uni we had to write this program (get information from user save it somewhere) for a SE assignment. And half the teams went off and used MySql to save data retrieved from the user via a GUI. And in no part of the requirements document did it write ; * Customer requires GUI frontend * Customer needs MySql databases server usage to store data So my team created a Command Line Program (i.e cmd module in python) as the UI and used object Serialization (pickling in python) to files. So we finished in half the time that other teams took (and many had to drop the database server usage in the end) and stressed like tomorow was Judgement Day. Oh yeah we designed our application so that it was easy to create a GUI or change the Serialization to saving stuff into a database and we had one of the top marks out of all the teams. So OP, if you really dont need to embed bash inside wxPython, then dont and use what Philippe suggested, unless its in the requirements :) Cheers From duncan.booth at invalid.invalid Wed Aug 2 16:45:21 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 Aug 2006 20:45:21 GMT Subject: Windows vs. Linux References: Message-ID: Tim Chase wrote: > Nice to see consistancy at work. Looks like leading slashes are > stripped and so it trys to find it relative to the current path. > > Nothing like predictable, cross-platform implementations there. > [rolls eyes] > > Thank goodness Python brings some brains to the table where > Windows/Dos is ::ehem:: seriously lacking. Ah, thank you. I couldn't figure out what on earth was happening. Sometimes the CD worked and sometimes it didn't. From bruce.who.hk at gmail.com Tue Aug 29 02:03:10 2006 From: bruce.who.hk at gmail.com (Bruce Who) Date: Tue, 29 Aug 2006 14:03:10 +0800 Subject: [ANN] NumPy 1.0b4 now available In-Reply-To: <44F341E4.7000003@ieee.org> References: <44F01802.8050505@ieee.org> <200608281448353906004@gmail.com> <44F341E4.7000003@ieee.org> Message-ID: Hi, Travis I can pack my scripts into an executable with py2exe, but errors occur once it runs: No scipy-style subpackage 'random' found in D:\test\dist\numpy. Ignoring: No module named info import core -> failed: No module named _internal import lib -> failed: 'module' object has no attribute '_ARRAY_API' import linalg -> failed: 'module' object has no attribute '_ARRAY_API' import dft -> failed: 'module' object has no attribute '_ARRAY_API' Traceback (most recent call last): File "main.py", line 9, in ? File "numpy\__init__.pyc", line 49, in ?  File "numpy\add_newdocs.pyc", line 2, in ? gkDc File "numpy\lib\__init__.pyc", line 5, in ? File "numpy\lib\type_check.pyc", line 8, in ? File "numpy\core\__init__.pyc", line 6, in ? File "numpy\core\umath.pyc", line 12, in ? File "numpy\core\umath.pyc", line 10, in __load AttributeError: 'module' object has no attribute '_ARRAY_API' This is the main.py file: #======================================= # filename:main.py import wx import numpy class myFrame(wx.Frame): def __init__(self, *args, **kwds): wx.Frame.__init__(self, *args, **kwds) ##------ your widgets ##------ put stuff into sizer self.sizer_ = wx.BoxSizer(wx.VERTICAL) ## self.sizer_.Add(your_ctrl, proportion = 1, flag = wx.EXPAND) ## apply sizer self.SetSizer(self.sizer_) self.SetAutoLayout(True) def main(): ## {{{ app = wx.PySimpleApp(0) frame = myFrame(None, -1, title = '') frame.Show(True) app.SetTopWindow(frame) app.MainLoop() ## }}} if __name__ == "__main__":main() #======================================= # filename:setup.py import glob import sys from distutils.core import setup import py2exe includes = ["encodings", "encodings.*", ] excludes = ["javax.comm"] options = { "py2exe": { #"compressed": 1, #"optimize": 0, #"bundle_files":2, "skip_archive":1, "includes": includes, 'excludes': excludes } } setup( version = "0.1", description = "", name = "test", options = options, windows = [ { "script":"main.py", } ], #zipfile = None, ) and I run this command to compile the scripts: python setup.py py2exe and all packages I use are: python2.4.3 numpy-0.98 py2exe-0.6.5 wxpython-2.6.3.2 I unistalled Numeric before I compiled scripts. If you google "numpy py2exe", you can find others guys stumbled by the same issue with ease: http://aspn.activestate.com/ASPN/Mail/Message/py2exe-users/3249182 http://www.nabble.com/matplotlib,-numpy-and-py2exe-t1901429.html I just hope this can be fixed in the next table release of numpy. On 8/29/06, Travis Oliphant wrote: > bruce.who.hk wrote: > > Hi, Travis > > > > I just wonder if NumPy 1.0b4 can get along with py2exe? Just a few weeks ago I made a application in Python. At first I used Numpy, it works OK, but I cannot pack it into a workable executable with py2exe and the XXX.log saied that numpy cannot find some module. I found some hints in py2exe wiki, but it still doesn't work. At Last I tried Numeric instead and it got OK. I just hope that you donnot stop the maintenance of Numeric before you are sure that Numpy can work with py2exe. > > > We've already stopped maintenance of Numeric nearly 1 year ago. If > NumPy doesn't work with py2exe then we need help figuring out why. The > beta-release period is the perfect time to fix that. I've never used > py2exe myself, but I seem to recall that some have been able to make it > work. > > The problem may just be listing the right set of modules to carry along > because you may not be able to get that with just the Python-side > imports. Post any errors you receive to > numpy-discussion at lists.sourceforge.net > > Thanks, > > > -Travis > > Bruce Who From blue99 at interia.pl Mon Aug 21 10:29:07 2006 From: blue99 at interia.pl (Rob Wolfe) Date: 21 Aug 2006 07:29:07 -0700 Subject: Regular Expression question In-Reply-To: <1156158574.263980.319450@i3g2000cwc.googlegroups.com> References: <1156153916.849933.178790@75g2000cwc.googlegroups.com> <1156154876.874272.283160@i3g2000cwc.googlegroups.com> <1156156724.165790.208880@b28g2000cwb.googlegroups.com> <1156157962.192238.116160@74g2000cwt.googlegroups.com> <1156158574.263980.319450@i3g2000cwc.googlegroups.com> Message-ID: <1156170547.123209.51280@74g2000cwt.googlegroups.com> stevebread at yahoo.com wrote: > got zero results on this one :) Really? >>> s = '''
''' >>> pat = re.compile('tag1.+?name="(.+?)".*?(?:<)(?=tag2).*?="adj__(.*?)__', re.DOTALL) >>> m = re.findall(pat, s) >>> m [('john', 'tall'), ('joe', 'short')] Regards, Rob From skip at pobox.com Wed Aug 30 08:11:57 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 30 Aug 2006 07:11:57 -0500 Subject: how can i change the text delimiter In-Reply-To: <1156938927.933389.101170@m73g2000cwd.googlegroups.com> References: <1156929540.715287.123060@h48g2000cwc.googlegroups.com> <1156932106.948885.63980@i3g2000cwc.googlegroups.com> <1156938927.933389.101170@m73g2000cwd.googlegroups.com> Message-ID: <17653.32909.333745.298209@montanaro.dyndns.org> sonald> fast csv is the the csv module for Python... and actually the sonald> string cannot be modified because it is received from a third sonald> party and we are not supposed to modify the data in any way.. sonald> for details on the fast CSV module please visit sonald> www.object-craft.com.au/projects/csv/ or sonald> import fastcsv sonald> csv = fastcsv.parser(strict = 1,field_sep = ',') // part of sonald> configuration sonald> and somewhere in the code... we are using sonald> data = csv.parse(line) sonald> all i mean to say is, csv.reader is nowhere in the code and sonald> somehow we got to modify the existing code. You're using Object Craft's old csv module. They are also the primary authors of the csv module that's been shipped with Python since 2.3. I suggest you convert your code to use the newer module if possible. If that's not possible (it's not all that hard - I did it a couple years ago), try posting a note to csv at mojam.com. The Object Craft folks are on that list and may be able to help you out. I think they're here as well, though may not watch this group/list as closely. Skip From p at ulmcnett.com Wed Aug 23 15:31:59 2006 From: p at ulmcnett.com (Paul McNett) Date: Wed, 23 Aug 2006 12:31:59 -0700 Subject: Class instantiation In-Reply-To: References: Message-ID: <44ECAD2F.80804@ulmcnett.com> Colin J. Williams wrote: > class arSpread(object): > def __init__(self, fileId= None, ar= None): > if fileId: > if ar is not None: > print fileId > self.connect(fileID, mode= 'r') # open sheet in the read mode > else: > self.connect(fileID, mode= 'w') # open the sheet in the 'dOH! . Change to self.connect(fileId, ...) :) -- Paul McNett http://paulmcnett.com http://dabodev.com From ksreddy25 at gmail.com Mon Aug 28 00:46:37 2006 From: ksreddy25 at gmail.com (NRI Events) Date: 27 Aug 2006 21:46:37 -0700 Subject: Improve memory for success Message-ID: <1156740397.595952.219260@m79g2000cwm.googlegroups.com> Hello Everybody, * HAPPY GANESH CHATHURTHI * For any professional or business men memory & Focus are required. I found useful tips to improve Memory & concentration. http://www.nrievents.com/Jai%20Ganesh/Ganesh_Index.htm Thanks & Regards Reddy From ian at excess.org Wed Aug 30 12:40:08 2006 From: ian at excess.org (Ian Ward) Date: Wed, 30 Aug 2006 12:40:08 -0400 Subject: ANN: Templayer 1.3 - HTML templating library Message-ID: <44F5BF68.20803@excess.org> Announcing Templayer 1.3 ------------------------ Templayer home page: http://excess.org/templayer/ Tarball: http://excess.org/templayer/templayer-1.3.tar.gz About this release: =================== This release includes new documentation and a new auto-reload feature useful for mod_python and web frameworks. Also, the internal template representation was changed to improve performance and consistency, and the HTML generated with HTML Markup is now more standards-compliant. New in this release: ==================== - Added reference documentation and a new tutorial. - Added an auto_reload parameter to Template.__init__ to make the Template.start_file function check and reload a template if it has been modified. This is useful for mod_python and web frameworks with long-lived processes. - Changed the internal representation of the templates to improve performance for large templates and to solve an issue with slots being filled with text that appears to contain another slot that is being filled at the same time. The new implementation no longer allows "%" and "{" characers in slot and layer names. - The Template.missing_slot function is now passed a list of missing slots for a layer. This should improve performance when ignoring a large number of missing slots. - The HTML markup has been adjusted to make its use of
and

tags more standards-compliant. - HtmlTemplate has been renamed to HTMLTemplate and MarkupException has been renamed to MarkupError. The old names are still provided for backwards compatibility. About Templayer =============== Templayer was created to offer an alternative to the more common ways of generating dynamic HTML: embedding code within the HTML or embedding HTML within code. Instead of mixing HTML and Python, two rich and extremely expressive languages, Templayer adds a small amount of syntax to each and keeps the two separate and coherent. Templayer is released under the GNU LGPL. From gabriel.murray at gmail.com Thu Aug 3 17:10:55 2006 From: gabriel.murray at gmail.com (Gabriel Murray) Date: Thu, 3 Aug 2006 22:10:55 +0100 Subject: regex question Message-ID: <1983a3190608031410n71eaa4d1s2a3db7c10c519b88@mail.gmail.com> Hello, I'm looking for a regular expression which will match strings as follows: if there are symbols a, b, c and d, then any pattern is valid if it begins with a and ends with d and proceeds in order through the symbols. However, at any point the pattern may reset to an earlier position in the sequence and begin again from there. For example, these would be valid patterns: aabbbaabbcccbbbcccddd aabcabcd abcd But these would not: aaaaabbbbbccccaaaaadddd (goes straight from a to d) aaaaaaaaaaabbbbbccc (does not reach d) Can anyone think of a concise way of writing this regex? The ones I can think of are very long and awkward. Gabriel -------------- next part -------------- An HTML attachment was scrubbed... URL: From swell at netcourrier.com Thu Aug 31 07:53:10 2006 From: swell at netcourrier.com (swell at netcourrier.com) Date: 31 Aug 2006 04:53:10 -0700 Subject: Broadcast server In-Reply-To: References: <1157015655.323891.154720@p79g2000cwp.googlegroups.com> Message-ID: <1157025190.780586.43070@i42g2000cwa.googlegroups.com> Hi Matt , It sounds very interesting and i will definitely take a deeper look but i was more considering something simpler as a learning exercise more that finding a package that should already do what i want to achieve. I want to find the basic guidelines to write that kind of client/server architecture and make some tests of different solutions(socket+select or socket+thread or mix of them) Your project seems very great and will try to read in to learn. From martin at v.loewis.de Mon Aug 14 18:40:44 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 15 Aug 2006 00:40:44 +0200 Subject: Memory problem In-Reply-To: References: <85mdnb4jzcpTRH3ZnZ2dnUVZ_t6dnZ2d@comcast.com> Message-ID: <44E0FBEC.8000405@v.loewis.de> Yi Xing wrote: > Thanks! I just found that that I have no problem with > x=[[10.0]*2560*2560]*500, but x=range(1*2560*2560*30) doesn't work. That's no surprise. In the first case, try x[0][0] = 20.0 print x[1][0] You have the very same (identical) list of 2560*2560 values in x 500 times. To create such a structure correctly, do x = [None] * 500 for i in range(500) x[i] = [10.0]*2560*2560 In any case, check ulimit(1). Regards, Martin From tim.peters at gmail.com Mon Aug 28 19:31:46 2006 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 28 Aug 2006 19:31:46 -0400 Subject: naive misuse? (of PyThreadState_SetAsyncExc) In-Reply-To: <1156804741.964769.98030@i42g2000cwa.googlegroups.com> References: <1156720585.068907.244240@i3g2000cwc.googlegroups.com> <1156804741.964769.98030@i42g2000cwa.googlegroups.com> Message-ID: <1f7befae0608281631j482f34b0x5bb49c044297ce48@mail.gmail.com> [johan2sson at gmail.com] >> The documentation for PyThreadState_SetAsyncExc says "To prevent naive >> misuse, you must write your own C extension to call this". Anyone care >> to list a few examples of such naive misuse? [and again] > No? I'll take that then as proof that it's impossible to misuse the > function. That's wise ;-) Stopping a thread asynchronously is in /general/ a dangerous thing to do, and for obvious reasons. For example, perhaps the victim thread is running in a library routine at the time the asynch exception is raised, and getting forcibly ejected from the normal control flow leaves a library-internal mutex locked forever. Or perhaps a catch-all "finally:" clause in the library manages to release the mutex, but leaves the internals in an inconsistent state. Etc. The same kinds of potential disasters accout for why Java deprecated its versions of this gimmick: http://java.sun.com/j2se/1.3/docs/guide/misc/threadPrimitiveDeprecation.html That said, you can invoke PyThreadState_SetAsyncExc() from Python using the `ctypes` module (which will be included in 2.5, and is available as an extension module for earlier Pythons). From spamspam at spam.eggs Tue Aug 8 03:39:15 2006 From: spamspam at spam.eggs (Ben C) Date: Tue, 08 Aug 2006 02:39:15 -0500 Subject: access abook addressbook with curses References: Message-ID: On 2006-08-08, Fabian Braennstroem wrote: > Hi Ben, > > * Ben C wrote: >> On 2006-08-06, Fabian Braennstroem wrote: >>> Hi Ben, >>> >>> * Ben C wrote: >>>> On 2006-08-05, Fabian Braennstroem wrote: >>>>> Hi, >>>>> >>>>> I want to get access to my abook address file with python. >>>>> Does anyone have some python lines to achive this using >>>>> curses? If not, maybe anybody has small python program doing >>>>> it with a gui!? >>>> >>>> You can just parse the abook addressbook with the ConfigParser, try >>>> this: >>>> >>>> import os >>>> from ConfigParser import * >>>> >>>> abook = ConfigParser() >>>> abook.read(os.environ["HOME"] + "/.abook/addressbook") >>>> >>>> for s in abook.sections(): >>>> print abook.items(s) >>> >>> Thanks! I found a different example too: >>> >>> import ConfigParser >>> import string >>> >>> config = ConfigParser.ConfigParser() >>> >>> config.read("/home/fab/.abook/addressbook") >>> >>> # print summary >>> print >>> for number in [2,200]: >>> print string.upper(config.get(str(number), "email")) >>> print string.upper(config.get(str(number), "name")) >>> print string.upper(config.get(str(number), "city")) >>> print string.upper(config.get(str(number), "address")) >>> >>> but the problem seems to be that abook does not write every >>> field, so I get an exception when there is a field missing: >>> >>> Traceback (most recent call last): >>> File "configparser-example-1.py", line 13, in ? >>> print string.upper(config.get(str(number), "city")) >>> File "/usr/lib/python2.4/ConfigParser.py", line 520, in get >>> raise NoOptionError(option, section) >>> ConfigParser.NoOptionError: No option 'city' in section: '2' >>> >>> Section 2 looks like: >>> >>> [2] >>> name=Andrs Gzi >>> email=anes.oi at ik.e >>> nick=oz >>> >>> Is there a workaround? >> >> You can construct the parser with a dictionary of defaults: >> >> config = ConfigParser.ConfigParser({"city" : "unknown", >> "zip" : "unknown"}) >> >> that kind of thing. >> >> Or catch the exceptions. Or use config.options("2") to see what options >> exist in section 2 before you try to read them. > > Thanks! I will try it out! Looking at the bigger picture here, though, I may be giving you the wrong advice. Mutt just invokes abook to get the addresses I think, that's why you put set query_command="abook --mutt-query '%s'" So you could do the same (if what you're trying to do is write a mutt clone in Python): import subprocess name = "Andrs" subprocess.Popen("abook --mutt-query " + name, stdout=subprocess.PIPE, shell=True).communicate()[0] The difference is that this "leverages" abook to do the search, not just to store the data, which is a logical approach. On the other hand, this way, you require that abook is installed on the machine, which is no good if the object of the exercise is a portable Python-only solution. From email at christoph-haas.de Thu Aug 17 16:06:51 2006 From: email at christoph-haas.de (Christoph Haas) Date: Thu, 17 Aug 2006 22:06:51 +0200 Subject: CGI script running not completely in HTML In-Reply-To: <20060817195019.16383158A0@net.tamu.edu> References: <20060817195019.16383158A0@net.tamu.edu> Message-ID: <200608172206.52517.email@christoph-haas.de> On Thursday 17 August 2006 21:50, Yong Wang wrote: > I have written a python CGI script to run in html web page. When I > access to the html page, it only runs part of the script, then abort > because the late part of the script is involved in database access, it > is slow. I wonder whether there is a way to control html running speed > so that it can wait for CGI script to complete execution, then write the > results to html page ? You could use output = '' output += 'Something else to print' instead of print 'Something else to print' And finally use print output Or to use that more efficiently use a list of strings and append to that list. That's probably faster than creating another immutable string time and again. And finally you just ' '.join(outputlist) and print that. Cheers Christoph From fredrik at pythonware.com Tue Aug 22 14:26:24 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Aug 2006 20:26:24 +0200 Subject: Problem of function calls from map() In-Reply-To: References: <200608211350.k7LDoBJb032411@fe12.bluebottle.com> <2Gf*MkSor@news.chiark.greenend.org.uk> Message-ID: Sion Arrowsmith wrote: >> (you cannot really use "profile" to *benchmark* things written in Python either; the >> profiler tells you where a given program spends the time, not how fast it is in com- >> parision with other programs) > > Hmm. Playing around with timeit suggests that although split() *is* > faster than split("\t"), it's fractional, rather than the OP's four > times faster. Is the overhead of profile keeping track of calls in > Python getting in the way? correct. > And why can map() keep everything at the C level when the list com- > prehension can't? map is called with two Python objects (the str.split callable and the sequence object), while the list comprehension is turned into a byte- code loop that evaluates s.split for each item in the sequence; compare and contrast: >>> def func(a): ... return map(str.split, a) ... >>> dis.dis(func) 2 0 LOAD_GLOBAL 0 (map) 3 LOAD_GLOBAL 1 (str) 6 LOAD_ATTR 2 (split) 9 LOAD_FAST 0 (a) 12 CALL_FUNCTION 2 15 RETURN_VALUE >>> def func(a): ... return [s.split() for s in a] ... >>> dis.dis(func) 2 0 BUILD_LIST 0 3 DUP_TOP 4 STORE_FAST 1 (_[1]) 7 LOAD_FAST 0 (a) 10 GET_ITER >> 11 FOR_ITER 19 (to 33) 14 STORE_FAST 2 (s) 17 LOAD_FAST 1 (_[1]) 20 LOAD_FAST 2 (s) 23 LOAD_ATTR 0 (split) 26 CALL_FUNCTION 0 29 LIST_APPEND 30 JUMP_ABSOLUTE 11 >> 33 DELETE_FAST 1 (_[1]) 36 RETURN_VALUE (LOAD_GLOBAL and LOAD_ATTR does full name lookups, while LOAD_FAST loads a local variable using an integer index) From luismgz at gmail.com Sun Aug 27 00:26:38 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 26 Aug 2006 21:26:38 -0700 Subject: Python web service ... In-Reply-To: <1156590455.555359.247410@h48g2000cwc.googlegroups.com> References: <1156590455.555359.247410@h48g2000cwc.googlegroups.com> Message-ID: <1156652798.618278.228100@i42g2000cwa.googlegroups.com> nicolasg at gmail.com wrote: > My question is how difficult is to set up a web server that can run > python easy ? should I try ZOPE or there is something better in mind ? I also second the suggestion of using Karrigell. It comes with its own built-in server, and the task would be as simle as writing the script and starting the server. If performance and scalability is an issue, you could try mod_python, which is an Apache module for running python, but this would require installing and configuring Apache and mod_python separately. luis From paolopantaleo at gmail.com Thu Aug 24 14:00:08 2006 From: paolopantaleo at gmail.com (Paolo Pantaleo) Date: Thu, 24 Aug 2006 20:00:08 +0200 Subject: Python & chess In-Reply-To: <83e8215e0608240358l4126bb83la93a4c61e4aa4499@mail.gmail.com> References: <83e8215e0608240358l4126bb83la93a4c61e4aa4499@mail.gmail.com> Message-ID: <83e8215e0608241100k66d09f12i2eed2b449d5f306c@mail.gmail.com> Well Python is not a good language for writing a chess engine (even if a chess engine exists: http://www.kolumbus.fi/jyrki.alakuijala/pychess.html), but it could be grat for chess interfaces, for drawing boards, and similar things. I foudn out a library for these things (http://www.alcyone.com/software/chess/). Does anyone konw about more chess related modules? Thnx PAolo From mccredie at gmail.com Wed Aug 16 19:01:44 2006 From: mccredie at gmail.com (Matimus) Date: 16 Aug 2006 16:01:44 -0700 Subject: Printing n elements per line in a list In-Reply-To: <1155685889.626881.37040@m73g2000cwd.googlegroups.com> References: <1155685889.626881.37040@m73g2000cwd.googlegroups.com> Message-ID: <1155769304.916282.183340@i3g2000cwc.googlegroups.com> unexpected wrote: > If have a list from 1 to 100, what's the easiest, most elegant way to > print them out, so that there are only n elements per line. > > So if n=5, the printed list would look like: > > 1 2 3 4 5 > 6 7 8 9 10 > 11 12 13 14 15 > etc. > > My search through the previous posts yields methods to print all the > values of the list on a single line, but that's not what I want. I feel > like there is an easy, pretty way to do this. I think it's possible to > hack it up using while loops and some ugly slicing, but hopefully I'm > missing something I suppose 'elegance' is in the eye of the beholder. I agree with the previous posts, a readable for loop is probably the best way to go. I've instead chosen to use the functional paradigm. I thought someone might appreciate this: p = sys.stdout.write map(p,[str(i)+("\n"+" "*(n-1))[i%n] for i in range(1,101)]) From n3llyb0y at aol.com Wed Aug 30 13:16:52 2006 From: n3llyb0y at aol.com (n3llyb0y) Date: Wed, 30 Aug 2006 17:16:52 GMT Subject: win32com.client & OS X Message-ID: <2006083018165316807-n3llyb0y@aolcom> Hi All, I'd like to know if it is possible to call the win32com.client component using Python on MAC OS X (or maybe Linux) and, if so, how? Cheers, Neil From kay.schluehr at gmx.net Wed Aug 2 06:02:18 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 2 Aug 2006 03:02:18 -0700 Subject: Attribute protection the 2nd Message-ID: <1154512937.978157.324850@s13g2000cwa.googlegroups.com> A new recipe for attribute protection which is aligned with Pythons convention of privacy indication using underscore name mangling. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496930 Regards, Kay From ptmcg at austin.rr._bogus_.com Fri Aug 25 07:02:44 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 25 Aug 2006 11:02:44 GMT Subject: Consistency in Python References: <1156497650.974905.196140@74g2000cwt.googlegroups.com> Message-ID: "Paul Boddie" wrote in message news:1156497650.974905.196140 at 74g2000cwt.googlegroups.com... > Moreover, append and insert return > no result because the change occurs within an existing object - if you > were to return a reference to the changed object, it would be the same > reference as the one you already had. > There's nothing wrong with returning self from a mutator. This was a common idiom in Smalltalk (the syntax for this was "^self", which was probably the most common statement in any Smalltalk program), and permitted the chaining of property mutators into a single line, each invoking a mutator and returning self, which was then used to invoke the next mutator, etc. For instance, you could have a class like this: class Box(object): def __init__(self): self.ln = 0 self.wd = 0 self.ht = 0 def length(self,ln): self.ln = ln return self def width(self,w): self.wd = w return self def height(self,h): self.ht = h return self volume = property(lambda self:self.ln*self.wd*self.ht) bx = Box().length(100).width(50).height(20) print bx.volume I guess this is sort of a trivial example, and in its triviality, even borders on un-Pythonic. But it is useful when you want to support a large set of object attributes, without creating an init method with many, many args. Even in this case, an init method that takes length, width and height args must always get them specified in the correct order, or use named args. But with mutators that return self, a client could write any of these: bx = Box().length(100).width(50).height(20) bx = Box().width(50).height(20).length(100) bx = Box().width(50).length(100).height(20) ...etc... and the results are the same. -- Paul From ronny.coder at gmail.com Wed Aug 16 13:16:11 2006 From: ronny.coder at gmail.com (Ronny Abraham) Date: Wed, 16 Aug 2006 13:16:11 -0400 Subject: profanity filter Message-ID: <7405d1440608161016k6ac6cce5t10973fc53f5b8072@mail.gmail.com> Hi guys, does anyone have any idea where I can find a profanity filter written in python? -ron -------------- next part -------------- An HTML attachment was scrubbed... URL: From jaysherby at gmail.com Tue Aug 8 20:43:44 2006 From: jaysherby at gmail.com (jaysherby at gmail.com) Date: 8 Aug 2006 17:43:44 -0700 Subject: newb question: file searching In-Reply-To: <1155067111.892386.130610@n13g2000cwa.googlegroups.com> References: <1155067111.892386.130610@n13g2000cwa.googlegroups.com> Message-ID: <1155084224.829101.63940@i42g2000cwa.googlegroups.com> I've narrowed down the problem. All the problems start when I try to eliminate the hidden files and directories. Is there a better way to do this? jaysherby at gmail.com wrote: > I'm new at Python and I need a little advice. Part of the script I'm > trying to write needs to be aware of all the files of a certain > extension in the script's path and all sub-directories. Can someone > set me on the right path to what modules and calls to use to do that? > You'd think that it would be a fairly simple proposition, but I can't > find examples anywhere. Thanks. From djoefish at gmail.com Sat Aug 19 15:01:43 2006 From: djoefish at gmail.com (djoefish) Date: 19 Aug 2006 12:01:43 -0700 Subject: install patch on windows Message-ID: <1156014103.715131.143360@i3g2000cwc.googlegroups.com> Does anyone know how to install a patch on Winodws? For example, I want to install the patch 'ocmalloc-free-arenas.diff' in Python 2.3. thanks... From fuzzyman at gmail.com Mon Aug 7 15:22:38 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 7 Aug 2006 12:22:38 -0700 Subject: Initializing the number of slots in a dictionary In-Reply-To: References: <1154903610.168312.289080@n13g2000cwa.googlegroups.com> Message-ID: <1154978558.448296.162700@h48g2000cwc.googlegroups.com> Jon Smirl wrote: > On Sun, 06 Aug 2006 15:33:30 -0700, John Machin wrote: [snip..] > > > > Do you have an application with a performance problem? If so, what makes > > you think inserting 1M items into a Python dict is contributing to the > > problem? > > I know in advance how many items will be added to the dictionary. Most > dictionary implementations I have previously worked with are more > efficient if they know ahead of time how big to make their tables. > > In this case I only need to do a presence test of the key, there is no > actual data associated with the key. The table is used for detecting > duplicate entries. Is there a more efficient to do this test that sticking > an empty string into a dict? The keys are sha1.digest(). Possibly a naive question - but would using sets be more efficient ? They are generally used for the sort of job you are describing (testing for duplicates rather than storing data associated with a key). We did some limited performance tests at Resolver Systems and found use of sets and dictionaries to be almost exactly hte same speed - but there could be memory advantages for you. Performance is also likely to be different for vast data sets, but I understand the hashing algorithm to be very similar for both... Fuzzyman http://www.voidspace.org.uk/python/index.shtml From stach at fr.pl Thu Aug 17 05:48:51 2006 From: stach at fr.pl (Krzysztof Stachlewski) Date: Thu, 17 Aug 2006 11:48:51 +0200 Subject: wxPython GUI update with data from a MySQL database References: <1155807053.375687.15930@i3g2000cwc.googlegroups.com> Message-ID: "Alina Ghergu" wrote in message news:1155807053.375687.15930 at i3g2000cwc.googlegroups.com... Hi, > I have to query the database periodically. I don't have enough > experience in programming and I would need some advice about the best > approach in this matter. > > I tried to solve it using wx.Timer but from time to time MySQL server > doesn't repond to queries. I use one db connection for all my queries. What is the error returned from MySQL when it is not responding to queries? Stach From schaffer at optonline.net Wed Aug 30 23:18:15 2006 From: schaffer at optonline.net (Les Schaffer) Date: Wed, 30 Aug 2006 23:18:15 -0400 Subject: GC and security In-Reply-To: References: <44F61EEB.8040207@optonline.net> Message-ID: <44F654F7.4060600@optonline.net> Aahz wrote: > Assuming you're talking about CPython, strings don't really participate > in garbage collection. Keep in mind that the primary mechanism for > reaping memory is reference counting, and generally as soon as the > refcount for an object goes to zero, it gets deleted from memory. ok so far ... > Garbage collection only gets used for objects that refer to other > objects, so it would only apply if string refcounts are being held by > GC-able objects. you lost me by here ... is there something different about string objects than other objects in Python? are you saying EVERY string in Python stays in memory for the lifetime of the app? > Also keep in mind, of course, that deleting objects has nothing to do > with whether the memory gets overwritten... no chance of being overwritten until deleted, no? and once deleted over time there is some probability of being overwritten, no? and i am curious how that works. it sounds like you are saying once a string, always the same string, in python. if thats true, i am glad i know that. Les Schaffer From tim.peters at gmail.com Thu Aug 31 02:03:45 2006 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 31 Aug 2006 02:03:45 -0400 Subject: GC and security In-Reply-To: <44F654F7.4060600@optonline.net> References: <44F61EEB.8040207@optonline.net> <44F654F7.4060600@optonline.net> Message-ID: <1f7befae0608302303x6d593980q4481aa9645581f01@mail.gmail.com> [Aahz] >> Assuming you're talking about CPython, strings don't really participate >> in garbage collection. Keep in mind that the primary mechanism for >> reaping memory is reference counting, and generally as soon as the >> refcount for an object goes to zero, it gets deleted from memory. [Les Schaffer] > ok so far ... Not really ;-) Refcounting is /a/ "garbage collection" technique, and drawing a distinction between refcount-based reclamation and other ways CPython reclaims memory has no bearing on your question. >> Garbage collection only gets used for objects that refer to other >> objects, so it would only apply if string refcounts are being held by >> GC-able objects. > you lost me by here ... That tends to happen when an irrelevant distinction gets made ;-) > is there something different about string objects than other objects in > Python? Not anything relevant wrt garbage collection. It may be relevant that strings are immutable, since that prevents you from overwriting a string's contents yourself. > are you saying EVERY string in Python stays in memory for the lifetime > of the app? He wasn't, and they don't. >> Also keep in mind, of course, that deleting objects has nothing to do >> with whether the memory gets overwritten... > no chance of being overwritten until deleted, no? True. > and once deleted over time there is some probability of being > overwritten, no? True. Also true if you add the intended "non-zero" qualifier to "probability" ;-) > and i am curious how that works. Purely accidental -- nothing guaranteed -- details can (& do) change across releases. Read obmalloc.c for a tour of the accidents du jour. > it sounds like you are saying once a string, always the same string, in python. > if thats true, i am glad i know that. Not true, so be glad to forget it. A curious possibility: if you do a debug build of Python, obmalloc.c arranges to overwrite all of an object's memory as soon as the object is reclaimed (by any means, refcounting or otherwise). That wasn't for "security" (faux or otherwise), it's to make it easier to detect buggy C code referencing freed memory. From onurb at xiludom.gro Thu Aug 10 09:00:40 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Thu, 10 Aug 2006 15:00:40 +0200 Subject: Make Object Oriented? In-Reply-To: References: Message-ID: <44db2df8$0$21144$7a628cd7@news.club-internet.fr> Michael Yanowitz wrote: > Hello: > > Are there any tools to convert non-object-oriented code > into object-oriented code? Yes, of course. That's what we call a "programmer". Why ? > If not, perhaps something that I can pass in two (or more) > classes and will create a base-class and simplify the passed > in classed to be derived from the base class? > Ideally this would be Python but if not, C-to-C++ would > be ok? Actually you need another language and processing device - AFAICT, a well-trained human being would do. A refactoring tool may help too (cf BicycleRepairMan ?) (NB : never tried using such a tool myself), but I'd still mostly rely on gray matter for this class (pun intented) of problems. From johnjsal at NOSPAMgmail.com Sat Aug 19 02:06:15 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 19 Aug 2006 02:06:15 -0400 Subject: text editor suggestion? In-Reply-To: References: <44e66724$0$2363$c3e8da3@news.astraweb.com> Message-ID: <44e6ab26$0$12557$c3e8da3@news.astraweb.com> Ben Finney wrote: > The two big names in text editing, Vim and Emacs, will both meet these > criteria easily. They also have the advantage that you'll find one or > the other, or both, on just about any Unix system intended for use by > a programmer. > > There is also an enormous amount of support for both these editors, > for all manner of text editing tasks, available online. It's a good > idea to learn at least one of them very well, rather than learn a > bunch of less-popular editors for specific tasks. > I'd really like to learn vim, but I spent days just trying to figure out how to get the syntax highlighting and indentation working, where these settings are and how to edit them, and it still doesn't work for me. It just feels so insurmountable that I can't even start working with it yet because I don't know how to tailor the settings. From superflit at gmail.com Wed Aug 2 15:01:17 2006 From: superflit at gmail.com (flit) Date: 2 Aug 2006 12:01:17 -0700 Subject: Simple HTML display of a select query Message-ID: <1154545277.612241.197490@i42g2000cwa.googlegroups.com> Hi all, How Can I do in the simplest way, display in html one table with the return of 3 collums? Like 1- consult mysql base 2- make the select query 3- show the values. I am a kind of lost in the frameworks, and modules. I think a lot of them with little documentation. Just a simple display in html for this, nothing more. No need this time for right coding, if I need to remake the program in the future its ok.. From rdiaz02 at gmail.com Sat Aug 26 11:16:16 2006 From: rdiaz02 at gmail.com (Ramon Diaz-Uriarte) Date: Sat, 26 Aug 2006 17:16:16 +0200 Subject: Python web service ... In-Reply-To: <1156590455.555359.247410@h48g2000cwc.googlegroups.com> References: <1156590455.555359.247410@h48g2000cwc.googlegroups.com> Message-ID: <624934630608260816q3662d21dx26caf892287e719d@mail.gmail.com> On 26 Aug 2006 04:07:35 -0700, nicolasg at gmail.com wrote: > Hi folks, I have accomplished to make a python program that make some > image manipulation to bmp files. > I now want to provide this program as a web service. A user can visit a > site and through a web interface he should upload the file to the web > server , the server then will do the image process with the python > program I have wrote and when it finish the user must get the image > file back . > > My question is how difficult is to set up a web server that can run > python easy ? should I try ZOPE or there is something better in mind ? > For a one-shot thing, plain old CGI might be enough. You can have a static HTML page with the form for the upload, have python do the image part, and generate the return HTML with the image with a python script. If you plan to do this a lot, or want fairly sophisticated stuff, or DB access underneath, authentication, etc, then you might want to look at any of the web framewoks. If you don't have the web server part already taken care of (e.g., you already have Apache up and running) then the web server framework can be more attractive. As for web frameworks there is a long list in the Python web site. Which framework fits you best might depend on what you want to accomplish now and in the future. You can try something simple and minimalist (and with docs that you can read in less than an afternoon) such as Karrigell, or try something more complex, such as Django, TurboGears, Pylons, CherryPy, etc. And then, you might try the CGI approach to begin with, and as your needs become more complex, move to a framework. (This has been our own path: we've used plain CGI for over a year for the web-based bioinformatics applications we've developed, that use R and Python for computations, and are now moving to framework). Good luck! R. -- Ramon Diaz-Uriarte Bioinformatics Unit Spanish National Cancer Centre (CNIO) http://ligarto.org/rdiaz From fdu.xiaojf at gmail.com Thu Aug 31 10:38:28 2006 From: fdu.xiaojf at gmail.com (Xiao Jianfeng) Date: Thu, 31 Aug 2006 22:38:28 +0800 Subject: genetic algorithms package for python ? Message-ID: <44F6F464.8080103@gmail.com> Hi all, I am looking for a genetic algorithms package for Python. I have googled the web before posting and found some links. The link of pygene(http://www.freenet.org.nz/python/pygene) cannot be opened. I also tried the recipe on ASPN, but it is too simple for my application, and the ga model in SciPy, which is in testing in the "sandbox". Are there any more genetic algorithms packages for Python ? Thanks a lot! xiaojf From Tim.Gallagher at gd-ais.com Mon Aug 21 14:16:32 2006 From: Tim.Gallagher at gd-ais.com (Gallagher, Tim (NE)) Date: Mon, 21 Aug 2006 14:16:32 -0400 Subject: Add users to directory/folder and set permissions in Windows Message-ID: <794CB73454A59D488ED061055AA282073CBA1F@miaa01-mail01.ad.gd-ais.com> I was wondering if there was a way to add a user in active directory to a folder and set the permissions. Thanks, Tim Timothy F. Gallagher CSC Systems Engineer From onurb at xiludom.gro Wed Aug 9 12:58:50 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 09 Aug 2006 18:58:50 +0200 Subject: __contains__ vs. __getitem__ In-Reply-To: References: Message-ID: <44da144b$0$21143$7a628cd7@news.club-internet.fr> David Isaac wrote: > I have a subclass of dict where __getitem__ returns None rather than > raising KeyError for missing keys. (The why of that is not important for > this question.) Well, actually it may be important... What's so wrong with d.get('key') that you need this behaviour ? From skip at pobox.com Wed Aug 9 12:03:52 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 9 Aug 2006 11:03:52 -0500 Subject: Eval (was Re: Question about using python as a scripting language) In-Reply-To: References: <73BFFFC6-760D-4794-9B5C-AA749287B78A@carnegielearning.com> <20060809150432.GA15121@kateandchris.net> Message-ID: <17626.1896.637896.271015@montanaro.dyndns.org> Brendon> I could do that, or I could do something like the re.* trick Brendon> mentioned by another poster. But, doesn't it offend anyone else Brendon> that the only clean way to access functionality that's already Brendon> in Python is to write long complicated Python code? Python Brendon> already knows how to extract a list object from a string; why Brendon> should I have to rewrite that? Doesn't bother me at all. One, it's not actually Python code, it's JavaScript. It's just serendipity that the table can be parsed as a Python list. Two, there's nothing to prevent the authors from changing the formatting in an incompatible way in the future. Three, it's completely untrusted input and shouldn't be fed to eval(). Four, it's not actually complicated code (using the csv module would probably be simpler). Had the NASD had a requirement that their HTML pages be easily assimilated into Python I might agree with you. I suspect that wasn't high up on their priority list though. Five, you have to stop thinking of it a "list object". It's just a string of bytes which happens at this point in time to intersect with the definition of a Python list. You're trying to wish it was something that it's not. Skip From paul at boddie.org.uk Fri Aug 11 08:53:52 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 11 Aug 2006 05:53:52 -0700 Subject: hide python code ! References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155253821.570487.165400@b28g2000cwb.googlegroups.com> <1155254631.617208.299550@m73g2000cwd.googlegroups.com> <654tq3-epj.ln1@lairds.us> Message-ID: <1155300831.873732.303770@p79g2000cwp.googlegroups.com> Cameron Laird wrote: > Steven D'Aprano wrote: > >Hiding source code is incompatible with Open Source software. You can hide > >code, or be Open Source, but not both. [...] > I also disagree with your characterization of Open Source. I don't know which part of the open source movement would tolerate the hiding of source code whilst simultaneously calling the resulting software "open source", but I'd imagine they'd have a hard time justifying their "open source" label. Of course, it is possible to be the "First Iranian Open Source Community" in terms of consuming open source software rather than producing it, so perhaps that's what the questioner intended to communicate in their signature. [...] > Myself, I just marvel at the different worlds in which we live. *My* > experience has to do with how tough it is to deploy and maintain > correct, working stuff, even with teams of seasoned pros. The thought > that users will routinely reverse-engineer our applications, and ... > well, I marvel. I've previously mentioned a very interesting paper which not only described the reverse engineering of the Skype protocol and software but also described how to make interoperating Skype clients. Given that the well-financed developers spent a lot of time introducing various protection measures (encryption, verification, etc.) and yet someone can write the aforementioned stuff up in a paper, I'd recommend an upgrade to any business plan which relies on obfuscation to prevent "unauthorised" use or modification. Indeed, I'd recommend that any such entrepreneur think twice about starting a traditional proprietary software business in this day and age. Paul From thomas at nomail.dk Fri Aug 18 03:31:54 2006 From: thomas at nomail.dk (thomas) Date: Fri, 18 Aug 2006 09:31:54 +0200 Subject: sorted Message-ID: <44e56ce6$0$196$edfadb0f@dread11.news.tele.dk> Hi NG I what to used the sorted function, and im getting this error Traceback (most recent call last): File "F:\home\thomas\src\guisample\test1.py", line 59, in ? main() File "F:\home\thomas\src\guisample\test1.py", line 31, in main sorted(cords, key=operator.itemgetter(1)) NameError: global name 'sorted' is not defined what do I needs to import, to use this function ? regards thomas From snail at objmedia.demon.co.uk Thu Aug 10 05:38:38 2006 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Thu, 10 Aug 2006 10:38:38 +0100 Subject: do people really complain about significant whitespace? References: <1154991523.887791.9640@i42g2000cwa.googlegroups.com> <1154994477.450666.226550@b28g2000cwb.googlegroups.com> <1155124820.123151.140580@p79g2000cwp.googlegroups.com> <9$lHo7FEZe2EFwf$@objmedia.demon.co.uk> Message-ID: In message , skip at pobox.com writes >No. In that case Python makes it more readily apparent that your code is >too complex. If only life and software engineering was that simple. Not every problem can be reduced to one screenful of code, not in the real world anyway. Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk/software.html Computer Consultancy, Software Development Windows C++, Java, Assembler, Performance Analysis, Troubleshooting From bobrien18 at yahoo.com Sat Aug 12 12:46:54 2006 From: bobrien18 at yahoo.com (KraftDiner) Date: 12 Aug 2006 09:46:54 -0700 Subject: Recurse Directories and process files in directory Message-ID: <1155401214.163465.235830@m79g2000cwm.googlegroups.com> Hi I need help writing a python script that traverses (recursivly) a directory and its sub directories and processes all files in the directory. So at each directory if there are files in it I must build a list of those files and process them by exectuing a system command (exec?) Can some one tell me what methods to use to: a) Walk the directory tree b) execute a system command with parameters. TIA. From jason at adapt.com Mon Aug 14 13:58:04 2006 From: jason at adapt.com (Jason Nordwick) Date: Mon, 14 Aug 2006 10:58:04 -0700 Subject: yet another noob question In-Reply-To: References: <1155492110.659011.196280@75g2000cwc.googlegroups.com> Message-ID: <44E0B9AC.6080508@adapt.com> Stargaming wrote: > > Also note that reduce will be removed in Python 3000. What will replace it? -j From rosedb0 at gmail.com Wed Aug 2 21:36:49 2006 From: rosedb0 at gmail.com (hiaips) Date: 2 Aug 2006 18:36:49 -0700 Subject: exception handling; python program that interacts with postgresql db In-Reply-To: <1154568651.386892.198840@s13g2000cwa.googlegroups.com> References: <1154567757.143305.19910@75g2000cwc.googlegroups.com> <1154568651.386892.198840@s13g2000cwa.googlegroups.com> Message-ID: <1154569009.315335.275350@i42g2000cwa.googlegroups.com> Another option would be to use the psycopg module to connect to postgres from within your Python code. See http://www.initd.org/projects/psycopg1 for more information. --hiaips From bearophileHUGS at lycos.com Sat Aug 5 16:49:47 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 5 Aug 2006 13:49:47 -0700 Subject: More int and float attributes In-Reply-To: <1154807223.104418.230270@i3g2000cwc.googlegroups.com> References: <1154780600.348169.158150@i42g2000cwa.googlegroups.com> <1154807223.104418.230270@i3g2000cwc.googlegroups.com> Message-ID: <1154810987.818618.110350@h48g2000cwc.googlegroups.com> Paddy: > Or do you mean the ability to choose between hardware supported float > s? e.g. float and double precision? No, I mean just having the ability to ask the float (his attribute) what are the max and min values it can represent, etc. stop = float.max ... I don't know any simple way to know that values now. And importing sys to know the max int looks stupid. maxi = int.max mini = int.min ... Such attributes can be given to the Decimal values too, if you want. Bye, bearophile From a at tempinbox.com Mon Aug 14 08:12:10 2006 From: a at tempinbox.com (a) Date: 14 Aug 2006 05:12:10 -0700 Subject: help parsing this Message-ID: <1155557530.383959.241150@75g2000cwc.googlegroups.com> mx.DateTime.RangeError at /podcasts Failed to parse "31 Apr 2006 20:19:00 -0400": day out of range: 31 Python /usr/lib/python2.4/site-packages/mx/DateTime/Parser.py in DateTimeFromString, line 608 how to parse this date thanks From wcampagner at hotmail.com Mon Aug 21 10:56:15 2006 From: wcampagner at hotmail.com (Wagner Garcia Campagner) Date: Mon, 21 Aug 2006 11:56:15 -0300 Subject: Dynamic RadioButton creation with Python + Qt In-Reply-To: Message-ID: Thanks Fredrik, Your suggestion solved my problems!!!!!!!!! Thanks, Wagner. >From: Fredrik Lundh >To: python-list at python.org >Subject: Re: Dynamic RadioButton creation with Python + Qt >Date: Mon, 21 Aug 2006 16:20:09 +0200 > >Wagner Garcia Campagner wrote: > > > I'm trying to create dynamic RadioButton as follows: > > > > for i in out.keys(): > > msg = "radioButton_" + str(i) > > msg2 = 20 * x > > msg = QRadioButton(self.buttonGroup_interfaces, msg) > > msg.setGeometry(QRect(30,msg2,121,23)) > > msg.setTect(i) > > x += 1 > > > > The problem is that Python is creating all RadioButton as "msg" and not >the > > value of "msg" so i can't access the RadioButton after the creation. > > > > Is there a way i can create the RadioButton with diferent names?? > >if you want to keep track of a list of things, store them in a list. > > > >-- >http://mail.python.org/mailman/listinfo/python-list From sjmachin at lexicon.net Tue Aug 29 19:58:39 2006 From: sjmachin at lexicon.net (John Machin) Date: 29 Aug 2006 16:58:39 -0700 Subject: Split with python In-Reply-To: <44f4c138$0$8860$88260bb3@free.teranews.com> References: <44F47F9E.9050404@khine.net> <44f4c138$0$8860$88260bb3@free.teranews.com> Message-ID: <1156895919.080126.310460@i42g2000cwa.googlegroups.com> tobiah wrote: > Of course, fixing the csv file takes a little more work. It sounds like the > test lines given were just one of the fields, and there are > the quotes to worry about. > [snip] > > But then this fails if there are commas in the > data. I could split and join on '","' but then > that fails when 'x' is either the first or last field. > > Are there tools in the csv module that make this > easier? There are no "tools". The main (whole?) purpose of the csv module is to intelligently handle the embedded comma and embedded quote problems on both input and output. May I suggest that you read the documentation? From g.brandl-nospam at gmx.net Thu Aug 10 11:59:53 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Thu, 10 Aug 2006 17:59:53 +0200 Subject: do people really complain about significant whitespace? In-Reply-To: References: <1154991523.887791.9640@i42g2000cwa.googlegroups.com> <1154994477.450666.226550@b28g2000cwb.googlegroups.com> <1155124820.123151.140580@p79g2000cwp.googlegroups.com> <9$lHo7FEZe2EFwf$@objmedia.demon.co.uk> <1155133454.975325.237770@b28g2000cwb.googlegroups.com> Message-ID: Gerhard Fiedler wrote: > function() > loop1() > blah > blah > > loop2() > blah > > loop3() > blah > #end loop3() > > blah3 > #end loop2() > #end loop1() > > otherloop() > blah > #end otherloop() > #end function() > > Of course, few people will write like this, but it probably is easier to > write a Python code formatter that adds them than it is to write a C code > formatter that adds proper indentation and provides your preferred > placement of braces. It's already there: Tools/scripts/pindent.py. Georg From dppdoran at gmail.com Thu Aug 31 03:22:20 2006 From: dppdoran at gmail.com (Dermot Doran) Date: Thu, 31 Aug 2006 09:22:20 +0200 Subject: How to avoid a warning message box when sending email via Outlook Message-ID: Hello All, I'm very new to using win32com! I just want to send an email message via Outlook. However, I keep getting an annoying message box (generated by Outlook) indicating that my program could be a virus. Does anybody know how to get around this? Here is the sample code I'm using: from win32com.client import Dispatch s=Dispatch("Outlook.Application") ns=s.GetNamespace("MAPI") ns.Logon() # Note: I've taken the login credentials out of the example :-) mi = ns.Application.CreateItem(0) mi.Recipients.Add("an,other") mi.Subject="Hello from Python!" mi.Body="I just need to figure out how to avoid the message box now!" mi.Send() ns.Logoff() I'm probably missing something silly or have hit a brick wall with what I want to do with CDO. Cheers!! Dermot. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVEME.cybersource.com.au Wed Aug 23 05:20:27 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 23 Aug 2006 19:20:27 +1000 Subject: how do you get the name of a dictionary? References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> <1156264475.968894.221710@p79g2000cwp.googlegroups.com> <1156266720.205126.284050@i3g2000cwc.googlegroups.com> Message-ID: On Wed, 23 Aug 2006 02:44:28 -0500, Robert Kern wrote: >> But consider that when you get an >> exception that says "a is too short", you often have to mentally change >> gears and think about where a came from and what it is called in the >> enclosing scope. After all, if the value of a is invalid, and the value of >> a is set in the enclosing scope, it makes sense to refer to "the object >> known locally as a" by the name it was known as when it was set. > > That's what tracebacks are for. You don't have to mentally change gears; you > just look. Here's a traceback. One of the arguments to spam() is too small. Can you tell which one just by looking at the traceback? >>> a, b, c, d = range(4) >>> spam(a, b, c, d) Traceback (most recent call last): File "", line 1, in ? File "", line 6, in spam File "", line 5, in eggs File "", line 4, in beans ValueError: x is too small Of course you can't. x could be any one of a, b, c or d, and the traceback doesn't give you enough information to tell which. >>> def spam(foo, bar, baz, qux): ... def eggs(alpha, beta, gamma, delta): ... def beans(w, x, y, z): ... raise ValueError("x is too small") ... beans(alpha, beta, gamma, delta) ... eggs(foo, bar, baz, qux) ... Nesting the functions was an arbitrary choice -- the same issue occurs regardless of whether they are nested or not. That's a relatively simple example, with only three layers of nested scopes (four if you count the global scope). I've seen tracebacks with twenty or thirty levels. Ouch. I could have come up with a devilishly convoluted example if I wished, reusing the same names for different purposes in different scopes, or re-binding the names multiple times, or even simply moving the order of arguments around from one function to another. But that would be overkill. This is NOT a complaint against Python's object module, merely a call to recognise that, in some instances, if objects knew their own name, it would be useful. As I've already said, the benefit gained is probably less than the cost required, so I'm not suggesting that Python work this way. But the idea isn't totally pointless. -- Steven D'Aprano From sjmachin at lexicon.net Wed Aug 16 18:25:39 2006 From: sjmachin at lexicon.net (John Machin) Date: 16 Aug 2006 15:25:39 -0700 Subject: PySequence_SetItem In-Reply-To: References: <1155754847.392950.266180@h48g2000cwc.googlegroups.com> <1155755905.233229.93440@74g2000cwt.googlegroups.com> <1155761144.583994.260150@m73g2000cwd.googlegroups.com> <1155764364.775366.76070@i3g2000cwc.googlegroups.com> Message-ID: <1155767139.084992.133200@i42g2000cwa.googlegroups.com> Jack Diederich wrote: > On Wed, Aug 16, 2006 at 02:39:24PM -0700, John Machin wrote: > > > > Jack Diederich wrote: > > > > > Changing the PySequence_SetItem to PyList_SetItem and dropping the > > > DECREF works for me too (PyList functions steal a reference). I also > > > tried setting the list to length 1, still no dice. The PySequence > > > version segs under 2.4 and 2.5. It segs even when the Int is changed > > > to a String. > > > > > > Yikes, I'll poke around some more. > > > > Yikes indeed. > > > > Not the OP's problem, but a bug in the manual: example in the chapter > > that the OP was reading acts as though the 2nd arg to PyObject_SetItem > > is a C int (as it is for the List and Sequence varieties) -- it is in > > fact a (PyObject *), which explains the SystemError that I got. > > The good news is that this is a documentation problem. Cop-out alert! I disagree. Elsewhere Python goes to great lengths to check for nasties instead of just segfaulting. > When working at the C level you use the concrete API when you can > (PyList_*) and at the abstract level (PySequence_*) only when someone > passes you something and you don't know what it is, you only know it > supports the Sequence API. > > The exmample should use the PyList API to construct the list. The > Sequence API requires valid objects to work. Here the object is only half > constructed and list_ass_item tries to DECREF the zeroth member which > is NULL because the list isn't constructed yet. PyList_SetItem does > an XDECREF (decrement only if the pointer isn't null) because it expects > to be used that way. PyList_SetItem is not sentient. It expects nothing. Now tell us what the developer was thinking -- certainly not consistency with the documantation. If the Sequence API requires valid objects to work, then in this case it should raise an error. In fact that manual section calls using the PySequence_SetItem the recommended approach!!! Are you suggesting a rework of the manual instead of inserting a X in the offending py_DECREF? Sheesh all round ... From bdesth.quelquechose at free.quelquepart.fr Sun Aug 27 15:53:14 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 27 Aug 2006 21:53:14 +0200 Subject: trouble understanding inheritance... In-Reply-To: References: <1155753183.207393.116940@m79g2000cwm.googlegroups.com> <1155754767.694480.256200@h48g2000cwc.googlegroups.com> <1155756282.851876.46470@b28g2000cwb.googlegroups.com> <1155757992.706040.288890@74g2000cwt.googlegroups.com> Message-ID: <44f1f578$0$27583$626a54ce@news.free.fr> Steven D'Aprano a ?crit : (snip) > class BaseClass(): > def foo(self): > return "foo" > > class Foo(BaseClass): > def foo(self): > return self.__class__.foo() # call the parent class method Err... May I suggest that you re-read the Fine Manual ? From DirkHagemann at gmail.com Wed Aug 23 11:48:47 2006 From: DirkHagemann at gmail.com (Dirk Hagemann) Date: 23 Aug 2006 08:48:47 -0700 Subject: MS SQL Server: NT Authentication. Possible? In-Reply-To: References: <1156164544.513073.242290@i3g2000cwc.googlegroups.com> <1156169675.734453.286700@74g2000cwt.googlegroups.com> <1156230890.526230.203290@p79g2000cwp.googlegroups.com> Message-ID: <1156348127.342667.232600@i42g2000cwa.googlegroups.com> I already mentioned, that it the following works when it's NOT executed by the webserver: > > import adodbapi > db = adodbapi.connect ("Provider=sqloledb;Data Source=VODEV1;Initial > Catalog=EVOBACK;Integrated Security=SSPI;") > q = db.cursor () > q.execute ("SELECT SYSTEM_USER") > print q.fetchone () > q.close () > Now I found this work-around: I have on a fileserver some directories with restricted rights. In every directory is a file which has always the same name. Now I let the script (executed by the IIS-Webserver) try to open this file (directory is chosen by the user): data = open("\\\\server\\directory\\"+variable+"\\index.py","r").readlines() If the NT-Account of the user has the right to open this file, the script will proceed with the addicted Database-View. If the user has not the right he gets an error-message. And this works! In this case the webserver is working on the fileserver with the NT-account of the user who has used the webinterface. So on the one hand the IIS works fine with the fileserver, but the IIS does not work with the SQL-Server. And it seems not to be the fault of the code, because it works when it's executed directly. It's so confusing... Dirk From vatamane at gmail.com Tue Aug 1 23:26:19 2006 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 1 Aug 2006 20:26:19 -0700 Subject: Programming newbie coming from Ruby: a few Python questions In-Reply-To: <1154458926.738922.156910@h48g2000cwc.googlegroups.com> References: <1154458926.738922.156910@h48g2000cwc.googlegroups.com> Message-ID: <1154489179.338943.288430@m73g2000cwd.googlegroups.com> For a tutorial try the Python Tutorial @ http://docs.python.org/tut/ For a book try "Learning Python" from O'Reilly Press For reference try the Python library reference @ http://docs.python.org/lib/lib.html For another good book try "Dive Into Python" @ http://diveintopython.org/ It is a book you can view online or download for free. It is written by Mark Pilgrim. If you like it, please support the author and buy a printed copy: http://www.amazon.com/gp/product/1590593561/ref=nosim/102-5606503-6853720?n=283155 Also take a look at common recipes on how to do things when you get more used to Python @ http://aspn.activestate.com/ASPN/Cookbook/Python/ Hope this helps, Nick V. simonharrison at fastmail.co.uk wrote: > Hi all. I've been try to learn ruby for a few months but I'm about > ready to give up. The available books either assume a programming > background, or are out of date. Anyway, I think python may suit me more > due to its 'theres one way to do it' philosophy (hope the quote is > right)! Another quote that I liked was: > > 'Clever is not considered a compliment in Python.' (don't know where I > read that...) > > In Ruby, there are many ways to do the same thing and cleverness seems > to be held in high regard. These attitudes are not too helpful for > beginners in my experience. Anyway, enough waffle. > > What books and tutorials are recommended to learn Python? The tutorial > that comes with Python is great and has given me a good overview but I > think I'd benefit from some programming projects, now I have a little > understanding of how Python works. > > Ideally, I'd like a whole series of projects where I'm walked through > how to go about writing real Python. The way I look at it, nobody > learnt to build a house just from reading about building materials! > > Any other tips for getting up to speed with Python fairly quickly will > be greatly appreciated. > > If anyone can help, thanks very much From jojoba12 at hotmail.com Mon Aug 21 21:20:26 2006 From: jojoba12 at hotmail.com (jojoba) Date: 21 Aug 2006 18:20:26 -0700 Subject: how do you get the name of a dictionary? In-Reply-To: <1156204770.339106.151110@m73g2000cwd.googlegroups.com> References: <1155926079.935209.21120@p79g2000cwp.googlegroups.com> <1155926705.233273.231650@75g2000cwc.googlegroups.com> <1156204770.339106.151110@m73g2000cwd.googlegroups.com> Message-ID: <1156209626.109983.118880@75g2000cwc.googlegroups.com> addendum: when asking python for the name of a dictionary, it shold return ONE, MANY, or NO strings thanks, jojoba From carsten at uniqsys.com Thu Aug 3 14:09:10 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 03 Aug 2006 14:09:10 -0400 Subject: Negative division bug? In-Reply-To: <00fb01c6b725$68c43580$0d7d12ac@kearfott.com> References: <00fb01c6b725$68c43580$0d7d12ac@kearfott.com> Message-ID: <1154628550.6267.31.camel@dot.uniqsys.com> On Thu, 2006-08-03 at 13:51, Michael Yanowitz wrote: > Hello: > > Just wondering if this is a bug, is this as designed, > or do I have to import math or something to make it correct: > > I was just screwing around. > and found: > >>> -1/100 > -1 > Shouldn't it be zero? > 1/100 returns 0 > but -1/ANY_POSITIVE_INTEGER_NUMBER > returns -1 > > >>> -10/3 > -4 > > It behaves correct for positive numbers, but for negative > integers it seems to subtract one from the expected result. It behaves correctly in both cases. Your expectation is incorrect. http://docs.python.org/ref/binary.html says: """ Plain or long integer division yields an integer of the same type; the result is that of mathematical division with the `floor' function applied to the result. """ The floor of x is the largest integer number that's less than or equal to x. The floor of -0.01 is -1. HTH, Carsten. From sjmachin at lexicon.net Sun Aug 13 22:48:55 2006 From: sjmachin at lexicon.net (John Machin) Date: 13 Aug 2006 19:48:55 -0700 Subject: recommended general-purpose string template packages? Message-ID: <1155523735.614470.199840@h48g2000cwc.googlegroups.com> Hi, In general, I'm mainly interested in a template engine for dynamic web pages but would like a general purpose one to avoid learning yet another package for generating e-mail messages, form letters, source code, whatever. In particular, does anyone have much experience with the Python interface to Terence Parr's StringTemplate (http://www.stringtemplate.org/)? Reading the website, I'm attracted by the approach, but a Google search (both generally and in this newsgroup) gives me the impression that it's little used in the Python world. TIA, John From thisdave75 at googlemail.com Sun Aug 20 16:20:06 2006 From: thisdave75 at googlemail.com (Dave Richards) Date: Sun, 20 Aug 2006 22:20:06 +0200 Subject: What do you want in a new web framework? In-Reply-To: <1156100330.768482.326760@h48g2000cwc.googlegroups.com> References: <1156100330.768482.326760@h48g2000cwc.googlegroups.com> Message-ID: Really, really good documentation. Dave On 20 Aug 2006 11:58:50 -0700, emrahayanoglu at gmail.com < emrahayanoglu at gmail.com> wrote: > > Hello Everyone, > > Now, I'm working on a new web framework. I tried many test on the other > programming languages. Then i decided to use python on my web framework > project. > > Now i want to listen all of you. What do you want in that web > framework(Easy use of Database, Easy use of XML, GUI Designer, etc...)? > > I'm wating your answers. Thank you for all answers...! > > King Regards, > > Emrah Ayanoglu > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From timr at probo.com Thu Aug 3 23:43:10 2006 From: timr at probo.com (Tim Roberts) Date: Fri, 04 Aug 2006 03:43:10 GMT Subject: looking for a regular expression References: <4POChV$9OC@bbs.wretch.cc> Message-ID: <5fg5d2t5c5j4s665bgut58s0diea3794u5@4ax.com> shadowcaster.bbs at bbs.wretch.cc (?????b?????????H) wrote: > >?? ???z?m__peter__ at web.de (Peter Otten)?n???????G >> ?????b?????????H wrote: >> > Thanks a lot! I have never thought of that. >> > But what if there's not only commas, but also periods and semicolons? I >> > want to find words between 2 near by punctuations. I think it would make >> > it difficult to use split instead of regular expression. >> Reenter re. Use >> re.split(r"[.;\-,]", my_string) >> instead of my_string.split(","). >> Peter > >Thank you for your help. >-- >???L???????????????c???G???D?????B?g?l?~?h?Q?????L?h?Q?k?L???????????D?g?l >???????o?w?????????H???W?????????????????O?????H???????H???h???i?o???????U >?o?N???|???????|?k???N?x?~???W?N?x?~?k???H?????B?????H?????H?s?d?_???????H >?????B???D?`?L?W?????p???U???????J???Y???u???U???N???????a???X?H?????S???? >???O???????l?????W?W???J???????N??210-64-83-167.adsl.dynamic.seed.net.tw?? What is your signature supposed to be? It looks like you are trying to inject ANSI terminal escape sequences. The vast majority of Usenet participants are now reading these articles through GUI newsreaders or web-based readers which show this as 5 lines of unrecognizable line noise. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From bborcic at gmail.com Thu Aug 10 16:05:13 2006 From: bborcic at gmail.com (Boris Borcic) Date: Thu, 10 Aug 2006 22:05:13 +0200 Subject: converting a nested try/except statement into try/except/else In-Reply-To: References: Message-ID: <44db91a8$1_6@news.bluewin.ch> Slawomir Nowaczyk wrote: > > try: > if int(text) > 0: > return True > except ValueError: > pass > self.error_message() > return False > Nicely DRY. To make it even more compact, it may be noticed that the default return value None is false in a boolean context - so that the last line is superfluous if the return value is only wanted to test it in such a context. From johnjsal at NOSPAMgmail.com Tue Aug 8 11:58:42 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 08 Aug 2006 15:58:42 GMT Subject: Tkinter module not found In-Reply-To: References: <1155049496.292471.37020@h48g2000cwc.googlegroups.com> Message-ID: Tim Chase wrote: >> The cause of this is usually that you are using a different >> version of Python than the one you installed Tkinter into, but >> being a Linux newbie I have yet to discover how to redirect >> the 'python' command to invoke the newer version of Python. > > > The OS looks for the first 'python' it finds in its path. > > In Linux (or other *nix OSes), you can use > > bash> which python A very helpful command to know! I'll have to wait til I get home to play on Linux though. Then I can try these things you suggested. I'm suddenly very bored here at work using Windows. :) From pupeno at pupeno.com Tue Aug 1 11:34:29 2006 From: pupeno at pupeno.com (Pupeno) Date: Tue, 01 Aug 2006 15:34:29 +0000 Subject: Jumping over in the class hierarchy Message-ID: <44cf7481$0$24888$9b4e6d93@newsread4.arcor-online.net> Hello, I want to jump over a method in the class hierarchy, that is: If I have class A(object), clas B(A), class C(B) and in C, I want a method to do exactly what A does but not what B does in its reimplementation, would it be correct to do: super(A, super(B, self)).method() in C ? Thank you. -- Pupeno (http://pupeno.com) From apardon at forel.vub.ac.be Tue Aug 29 05:46:37 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 29 Aug 2006 09:46:37 GMT Subject: Is this a good idea or a waste of time? References: <1156449402.022781.292840@p79g2000cwp.googlegroups.com> <1156485945.967160.238790@m73g2000cwd.googlegroups.com> <44f322cd$1@nntp0.pdx.net> <1156802762.331853.80000@75g2000cwc.googlegroups.com> Message-ID: On 2006-08-29, Steve Holden wrote: > Antoon Pardon wrote: >> On 2006-08-29, Gabriel Genellina wrote: >> >>>At Tuesday 29/8/2006 02:45, Antoon Pardon wrote: >>> >>> >>>>>>That may be true. But one may wonder if this is a failing of the >>>>>>programmer or a failing of the language that doesn't support >>>>>>such things. >>>>> >>>>>In any case, I don't see how this supports the original claim that >>>>>strict type checking input params is good practice. >>>> >>>>I'm not defending that claim. I'm just putting question marks >>>>with the claim that strict type checking input parameters is >>>>bad practice. >>> >>>I think others have shown enough examples of good things that can be >>>done by *not* enforcing a specific type... >> >> That doesn't contradict that in other situations good things can be >> done by enforcing specific type or at least limiting to a subset >> of specific types. >> > Indeed it doesn't, but perhaps in future we could leave others to work > out the glaringly obvious for themselves rather than having to > explicitly provide the counterargument to each single response to a posting? That Gabriel found it necessary to respond with that particular remark suggest to me it wasn't glaringly obvious to him. If we leave others to work out for themselves what is glaringly obvious to us, I think a lot of newbee questions won't get answered. > crabbi-ly y'rs - steve Sorry if I got on your nerves. But why don't you just skip my articles if they irritate you or put me in a kill file if you think of me as irratable in general? -- Antoon Pardon From chosechu at gmail.com Tue Aug 29 10:08:53 2006 From: chosechu at gmail.com (chosechu) Date: 29 Aug 2006 07:08:53 -0700 Subject: Extending the dict class In-Reply-To: <1156858575.269538.197480@m73g2000cwd.googlegroups.com> References: <1156852916.254032.172390@b28g2000cwb.googlegroups.com> <44f4313e$0$26985$626a54ce@news.free.fr> <1156854958.228815.107090@m73g2000cwd.googlegroups.com> <1156856325.095181.303140@p79g2000cwp.googlegroups.com> <1156858575.269538.197480@m73g2000cwd.googlegroups.com> Message-ID: <1156860533.910906.4020@b28g2000cwb.googlegroups.com> Tim N. van der Leeuw wrote: > Anyways, modifiying SOAPpy might not be a bad idea: submit your changes > to the project, and you can write on your CV that you have contributed > to open-source projects! ;-) Been there, done that. Don't worry, my contributions to open-source projects is largely positive (though under different aliases). About SOAPpy: the author mentions something about ordering (or not) parameters in the XML request. Quoting: "There is an incompatibility with the way that Python and SOAP handle method arguments: SOAP requires that all arguments have names and that they are presented in the same order as the method signature. [...]" See SOAPpy/docs/MethodParameterNaming.txt for more details. > I do hope for you that you will find something better to do than > pushing template-instances down a socket-hole. It is not the first time I end up implementing some kind of support for ASCII-based protocols with templatized strings You would be surprised how easy it is to maintain when the emitter is required to be as stable as possible. Just have to be aware that you have a potential maintenance nightmare somewhere out there. From wqhflp at gmail.com Sun Aug 6 22:47:19 2006 From: wqhflp at gmail.com (wqhflp at gmail.com) Date: 6 Aug 2006 19:47:19 -0700 Subject: bind invalid when execute oracle sql statement. Message-ID: <1154918839.071284.5390@i3g2000cwc.googlegroups.com> Hi, I want to insert data into a table SQL> desc jijin Name Null? Type ----------------------------------------- -------- ------------- ID NOT NULL NUMBER(6) T_TIME NOT NULL DATE NET_VALUE NUMBER(5,4) TOTAL_VALUE NUMBER(5,4) INCREASE NUMBER(5,4) The code I used is sql="insert into jijin values (:id,to_date(:date,'yyyymmdd'),:net_value,:total_value)" day=int(date) bindVars={'id':int(id),'date':int(day),'net_value':float(net),'total_value':float(total)} cur.execute(sql,bindVars) conn.commit() the net ,total are in format of a string, a type of string, so we must convert it into a number. But the problem is if we use float to convert a string like '0.1' will be translated into 0.10000000000000001, which is invalid for oracle type NUMBER(5,4). How to resolve the problem? From gherzig at fmed.uba.ar Thu Aug 17 18:22:25 2006 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Thu, 17 Aug 2006 19:22:25 -0300 Subject: plpython and pickle Message-ID: <1155853345.31794.27.camel@linux.site> Hi all, sory if this is kind of [OT], but cannot find the answer for this behaviour Im programming a db function using plpython...i have a db called 'sessions', and a postgres 8.1.2 database called 'test'. In 'sessions', i store several values in a `pickled' way so If a do """ You are now connected to database "sessions". sessions=# select * from getsessiondata('QQtEpLoKHnvbKGSpgJgYMPyCdHgXSi'); getsessiondata ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ (dp0--ENTER--S---alucod-----ENTER--p1--ENTER--S---32009436-----ENTER--p2--ENTER--sS---respuestas_1-----ENTER--p3--ENTER--S---3-----ENTER--p4--ENTER--sS---respuestas_2-----ENTER--p5--ENTER--S---2-----ENTER--p6--ENTER--sS---respuestas_3-----ENTER--p7--ENTER--S---4-----ENTER--p8--ENTER--sS---submit-----ENTER--p9--ENTER--S---Responder-----ENTER--p10--ENTER--s. (1 row) """ Perfect. Thats what i spect to see. Now, if i do (in 'test' database) """ data = plpy.execute("SELECT * from dblink('dbname=sessions', 'select * from getsessiondata(\'\'%s\'\')') as t1(session_data name); " % session_id)[0]["session_data"]; plpy.notice(data) """ i got this NOTICE: ("'(dp0--ENTER--S---alucod-----ENTER--p1--ENTER--S---32009436-----'",) The pickled string as been truncated at some point, and when i try to unpickle it, i got error. Now, the question: What da hell can i do? -Postgresql 8.1.2 -Python 2.4.2 Im not even sure if this is a pickle, plpython nor postgresql issue, so im sory if this is [OT] here. Thanks!! Gerardo From deets at nospam.web.de Wed Aug 2 08:54:10 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 02 Aug 2006 14:54:10 +0200 Subject: Class definition within function References: <1154520636.055317.292700@b28g2000cwb.googlegroups.com> Message-ID: <4jbldtF74huaU1@uni-berlin.de> Kay Schluehr wrote: > > Tomi Lindberg wrote: >> Hi, >> >> With the following function definition, is it possible to >> create an instance of class C outside the function f (and if >> it is, how)? > > def f(): > class C(object): > def __init__(self): > self.a = 'a' > f.C = C > return C() > >>>> f.C > Not working, unless f has been called at least once. But what I didn't know (and always wondered) if the classdefinition inside a function can use the outer scope - and apparently, it can! Cool. def f(baseclass): class C(baseclass): def __init__(self): self.a = 'a' f.C = C def foo(self): print baseclass return C() c = f(object) print f.C c.foo() Diez From python.list at tim.thechases.com Thu Aug 17 17:04:36 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 17 Aug 2006 16:04:36 -0500 Subject: CGI script running not completely in HTML In-Reply-To: <44E4D7D0.9000904@holdenweb.com> References: <20060817204720.A721E158A0@net.tamu.edu> <44E4D7D0.9000904@holdenweb.com> Message-ID: <44E4D9E4.2030307@tim.thechases.com> > In which case you probably need to tweak the server timeout > setting. Nothing you can do from Python (except possibly make > your CGI run faster). Or have Python send a better SQL statement that would run faster...a little SQL mojo goes a long way. The OP failed (as far as my thread-dabbling has noticed) to specify what sort of SQL is being run. If full table results are being returned just to be discarded, or there are more efficient ways of doing things in the SQL, one would be better off doing it on the server and letting it return a single finely-honed result-set. With some insight into the SQL statement(s), one might be able to find glaring bottlenecks. -tkc From paddy3118 at netscape.net Wed Aug 9 14:47:53 2006 From: paddy3118 at netscape.net (Paddy) Date: 9 Aug 2006 11:47:53 -0700 Subject: What's the cleanest way to compare 2 dictionary? In-Reply-To: <1155147450.628625.20270@m79g2000cwm.googlegroups.com> References: <1155147450.628625.20270@m79g2000cwm.googlegroups.com> Message-ID: <1155149273.270320.176030@75g2000cwc.googlegroups.com> John Henry wrote: > Hi list, > > I am sure there are many ways of doing comparision but I like to see > what you would do if you have 2 dictionary sets (containing lots of > data - like 20000 keys and each key contains a dozen or so of records) > and you want to build a list of differences about these two sets. > > I like to end up with 3 lists: what's in A and not in B, what's in B > and not in A, and of course, what's in both A and B. > > What do you think is the cleanest way to do it? (I am sure you will > come up with ways that astonishes me :=) ) > > Thanks, I make it 4 bins: a_exclusive_keys b_exclusive_keys common_keys_equal_values common_keys_diff_values Something like: a={1:1, 2:2,3:3,4:4} b = {2:2, 3:-3, 5:5} keya=set(a.keys()) keyb=set(b.keys()) a_xclusive = keya - keyb b_xclusive = keyb - keya _common = keya & keyb common_eq = set(k for k in _common if a[k] == b[k]) common_neq = _common - common_eq If you now simple set arithmatic, it should read OK. - Paddy. From SPAMworFREEwor at bellsouth.net Mon Aug 14 17:51:43 2006 From: SPAMworFREEwor at bellsouth.net (Charles Russell) Date: Mon, 14 Aug 2006 21:51:43 GMT Subject: TypeError: 'module' object is not callable (newby question) In-Reply-To: References: Message-ID: Charles Russell wrote: But why does the > conflict not occur when the code is run interactively from the python > prompt? Because, I now realize, I had not yet created glob.py when I tried that. From Bulkan at gmail.com Fri Aug 18 02:32:43 2006 From: Bulkan at gmail.com (placid) Date: 17 Aug 2006 23:32:43 -0700 Subject: os.path.normpath In-Reply-To: <1155882571.136619.154510@75g2000cwc.googlegroups.com> References: <1155882571.136619.154510@75g2000cwc.googlegroups.com> Message-ID: <1155882763.891924.207870@i3g2000cwc.googlegroups.com> placid wrote: > Hi all, > > I was just wondering if there is a anti-os.path.normpath function? For > example if i have the path "C:\Program Files\Games" i want to > anti-os.path.normpath is so that it becomes "C:\\Program Files\\Games" > ? > > Cheers Ahh ignore my post. I was using abspath, and normpath is what i what. Doh, stupid me! Cheers From jsceballos at gmail.com Sun Aug 20 12:20:45 2006 From: jsceballos at gmail.com (jsceballos at gmail.com) Date: 20 Aug 2006 09:20:45 -0700 Subject: Help in using introspection to simplify repetitive code Message-ID: <1156090845.875872.41220@75g2000cwc.googlegroups.com> Hello. I'm writing a proxy class, i.e: a class whose methods mostly delegate their functionality to other class object. Most of the methods (which are quite a lot) defined in the class would end up being: def thisIsTheMethodName(self): self._handlerClass.thisIsTheMethodName() The handler object is the same in all methods. I was wondering if there is a way to simplify this proxy class, maybe using some pythonic technique like metaclasses, introspection... any suggestion is appreciated. Thanks, Javier Sanz From duncan.booth at invalid.invalid Wed Aug 30 09:50:17 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 Aug 2006 13:50:17 GMT Subject: where or filter on list References: <1156939493.558819.8410@i42g2000cwa.googlegroups.com> Message-ID: skip at pobox.com wrote: > > >> Another way might be to sort by absolute value: > >> > >> intermed = [(abs(v), v) for v in foo] > >> intermed.sort() > >> intermed[0][1] > > Duncan> It is slightly simpler if you use sorted (assuming a recent > Duncan> enough Python): > > Duncan> intermed = sorted(foo, key=abs) > Duncan> print intermed[0] > > Yeah, sorted() is new enough that my brain generally doesn't realize it's > available. I also never remember the key parameter to list.sort(). You're not the only one who has trouble remembering just what is in each version. > Now that you mention it: > > >>> foo = [5, 2, -1, -7, 3, -6, 2, 12] > >>> foo.sort(key=abs) > >>> foo > [-1, 2, 2, 3, 5, -6, -7, 12] > > (assuming you don't mind reording the list - if you do, then sorted() is > your friend). And for Python 2.5 users only we have the exciting new option of: >>> foo = [5, 2, -1, -7, 3, -6, 2, 12] >>> min(foo, key=abs) -1 From jaysherby at gmail.com Tue Aug 8 20:53:53 2006 From: jaysherby at gmail.com (jaysherby at gmail.com) Date: 8 Aug 2006 17:53:53 -0700 Subject: newb question: file searching In-Reply-To: References: <1155067111.892386.130610@n13g2000cwa.googlegroups.com> <1155082260.661319.240760@h48g2000cwc.googlegroups.com> Message-ID: <1155084833.915620.133260@h48g2000cwc.googlegroups.com> That worked perfectly. Thank you. That was exactly what I was looking for. However, can you explain to me what the following code actually does? reversed(range(len(dirnames))) Gabriel Genellina wrote: > At Tuesday 8/8/2006 21:11, jaysherby at gmail.com wrote: > > > >Here's my code: > > > >def getFileList(): > > import os > > imageList = [] > > for dirpath, dirnames, filenames in os.walk(os.getcwd()): > > for filename in filenames: > > for dirname in dirnames: > > if not dirname.startswith('.'): > > if > > filename.lower().endswith('.jpg') and not > >filename.startswith('.'): > > > >imageList.append(os.path.join(dirpath, filename)) > > return imageList > > > >I've adapted it around all the much appreciated suggestions. However, > >I'm running into two very peculiar logical errors. First, I'm getting > >repeated entries. That's no good. One image, one entry in the list. > > That's because of the double iteration. dirnames and filenames are > two distinct, complementary, lists. (If a directory entry is a > directory it goes into dirnames; if it's a file it goes into > filenames). So you have to process them one after another. > > >def getFileList(): > > import os > > imageList = [] > > for dirpath, dirnames, filenames in os.walk(os.getcwd()): > > for filename in filenames: > > if filename.lower().endswith('.jpg') and > > not filename.startswith('.'): > > > >imageList.append(os.path.join(dirpath, filename)) > > for i in reversed(range(len(dirnames))): > > if dirnames[i].startswith('.'): del dirnames[i] > > return imageList > > reversed() because you need to modify dirnames in-place, so it's > better to process the list backwards. > > > > Gabriel Genellina > Softlab SRL > > > > > > __________________________________________________ > Pregunt?. Respond?. Descubr?. > Todo lo que quer?as saber, y lo que ni imaginabas, > est? en Yahoo! Respuestas (Beta). > ?Probalo ya! > http://www.yahoo.com.ar/respuestas From software.datagrep at gmail.com Fri Aug 4 03:53:35 2006 From: software.datagrep at gmail.com (software.datagrep at gmail.com) Date: 4 Aug 2006 00:53:35 -0700 Subject: software thuriam Message-ID: <1154678015.308461.88260@m73g2000cwd.googlegroups.com> Thuriam Software Services >From solution design and offshore software development to outsourcing application support and improvement, Thuriam's offers a compelling alternative to minimize software development costs, and improve the quality of your software solutions and compress software development time. We have been using state-of-the-art Quality Assurance methodologies and practices in all its projects, focusing to deliver error-free software services. We delivere our services to verticals including Healthcare, Financial Services and Banking, Telecommunication, Retail, Security, Construction, Transportation etc. Few of our services for preview ? Application development Our Team of programmers can develop and design personalized software for any particular business functions. We can manage from DESKTOP or NETWORK programming for large organization database: ORACLE, SYBASE, INTERBASE, INFORMIX, MS-SQL and in kind of CLIENT/SERVER or program type DISTRIBUTED, that includes any multi-platform of any new technology. ? Database design & development tasks include Website Design / Website Marketing/Graphic Design / Presentations / Multimedia/ Writing / Editing / Translation/ Programming / Software / Database Development/ GIS and Spatial Analysis/ GIS Cartography, Conversion, & CAD/ Remote Sensing & Image Processing / Land Surveying & Mapping/ E911-Integrated Mapping/ Photogrammetry & Aerial Photography, Packaged software development and sales in the areas of CAD, CAM, GIS, Graphics, DTP, Vision and Expert Systems, Turnkey software development, Engineering consultancy with computerized analysis and MIS tools, Services in the areas of CAD, Cartographic Databases, MIS and Multimedia, Cross-platform conversions/porting of applications and software maintenance ? Security We have offered software solutions for complex problems such as implementation of constraint solver, parametric sketcher, Solver for Finite element analysis of beams with variable loading, modules for optimization, software for data encryption for software security. We have productively implemented many projects relating visualization based on geometry data. We have delivered Surface, Volumetric data viewers for Geometric, manufacturing and medical domain. We utilize skills in the following domains Computational Geometry, Algorithm Design, Object oriented methodology, Software Engineering, Manufacturing technology and Industrial production ? Software Packages like Escrow Software, Macintosh Accounting Software, Punch Design Software, Chiropractic Software, Medical Appointment Scheduling Software, Contract Management Software, Lease Accounting Software, Small Business Accounting Software, Business Intelligence Software, Medical Billing Software, Recruiting Software, Business Accounting Software, Marketing Automation Software, Small Business Payroll Software, Help Desk Software, Facility Scheduling Software, Small Business Bookkeeping Software, Billing Software, Accounting Software, Business Scheduling Software, Field Service Software, Network Management Software ? Other services include ERP, Web Development, Customized Enterprise Solutions, Wireless/Mobile Application Development, Science Intensive Development, Software Project Recovery, Database Development and Migration, Linux/Unix Development, Embedded Software Development, Porting and Migration, Legacy Systems, Re-engineering, Enterprise Application Integration, Quality Engineering, Microsoft .NET Development, Java Card Applications, Database solutions Java / J2EE Development, Smart Card Solutions, Handhelds & PDAs, Embedded system design and programming, Networking, Scripts & Utilities, System administration, Technical support, Wireless, Game, VOIP, Game programming, Database administration, Custom programming Thuriam monitors the overall direction for the project, including determining which features the solution will and will not include, and a general schedule for delivery. Then our team prepares the functional specifications, works the design process through, and work plans, cost estimates and schedules for the various deliverables. Testing highlights usage and operation under realistic environmental conditions. The team aims on resolving and triaging (prioritizing) bugs and preparing the solution for release. Our testers develop the Test Plan, test cases and scripts, the system and verify whether it functions as per the specification. We support our customers with all required activities and procedures to establish productive customer-contractor communication environment. ? Project kick-off visits ? Normal visits to customer ? Onsite & offsite work ? Regular project status reports, feedback ? Regular telephone conferences (conference calls) Contact Name Thuriam Website www.thuriam.net Email info at thuriam.net software at thuriam.net From skip at pobox.com Tue Aug 15 14:56:09 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 15 Aug 2006 13:56:09 -0500 Subject: X windows and Python? In-Reply-To: <7xy7tpyhbf.fsf_-_@ruckus.brouhaha.com> References: <7xy7tpyhbf.fsf_-_@ruckus.brouhaha.com> Message-ID: <17634.6345.410950.897070@montanaro.dyndns.org> >>>>> "Paul" == Paul Rubin <"http://phr.cx"@NOSPAM.invalid> writes: Paul> I'd like to program my Python script to put a string into the X Paul> windows cut buffer. Can anyone suggest the simplest way to do Paul> that? Maybe there's some useful functionality exposed through the Python Xlib module: http://python-xlib.sourceforge.net/ Skip From Bulkan at gmail.com Wed Aug 9 18:59:36 2006 From: Bulkan at gmail.com (placid) Date: 9 Aug 2006 15:59:36 -0700 Subject: Regd:Video Converter Programming In-Reply-To: <12djo0melsc5icb@corp.supernews.com> References: <1155092497.011057.219180@m79g2000cwm.googlegroups.com> <1155098914.953285.48410@i42g2000cwa.googlegroups.com> <12djo0melsc5icb@corp.supernews.com> Message-ID: <1155164376.036405.231040@n13g2000cwa.googlegroups.com> Grant Edwards wrote: > On 2006-08-09, placid wrote: > > >> I want to write an avi to flv converter in php but i am a complete > >> newbie to it. > > > via a Google search for "python video convert" i found the following > > > > http://pymedia.org/ > > Except he wants to write it in PHP. > > Not sure why he's asking us about it here in c.l.python. well if i see a post on comp.lang.python, then i assume its related to python and thats what my brain did! From sjmachin at lexicon.net Thu Aug 10 20:55:22 2006 From: sjmachin at lexicon.net (John Machin) Date: 10 Aug 2006 17:55:22 -0700 Subject: error handling In-Reply-To: <1155253063.322440.97300@b28g2000cwb.googlegroups.com> References: <1155253063.322440.97300@b28g2000cwb.googlegroups.com> Message-ID: <1155257721.952250.122590@h48g2000cwc.googlegroups.com> Chris wrote: > I want to handle errors for a program i'm building in a specific way, > but I don't want to use try/except/finally because it requires forming > new blocks of code. I want to be able things like this: > > a = [2, 423, "brownie", 234.34] > try: a[890] > except IndexError: # I don't use 'finally' here because I specifically > want to check for an IndexError > sys.exit("That number is way too big!") > > But sometimes you can have too many of these statements in your > program, and it starts to get tangled and nasty looking. Is there a way > I can modify sys.error so that when the interpreter comes accross an > IndexError it prints "That number is way too big!" before it exits? Call me crazy, but I don't think convoluted mucking about to produce "That number is way too big!" -- especially when it could be negative (way too small) -- is better than doing nothing (no try/except at all) and getting "list index out of range": #>>> a = [1,42, 666] #>>> a[890] Traceback (most recent call last): File "", line 1, in ? IndexError: list index out of range #>>> Although the manual says "In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs." this is scarcely to be recommended. You should at the very least produce a stack trace so that you can see *where* the error occurred. If you are interacting with a user, you need to give feedback for *expected* problems like invalid input as close to the point of error as possible -- online: validate the input before attempting to use it; batch -- validate it and give feedback which pinpoints the problem (and it may be required to identify all problems, not just bail out on seeing the first puff of flak). If it is for your own use: do yourself a favour and treat yourself like a customer should be treated. You should have traps for *unexpected* exceptions that likewise pinpoint what was happening when the exception occurred. Consider dumping salient info to a file before pulling the ripcord -- that way you don't have to rely on users reporting what they thought they saw before hitting the power button. Time passing has not meant progress; user memory capacity has not increased and the usual cycle-power response time is worse; rebooting a PC takes way longer than rebooting a green-screen terminal :-) HTH, John From o.evans at gmail.com Fri Aug 11 08:18:15 2006 From: o.evans at gmail.com (O Evans) Date: 11 Aug 2006 05:18:15 -0700 Subject: Adding private tags to a tiff file. Message-ID: <1155298695.458493.247230@i3g2000cwc.googlegroups.com> Hi there, I'm manipualating tiff images captured by a program that insists on using annoying private tags. I want to be able to import an image that I have created into the program but I cannot get PIL to save the private tag. Here is a simplified version of the code I am using: import Image original = Image.open(r"test.tif") original.tag[34118] = "life" print "Before saving" , original.tag[34118] original.save("test2.tif") altered = Image.open(r"test2.tif") if altered.tag.tagdata.has_key(34118): print "It worked!" Is there a way of getting this to work? I have tried looking at TiffTags and TiffImageFile, but I cannot understand why the tags are not preserved. Or should I be looking at a different library? Many thanks. From horpner at yahoo.com Thu Aug 24 08:25:15 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 24 Aug 2006 14:25:15 +0200 Subject: Best Editor References: <44ed8db6$0$75034$14726298@news.sunsite.dk> Message-ID: On 2006-08-24, JAG CHAN wrote: > Friends, I am trying to learn Python. It will be of great help > to me if you let me know which one would be best editor for > learning Python. Plese note that I would like to have > multiplatform editor which will be useful for both LInux and > Windows XP. Start with IDLE, which will likely be available everywhere you use Python. The full instructions for using IDLE take up about two pages of text, which means it's lightweight, and it comes preconfigured with good Python integration. Learning a highly portable, industrial-strength program like Vim or emacs is something I highly recommend, but it's not necessarily a productive thing to do that at the same time you're learning Python. -- Neil Cerutti From aleax at mac.com Tue Aug 15 11:04:18 2006 From: aleax at mac.com (Alex Martelli) Date: Tue, 15 Aug 2006 08:04:18 -0700 Subject: hide python code ! References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155300852.497741.73230@74g2000cwt.googlegroups.com> <1155301468.870340.82920@b28g2000cwb.googlegroups.com> <1155307415.855555.124760@i3g2000cwc.googlegroups.com> <1155309563.898182.195950@p79g2000cwp.googlegroups.com> <1155313092.743230.33950@m73g2000cwd.googlegroups.com> <44e10b95$0$15787$14726298@news.sunsite.dk> Message-ID: <1hk3pm7.pxdu0v3byt8qN%aleax@mac.com> Gerhard Fiedler wrote: > On 2006-08-14 20:48:45, Damjan wrote: > > > I think you increase your chances of Microsoft not even being in the same > > room with your software 100-fold if you release it under.. say GPL. > > ... and have the money to run a law suit? Patents, licenses etc are only as > strong as the money that backs them, mostly. I guess that's an advantage of GPL: there's a foundation (with much better funding than you could raise as an individual) which will gladly fight for GPL, both in the courts and in the arena of public opinion -- I believe that, so, far, they've won every single fight they've picked, by just the joint threat of lawsuits and public shaming campaigns. It just isn't worth Microsoft's while to take the public-relations hit of such a fight: much cheaper for them to re-implement your ideas than to copy your GPL'd code. Alex From blue99 at interia.pl Mon Aug 21 02:59:35 2006 From: blue99 at interia.pl (Rob Wolfe) Date: 20 Aug 2006 23:59:35 -0700 Subject: Create a Multilanguage PDF in Python In-Reply-To: <1156108451.762961.70140@h48g2000cwc.googlegroups.com> References: <1156073383.983914.149180@i3g2000cwc.googlegroups.com> <87mz9z4f8h.fsf@smsnet.pl> <1156108451.762961.70140@h48g2000cwc.googlegroups.com> Message-ID: <1156143575.547217.237270@p79g2000cwp.googlegroups.com> Perseo wrote: > Hi again, > > WORKS!!! I download all I need as python + reportlab. Only 2 questions: > > 1. I need all of this package? because it is 6Mb! I'm afraid you need all of it. BTW My reportlab package is only 3MB... hmm strange. > 2. How can I connect my software with MySql. In my Hosting is present > the Python support but I don't thing that the MySQLdb is present. How > can I solve this little problem? You can install MySQLdb wherever you want. You need only to make sure the module is in your PYTHONPATH. HTH, Rob From SPAMworFREEwor at bellsouth.net Mon Aug 14 16:59:03 2006 From: SPAMworFREEwor at bellsouth.net (Charles Russell) Date: Mon, 14 Aug 2006 20:59:03 GMT Subject: TypeError: 'module' object is not callable (newby question) In-Reply-To: References: Message-ID: Marc 'BlackJack' Rintsch wrote: > > Don't call your file `glob.py` because then you import this module and not > the `glob` module from the standard library. > > Ciao, > Marc 'BlackJack' Rintsch Yes, thanks. Renaming to myglob.py solved the problem. But why does the conflict not occur when the code is run interactively from the python prompt? Somewhat related - I haven't found the magic word to invoke a .py script from the python prompt (like the command "source" in csh, bash, tcl?) "import" runs the script, but then complains that it is not a module. From duncan.booth at invalid.invalid Tue Aug 1 13:35:58 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Aug 2006 17:35:58 GMT Subject: list comprehension syntax..? References: <1154451119_25085@sp6iad.superfeed.net> Message-ID: Gregory Guthrie wrote: > Sorry for a simple question- but I don't understand how to parse this > use of a list comprehension. > > The "or" clauses are odd to me. > > It also seems like it is being overly clever (?) in using a lc > expression as a for loop to drive the recursion. You are spot on there. It is a list comprehension, but the resulting list is just thrown away, so using a list comprehension is a complete waste of time serving only to confuse the issue. Presumably it saved the author a character or two. [ exp for var in seq ] when the result isn't used can be rewritten as: for var in seq: exp and: exp1 or exp2 when the result is thrown away is just: if not exp1: exp2 So: [ m in [(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3) or board[j] for j in range(81) ] or solve(board[:i]+m+board[i+1:]) for m in'%d'%5**18 ] is equivalent to: inner = [(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3) or board[j] for j in range(81) ] for m in '3814697265625': if m not in inner: solve(board[:i]+m+board[i+1:]) (That inner list comprehension doesn't depend on m, so it doesn't need to be reevaluated each time round the loop except, again, to save a few characters.) The '%d'%5**18 looks to be a silly way to iterate through all possible digits for m even though it does some of them twice while saving one character over writing range(1,10). The strange expression I called 'inner' is a list containing the string value board[j] if j is in the same row, column or block as i, or an integer for any other cells. So 'm not in inner' is true only if the value for m is not already used in that row column or block and is therefore a possible candidate for that location in the board. From danielwong at berkeley.edu Sun Aug 13 22:49:41 2006 From: danielwong at berkeley.edu (danielx) Date: 13 Aug 2006 19:49:41 -0700 Subject: selecting base class from user input In-Reply-To: References: Message-ID: <1155523781.860117.203140@h48g2000cwc.googlegroups.com> Is your declaration of ABC supposed to have some_super as one of the base classes? Your constructor has some_super as a parameter. What is this supposed to mean in light of the declaration for ABC? If you are trying to customize the base class of ABC by passing an argument to the constructor of ABC, you should probably reconsider. If constructing one instance of ABC can change ABC (the class) itself, then the behavior of other instances will be affected as well. No programmer can stay sane if he creates instances of a class that could suddenly change its behavior (due to someone else's code). What you could do instead is to create a function which constructs classes based on the arguments it recieves. Then, you'll be able to create instances of the generated classes (all this meta-thinking is huring my brain ;). I am talking about something like this: def createClass(name, base): exec "class %s(%s): pass" % (name, base) return eval( "name" ) ... Can you please tell us why you are doing this? My curiosity is killing me! Another meta-thought: Hopefully I've beaten everyone else to the punch about that question. Is it just me, or will a reply with such a question always tell the original poster that what he wants to do MUST be flawed? I hope I have been gentler than this. Jackson wrote: > I want a class that will determine its base class by the argument passed > in. What I am about to write _does_not_work_, but it shows what I am > trying to do. > > class ABC(some_super): > def __init__(self,some_super): > some_super.__init__(self) > > if some_super == list: > self.append('ABC') > > elif some_super == dict: > self['ABC'] = None > > > Then, the user can call this function: > > >>> example = ABC(list) > >>> print example > ['ABC'] > > >>> example = ABC(dict) > >>> print example > {'ABC': None} > > Clearly, this is a bad example, but the central idea is what I am trying > to do. ABC is a particular example which can be represented in various > forms. I want an ABC class that will create the example in the form > specified by the user. > > So how can I achieve this? Thanks. From tim at tdw.net Fri Aug 11 12:55:52 2006 From: tim at tdw.net (Tim Williams) Date: Fri, 11 Aug 2006 17:55:52 +0100 Subject: Read a file with open command In-Reply-To: References: <1155288288.954142.293000@i3g2000cwc.googlegroups.com> <1155288697.170018.61160@m79g2000cwm.googlegroups.com> Message-ID: <9afea2ac0608110955y4c396378ib839a1460783f535@mail.gmail.com> On 11 Aug 2006 09:39:23 -0700, jean-jeanot wrote: > Anyway many thanks.Here is the program: > > >>> file_obj= open ("D:/Mes documents/ADB Anna.ods",'r') > >>> s = file_obj > >>> s.readlines() Please remember not to top-post :) Try this >>> s = open ("D:/Mes documents/ADB Anna.ods",'r') >>> s.readlines() >>> s.close() or >>> s = open ("D:/Mes documents/ADB Anna.ods",'r').readlines() HTH :) From guotie.9 at gmail.com Tue Aug 29 05:42:00 2006 From: guotie.9 at gmail.com (=?utf-8?B?5Y+u5Y+u5b2T5b2T?=) Date: 29 Aug 2006 02:42:00 -0700 Subject: The lib email parse problem... In-Reply-To: References: <1156837260.222395.305960@b28g2000cwb.googlegroups.com> <1156841437.692537.68200@i42g2000cwa.googlegroups.com> <1156841950.866776.66400@b28g2000cwb.googlegroups.com> <1156842395.855885.183330@p79g2000cwp.googlegroups.com> Message-ID: <1156844520.044398.7900@h48g2000cwc.googlegroups.com> i know how to use email module lib. the question is about how to handle the rfc 1521 mime mulitpart/alternitave part . i know emai can handle mulitpart , but the subpart alternative is special . Steve Holden ??? > ???? wrote: > > supose a email part like this: > > > > Content-Type: Multipart/Alternative; > > boundary="Boundary-=_iTIraXJMjfQvFKkvZlqprUgHZWDm" > > > > > > --Boundary-=_iTIraXJMjfQvFKkvZlqprUgHZWDm > > Content-Type: text/plain; charset="gb2312" > > Content-Transfer-Encoding: 7bit > > > > abcd. > > --Boundary-=_iTIraXJMjfQvFKkvZlqprUgHZWDm > > Content-Type: text/html; charset="gb2312" > > Content-Transfer-Encoding: quoted-printable > > > > .................. > > --Boundary-=_iTIraXJMjfQvFKkvZlqprUgHZWDm-- > > > > the plain text is abcd, and the alternative content type is text/html, > > i should prefer explain the html content, and i must not explaint the > > two part ,so i want to get the boundary end. > > > > thanks all. > > > In other words, you *haven't* tried the email module. > > email.Parser can cope with arbitrarily complex message structures, > including oddities like attachments which are themselves email messages > containing their own attachments. > > Read the documentation and look for sample code, then get back to the > list with questions about how to make email do what you want it to. > > Please don't ask us to re-invent existing libraries. that's why the > libraries are there. > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://holdenweb.blogspot.com > Recent Ramblings http://del.icio.us/steve.holden From aleax at mac.com Sat Aug 5 21:22:33 2006 From: aleax at mac.com (Alex Martelli) Date: Sat, 5 Aug 2006 18:22:33 -0700 Subject: Design Patterns in Python References: Message-ID: <1hjlz48.1o1bhxg1yabltmN%aleax@mac.com> Gabriel Genellina wrote: > Hello > > Most authors talk about Java/C++, and describe patterns used as a > workaround to their static class model; the dynamic nature of Python > allows for trivial implementations in some cases. > I've seen some design patterns examples on the ActiveState site, and > some discussions some time ago on this list. > But does anyone know of a complete discussion/analysis of patterns in > Python? Books, articles, web pages... Many of my presentations and articles have covered this area, and you can find the various PDFs at -- of course, they're somewhat fragmentary, but I hope they can be of some help! Alex From michele.petrazzo at TOGLIunipex.it Mon Aug 21 08:25:15 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Mon, 21 Aug 2006 12:25:15 GMT Subject: Python for EXIF-info-additions ? In-Reply-To: References: <4kmp5jFctg9cU1@individual.net> Message-ID: Bruno Dilly wrote: > I think you can find what do you need into this repository, it's a > creative commons tool: > https://svn.berlios.de/svnroot/repos/cctools/publisher/branches/flickr-storage-branch/ > > > > > take a look in the follow directory: ccpublisher/jpeg/ > > I'm not sure if it's what you want, let me know. > This is more and more times harder than I need! This code add the exif tags to the image by itself, but I need only to wrap and add some python code for make freeimagepy talk with the tags freeimage's functions. Only this! All the tags code for add/remove/modify them are already inside freeimage! > See you, > > Dilly > Bye, Michele From sjmachin at lexicon.net Fri Aug 4 18:19:53 2006 From: sjmachin at lexicon.net (John Machin) Date: 4 Aug 2006 15:19:53 -0700 Subject: super quick question In-Reply-To: <1154729477.526898.57980@i3g2000cwc.googlegroups.com> References: <1154726397.778270.28810@75g2000cwc.googlegroups.com> <1154727052.378868.277770@s13g2000cwa.googlegroups.com> <1154729477.526898.57980@i3g2000cwc.googlegroups.com> Message-ID: <1154729993.297406.207120@s13g2000cwa.googlegroups.com> Chris wrote: > It's very beautiful. Thanks You think that's beautiful? Try these: 'abcdef'[::-1] 'abcdef'[::-2] Cheers, John From claudio.grondi at freenet.de Sat Aug 26 18:19:14 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Sun, 27 Aug 2006 00:19:14 +0200 Subject: random writing access to a file in Python In-Reply-To: <7xhczzqoi3.fsf@ruckus.brouhaha.com> References: <5a9ue2lrjh214ecmme09fsodhm3ico1ntm@4ax.com> <7xhczzqoi3.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Claudio Grondi writes: > >>Is there a ready to use (free, best Open Source) tool able to sort >>lines (each line appr. 20 bytes long) of a XXX GByte large text file >>(i.e. in place) taking full advantage of available memory to speed up >>the process as much as possible? > > > Try the standard Unix/Linux sort utility. Use the --buffer-size=SIZE > to tell it how much memory to use. I am on Windows and it seems, that Windows XP SP2 'sort' can work with the file, but not without a temporary file and space for the resulting file, so triple of space of the file to sort must be provided. Windows XP 'sort' uses constantly appr. 300 MByte of memory and can't use 100% of CPU all the time, probably due to I/O operations via USB (25 MByte/s experienced top data transfer speed). I can't tell yet if it succeeded as the sorting of the appr. 80 GByte file with fixed length records of 20 bytes is still in progress (for eleven CPU time hours / 18 daytime hours). I am not sure if own programming would help in my case to be much faster than the systems own sort (I haven't tried yet to set the size of memory to use in the options to e.g 1.5 GByte as the sort help tells it is better not to specify it). My machine is a Pentium 4, 2.8 GHz with 2.0 GByte RAM. I would be glad to hear if the time required for sorting I currently experience is as expected for such kind of task or is there still much space for improvement? Claudio Grondi From Eric_Dexter at msn.com Sun Aug 27 17:35:34 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 27 Aug 2006 14:35:34 -0700 Subject: newbe question about removing items from one file to another file Message-ID: <1156714534.318183.326220@i3g2000cwc.googlegroups.com> def simplecsdtoorc(filename): file = open(filename,"r") alllines = file.read_until("") pattern1 = re.compile(">orcfilename, line I am pretty sure my code isn't close to what I want. I need to be able to skip html like commands from to and to key on another word in adition to to end the routine I was also looking at se 2.2 beta but didn't see any easy way to use it for this or for that matter search and replace where I could just add it as a menu item and not worry about it. thanks for any help in advance From gagsl-py at yahoo.com.ar Wed Aug 9 23:03:36 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 10 Aug 2006 00:03:36 -0300 Subject: Two Classes In Two Files In-Reply-To: <1155151480.848276.52650@75g2000cwc.googlegroups.com> References: <1155151480.848276.52650@75g2000cwc.googlegroups.com> Message-ID: <7.0.1.0.0.20060810000051.03f71330@yahoo.com.ar> At Wednesday 9/8/2006 16:24, dhable at gmail.com wrote: >I just started working with Python and ran into an annoyance. Is there >a way to avoid having to use the "from xxx import yyy" syntax from >files in the same directory? I'm sure it's been asked a million times, >but I can't seem to find the answer. [...] >When I run the Two.py file, I get the expected output but I'd like to >eliminate the from line in two.py. Embody the Zen of Python: http://www.python.org/dev/peps/pep-0020/ Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From grante at visi.com Sat Aug 19 11:13:46 2006 From: grante at visi.com (Grant Edwards) Date: Sat, 19 Aug 2006 15:13:46 -0000 Subject: write eof without closing References: Message-ID: <12eeala1klcrtcf@corp.supernews.com> On 2006-08-19, cage wrote: > can i write a eof to a file descriptor without closing it? No. Not on Windows, OS-X, or Unix. There is no such thing as "an eof". On CP/M Ctrl-Z is used as EOF for text files. -- Grant Edwards grante at visi.com From j_mckitrick at yahoo.com Thu Aug 17 10:41:57 2006 From: j_mckitrick at yahoo.com (jmckitrick) Date: 17 Aug 2006 07:41:57 -0700 Subject: The Semicolon Wars as a software industry and human condition References: <1155822175.534005.100490@75g2000cwc.googlegroups.com> Message-ID: <1155825717.383393.146500@b28g2000cwb.googlegroups.com> What's more of a waste of time: 1. The 30 minutes he took to write his vacuous essay. 2. The 15 seconds it took to skim it and see nothing worth reading. 3. The 30 seconds it took to write this post. Tough call. From bobrien18 at yahoo.com Fri Aug 18 13:14:55 2006 From: bobrien18 at yahoo.com (KraftDiner) Date: 18 Aug 2006 10:14:55 -0700 Subject: Type conversion? In-Reply-To: <1155915914.141274.99020@m79g2000cwm.googlegroups.com> References: <1155915139.622448.178160@m73g2000cwd.googlegroups.com> <1155915914.141274.99020@m79g2000cwm.googlegroups.com> Message-ID: <1155921295.608755.269970@i3g2000cwc.googlegroups.com> Rob Cowie wrote: > KraftDiner wrote: > > I have the following code... > > > > import array > > len32 = array.array('L') > > len16 = array.array('H') > > > > len32.append(0) > > len16.append(0) > > > > y = len32[0] > > print y.__class__ > > > > z = len16[0] > > print z.__class__ > > > > > > how can I change Zs type to long? > > z_long = long(z) > type(z_long) > > > > Or how how can I change an arrays type? In C++ you can cast one class type to another if you override the operator= Then you can convert one class type to another... In Python it would appear that the left hand side of the assignment operator is not used to determine if a cast is necessary. So how would I do this in python? a = classA() b = classB() b = a In the end b would end up just being a refrence to a no conversion would have been done. From grante at visi.com Wed Aug 9 09:16:06 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 09 Aug 2006 13:16:06 -0000 Subject: Regd:Video Converter Programming References: <1155092497.011057.219180@m79g2000cwm.googlegroups.com> <1155098914.953285.48410@i42g2000cwa.googlegroups.com> Message-ID: <12djo0melsc5icb@corp.supernews.com> On 2006-08-09, placid wrote: >> I want to write an avi to flv converter in php but i am a complete >> newbie to it. > via a Google search for "python video convert" i found the following > > http://pymedia.org/ Except he wants to write it in PHP. Not sure why he's asking us about it here in c.l.python. -- Grant Edwards grante Yow! Like I always at say -- nothing can beat visi.com the BRATWURST here in DUSSELDORF!! From moverx at gmail.com Tue Aug 29 10:13:44 2006 From: moverx at gmail.com (Yusnel Rojas) Date: Tue, 29 Aug 2006 07:13:44 -0700 Subject: SOAPpy question In-Reply-To: <28b127080608281935k744c73fv5b58b271e2099f7c@mail.gmail.com> References: <28b127080608281935k744c73fv5b58b271e2099f7c@mail.gmail.com> Message-ID: <28b127080608290713w19f91efeu338367ea2b686827@mail.gmail.com> hello , I'm wondering if SOAPpy doesn't have something to generate a wsdl for a specific application. Let's say, I wrote a web service with SOAPpy, is there any way to generate the wsdl for it. If there aren't can someone give a little example of both. thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From eugene at boardkulture.com Wed Aug 16 14:37:08 2006 From: eugene at boardkulture.com (3KWA) Date: 16 Aug 2006 11:37:08 -0700 Subject: sending mailing list with smtplib In-Reply-To: <1155705965.315443.239350@b28g2000cwb.googlegroups.com> References: <1155561746.812918.128770@h48g2000cwc.googlegroups.com> <1155630010.956035.270580@74g2000cwt.googlegroups.com> <1155674513.096396.4430@i3g2000cwc.googlegroups.com> <1155705965.315443.239350@b28g2000cwb.googlegroups.com> Message-ID: <1155753428.851003.171680@74g2000cwt.googlegroups.com> 3KWA wrote: > Just for education purposes (mine I guess :P) what was the idea behind > that design decision? >From the doc (self education :P) The following methods implement a mapping-like interface for accessing the message's RFC 2822 headers. Note that there are some semantic differences between these methods and a normal mapping (i.e. dictionary) interface. For example, in a dictionary there are no duplicate keys, but here there may be duplicate message headers. Also, in dictionaries there is no guaranteed order to the keys returned by keys(), but in a Message object, headers are always returned in the order they appeared in the original message, or were added to the message later. Any header deleted and then re-added are always appended to the end of the header list. These semantic differences are intentional and are biased toward maximal convenience. From bj_666 at gmx.net Wed Aug 2 13:45:07 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 02 Aug 2006 19:45:07 +0200 Subject: ElementTree and Unicode References: <1154530195.741884.34350@h48g2000cwc.googlegroups.com> <1154532671.351968.142890@b28g2000cwb.googlegroups.com> Message-ID: In <1154532671.351968.142890 at b28g2000cwb.googlegroups.com>, S?bastien Boisg?rault wrote: > I am trying to embed an *arbitrary* (unicode) strings inside > an XML document. Of course I'd like to be able to reconstruct > it later from the xml document ... If the naive way to do it does > not work, can anyone suggest a way to do it ? Encode it in UTF-8 and then Base64. AFAIK the only reliable way to put an arbitrary string into XML and get exactly the same string back again. Ciao, Marc 'BlackJack' Rintsch From sxn02 at yahoo.com Mon Aug 28 10:57:56 2006 From: sxn02 at yahoo.com (Sorin Schwimmer) Date: Mon, 28 Aug 2006 07:57:56 -0700 (PDT) Subject: rollover effect Message-ID: <20060828145756.3225.qmail@web56003.mail.re3.yahoo.com> Hi, For the right-click event, you should use a bind to . If you have a new version of Python, chances are that you already have Tix installed. Tix, like Pmw, is an extension package for Tkinter, and it also offers a Balloon widget. See the following example: from Tix import * r=Tk() l=Label(r,text='This is my label') def fn(e): global l print 'Right clicked :-)' l.bind('',fn) l.grid() b=Balloon(r) b.bind_widget(l,balloonmsg='text in balloon') r.mainloop() If you're a beginer, than you may want to have a look to some of the following links regarding Tkinter and extensions: http://www.pythonware.com/library/tkinter/introduction/index.htm http://infohost.nmt.edu/tcc/help/pubs/tkinter/ http://www.ferg.org/thinking_in_tkinter/index.html http://mail.python.org/pipermail/tkinter-discuss/ http://www.3dartist.com/WP/python/tknotes.htm http://tkinter.unpy.net/wiki/FrontPage http://www.faqts.com/knowledge_base/index.phtml/fid/264 http://pmw.sourceforge.net/doc/index.html http://heim.ifi.uio.no/~hpl/Pmw.Blt/doc/ http://pmwcontribd.sourceforge.net/ http://tcltk.free.fr/blt/ http://tkinter.unpythonic.net/bwidget/BWman/ http://tcltk.free.fr/Bwidget/ http://tktreectrl.sourceforge.net/treectrl.html http://tix.sourceforge.net/docs.shtml http://groups.yahoo.com/group/tix/messages/1 http://cvs.sourceforge.net/viewcvs.py/tkta http://www.tkzinc.org/ble/ http://tktreectrl.sourceforge.net/Understanding TkTreeCtrl.html http://cvs.sourceforge.net/viewcvs.py/*checkout*/tktable/tile-www/doc/index.html http://wiki.tcl.tk/6172http://www.faqts.com/knowledge_base/view.phtml/aid/3728 http://www.faqts.com/knowledge_base/view.phtml/aid/3728 I see I have a rather long list of bookmarks ;-) I hope this helps. Sorin __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From davideugenewarren at gmail.com Thu Aug 10 16:15:06 2006 From: davideugenewarren at gmail.com (davideugenewarren at gmail.com) Date: 10 Aug 2006 13:15:06 -0700 Subject: semi-Newbie question In-Reply-To: <1155229897.356144.183750@m79g2000cwm.googlegroups.com> References: <1155229897.356144.183750@m79g2000cwm.googlegroups.com> Message-ID: <1155240906.769756.294620@74g2000cwt.googlegroups.com> Do you absolutely need to use variables? A dictionary would serve if each case has a unique identifier. client_info_dict = {} for i in tagfile: tagname,scope,value = i.replace('"','').split(',') # split fields, strip redundant characters client_info_dict.setdefault(scope,{}) # set up an empty nested dict for the unique ID client_info_dict[scope][tagname] = value # set the tagname's value Then client info can be retrieved from the dictionary using unique IDs and stereotyped tags (with .get() if some tags are not always present). I won't make any claims about the efficiency of this approach, but it works for me. len wrote: > Hi all > > I have a file that I receive from another party which is basicly a csv > file containing the following type of information; > > Tagname Scope Value > "first_name","POL01","John" > "last_name","POL01","Doe" > "birthday","POL01","04/03/61" > etc > > I need to convert this file info into my file format used in my > application. > > I have been given a file from the other company that gives me all of > the tagname that could be used and their scope. I want to build a > table which would have all of the various tagnames, scope, and put a > fieldname equivalent in the fieldname in my file structure in my > application. Then read through the vendors csv file index into my > table file and get the field name of where to move the data into my > data structure. > > Here is my question? basicly I need to get the data referenced by > fieldname variable in my table and then use that data as a variable > name in a python assignment statement. Thus changing the actual python > code at each iteration through the lines in the csv file. > > for i in tagfile > find tagname in tagtable > > *** the following line of code would change through each iteration *** > myfirst = value > > *** next iteration > mylast = value > > *** next iteration > mybirth = value > > etc > > I hope this make sense. I remember seeing something like this > somewhere. > > Any help appreciated. > > Len Sumnler > Unique Insurance From johnjsal at NOSPAMgmail.com Sat Aug 12 20:32:38 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 12 Aug 2006 20:32:38 -0400 Subject: [OT] John Salerno In-Reply-To: References: <44dd3a65$0$2381$c3e8da3@news.astraweb.com> Message-ID: <44de73c3$0$12587$c3e8da3@news.astraweb.com> Alan Connor wrote: > Almost certainly bogus. I wouldn't believe anything in this > fellow's headers or articles. > > TROLL. > > I don't help trolls. Ok, I don't know how seriously to take this post, so I won't spend much time addressing it. All I will say is yes, this is really me and I am asking a genuine question. From apardon at forel.vub.ac.be Fri Aug 25 03:38:32 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 25 Aug 2006 07:38:32 GMT Subject: callable to disappear? References: <1156357324.838315.234500@i42g2000cwa.googlegroups.com> Message-ID: On 2006-08-23, Terry Reedy wrote: > > "faulkner" wrote in message > news:1156357324.838315.234500 at i42g2000cwa.googlegroups.com... >> what's wrong with hasattr(obj, '__call__')? > > I have the impression that this is not currently true for all callables . > If not, this may be improved in the future. > >>> Antoon Pardon >>> Is there a chance this will be reconsidered? > > The items in PEP 3100 have different levels of certainly. Some may even > get changed after experience with the alpha versions. Guido is allowing a > year from first alpha (early 2007?) to final release, instead of the > current 4-5 months. > > There has been recent discussion since of iscallable and some other > isxxxx()s. The points you mentioned were raised and considered. I don't > remember if there was a decision for the present. > > Two of the bigger negatives for 'iscallable': > 1. You cannot know for sure until you call and get a return. Even that is not sure. Consider the following: Bar = 1 def Foo(): Bar() try: Foo() except ...: warning("...") Calling Foo will result in the same exception being raised as if Foo wasn't callable, while in fact it is callable. > 2. It does not say if the candidate is callable with any particular number > or set of parameters. But the "raise an exception" option doesn't make this distinction either. A TypeError will be raised both when the object isn't callable or when it is called with the wrong parameters. -- Antoon Pardon From aisaac0 at verizon.net Wed Aug 9 14:56:18 2006 From: aisaac0 at verizon.net (David Isaac) Date: Wed, 09 Aug 2006 18:56:18 GMT Subject: __contains__ vs. __getitem__ References: <44da144b$0$21143$7a628cd7@news.club-internet.fr> Message-ID: > Alan Isaac wrote: > > I have a subclass of dict where __getitem__ returns None rather than > > raising KeyError for missing keys. (The why of that is not important for > > this question.) "Bruno Desthuilliers" wrote: > Well, actually it may be important... What's so wrong with d.get('key') > that you need this behaviour ? I want to use the mapping with string interpolation. Alan Isaac From Fuzzygoth at gmail.com Wed Aug 16 03:55:07 2006 From: Fuzzygoth at gmail.com (Fuzzydave) Date: 16 Aug 2006 00:55:07 -0700 Subject: round not rounding to 0 places In-Reply-To: References: <1155712764.516132.251800@m73g2000cwd.googlegroups.com> Message-ID: <1155714907.341067.111930@m73g2000cwd.googlegroups.com> > Sybren Stuvel wrote: > round returns a float. Use > int(round('+value+', 0)) > to get an integer. > Sybren ahh of course it does, slaps own forehead sorted thanks :) David P From mturillo at gmail.com Wed Aug 23 13:23:20 2006 From: mturillo at gmail.com (Perseo) Date: 23 Aug 2006 10:23:20 -0700 Subject: Create a Multilanguage PDF in Python In-Reply-To: <87mz9z4f8h.fsf@smsnet.pl> References: <1156073383.983914.149180@i3g2000cwc.googlegroups.com> <87mz9z4f8h.fsf@smsnet.pl> Message-ID: <1156353800.364034.156710@75g2000cwc.googlegroups.com> Hi Rob this is my code: #!/usr/bin/python import time, os, sys from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfgen import canvas from reportlab.lib.units import inch, cm from reportlab.lib.pagesizes import A4 #precalculate some basics top_margin = A4[1] - inch bottom_margin = inch left_margin = inch right_margin = A4[0] - inch frame_width = right_margin - left_margin pdfmetrics.registerFont(TTFont('Verdana', 'verdana.ttf')) canv = canvas.Canvas("test.pdf") def drawPageFrame(mycanv): mycanv.line(left_margin, top_margin, right_margin, top_margin) mycanv.setFont('Verdana',12) mycanv.drawString(left_margin, top_margin + 2, "Pdf Test") mycanv.line(left_margin, top_margin, right_margin, top_margin) mycanv.line(left_margin, bottom_margin, right_margin, bottom_margin) mycanv.drawCentredString(0.5*A4[0], 0.5 * inch, "Page %d" % mycanv.getPageNumber()) canv.setPageCompression(1) drawPageFrame(canv) #do some title page stuff canv.setFont("Verdana", 36) canv.drawCentredString(0.5 * A4[0], 7 * inch, "Pdf Test") canv.setFont("Verdana", 18) canv.drawCentredString(0.5 * A4[0], 5 * inch, "Test Staff") canv.setFont("Verdana", 12) tx = canv.beginText(left_margin, 3 * inch) tx.textLine("This is a test to a PDF Exporting Tool") canv.drawText(tx) canv.showPage() canv.save() print "Content-Type: text/html\n\n" print "PDF Test" I would like to create a simple pdf splitted in two column with a vertical row. | ?????, ??????? | John, Malkovic ????????? (1) | 11 Main Street, Athens 54640 | Thessaloniki Greece ????????? (2) | ???????? | 00302310886995 ????????? | john.m at otenet.gr ???????????? | ???????????? | ?????? ???????? | 00345353453453 ????? ???????? | Thessaloniki ???? | Greece ?????????? | Greek ?????????? | ???????? | ??????? ?????? | Greek Rob Wolfe wrote: > "Perseo" writes: > > > Hi guys, > > > > I'm disprate with the Pdf Unicode. I try to create a class using ufpdf > > but some chars are not correct and now I would like try Python because > > a friend tolds me that it's very powerful. > > I need a simple script in Python that grab all Records from a MySql > > table and print in the pdf file. > > > > The languages stored in my db are about 25 and they are: > > Greek English French Hungarian Italian Lithuanian Dutch Portuguese > > Albanian > > Czech Danish German Spanish Estonian Finnish Irish Latvian Maltese > > Polish Romanian > > Russian Slovene Slovak Swedish > > You can give reportlab [1] a try. It has support for TrueType fonts > and unicode translation using UTF-8. I used to use it for pdf files > with polish chars. > > Some example code: > > > from reportlab.pdfbase import pdfmetrics > from reportlab.pdfbase.ttfonts import TTFont > from reportlab.pdfgen import canvas > > pdfmetrics.registerFont(TTFont('Verdana', 'Verdana.ttf')) > c = canvas.Canvas("pl.pdf") > c.setFont("Verdana", 12) > c.drawString(100, 600, "Witaj, ?wiecie!".decode("iso-8859-2").encode("utf-8")) > c.showPage() > c.save() > > > > [1] http://www.reportlab.org/ > > -- > HTH, > Rob From vatamane at gmail.com Thu Aug 3 22:28:25 2006 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 3 Aug 2006 19:28:25 -0700 Subject: Is there an obvious way to do this in python? In-Reply-To: References: <1154602887.279222.37980@75g2000cwc.googlegroups.com> Message-ID: <1154658505.666987.304320@m79g2000cwm.googlegroups.com> Hendrik, ---snip--- Now part of the reason I would like to go the transaction type route instead of the "per user" route is robustness and maintainability, and the ability it would give me to introduce new transaction types easily - as I see it if say an invoice's GUI code is stable I would never have to touch it again even if I combine it with anything else, as it would have been designed from the start to combine with others of it's own ilk, under a kind of communications controller that is standard... ---snip--- It could be possible to separate your GUI into various modules. So you could have for example: BillingGUI.py InvoicingGUI.py QueryGUI.py and so on. Then your central control application (Application.py) would get the set of module names allowed for that client to run during login. So after the user logs in, the next thing would be to "SELECT ..." all the GUI modules from the database to be downloaded. The client won't know which ones are there, only the server. So the set of possible GUIs will be sent over to the client (preferable in a zipped form). They are unzipped in some temporary folder (here you can do some caching to only download if the set changed). Then it would be imporant for you to create some nameing rule or some interface so the Application.py will know what GUI modules look like. For example you could have the pattern [Capitalizedname]GUI.py be a GUI module. The Application.py will then inspect the folder, and create a button and label for each possible GUI module and present that to the user. When the user clicks on the Button, the Application.py window gets hidden and the [Modulename]GUI.py module is executed. When done, the Application.py will be shown again and the user can either continue with another module they are allowed to use or quit. How does that sound? Also, you mentioned that you won't have more than a couple of simple fill-in forms and with drop-down options and so on. HTML then might be the way to go. If that's all there will ever be just try to do HTML (see Cherrypy, Turbogears and others....). If your GUI will be more complicated in the future, just stick with what you know (Tkinter for example). Good luck, Nick Vatamaniuc H J van Rooyen wrote: > "Nick Vatamaniuc" wrote: > > > |HJ, > | > |As far as GUI language/library goes: > | > |Some people suggested HTML, but I think HTML is a very awkward way to > |create a good looking dynamic GUI that is _both_ easy to use and fast > |and easy to design (which is what you would want probably). Just to > |have a nice user editable table for example, you would have to jump > |through hoops (using Javascript, DOM, CSS etc), while you could do it > |much easier with PyGTK and wxPython, especially if you use a gui > |designer like Glade or wxGlade. Even Tkinter beats HTML as far as > |building GUIs in Python goes. I believe this might change in the future > |with the adaption of SVG but that will take a while... That said, if > |your interface can "get by" with just buttons, text boxes, and text > |areas HTML will be the best choice. > | > > At the moment my toy system just uses Tkinter- Buttons, Labels, Entry boxes and > Listboxes (which I populate from a dict) - and it has logic in it to do only one > dummy transaction, which I just ship to the server machine where nothing > happens - it is just echoed back to the client which prints it on stdout - If I > stay with this it will be a most uninteresting GUI - but that is not the point > at issue now... > > | > |As far as "updating-on-the-fly" goes: > | > |For the client to get the code on the fly you will have to implement > |some sort of a downloader in the first place that when the user logs > |in, it downloads the GUI code from the server and runs it. So if you > |update the code the day before the next day they will get a different > |interface, or if a new user/machine type is created you just have the > |new code ready on the server and it will automatically be downloaded > |and run, is that right? > | > > This is broadly what I had in mind, yes - but sort of down to a transaction > level - this user does invoicing, this one enters cheques, this one does credit > notes, and their supervisor can do all three, and in a different department its > different because the jobs are different, but the invoicing GUI module is the > same for wherever its used... > > |Here is then how I see your use case: > |1) You would define your business rules in your database, you will have > |usernames, user types, access rights, data tables, columns types, > |relations, views, etc... > > Yes no matter how you do it, you need to keep a per user or per machine set of > what can be done. - in banking terms - a sort of Terminal Management System... > > My thinking is simpler than this, because you are already thinking in "data base > speak" - now dont get me wrong - I realise that I will have to use a database - > but for me to start thinking in terms of views and stuff is kind of premature > when I dont even have a clear picture in my head of the kind of data the said > management system should keep, as I am not sure of what can, and cannot be done. > > |2) Then each user type will have a specific interface GUI code kept on > |the server (perhaps as a zipped binary GUI.zip in a database column > |called ClientSpecificGUI). > > I would like to split this down further - see above - so for each user there is > a sort of *pointer* to each of the kinds of transactions she can do, and these > are shipped separately and *linked* at the client side... > > |3) The client starts your Application.py which is the same across all > |clients. They will enter their username/password. The Application.py > |then sends those to the server to log into the DB. > > *nods* > > |4) After successful login, the Application.py performs a SELECT query > |to download the zipped GUI.py file. > |5) GUI.py is unzipped and executed to start the GUI. The Application.py > |code will pass the DB connection object to the GUI.py, so the GUI can > |continue to talk with the database. GUI.py runs and does its magic, in > |the meantime Application.py waits for GUI.py to finished and then both > |exit. > > |Is that what you had in mind? > > Very close - I have not even thought this far - I did not think of building a > GUI for each user, I thought of building it for each transaction - kind of a > series of things like my toy - and then I got stuck on the "linking the separate > transaction guis into an app on the fly" bit, which is why I started the > thread - I really want to know if it is possible to do this sort of thing in > Python, and so far Bruno has come up with Pyro, while everybody else (including > Bruno) is beating me over the head with HTML > > Now part of the reason I would like to go the transaction type route instead of > the "per user" route is robustness and maintainability, and the ability it > would give me to introduce new transaction types easily - as I see it if say an > invoice's GUI code is stable I would never have to touch it again even if I > combine it with anything else, as it would have been designed from the start to > combine with others of it's own ilk, under a kind of communications controller > that is standard... > > > |NOTE: This means that the client will need to have all the required > |libraries at just the right versions. Imagine that your user decides to > |upgrade to Python 3000 because it sounds cooler than plain old Python > |2.4 ;) , but then they won't realize that it will break your code and > |they might not be able to run your application anymore. So you would > |have to know at least roughly how much control over the whole client > |machine you will have. Will they all be regular desktops that users > |will use day to day and then once in a while launch your application > |then close it, or will these all be dedicated terminals like an ATM? > |The two are very different. You can assume complete control of all the > |OS environment in a dedicated terminal but not in the case of a user > |desktop. > > True - have not even considered this - this would, I imagine, vary from site to > site, and depend more on local IT policy - this is probably the strongest > argument to date against going this route, as these machines would not be as > tightly controlled as an ATM... > > but then - If I want to use Python in the client at all, I would have to somehow > come to terms with this - its more the normal sort of version control that would > have to be done - after all if a user's machine is an XT running DOS - then its > going to have to be upgraded before it can be used as a terminal... > > So this is more an argument against the use of Python on the client and I don't > like that... > > |Hope this helps, > |Nick Vatamaniuc > > 8<---------------------------------------------------- > > Yes it does, Thanks. I feel we are getting closer to the point where I can > decide if what I am thinking of is practical or a pipe dream - it sounded so > simple - make a series of guis for a series of transactions, ship them to the > client, where there is a simple top level thingy that swallows them and ties > them all together and handles the comms to the server... I mean the language is > called Python... :-) > > - Hendrik From subramanian2003 at indiatimes.com Wed Aug 2 03:52:36 2006 From: subramanian2003 at indiatimes.com (subramanian2003) Date: Wed, 02 Aug 2006 13:22:36 +0530 Subject: Python for arcgis Message-ID: <200608020644.MAA23784@WS0005.indiatimes.com> Hello All, From where I can get "Python for arcgis" tutorial. Bye, Subramanian. Sign Up for your FREE eWallet at www.wallet365.com From bignose+hates-spam at benfinney.id.au Mon Aug 7 23:21:36 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 08 Aug 2006 13:21:36 +1000 Subject: Import module with non-standard file name References: <1155002526.831944.240480@h48g2000cwc.googlegroups.com> <1155005565.456068.156350@b28g2000cwb.googlegroups.com> Message-ID: <87vep3yksf.fsf@benfinney.id.au> "John Machin" writes: > Ben Finney wrote: > > "John Machin" writes: > > > If it can [modify sys.path], it can copy the MUT to some temp > > > directory, adding .py to the end of the name of the new file, > > > and put the temp directory in sys.path .... can't it? > > > > The problem with importing the program module from a file in a > > different directory is that the program won't be able to find its > > own relative modules. That leads to either *more* sys.path > > hackery, or importing from a temporary file in the *same* > > directory. > > Please explain both the "own" and "relative" in "its own relative > modules". Do these modules not have names that end in ".py"? The program can import modules with relative paths, because it can expect its position in the directory tree to remain the same relative to those modules. If the program module suddenly exists in a different directory, that assumption no longer holds and the relative imports performed by the program will fail. Thus to avoid that problem, testing needs to be done on the program module with its position relative to all other modules the same as when that program runs. -- \ "It may be that our role on this planet is not to worship God | `\ -- but to create him." -- Arthur C. Clarke | _o__) | Ben Finney From bborcic at gmail.com Thu Aug 10 18:04:49 2006 From: bborcic at gmail.com (Boris Borcic) Date: Fri, 11 Aug 2006 00:04:49 +0200 Subject: converting a nested try/except statement into try/except/else In-Reply-To: <44dba661$1_4@news.bluewin.ch> References: <44db91a8$1_6@news.bluewin.ch> <8ZMCg.2676$No6.52114@news.tufts.edu> <44dba661$1_4@news.bluewin.ch> Message-ID: <44dbadc2_2@news.bluewin.ch> Boris Borcic wrote: > John Salerno wrote: >> In this case the method must return False, because it's a wxPython >> method that needs a True or False value. If it doesn't, the program >> will continue even after the error message. > > Just as it should do if the method returns True and no error message is > produced if I understand you well... Are you sure ? I don't know > wxPython, but this strikes me as surprisingly unpythonic behavior. I just verified on the wxWindows demo I had somehow installed on my box, that indeed returning None appears to produce the same behavior as returning True, distinct from the behavior obtained by returning False. Ugh... From cwarren89 at gmail.com Sat Aug 19 12:14:07 2006 From: cwarren89 at gmail.com (cwarren89 at gmail.com) Date: 19 Aug 2006 09:14:07 -0700 Subject: write eof without closing In-Reply-To: References: <12eeala1klcrtcf@corp.supernews.com> Message-ID: <1156004047.038032.26120@b28g2000cwb.googlegroups.com> Writing the binary value for ^D into the stream will not do anything. That value signals the shell to close the stream, as such it only has significance when you're typing something into the shell. To the OP: writing an EOF to a stream without closing it makes no sense. EOF means just that--end of file. Once the program reaches an EOF, it can't read any more values from the stream, so keeping it open to write more stuff into it wouldn't even work. From fabio.pliger at gmail.com Thu Aug 10 15:48:58 2006 From: fabio.pliger at gmail.com (Mr BigSmoke) Date: 10 Aug 2006 12:48:58 -0700 Subject: "running" code on client side with cherrypy? Message-ID: <1155239338.574898.193520@m79g2000cwm.googlegroups.com> Hi All, I'm developing a website to handle some code/application version control on a intranet. I'm using cherrypy and pysvn. Everything runs quite good but i want the user to be able to checkout some projects from the server. The user(on the client side) selects a folder in his machine (i.e.: C:\Project1) and the server should checkout (download/copy) all the project selected to the client machine. But what happens is that the webserver shckout the project on the same folder selected by the user but at server side. Everything works if the user gives a network path (like \\pcname\sharedFolder). Any hint? tnx! Fabio From btowle at carnegielearning.com Fri Aug 25 11:19:53 2006 From: btowle at carnegielearning.com (Brendon Towle) Date: Fri, 25 Aug 2006 11:19:53 -0400 Subject: Consistency in Python In-Reply-To: References: Message-ID: > Message: 3 > Date: Fri, 25 Aug 2006 15:28:46 +0200 > From: "Fredrik Lundh" > Subject: Re: Consistency in Python > > Brendon Towle wrote: > >> So, my question is: Someone obviously thought that it was wise and >> proper to require the longer versions that I write above. Why? > > a) maybe they had a working carriage return key ? Riiiiight. Now that we've got the "Frederik gets sarcastic with a relative Python newcomer" bit out of the way, is there an actual *answer* somewhere in the community? > b) http://pyfaq.infogami.com/why-doesn-t-list-sort-return-the- > sorted-list > (this also explains how to handle your specific use case) Well, I posted working code, so I thought it should have been obvious that I knew how to handle my use case, and was (am) looking for a language-design level answer as opposed to a working-code level answer. Besides, the article above (although useful *and* freshly modified) doesn't explain how to handle the use case I posted with append(), or the ones I didn't post with extend(), insert(), remove (), dict.update(), and a bunch of others I can't think of off the top of my head. > c) in general, mutating *and* returning may be confusing; consider: > > lst = [1, 2, 3] > for item in lst.reverse(): > print item > ... some other code ... > for item in lst.reverse(): > print item I guess I have three responses to this. The first is that generations of Lisp programmers seem to have handled mutating *and* returning just fine for about the last 50 years; maybe it really isn't all that hard. ("Always know where your CONS cells are coming from." is pretty ingrained in my programming DNA; the Python analog isn't hard.) My second response is that if "... some other code ..." is so long and involved that you've forgotten that you already reversed lst, then your function probably needs to be refactored and/or rewritten. My third response is that it's *always* possible to shoot yourself in the foot. Protecting a naive user from one particular metatarsal projectile insertion at the expense of letting the power-user write more concise code seems a bad tradeoff to me -- but, I'm not involved with Python design, which brings me back to my original question above. Anyone? B. -- Brendon Towle, PhD Cognitive Scientist +1-412-690-2442x127 Carnegie Learning, Inc. The Cognitive Tutor Company ? Helping over 375,000 students in 1000 school districts succeed in math. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lsumnler at gmail.com Fri Aug 11 00:00:55 2006 From: lsumnler at gmail.com (len) Date: 10 Aug 2006 21:00:55 -0700 Subject: semi-Newbie question In-Reply-To: <9upsq3-9ng.ln1@lairds.us> References: <1155229897.356144.183750@m79g2000cwm.googlegroups.com> <1155240906.769756.294620@74g2000cwt.googlegroups.com> <1155245290.532108.75560@75g2000cwc.googlegroups.com> <9upsq3-9ng.ln1@lairds.us> Message-ID: <1155268855.612545.108870@h48g2000cwc.googlegroups.com> Thank all for your reply. I will try again to state the problem. I have three files. 1. Tagfile - This file contains data in a CSV format each record in the file contains three fields 'Tagname', 'Scope', and 'Value' and exampe of this data file follows; "totalpolicypremium","pol0","1584" "quotenumber","pol0","5" "address1","pol0","123 Testing Street" "address2","pol0","" "apartmentnumber","pol0","" "cellphone","pol0","( ) -" ... "annualmiles","car1","0" "antilock","car1","A" "antitheft","car1","1" "bodytype","car1","4D" "buybackpip","car1","N" "carphone","car1","N" "city","car1","ALEXANDRIA" "coaccdeathlimit","car1","0" ... "annualmiles","car2","0" "antilock","car2","N" "antitheft","car2","1" "bodytype","car2","4D" "buybackpip","car2","N" "carphone","car2","N" "city","car2","ALEXANDRIA" ... "address1","drv1","123 Testing Street" "address2","drv1","" "agerated","drv1","0" "banklienjudgstat","drv1","N" "cellphone","drv1","( ) -" "city","drv1","Testing City" "cluestatus","drv1","N" etc I have already written the code that can pass through this file using the CSV module and extract the data as I need it from this file, no problem here. 2. TagToSQL - This is a file which I created which also contains 3 fields as follows 'theirTagname', 'theirScope', and 'mySQLfieldname' and acts as a crossreference file between the Tagfile and my SQL file example of TagToSQL this file has a primary index on theirTagname; "address1","POL1","bnd.addr1" "address2","POL1","bnd.addr2" "appartmentnumber","POL1","bnd.apptno" etc 3. Binder - This is the primary Policy header file and is in MySQL this file contains information such as; bnd.policyno bnd.last bnd.first bnd.addr1 bnd.addr2 bnd.city bnd.state etc Now most of my coding experience is in compiled languages such as cobol, c, assembler etc I have all of the file access code completed as far as reading through the CSV file and indexing into my TagToSQL file and writing to my SQL files the only problem I have is how to create what I believe to be the couple of lines of code which would allow me to move the date in 'Value' from the Tagfile into my SQL file using the data in the TagToSQL field mySQLfieldname. I have done some more reading and I think the code I need is as follows; mycode = "TagToSQL['mySQLfieldname'] = Tagfile['Value']" exec mycode This is very new to me because I don't believe this can be done in a compiled language or at least not as easily as in an interpeted language like Python. I hope this clarifies the problem Len Sumnler Unique Insurance Cameron Laird wrote: > In article <1155245290.532108.75560 at 75g2000cwc.googlegroups.com>, > len wrote: > >I appoligize I don't think I have done a very good job of explaining my > >problem. > . > . > . > >The program I am writing is nothing more than a conversion program to > >take the value out of the CSV file and map it into the appropriate > >field in my SQL files. Rather than creating some huge if than else > >(there are over 1000 tagnames) I created the xreffile. > > > >Now when I read a record from the tagfile I use the data in the tagname > >field to lookup the tagname in my xreffile. The data in the > >SQL_fieldname is the fieldname in my SQL files I want to place the data > >from the tagfile in the tagfile.value field into this field in my SQL > >files; > > > >data referenced by(xreffile.SQL_fieldname) = tagfile.value > > > >what I see as the problem is I want to use what is the data reference > >by xreffile.SQL.fieldname and now make it part of the python code as a > >reference variable in an assignement code statement. > . > . > . > 1. Take Daniel Wong's advice, elsewhere in this thread, > and use the Python CSV module. > 2. "what I see as the problem is I want ...": what you > want *is* rather a problem, because it's a troublesome > way to achieve what I understand to be your larger > aims. It was certainly good that you didn't create > "some huge if than else". > > Once you have an SQL_fieldname, and a tagfile.value, > what do you want to do? Are you stuffing data into > an SQL table? Continuing on with Python computations? > In almost any case, it sounds as though you will profit > greatly from study of Python's dictionaries http://www.developer.com/lang/other/article.php/630721 > > . From kyle.tk at gmail.com Wed Aug 2 19:49:56 2006 From: kyle.tk at gmail.com (kyle.tk) Date: 2 Aug 2006 16:49:56 -0700 Subject: Hiding Console Output In-Reply-To: <1154549874.490652.106980@m73g2000cwd.googlegroups.com> References: <1154549874.490652.106980@m73g2000cwd.googlegroups.com> Message-ID: <1154562596.454857.98470@i42g2000cwa.googlegroups.com> Kkaa wrote: > I'm using the os.system command in a python script on Windows to run a > batch file like this: > > os.system('x.exe') > > The third-party program x.exe outputs some text to the console that I > want to prevent from being displayed. Is there a way to prevent the > output of x.exe from python? Use os.popen('x.exe') instead. -kyle From horpner at yahoo.com Mon Aug 21 10:42:46 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 21 Aug 2006 16:42:46 +0200 Subject: istep() addition to itertool? (Was: Re: Printing n elements per line in a list) References: <1155685889.626881.37040@m73g2000cwd.googlegroups.com> <1156029171.940365.234010@m73g2000cwd.googlegroups.com> Message-ID: On 2006-08-19, Rhamphoryncus wrote: > unexpected wrote: >> If have a list from 1 to 100, what's the easiest, most elegant >> way to print them out, so that there are only n elements per >> line. > > I've run into this problem a few times, and although many > solutions have been presented specifically for printing I would > like to present a more general alternative. > > from itertools import chain > def istepline(step, iterator): > i = 0 > while i < step: > yield iterator.next() > i += 1 > > def istep(iterable, step): > iterator = iter(iterable) # Make sure we won't restart iteration > while True: > # We rely on istepline()'s side-effect of progressing the > # iterator. > start = iterator.next() > rest = istepline(step - 1, iterator) > yield chain((start,), rest) > for i in rest: > pass # Exhaust rest to make sure the iterator has > # progressed properly. > > Would anybody else find this useful? Maybe worth adding it to > itertool? Your note me curious enough to re-read the itertools documentation, and I found the following in 5.16.3 Recipes: def grouper(n, iterable, padvalue=None): "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')" return izip(*[chain(iterable, repeat(padvalue, n-1))]*n) Wish I'd found that yesterday. ;) -- Neil Cerutti From jslowery at gmail.com Wed Aug 30 19:42:17 2006 From: jslowery at gmail.com (jslowery at gmail.com) Date: 30 Aug 2006 16:42:17 -0700 Subject: Large LCD/Plasma TV Output Message-ID: <1156981337.436708.201880@e3g2000cwe.googlegroups.com> I'm soon going to be starting on a little program that needs to output tabular information to a large LCD or Plasma screen. Python is, of course, my preferred language. My first instinct is PyGame, which I have programming for a PC monitor before. Has anyone else had any experience with any Python libraries for large TV displays? From sjmaster at gmail.com Tue Aug 8 18:26:53 2006 From: sjmaster at gmail.com (Steve M) Date: 8 Aug 2006 15:26:53 -0700 Subject: newb question: file searching In-Reply-To: <1155074494.961508.199230@i3g2000cwc.googlegroups.com> References: <1155067111.892386.130610@n13g2000cwa.googlegroups.com> <1155074494.961508.199230@i3g2000cwc.googlegroups.com> Message-ID: <1155076013.744994.7570@i42g2000cwa.googlegroups.com> jaysherby at gmail.com wrote: > Okay. This is almost solved. I just need to know how to have each > entry in my final list have the full path, not just the file name. from http://docs.python.org/lib/os-file-dir.html: walk() generates the file names in a directory tree, by walking the tree either top down or bottom up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames). dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..'). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists contain no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name). -------- So walk yields a 3-tuple, not just a filename. You seem to be somewhat aware of this where you refer to files[2] in your list comprehension, but I believe that is not constructed correctly. Try this (untested): def get_image_filepaths(target_folder): """Return a list of filepaths (path plus filename) for all images in target_folder or any subfolder""" import os images = [] for dirpath, dirnames, filenames in os.walk(target_folder): for filename in filenames: normalized_filename = filename.lower() if normalized_filename.endswith('.jpg') or normalized_filename.endswith('.gif'): filepath = os.path.join(dirpath, filename) images.append(filepath) return images import os images = get_image_filepaths(os.getcwd()) > Also, I've noticed that files are being found within hidden > directories. I'd like to exclude hidden directories from the walk, or > at least not add anything within them. Any advice? Decide how you identify a hidden directory and test dirpath before adding it to the images list. E.g., test whether dirpath starts with '.' and skip it if so. > > Here's what I've got so far: > > def getFileList(): > import os > imageList = [] > for files in os.walk(os.getcwd(), topdown=True): > imageList += [file for file in files[2] if file.endswith('jpg') or > file.endswith('gif')] > return imageList From jorge.vargas at gmail.com Mon Aug 28 17:44:05 2006 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Mon, 28 Aug 2006 17:44:05 -0400 Subject: how to varify if a URL is valid in python? In-Reply-To: <1156801093.407783.25780@h48g2000cwc.googlegroups.com> References: <1156801093.407783.25780@h48g2000cwc.googlegroups.com> Message-ID: <32822fe60608281444p9d078bdteb8f8898c9ec9830@mail.gmail.com> http://docs.python.org/lib/module-urllib.html On 28 Aug 2006 14:38:13 -0700, fegge wrote: > what module should i import? > > -- > http://mail.python.org/mailman/listinfo/python-list > From tenax.raccoon at gmail.com Tue Aug 8 16:58:25 2006 From: tenax.raccoon at gmail.com (Jason) Date: 8 Aug 2006 13:58:25 -0700 Subject: newb question: file searching In-Reply-To: <1155069065.129575.10650@i42g2000cwa.googlegroups.com> References: <1155067111.892386.130610@n13g2000cwa.googlegroups.com> <1155068505.141479.5210@m79g2000cwm.googlegroups.com> <1155069065.129575.10650@i42g2000cwa.googlegroups.com> Message-ID: <1155070705.396649.158820@i42g2000cwa.googlegroups.com> jaysherby at gmail.com wrote: > Mike Kent wrote: > > What you want is os.walk(). > > > > http://www.python.org/doc/current/lib/os-file-dir.html > > I'm thinking os.walk() could definitely be a big part of my solution, > but I need a little for info. If I'm reading this correctly, os.walk() > just goes file by file and serves it up for your script to decide what > to do with each one. Is that right? So, for each file it found, I'd > have to decide if it met the criteria of the filetype I'm searching for > and then add that info to whatever datatype I want to make a little > list for myself? Am I being coherent? > > Something like: > > for files in os.walk(top, topdown=False): > for name in files: > (do whatever to decide if criteria is met, etc.) > > Does this look correct? Not completely. According to the documentation, os.walk returns a tuple: (directory, subdirectories, files) So the files you want are in the third element of the tuple. You can use the fnmatch module to find the names that match your filename pattern. You'll want to do something like this: >>> for (dir, subdirs, files) in os.walk('.'): ... for cppFile in fnmatch.filter(files, '*.cpp'): ... print cppFile ... ActiveX Test.cpp ActiveX TestDoc.cpp ActiveX TestView.cpp MainFrm.cpp StdAfx.cpp >>> Please note that your results will vary, of course. From stevebread at yahoo.com Mon Aug 21 17:35:58 2006 From: stevebread at yahoo.com (stevebread at yahoo.com) Date: 21 Aug 2006 14:35:58 -0700 Subject: Regular Expression question References: <1156153916.849933.178790@75g2000cwc.googlegroups.com> Message-ID: <1156196158.321416.244700@b28g2000cwb.googlegroups.com> Hi, thanks everyone for the information! Still going through it :) The reason I did not match on tag2 in my original expression (and I apologize because I should have mentioned this before) is that other tags could also have an attribute with the value of "adj__" and the attribute name may not be the same for the other tags. The only thing I can be sure of is that the value will begin with "adj__". I need to match the "adj__" value with the closest preceding tag1 irrespective of what tag the "adj__" is in, or what the attribute holding it is called, or the order of the attributes (there may be others). This data will be inside an html page and so there will be plenty of html tags in the middle all of which I need to ignore. Thanks very much! Steve From gelists at gmail.com Fri Aug 4 08:31:16 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Fri, 4 Aug 2006 09:31:16 -0300 Subject: Windows vs. Linux References: <1154301694.445639.99580@m79g2000cwm.googlegroups.com> <44cddfb3$0$7761$7a628cd7@news.club-internet.fr> Message-ID: <1ue7uay114ccc.dlg@gelists.gmail.com> On 2006-08-04 05:30:00, Sybren Stuvel wrote: >> Besides, you probably don't know whether it's not one of your direct >> suppliers who's affected. You're sure you don't buy from anybody >> running a Windows system? I'd bet against that, and I only bet when >> I know I win :) > > Good point. I don't buy much software, though. The only things I buy > are some games every now and then. No food? No clothes? No furniture? No household supplies? No transportation? No bike/bicycle/car? They all (well, most of them) use computers in their administration; /that's/ the cost I was talking about, not the cost for the software industry :) Gerhard From larry.bates at websafe.com Wed Aug 16 16:05:12 2006 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 16 Aug 2006 15:05:12 -0500 Subject: Adding a char inside path string In-Reply-To: <1155757548.080769.213490@p79g2000cwp.googlegroups.com> References: <1155737700.290268.248250@i42g2000cwa.googlegroups.com> <1155744057.573884.111850@m73g2000cwd.googlegroups.com> <1155757548.080769.213490@p79g2000cwp.googlegroups.com> Message-ID: Sounds like you can split the string on a space and throw away the right side: s='\\serverName\C:\FolderName1\FolderName2\example.exe' -u ABC -g XYZ p=s.split(" ", 1)[0] print p '\\serverName\C:\FolderName1\FolderName2\example.exe' Larry Bates Hitesh wrote: > > > Hi, > > Everything is working fine and dandy but I ran across another issue > here. > Some of the path comes with some extra chars padded at the end. > i.e. > > '\\serverName\C:\FolderName1\FolderName2\example.exe' -u ABC -g XYZ > abcdef > > Now those padded chars are not constant all the time. It can be > anything. > Only common denometer in each string that comes with those padded chars > is that it is after .exe and then there is space and then 99% of the > time it is -u and then there can be anything, I meant its dynemic after > that. > > so I am using string1.find(".exe") and could retrive the index but > don't know how to get rid any garbase after index + 4 > > hj > > > Dennis Lee Bieber wrote: >> On 16 Aug 2006 09:00:57 -0700, "Hitesh" declaimed >> the following in comp.lang.python: >> >>> Thank you Fredrik. That works for a string. >>> But I am getting list of tuples from DB. >>> >>> rows = [('\\serverName\C:\FolderName1\FolderName2\example.exe',), >>> ('\\serverName\C:\FolderName1\FolderName2\example2.exe',), >>> ('\\serverName\C:\FolderName1\FolderName2\example3.exe',), >>> ('\\serverName\C:\FolderName1\FolderName2\example4.exe',)] >>> >>> I tried this: >>> for i in rows: >>> row = str(i) >>> path = row.replace("C:" , "c$") >>> print path >>> >>> I am getting path something like >>> >>> ('\\serverName\c$:\FolderName1\FolderName2\example.exe',) >>> >>> How on the earth I can remove those paranthesis? >>> >> By accessing the contents of the tuple, not the tuple itself >> >>>>> rows = [('\\serverName\C:\FolderName1\FolderName2\example.exe',), >> ... ('\\serverName\C:\FolderName1\FolderName2\example2.exe',), >> ... ('\\serverName\C:\FolderName1\FolderName2\example3.exe',), >> ... ('\\serverName\C:\FolderName1\FolderName2\example4.exe',)] >>>>> rows >> [('\\serverName\\C:\\FolderName1\\FolderName2\\example.exe',), >> ('\\serverName\\C:\\FolderName1\\FolderName2\\example2.exe',), >> ('\\serverName\\C:\\FolderName1\\FolderName2\\example3.exe',), >> ('\\serverName\\C:\\FolderName1\\FolderName2\\example4.exe',)] >>>>> modRows = [itm[0].replace("C:", "C$") for itm in rows] >>>>> modRows >> ['\\serverName\\C$\\FolderName1\\FolderName2\\example.exe', >> '\\serverName\\C$\\FolderName1\\FolderName2\\example2.exe', >> '\\serverName\\C$\\FolderName1\\FolderName2\\example3.exe', >> '\\serverName\\C$\\FolderName1\\FolderName2\\example4.exe'] >> -- >> Wulfraed Dennis Lee Bieber KD6MOG >> wlfraed at ix.netcom.com wulfraed at bestiaria.com >> HTTP://wlfraed.home.netcom.com/ >> (Bestiaria Support Staff: web-asst at bestiaria.com) >> HTTP://www.bestiaria.com/ > From rogue_pedro at yahoo.com Mon Aug 14 14:47:52 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 14 Aug 2006 11:47:52 -0700 Subject: outputting a command to the terminal? In-Reply-To: References: <44df99f7$0$25025$c3e8da3@news.astraweb.com> <44dfc1cb$0$2397$c3e8da3@news.astraweb.com> <1155580175.313400.136900@m79g2000cwm.googlegroups.com> Message-ID: <1155581272.460369.37810@b28g2000cwb.googlegroups.com> John Salerno wrote: > Simon Forman wrote: > > > It's simple, short, and to-the-point. The equivalent python script > > would be much longer, for no appreciable gain. I write most of my tiny > > little helper scripts in python, but in this case, bash is the clear > > winnar. (And on *nix. man pages are your best friend. Plus you get to > > feel all l33t when you grok them. lol) > > Thanks for the info! I might grudgingly decide to use a bash script in > this case. :) You're welcome. lol :) > And yes, it seems every time I ask a Linux question, everyone points me > to a man page. Sometimes I find them difficult to decipher, but they are > still a great help. Yup. When I started with Linux, man pages were one of those things I resisted... until I started actually reading them. Then I kicked myself for not starting sooner. :) Neat trick: man -k Shows you man pages matching your search term (I think it's the same thing as the "apropos" command.) It searches the command names and summary lines. Peace, ~Simon From codecraig at gmail.com Mon Aug 7 10:55:11 2006 From: codecraig at gmail.com (abcd) Date: 7 Aug 2006 07:55:11 -0700 Subject: format a number for output Message-ID: <1154962511.485221.229830@i3g2000cwc.googlegroups.com> if i have a number, say the size of a file, is there an easy way to output it so that it includes commas? for example: 1890284 would be: 1,890,284 I am looking for something builtin to python, not a third party lib. thanks From fredrik at pythonware.com Sun Aug 27 09:34:09 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 27 Aug 2006 15:34:09 +0200 Subject: How to let a loop run for a while before checking for break condition? In-Reply-To: <4ldiacF1ckeeU1@uni-berlin.de> References: <4ldfp0F1csmpU1@uni-berlin.de> <4ldiacF1ckeeU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > A while loop has a condition. period. The only thing to change that is > to introduce a uncoditioned loop, and use self-modifying code to make it > a while-loop after that timer interrupt of yours. or use a timer interrupt to interrupt the loop: import signal, time def func1(timeout): def callback(signum, frame): raise EOFError # could use a custom exception instead signal.signal(signal.SIGALRM, callback) signal.alarm(timeout) count = 0 try: while 1: count += 1 except EOFError: for i in range(10): count += 1 print count for an utterly trivial task like the one in that example, the alarm version runs about five times faster than a polling version, on my test machine (ymmv): def func2(timeout): gettime = time.time t_limit = gettime() + timeout count = 0 while gettime() < t_limit: count += 1 for i in range(10): count += 1 print count From fredrik at pythonware.com Mon Aug 28 06:17:51 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 28 Aug 2006 12:17:51 +0200 Subject: how to get the os file icon for a given content-type? References: <1156753983.080547.306100@h48g2000cwc.googlegroups.com><44f2b8cc$0$11818$636a55ce@news.free.fr> <1156759387.819060.266380@m73g2000cwd.googlegroups.com> Message-ID: "neoedmund" wrote: > So what? Java 5.0 has the method, why python has not? python's developed by volunteers, and nobody has volunteered to develop such a function. why not check how Java does this, and contribute the code ? From rpdooling at gmail.com Sat Aug 19 00:16:54 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 18 Aug 2006 21:16:54 -0700 Subject: text editor suggestion? In-Reply-To: <44e66724$0$2363$c3e8da3@news.astraweb.com> References: <44e66724$0$2363$c3e8da3@news.astraweb.com> Message-ID: <1155961014.072903.115030@m73g2000cwd.googlegroups.com> John Salerno wrote: > Ok, I know it's been asked a million times, but I have a more specific > question so hopefully this won't be just the same old post. You got 65 answers last time :) http://tinyurl.com/rsfjq rd From sjmachin at lexicon.net Thu Aug 31 16:16:17 2006 From: sjmachin at lexicon.net (John Machin) Date: 31 Aug 2006 13:16:17 -0700 Subject: csv module strangeness. In-Reply-To: References: <44f5e870$0$8814$88260bb3@free.teranews.com> <44f5f347$0$8846$88260bb3@free.teranews.com> Message-ID: <1157055377.000676.243270@b28g2000cwb.googlegroups.com> tobiah wrote: > > > > > > > > I agree with Henryk's evaluation Henryk?? Have I missed a message in the thread, or has the effbot metamorphosed into the aitchbot? From bearophileHUGS at lycos.com Mon Aug 14 15:02:59 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 14 Aug 2006 12:02:59 -0700 Subject: Memory problem In-Reply-To: References: Message-ID: <1155582179.187999.202600@m73g2000cwd.googlegroups.com> Yi Xing wrote: > I need to read a large amount of data into a list. So I am trying to > see if I'll have any memory problem. When I do > x=range(2700*2700*3) I got the following message: > Traceback (most recent call last): > File "", line 1, in ? > MemoryError > Any way to get around this problem? I have a machine of 4G memory. The > total number of data points (float) that I need to read is in the order > of 200-300 millions. If you know that you need floats only, then you can use a typed array (an array.array) instead of an untyped array (a Python list): import array a = array.array("f") You can also try with a numerical library like scipy, it may support up to 2 GB long arrays. Bye, bearophile From claudio.grondi at freenet.de Sun Aug 27 16:32:21 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Sun, 27 Aug 2006 22:32:21 +0200 Subject: random writing access to a file in Python In-Reply-To: <7xr6z2dpt0.fsf@ruckus.brouhaha.com> References: <5a9ue2lrjh214ecmme09fsodhm3ico1ntm@4ax.com> <7xhczzqoi3.fsf@ruckus.brouhaha.com> <7xbqq7f6q7.fsf@ruckus.brouhaha.com> <7xd5anf23u.fsf@ruckus.brouhaha.com> <7xr6z2dpt0.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Claudio Grondi writes: > >>The Windows XP SP 2 '/> sort' (sorting of four Gigs of 20 byte records >>took 12 CPU and 18 usual hours) has, from what I could observe on the >>task manager, done the job in only two runs of 'copying' : > > > That is terrible; on a reasonably fast machine these days it should > take just a few minutes. Ok, I see - the misunderstanding is, that there were 4.294.967.296 records each 20 bytes long, what makes the actual file 85.899.345.920 bytes large (I just used 'Gigs' for telling the number of records, not the size of the file). Still not acceptable sorting time? Claudio Grondi From gene.tani at gmail.com Mon Aug 21 11:19:29 2006 From: gene.tani at gmail.com (gene tani) Date: 21 Aug 2006 08:19:29 -0700 Subject: Python Syntax Highlighting Module In-Reply-To: <1156172592.903109.172520@p79g2000cwp.googlegroups.com> References: <1156172592.903109.172520@p79g2000cwp.googlegroups.com> Message-ID: <1156173569.306945.320640@m79g2000cwm.googlegroups.com> frikker at gmail.com wrote: > Hello, > I have an idea for a project which involves an editor that supports > syntax highlighting. This would be for any language, particularly php, > html, css, etc. I would like to write this program using python. It > would only make sense to base this upon existing open source code. My > question is there a python module or examples on how to write a code > editor which supports modulated syntax highlighting? > > Thank you, > Blaine just a *few* examples http://lfw.org/python/cedit http://mathieu.fenniak.net/formatting-a-simple-function-in-python/ http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/200638 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442482 http://effbot.python-hosting.com/browser/stuff/sandbox/pythondoc/ http://qbnz.com/highlighter/index.php http://pudge.lesscode.org/ also look at GNU / emacs: http://fly.srk.fer.hr/~hniksic/emacs/htmlize.el.html http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52298 http://www.danbala.com/python/lpy/lpy.py.html http://www.gnu.org/software/src-highlite/ From gelists at gmail.com Tue Aug 15 13:49:22 2006 From: gelists at gmail.com (Gerhard Fiedler) Date: Tue, 15 Aug 2006 14:49:22 -0300 Subject: hide python code ! References: <1155252840.393678.205060@m79g2000cwm.googlegroups.com> <1155300852.497741.73230@74g2000cwt.googlegroups.com> <1155301468.870340.82920@b28g2000cwb.googlegroups.com> <1155307415.855555.124760@i3g2000cwc.googlegroups.com> <1155309563.898182.195950@p79g2000cwp.googlegroups.com> <1155313092.743230.33950@m73g2000cwd.googlegroups.com> <44e10b95$0$15787$14726298@news.sunsite.dk> <1hk3pm7.pxdu0v3byt8qN%aleax@mac.com> Message-ID: On 2006-08-15 12:04:18, Alex Martelli wrote: > It just isn't worth Microsoft's while to take the public-relations hit > of such a fight: much cheaper for them to re-implement your ideas than > to copy your GPL'd code. Exactly. So by publishing the ideas as GPL code, the author presents them not only the ideas very clearly and well documented, but also an example implementation. If there was some R&D work involved, it may be a better thing (in terms of protection) not to publish it. The protection from GPL is pretty much worthless if the worth is more in the principle than it the execution. Gerhard From metaperl at gmail.com Thu Aug 31 15:12:09 2006 From: metaperl at gmail.com (metaperl) Date: 31 Aug 2006 12:12:09 -0700 Subject: SQLObject or SQLAlchemy? In-Reply-To: References: <1157051071.018925.144950@b28g2000cwb.googlegroups.com> Message-ID: <1157051529.906778.43380@i3g2000cwc.googlegroups.com> John Salerno wrote: > Thanks for the reply. Do you mean in the above quote that SA is a little > more complicated than SO? Don't be afraid to download them and try their respective tutorials. Each one would take about an hour and then you'd have a feel for yourself. I agree with adam that SQLAlchemy has far more features and flexibility. SQLObject would be very great and convenient if you were throwing up a website that you knew would never require high volumne. SA does have an IRC group. It's not incredibly lively but at least there is one. From rogue_pedro at yahoo.com Fri Aug 25 01:59:32 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 24 Aug 2006 22:59:32 -0700 Subject: lazy arithmetic In-Reply-To: <1156484042.437296.55890@m73g2000cwd.googlegroups.com> References: <1156476992.102203.304450@p79g2000cwp.googlegroups.com> <1156481896.043165.84770@i3g2000cwc.googlegroups.com> <1156484042.437296.55890@m73g2000cwd.googlegroups.com> Message-ID: <1156485572.250820.27040@74g2000cwt.googlegroups.com> pianomaestro at gmail.com wrote: > Simon Forman wrote: > > > > > "Item.__add__ = Add" is a very strange thing to do, I'm not surprised > > it didn't work. > > Yes it is strange. > I also tried this even stranger thing: > > class Item(object): > class __add__(object): > def __init__(self, a, b=None): > print self, a, b > self.a = a > self.b = b > > :) > > Simon. That didn't work either did it? :-) ~Simon F. From bobrien18 at yahoo.com Wed Aug 16 15:53:12 2006 From: bobrien18 at yahoo.com (KraftDiner) Date: 16 Aug 2006 12:53:12 -0700 Subject: trouble understanding inheritance... In-Reply-To: <1155756282.851876.46470@b28g2000cwb.googlegroups.com> References: <1155753183.207393.116940@m79g2000cwm.googlegroups.com> <1155754767.694480.256200@h48g2000cwc.googlegroups.com> <1155756282.851876.46470@b28g2000cwb.googlegroups.com> Message-ID: <1155757992.706040.288890@74g2000cwt.googlegroups.com> Simon Forman wrote: > KraftDiner wrote: > > Fredrik Lundh wrote: > > > KraftDiner wrote: > > > > > > > This is not working the way I think it should.... > > > > it would appear that fromfile and getName are calling the baseClass > > > > methods which are > > > > simple passes.... What have I done wrong? > > > > > > > > class baseClass: > > > > def __init__(self, type): > > > > if type == 'A': > > > > self = typeA() > > > > else: > > > > self = typeB() > > > > > > __init__ is not a constructor, and assigning to self doesn't change the > > > type of the constructed object. > > > > > > looks like you need to get a better tutorial. > > > > > > > > > > Well how does one select which class baseClass really is when you > > contruct the object? > > What am I missing? > > > > a = typeA() > > b = typeB() > > c = baseClass(a) > > a = typeA() > b = typeB() > > You're done. Stop there. > I can see that this might work... c = [a, b] for c in [a,b]: c.getName() but when does baseClass ever get used? Why did i even have to define it? > You can't "select which class baseClass really is"-- it really is > baseClass. You "select" which class your object is by choosing which > class to use to construct the object. > > HTH, > ~Simon From sjmachin at lexicon.net Wed Aug 30 18:28:36 2006 From: sjmachin at lexicon.net (John Machin) Date: 30 Aug 2006 15:28:36 -0700 Subject: csv module strangeness. References: <44f5e870$0$8814$88260bb3@free.teranews.com> <44f5f347$0$8846$88260bb3@free.teranews.com> Message-ID: <1156976916.699378.17330@p79g2000cwp.googlegroups.com> tobiah wrote: > > The docs clearly state what the defaults are, but they are not > in the code. It seems so clumsy to have to specify every one > of these, just to change the delimiter from comma to tab. > That particular case is handled by the built-in (but cunningly concealed) 'excel-tab' class: |>>> import csv |>>> csv.list_dialects() ['excel-tab', 'excel'] |>>> td = csv.get_dialect('excel-tab') |>>> dir(td) ['__doc__', '__init__', '__module__', '_name', '_valid', '_validate', 'delimiter', 'doublequote', 'escapechar', 'lineterminator', 'quotechar', 'quoting', 'skipinitialspace'] |>>> td.delimiter '\t' However, more generally, the docs also clearly state that "In addition to, or instead of, the dialect parameter, the programmer can also specify individual formatting parameters, which have the same names as the attributes defined below for the Dialect class." In practice, using a Dialect class would be a rather rare occurrence. E.g. here's the guts of the solution to the "fix a csv file by rsplitting one column" problem, using the "quoting" attribute on the assumption that the solution really needs those usually redundant quotes: import sys, csv def fix(inf, outf, fixcol): wtr = csv.writer(outf, quoting=csv.QUOTE_ALL) for fields in csv.reader(inf): fields[fixcol:fixcol+1] = fields[fixcol].rsplit(None, 1) wtr.writerow(fields) if __name__ == "__main__": av = sys.argv fix(open(av[1], 'rb'), open(av[2], 'wb'), int(av[3])) HTH, John From neoedmund at gmail.com Mon Aug 28 04:33:03 2006 From: neoedmund at gmail.com (neoedmund) Date: 28 Aug 2006 01:33:03 -0700 Subject: how to get the os file icon for a given content-type? Message-ID: <1156753983.080547.306100@h48g2000cwc.googlegroups.com> any simple method? From xrobledo at purdue.edu Sat Aug 12 20:55:41 2006 From: xrobledo at purdue.edu (Xavier) Date: Sat, 12 Aug 2006 19:55:41 -0500 Subject: proxy for xmlrpc calls Message-ID: I'm attempting to write a proxy for xmlrpc calls. I'm starting from this code; class MagicObject: def __call__(self,*args,**kwargs): return MagicObject.__dict__['_stop'](self,self.n,*args,**kwargs) def __getattr__(self,name): if name in ('__str__','__repr__'): return lambda:'instance of %s at %s' % (str(self.__class__),id(self)) if not self.__dict__.has_key('n'):self.n=[] self.n.append(name) return self def _stop(self,n,*args,**kwargs): self.n=[] return self.default(n,*args,**kwargs) def default(self,n,*args,**kwargs): return 'stop',n,args,kwargs ################################################################ >>c=MagicObject() >>x=c.beubeb.zzzzz(1,2,3,a='bbb') >>print x ('stop', ['beubeb', 'zzzzz'], (1, 2, 3), {'a': 'bbb'}) I did not write this, the source is here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/435757 I want to expand this to do something like; >>a=MagicObject() >>x = a.b.c.d Then on the last __getattr__ send a call over xmlrpc. How do I determine when the last __getattr__ will be? With method calls you know to send a call on xmlrpc when you hit __call__. But if you're dealing with a getting nested attributes what do you do? How do I know when there are no more attributes? I thought about getting the source code from the correct frame, but I don't think thats a good solution. Any ideas? Thanks in advance. From pianomaestro at gmail.com Fri Aug 25 05:43:52 2006 From: pianomaestro at gmail.com (pianomaestro at gmail.com) Date: 25 Aug 2006 02:43:52 -0700 Subject: lazy arithmetic In-Reply-To: <1156485503.816318.315150@75g2000cwc.googlegroups.com> References: <1156476992.102203.304450@p79g2000cwp.googlegroups.com> <1156483096.397300.110210@75g2000cwc.googlegroups.com> <1156485503.816318.315150@75g2000cwc.googlegroups.com> Message-ID: <1156499031.982640.157730@b28g2000cwb.googlegroups.com> Simon Forman wrote: > But that's a function, not a class. When you assign add to an > attribute of Item it "magically" becomes a method of Item: > Yes, I am looking to understand this magic. Sounds like I need to dig into these descriptor thingies (again). (sound of brain exploding).. Simon. From lgoh at optonline.net Thu Aug 24 03:33:33 2006 From: lgoh at optonline.net (leo) Date: Thu, 24 Aug 2006 03:33:33 -0400 Subject: what is the data from loads() Message-ID: Hi, Following is the python scripts: import marshal exec(marshal.loads('c\000\000\000\000\001\000\000\000s\017\000\000\000\177\000\000\177\002\000d\000\000GHd\001\000S(\002\000\000\000s\005\000\000\000helloN(\000\000\000\000(\000\000\000\000s\010\000\000\000